@mengine/medeo-client 2.0.1-alpha.15 → 2.0.1-alpha.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,8 @@
1
- import { $ as partUnionSchema, A as decodeEntityRelationRows, B as isJsonObject, C as applyFieldChanges, Ct as recordEntries, D as EntityProjectionGraph, E as projectEntityTimeline, Et as bytesToBase64, F as assembleScriptText, G as buildInitialVideoDocument, H as createRelationId, I as findComposedAudioScript, J as fromVideoDocument, K as buildSpeechHostMap, L as selectAudioScriptSegment, M as assembleCaptionContent, N as assembleEntityContent, O as resolveEntityTimelineLayout, P as assemblePhoneticScriptContent, Q as validateVideoDocument, R as updateEntityFields, S as equalJson, St as partUnionToDraft, T as resolveFieldPath, Tt as base64ToBytes, U as hasSequence, V as createEntityId, W as isMediaAssetVariantKind, X as VideoDocumentValidationError, Y as toVideoDocument, Z as assertValidVideoDocument, _ as audioScriptAssetOf, _t as partDurationMs, a as createMirrorVideoDocument, at as laneTrackId, b as phoneticScriptAssetOf, bt as effectiveVideoClipDurationMs, c as DocumentMutationGuard, ct as arrangeMainTrackSeamlessly, d as LoroEntityDraft, dt as recalculateTimelineDuration, et as videoDocumentSchema, f as readEntityDocument, ft as resolveAllSpeechOverlaps, g as audioScriptAssetHash, gt as isEmptyVideoClip, h as audioScriptAssetFields, ht as TIMELINE_SKELETON_DURATION_MS, i as MirrorVideoDocumentAdapter, it as hasResolvedPlacement, j as ScriptCompositionError, k as EntityTimelineProjectionError, l as LORO_ENTITY_SCHEMA, lt as fillMainTrackTimeGaps, m as audioScriptAssetContent, mt as syncAggregatedClipsTimePosition, n as createPlainMemoryAdapter, nt as ensureLaneTrack, o as createMirrorVideoDocumentAdapter, ot as solveVideoDocument, p as entityOrderGroups, pt as resolveSpeechOverlapByShiftingVideos, q as derivePositionFromAbs, r as generatePartId, rt as findLaneTrack, s as readVideoDocumentFromDraft, st as cascadeAfterVideoClipChanges, t as PlainMemoryAdapter, tt as LANE_KINDS_IN_STACK_ORDER, u as LoroEntityDocument, ut as reassignSpeechesToVideoClipsByTime, v as phoneticScriptAssetContent, vt as safeDurationMs, w as assertFieldChanges, wt as videoDocumentMirrorSchema, x as scriptSourceAssetOf, xt as speedOf, y as phoneticScriptAssetHash, yt as DEFAULT_UNIT_TIME_MS, z as variantBaseEntityIds } from "./document-CAZ_A9R8.js";
1
+ import { $ as validateVideoDocument, A as EntityTimelineProjectionError, B as variantBaseEntityIds, C as equalJson, Ct as partUnionToDraft, D as projectEntityTimeline, Dt as bytesToBase64, E as resolveFieldPath, Et as base64ToBytes, F as assemblePhoneticScriptContent, G as isMediaAssetVariantKind, H as createEntityId, I as assembleScriptText, J as derivePositionFromAbs, K as buildInitialVideoDocument, L as findComposedAudioScript, M as ScriptCompositionError, N as assembleCaptionContent, O as EntityProjectionGraph, P as assembleEntityContent, Q as assertValidVideoDocument, R as selectAudioScriptSegment, S as canonicalJson, St as speedOf, T as assertFieldChanges, Tt as videoDocumentMirrorSchema, U as createRelationId, V as isJsonObject, W as hasSequence, X as toVideoDocument, Y as fromVideoDocument, Z as VideoDocumentValidationError, _ as audioScriptAssetOf, _t as isEmptyVideoClip, a as createMirrorVideoDocument, at as hasResolvedPlacement, b as phoneticScriptAssetOf, bt as DEFAULT_UNIT_TIME_MS, c as DocumentMutationGuard, ct as cascadeAfterVideoClipChanges, d as LoroEntityDraft, dt as reassignSpeechesToVideoClipsByTime, et as partUnionSchema, f as readEntityDocument, ft as recalculateTimelineDuration, g as audioScriptAssetHash, gt as TIMELINE_SKELETON_DURATION_MS, h as audioScriptAssetFields, ht as syncAggregatedClipsTimePosition, i as MirrorVideoDocumentAdapter, it as findLaneTrack, j as decodeEntityRelationRows, k as resolveEntityTimelineLayout, l as LORO_ENTITY_SCHEMA, lt as arrangeMainTrackSeamlessly, m as audioScriptAssetContent, mt as resolveSpeechOverlapByShiftingVideos, n as createPlainMemoryAdapter, nt as LANE_KINDS_IN_STACK_ORDER, o as createMirrorVideoDocumentAdapter, ot as laneTrackId, p as entityOrderGroups, pt as resolveAllSpeechOverlaps, q as buildSpeechHostMap, r as generatePartId, rt as ensureLaneTrack, s as readVideoDocumentFromDraft, st as solveVideoDocument, t as PlainMemoryAdapter, tt as videoDocumentSchema, u as LoroEntityDocument, ut as fillMainTrackTimeGaps, v as phoneticScriptAssetContent, vt as partDurationMs, w as applyFieldChanges, wt as recordEntries, x as scriptSourceAssetOf, xt as effectiveVideoClipDurationMs, y as phoneticScriptAssetHash, yt as safeDurationMs, z as updateEntityFields } from "./document-ecRldQY4.js";
2
2
  import { addSpeechesInputSchema, addVideoClipsInputSchema, adjustBgmVolumeInputSchema, adjustSpeechVolumeInputSchema, adjustVideoClipDurationInputSchema, adjustVideoClipVolumeInputSchema, changeSpeechScriptInputSchema, changeSpeechVoiceInputSchema, deleteBgmInputSchema, deleteSpeechesInputSchema, deleteVideoClipsInputSchema, moveSpeechesInputSchema, moveVideoClipsByAnchorInputSchema, moveVideoClipsInputSchema, replaceVideoClipContentInputSchema, replaceVideoClipSequenceInputSchema, setBgmInputSchema, setCaptionStyleInputSchema, setCaptionVisibilityInputSchema, setVideoClipSpeedShiftInputSchema, t as schemas_exports } from "./schemas.js";
3
3
  import { LoroDoc, UndoManager, VersionVector } from "loro-crdt";
4
+ import { sha256 } from "@noble/hashes/sha2.js";
5
+ import { bytesToHex } from "@noble/hashes/utils.js";
4
6
  import { ClientServerSynchronizer, DocManager } from "@mengine/sync";
5
7
  import { DisposableSet, EventBus, Task } from "@mengine/utils";
6
8
  import { BaseDocStorage, DummyConnection } from "@mengine/storage";
@@ -554,6 +556,30 @@ const numericCoordinates = { compareMarkerPoints: (_marker, _range, left, right)
554
556
  if (typeof left !== "number" || typeof right !== "number" || !Number.isFinite(left) || !Number.isFinite(right)) throw new Error("Media editor requires numeric coordinates");
555
557
  return left - right;
556
558
  } };
559
+ /** Import only the fixed ASR artifact; Caption entities are authored separately. */
560
+ function importCaptionAsset(initial, fact, idFactory = (prefix) => `${prefix}_${globalThis.crypto.randomUUID()}`) {
561
+ if (!fact.assetId || fact.assetId.trim() !== fact.assetId) throw new Error("Expected a caption asset id");
562
+ if (fact.storageKey !== void 0 && (!fact.storageKey || fact.storageKey.trim() !== fact.storageKey)) throw new Error("Caption asset storage key must be non-empty and trimmed");
563
+ decodeEntityRelationRows(initial, numericCoordinates);
564
+ assertCanonicalEditorResources(initial);
565
+ const entities = structuredClone([...initial.entities]);
566
+ const relations = structuredClone([...initial.relations]);
567
+ const asset = ensureAsset(entities, relations, {
568
+ system: "memota",
569
+ key: fact.assetId,
570
+ ...fact.storageKey === void 0 ? {} : { storageKey: fact.storageKey }
571
+ }, idFactory);
572
+ const rows = {
573
+ entities,
574
+ relations
575
+ };
576
+ decodeEntityRelationRows(rows, numericCoordinates);
577
+ assertCanonicalEditorResources(rows);
578
+ return {
579
+ rows,
580
+ assetEntityId: asset.entityId
581
+ };
582
+ }
557
583
  /**
558
584
  * Import at the editor boundary, not at asset generation time. Existing
559
585
  * provenance is retained.
@@ -581,7 +607,7 @@ function importMediaAsset(initial, fact, idFactory = (prefix) => `${prefix}_${gl
581
607
  const entityKind = fact.kind === "voiceover" ? "audio" : fact.kind;
582
608
  const timbre = fact.kind === "voiceover" ? fact.voice : void 0;
583
609
  const durationMs = fact.kind === "image" ? null : fact.durationMs;
584
- const asset = ensureAsset(entities, {
610
+ const asset = ensureAsset(entities, relations, {
585
611
  system,
586
612
  key: fact.assetId,
587
613
  storageKey: fact.storageKey
@@ -625,20 +651,31 @@ function importMediaAsset(initial, fact, idFactory = (prefix) => `${prefix}_${gl
625
651
  };
626
652
  }
627
653
  /** One Asset per `(system, key)`: the bytes are named in exactly one row. */
628
- function ensureAsset(entities, locator, idFactory) {
654
+ function ensureAsset(entities, relations, locator, idFactory) {
629
655
  const found = entities.find((row) => row.entityKind === "asset" && row.payload.system === locator.system && row.payload.key === locator.key);
630
656
  if (found !== void 0) {
631
657
  if (locator.storageKey === void 0 || found.payload.storageKey === locator.storageKey) return found;
632
658
  if (found.payload.storageKey !== void 0) throw new Error(`Media facts conflict with existing storage key for ${locator.key}`);
633
- const filled = {
634
- ...found,
659
+ const replacement = {
660
+ entityId: createEntityId(idFactory("entity")),
661
+ entityKind: "asset",
635
662
  payload: {
636
663
  ...found.payload,
637
664
  storageKey: locator.storageKey
638
665
  }
639
666
  };
640
- replaceEntity$1(entities, found.entityId, filled);
641
- return filled;
667
+ if (entities.some((row) => row.entityId === replacement.entityId)) throw new Error(`Duplicate entity id ${replacement.entityId}`);
668
+ const bindings = relations.filter((relation) => relation.relationKind === "from-asset" && (relation.endpoint0EntityId === found.entityId || relation.endpoint1EntityId === found.entityId)).sort((left, right) => String(left.relationId).localeCompare(String(right.relationId)));
669
+ const replaced = new Set(bindings.map((relation) => relation.relationId));
670
+ const nextBindings = bindings.map((relation) => ({
671
+ ...relation,
672
+ relationId: createRelationId(idFactory("relation")),
673
+ endpoint0EntityId: relation.endpoint0EntityId === found.entityId ? replacement.entityId : relation.endpoint0EntityId,
674
+ endpoint1EntityId: relation.endpoint1EntityId === found.entityId ? replacement.entityId : relation.endpoint1EntityId
675
+ }));
676
+ relations.splice(0, relations.length, ...relations.filter((relation) => !replaced.has(relation.relationId)), ...nextBindings);
677
+ replaceEntity$1(entities, found.entityId, replacement);
678
+ return replacement;
642
679
  }
643
680
  const asset = {
644
681
  entityId: createEntityId(idFactory("entity")),
@@ -747,7 +784,7 @@ const defaultIdFactory = (prefix) => `${prefix}_${globalThis.crypto.randomUUID()
747
784
  * Each mutation is applied to a detached graph, validated as a complete DSL set,
748
785
  * and committed only after validation succeeds.
749
786
  */
750
- var EntityTimelineEditor = class {
787
+ var EntityTimelineEditor = class EntityTimelineEditor {
751
788
  idFactory;
752
789
  state;
753
790
  constructor(initialRows, idFactory = defaultIdFactory) {
@@ -1058,49 +1095,65 @@ var EntityTimelineEditor = class {
1058
1095
  });
1059
1096
  }
1060
1097
  setClipSpeed(input) {
1098
+ this.transact((draft) => this.setClipSpeedIntoDraft(draft, input));
1099
+ }
1100
+ /** Apply one typed Director speed effect as a single graph transaction. */
1101
+ setVideoClipSpeeds(input) {
1102
+ if (input.clips.length === 0) throw new Error("At least one Video Clip speed is required");
1103
+ if (new Set(input.clips.map((clip) => clip.videoClipEntityId)).size !== input.clips.length) throw new Error("Video Clip speed targets must be unique");
1061
1104
  this.transact((draft) => {
1062
- const initialTopology = requireClipOnRole(draft, input.clipEntityId, "video_clip");
1063
- const content = requireSequenceContent(draft, otherEndpoint(initialTopology.markerContentRelation, initialTopology.marker.entityId));
1064
- if (content.entityKind !== "video" && content.entityKind !== "image") throw new Error("Clip speed is supported only for Video or Image content");
1065
- const initialPayload = cloneJsonObject(initialTopology.marker.payload, "Sequence Marker payload");
1066
- const priorSource = requirePositiveRange(initialPayload.sourceRange, "sourceRange");
1067
- if (input.timeRemapping === null && initialPayload.timeRemapping === void 0) return;
1068
- this.normalizeMainSequential(draft);
1069
- const topology = requireClipTopology(draft, input.clipEntityId);
1070
- const payload = { ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload") };
1071
- let sourceRange = priorSource;
1072
- if (content.entityKind === "image" && initialPayload.timeRemapping === void 0 && input.timeRemapping !== null) sourceRange = {
1073
- start: 0,
1074
- end: markerDuration(initialPayload, priorSource)
1075
- };
1076
- if (input.timeRemapping === null) {
1077
- delete payload.timeRemapping;
1078
- payload.sourceRange = sourceRange;
1079
- payload.duration = {
1080
- mode: "fixed",
1081
- value: sourceRange.end - sourceRange.start
1082
- };
1083
- } else {
1084
- const rate = finitePositive(input.timeRemapping.rate, "linear speed rate");
1085
- const duration = Math.round((sourceRange.end - sourceRange.start) / rate);
1086
- if (duration <= 0 || !Number.isSafeInteger(duration)) throw new Error("Linear speed produces an invalid duration");
1087
- payload.sourceRange = sourceRange;
1088
- payload.duration = {
1089
- mode: "fixed",
1090
- value: duration
1091
- };
1092
- payload.timeRemapping = {
1093
- kind: "linear",
1094
- rate,
1095
- ...input.timeRemapping.mode === void 0 ? {} : { mode: input.timeRemapping.mode }
1096
- };
1105
+ for (const clip of input.clips) {
1106
+ const rate = speedModeRate(clip.mode);
1107
+ this.setClipSpeedIntoDraft(draft, {
1108
+ clipEntityId: clip.videoClipEntityId,
1109
+ timeRemapping: rate === 1 ? null : {
1110
+ kind: "linear",
1111
+ rate,
1112
+ mode: "constant"
1113
+ }
1114
+ });
1097
1115
  }
1098
- resizeAbsoluteTarget(payload, markerDuration(payload, sourceRange));
1099
- replaceEntity(draft, topology.marker.entityId, {
1100
- ...topology.marker,
1101
- payload
1102
- });
1103
- this.resolveOneVoiceoverOverlap(draft);
1116
+ });
1117
+ }
1118
+ setClipSpeedIntoDraft(draft, input) {
1119
+ const topology = requireCanonicalClipOnRole(draft, input.clipEntityId, "video_clip");
1120
+ const content = requireSequenceContent(draft, topology.markerContentRelation.endpoint1EntityId);
1121
+ if (content.entityKind !== "video" && content.entityKind !== "image") throw new Error("Clip speed is supported only for Video or Image content");
1122
+ const initialPayload = cloneJsonObject(topology.marker.payload, "Sequence Marker payload");
1123
+ const priorSource = requirePositiveRange(initialPayload.sourceRange, "sourceRange");
1124
+ if (input.timeRemapping === null && initialPayload.timeRemapping === void 0) return;
1125
+ const payload = { ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload") };
1126
+ let sourceRange = priorSource;
1127
+ if (content.entityKind === "image" && initialPayload.timeRemapping === void 0 && input.timeRemapping !== null) sourceRange = {
1128
+ start: 0,
1129
+ end: markerDuration(initialPayload, priorSource)
1130
+ };
1131
+ if (input.timeRemapping === null) {
1132
+ delete payload.timeRemapping;
1133
+ payload.sourceRange = sourceRange;
1134
+ payload.duration = {
1135
+ mode: "fixed",
1136
+ value: sourceRange.end - sourceRange.start
1137
+ };
1138
+ } else {
1139
+ const rate = finitePositive(input.timeRemapping.rate, "linear speed rate");
1140
+ const duration = Math.round((sourceRange.end - sourceRange.start) / rate);
1141
+ if (duration <= 0 || !Number.isSafeInteger(duration)) throw new Error("Linear speed produces an invalid duration");
1142
+ payload.sourceRange = sourceRange;
1143
+ payload.duration = {
1144
+ mode: "fixed",
1145
+ value: duration
1146
+ };
1147
+ payload.timeRemapping = {
1148
+ kind: "linear",
1149
+ rate,
1150
+ ...input.timeRemapping.mode === void 0 ? {} : { mode: input.timeRemapping.mode }
1151
+ };
1152
+ }
1153
+ resizeAbsoluteTarget(payload, markerDuration(payload, sourceRange));
1154
+ replaceEntity(draft, topology.marker.entityId, {
1155
+ ...topology.marker,
1156
+ payload
1104
1157
  });
1105
1158
  }
1106
1159
  trimClip(input) {
@@ -1450,12 +1503,447 @@ var EntityTimelineEditor = class {
1450
1503
  });
1451
1504
  });
1452
1505
  }
1506
+ #applyCaptionAssets(envelope) {
1507
+ return this.transact((draft) => {
1508
+ const input = envelope.input;
1509
+ const effectId = requireTrimmed(input.effectId, "Caption effect id");
1510
+ const identityScope = stableEffectScope(captionAssetsCommand, effectId, envelope.baselineFingerprint);
1511
+ const segments = validateAsrSegments(input.segments);
1512
+ const source = requireEntityKind(draft, input.source.entityId, input.source.entityKind);
1513
+ const track = requireCanonicalCaptionTrack(draft, input.timelineEntityId, input.trackEntityId);
1514
+ const signature = envelope.signature;
1515
+ const replay = resolveCaptionAssetsReplay(draft, input, effectId, signature, segments, source.entityId, track.entityId);
1516
+ if (replay !== void 0) return replay;
1517
+ const imported = importCaptionAsset(draft, input.captionAsset, stableEffectIdFactory(identityScope, "caption-asset"));
1518
+ if (imported.assetEntityId !== envelope.decisions.captionAsset.resultAssetEntityId) throw new Error("Frozen Caption Asset decision no longer matches the causal baseline");
1519
+ replaceRows(draft, imported.rows);
1520
+ const scriptId = requireAvailableEntityId(draft, stableEffectId("entity", identityScope, "audio-script"));
1521
+ const scriptMarkerId = requireAvailableEntityId(draft, stableEffectId("entity", identityScope, "audio-script-marker"));
1522
+ const asrStartMs = Math.min(...segments.map((segment) => segment.startMs));
1523
+ const asrEndMs = Math.max(...segments.map((segment) => segment.endMs));
1524
+ draft.entities.push({
1525
+ entityId: scriptId,
1526
+ entityKind: "audio-script",
1527
+ payload: { segments: segments.map(({ segmentId, text, language }) => ({
1528
+ segmentId,
1529
+ text,
1530
+ ...language === void 0 ? {} : { language }
1531
+ })) }
1532
+ });
1533
+ draft.entities.push({
1534
+ entityId: scriptMarkerId,
1535
+ entityKind: "sequence-marker",
1536
+ payload: {
1537
+ sourceRange: {
1538
+ start: asrStartMs,
1539
+ end: asrEndMs
1540
+ },
1541
+ duration: {
1542
+ mode: "fixed",
1543
+ value: asrEndMs - asrStartMs
1544
+ },
1545
+ segmentRanges: segments.map(({ segmentId, startMs, endMs }) => ({
1546
+ segmentId,
1547
+ startMs,
1548
+ endMs
1549
+ }))
1550
+ }
1551
+ });
1552
+ draft.relations.push(this.createRelation(draft, "audio-script-source", scriptId, source.entityId, {}, effectTrace(effectId, signature), stableEffectId("relation", identityScope, "audio-script-source")), this.createRelation(draft, "audio-script-marker", scriptId, scriptMarkerId, {}, effectTrace(effectId, signature), stableEffectId("relation", identityScope, "audio-script-marker")));
1553
+ const captionEntityIds = [];
1554
+ const captionClipEntityIds = [];
1555
+ for (const [index, segment] of segments.entries()) {
1556
+ const durationMs = segment.endMs - segment.startMs;
1557
+ const target = envelope.decisions.targetRanges[index];
1558
+ if (target?.segmentId !== segment.segmentId) throw new Error("Frozen Caption placement order is invalid");
1559
+ const targetRange = {
1560
+ start: target.start,
1561
+ end: target.end
1562
+ };
1563
+ const captionId = requireAvailableEntityId(draft, stableEffectId("entity", identityScope, `caption:${segment.segmentId}`));
1564
+ draft.entities.push({
1565
+ entityId: captionId,
1566
+ entityKind: "caption",
1567
+ payload: {
1568
+ durationMs,
1569
+ baseEntityIds: [scriptId],
1570
+ selection: { segmentId: segment.segmentId }
1571
+ }
1572
+ });
1573
+ const trace = effectTrace(effectId, signature, segment.segmentId);
1574
+ draft.relations.push(this.createRelation(draft, "from-asset", captionId, createEntityId(imported.assetEntityId), {}, trace, stableEffectId("relation", identityScope, `caption-asset:${segment.segmentId}`)));
1575
+ const clipId = this.insertPlacedClipIntoDraft(draft, {
1576
+ clipEntityId: stableEffectId("entity", identityScope, `caption-clip:${segment.segmentId}`),
1577
+ markerEntityId: stableEffectId("entity", identityScope, `caption-marker:${segment.segmentId}`),
1578
+ trackEntityId: track.entityId,
1579
+ contentEntityId: captionId,
1580
+ sourceRange: {
1581
+ start: 0,
1582
+ end: durationMs
1583
+ },
1584
+ duration: {
1585
+ mode: "fixed",
1586
+ value: targetRange.end - targetRange.start
1587
+ },
1588
+ placement: {
1589
+ kind: "absolute",
1590
+ targetRange
1591
+ },
1592
+ relationTrace: trace,
1593
+ relationIds: {
1594
+ trackClip: stableEffectId("relation", identityScope, `track-clip:${segment.segmentId}`),
1595
+ clipMarker: stableEffectId("relation", identityScope, `clip-marker:${segment.segmentId}`),
1596
+ markerContent: stableEffectId("relation", identityScope, `marker-content:${segment.segmentId}`)
1597
+ }
1598
+ });
1599
+ captionEntityIds.push(captionId);
1600
+ captionClipEntityIds.push(clipId);
1601
+ }
1602
+ return {
1603
+ audioScriptEntityId: scriptId,
1604
+ audioScriptMarkerEntityId: scriptMarkerId,
1605
+ captionAssetEntityId: imported.assetEntityId,
1606
+ captionEntityIds,
1607
+ captionClipEntityIds
1608
+ };
1609
+ });
1610
+ }
1611
+ static compileCaptionAssetsEffect(base, envelope) {
1612
+ assertCaptionAssetsEnvelope(envelope);
1613
+ const input = envelope.input;
1614
+ const effectId = requireTrimmed(input.effectId, "Caption effect id");
1615
+ const segments = validateAsrSegments(input.segments);
1616
+ if (effectId !== envelope.effectId || captionEffectSignature(input, segments) !== envelope.signature) throw new Error("Caption effect envelope signature does not match its canonical input");
1617
+ const current = cloneRows(base.snapshot().rows);
1618
+ const replay = resolveCaptionAssetsReplay(current, input, effectId, envelope.signature, segments, createEntityId(input.source.entityId), createEntityId(input.trackEntityId));
1619
+ if (replay !== void 0) return {
1620
+ result: replay,
1621
+ replayed: true,
1622
+ rows: current
1623
+ };
1624
+ const fingerprint = captionBaselineFingerprint(base);
1625
+ if (fingerprint !== envelope.baselineFingerprint) throw new Error("Caption effect baseline changed; independently prepared envelopes on divergent baselines are unsupported");
1626
+ if (canonicalJson(resolveCaptionEffectDecisions(current, input, stableEffectScope(captionAssetsCommand, effectId, fingerprint), segments)) !== canonicalJson(envelope.decisions)) throw new Error("Caption effect decisions no longer match the frozen causal baseline");
1627
+ const doc = base.doc.fork();
1628
+ doc.setPeerId(stableEffectPeerId(captionAssetsCommand, effectId, fingerprint));
1629
+ const staged = new LoroEntityDocument(doc);
1630
+ const editor = new EntityTimelineEditor(staged.snapshot().rows, () => {
1631
+ throw new Error("Caption effects must use effect-derived identities");
1632
+ });
1633
+ const result = editor.#applyCaptionAssets(envelope);
1634
+ const applied = applyEntityRows(staged, editor.rows());
1635
+ return {
1636
+ result,
1637
+ replayed: false,
1638
+ update: applied.update,
1639
+ rows: applied.state.rows
1640
+ };
1641
+ }
1642
+ #applyGeneratedVisuals(envelope) {
1643
+ return this.transact((draft) => {
1644
+ const { input } = envelope;
1645
+ const identityScope = stableEffectScope(generatedVisualsCommand, envelope.effectId, envelope.baselineFingerprint);
1646
+ const anchorInput = visualInsertionAnchor(input);
1647
+ const anchor = requireCanonicalClipOnRole(draft, anchorInput.clipEntityId, "video_clip");
1648
+ if (anchor.trackRelation.endpoint0EntityId !== envelope.decisions.trackEntityId || anchor.trackRelation.endpoint1EntityId !== anchor.clip.entityId || anchorInput.position !== envelope.decisions.anchorPosition) throw new Error("Frozen visual insertion anchor is no longer canonical");
1649
+ const ordered = resolveEntityTimelineLayout(draft).tracks.find((candidate) => candidate.entityId === envelope.decisions.trackEntityId)?.clips.map((clip) => clip.clipEntityId);
1650
+ const anchorIndex = ordered?.indexOf(anchor.clip.entityId) ?? -1;
1651
+ if (ordered === void 0 || anchorIndex < 0 || anchorIndex !== envelope.decisions.anchorOrder) throw new Error("Frozen visual insertion order no longer matches the causal baseline");
1652
+ const clipEntityIds = [];
1653
+ const mediaEntityIds = [];
1654
+ for (const [index, clip] of input.clips.entries()) {
1655
+ const imported = importMediaAsset(draft, clip.media, stableEffectIdFactory(identityScope, `visual:${index}:media`));
1656
+ replaceRows(draft, imported.rows);
1657
+ const media = requireSequenceContent(draft, imported.contentEntityId);
1658
+ if (media.entityKind !== "video" && media.entityKind !== "image") throw new Error("Generated visual content must be Video or Image");
1659
+ const durationMs = safeWholeMs(clip.durationMs, "Generated visual durationMs");
1660
+ if (durationMs === 0 || clip.media.kind === "video" && durationMs > clip.media.durationMs) throw new Error("Generated visual duration must fit its immutable media Sequence");
1661
+ const trace = generatedVisualTrace(envelope, index, clip.generationJobId);
1662
+ const clipId = this.insertPlacedClipIntoDraft(draft, {
1663
+ clipEntityId: stableEffectId("entity", identityScope, `visual:${index}:clip`),
1664
+ markerEntityId: stableEffectId("entity", identityScope, `visual:${index}:marker`),
1665
+ trackEntityId: envelope.decisions.trackEntityId,
1666
+ contentEntityId: media.entityId,
1667
+ sourceRange: {
1668
+ start: 0,
1669
+ end: durationMs
1670
+ },
1671
+ duration: {
1672
+ mode: "fixed",
1673
+ value: durationMs
1674
+ },
1675
+ placement: {
1676
+ kind: "sequential",
1677
+ order: envelope.decisions.insertionOrders[index]
1678
+ },
1679
+ ...clip.volume === void 0 ? {} : { clipPayload: { volume: clip.volume } },
1680
+ relationTrace: trace,
1681
+ relationIds: {
1682
+ trackClip: stableEffectId("relation", identityScope, `visual:${index}:track-clip`),
1683
+ clipMarker: stableEffectId("relation", identityScope, `visual:${index}:clip-marker`),
1684
+ markerContent: stableEffectId("relation", identityScope, `visual:${index}:marker-content`)
1685
+ }
1686
+ });
1687
+ for (const [sourceIndex, sourceId] of clip.sourceMediaEntityIds.entries()) {
1688
+ const source = requireSequenceContent(draft, sourceId);
1689
+ if (![
1690
+ "video",
1691
+ "image",
1692
+ "audio"
1693
+ ].includes(source.entityKind)) throw new Error("Generated visual lineage requires Video, Image, or Audio inputs");
1694
+ draft.relations.push(this.createRelation(draft, "generated", media.entityId, source.entityId, {}, generatedVisualTrace(envelope, index, clip.generationJobId, sourceIndex), stableEffectId("relation", identityScope, `visual:${index}:generated:${sourceIndex}`)));
1695
+ }
1696
+ clipEntityIds.push(clipId);
1697
+ mediaEntityIds.push(media.entityId);
1698
+ }
1699
+ return {
1700
+ clipEntityIds,
1701
+ mediaEntityIds
1702
+ };
1703
+ });
1704
+ }
1705
+ static compileGeneratedVisualEffect(base, envelope) {
1706
+ assertGeneratedVisualEnvelope(envelope);
1707
+ consumeEffectEnvelope(consumedGeneratedVisualEnvelopes, envelope, "Generated visual");
1708
+ const current = cloneRows(base.snapshot().rows);
1709
+ const replay = resolveGeneratedVisualReplay(current, envelope);
1710
+ if (replay !== void 0) return {
1711
+ result: replay,
1712
+ replayed: true,
1713
+ rows: current
1714
+ };
1715
+ const fingerprint = captionBaselineFingerprint(base);
1716
+ if (fingerprint !== envelope.baselineFingerprint) throw new Error("Generated visual effect baseline changed; prepare a new effect from the authority");
1717
+ if (canonicalJson(resolveGeneratedVisualDecisions(current, envelope.input)) !== canonicalJson(envelope.decisions)) throw new Error("Generated visual decisions no longer match the frozen causal baseline");
1718
+ const doc = base.doc.fork();
1719
+ doc.setPeerId(stableEffectPeerId(generatedVisualsCommand, envelope.effectId, fingerprint));
1720
+ const staged = new LoroEntityDocument(doc);
1721
+ const editor = new EntityTimelineEditor(staged.snapshot().rows, () => {
1722
+ throw new Error("Generated visual effects must use effect-derived identities");
1723
+ });
1724
+ const result = editor.#applyGeneratedVisuals(envelope);
1725
+ const applied = applyEntityRows(staged, editor.rows());
1726
+ return {
1727
+ result,
1728
+ replayed: false,
1729
+ update: applied.update,
1730
+ rows: applied.state.rows
1731
+ };
1732
+ }
1733
+ #applySpeechAssets(envelope) {
1734
+ return this.transact((draft) => {
1735
+ const { input } = envelope;
1736
+ const value = input.value;
1737
+ const identityScope = stableEffectScope(speechAssetsCommand, envelope.effectId, envelope.baselineFingerprint);
1738
+ const speechTrack = ensureEffectRoleTrack(draft, value.timelineEntityId, "speech", envelope.decisions.speechTrackEntityId, identityScope);
1739
+ const captionTrack = value.items.some((item) => item.captions.length > 0) ? ensureEffectRoleTrack(draft, value.timelineEntityId, "caption", envelope.decisions.captionTrackEntityId, identityScope) : void 0;
1740
+ const speechClipEntityIds = [];
1741
+ const speechAudioEntityIds = [];
1742
+ const audioScriptEntityIds = [];
1743
+ const phoneticScriptEntityIds = [];
1744
+ const captionClipEntityIds = [];
1745
+ for (const [index, item] of value.items.entries()) {
1746
+ const trace = speechEffectTrace(envelope, index);
1747
+ const scripts = materializeSpeechSource(draft, item, identityScope, index, trace);
1748
+ const imported = importMediaAsset(draft, item.media, stableEffectIdFactory(identityScope, `speech:${index}:media`));
1749
+ replaceRows(draft, imported.rows);
1750
+ const speech = requireEntityKind(draft, imported.contentEntityId, "audio");
1751
+ if (imported.voiceEntityId === void 0 || item.media.voice === void 0) throw new Error("Generated speech requires an explicit Voice identity");
1752
+ if (incidentRelations(draft, speech.entityId).filter((relation) => relation.relationKind === "phonetic-script-render").length > 0) throw new Error(`Speech Audio "${speech.entityId}" already has render lineage`);
1753
+ draft.relations.push(this.createRelation(draft, "phonetic-script-render", speech.entityId, scripts.phonetic.entityId, {}, {
1754
+ ...trace,
1755
+ role: "speech-render"
1756
+ }, stableEffectId("relation", identityScope, `speech:${index}:render`)));
1757
+ const startMs = envelope.decisions.targetStartsMs[index];
1758
+ let speechClipId;
1759
+ if (!("targetSpeechClipEntityId" in item)) speechClipId = this.insertPlacedClipIntoDraft(draft, {
1760
+ clipEntityId: stableEffectId("entity", identityScope, `speech:${index}:clip`),
1761
+ markerEntityId: stableEffectId("entity", identityScope, `speech:${index}:marker`),
1762
+ trackEntityId: speechTrack.entityId,
1763
+ contentEntityId: speech.entityId,
1764
+ sourceRange: {
1765
+ start: 0,
1766
+ end: item.media.durationMs
1767
+ },
1768
+ duration: {
1769
+ mode: "fixed",
1770
+ value: item.media.durationMs
1771
+ },
1772
+ placement: {
1773
+ kind: "absolute",
1774
+ targetRange: {
1775
+ start: startMs,
1776
+ end: startMs + item.media.durationMs
1777
+ }
1778
+ },
1779
+ clipPayload: { volume: requireVolume(item.volume ?? 0) },
1780
+ relationTrace: trace,
1781
+ relationIds: {
1782
+ trackClip: stableEffectId("relation", identityScope, `speech:${index}:track-clip`),
1783
+ clipMarker: stableEffectId("relation", identityScope, `speech:${index}:clip-marker`),
1784
+ markerContent: stableEffectId("relation", identityScope, `speech:${index}:marker-content`)
1785
+ }
1786
+ });
1787
+ else {
1788
+ const target = requireCanonicalClipOnRole(draft, item.targetSpeechClipEntityId, "speech");
1789
+ if (target.trackRelation.endpoint0EntityId !== speechTrack.entityId) throw new Error("Replacement Speech occurrence is not on the frozen Speech Track");
1790
+ speechClipId = target.clip.entityId;
1791
+ replaceEntity(draft, target.clip.entityId, {
1792
+ ...target.clip,
1793
+ payload: {
1794
+ ...target.clip.payload,
1795
+ volume: requireVolume(item.volume ?? 0)
1796
+ }
1797
+ });
1798
+ replaceRelationWithTrace(draft, target.markerContentRelation, target.marker.entityId, speech.entityId, {
1799
+ ...trace,
1800
+ role: "speech-content"
1801
+ }, stableEffectId("relation", identityScope, `speech:${index}:marker-content`));
1802
+ const markerPayload = { ...cloneJsonObject(target.marker.payload, "Speech Marker payload") };
1803
+ markerPayload.sourceRange = {
1804
+ start: 0,
1805
+ end: item.media.durationMs
1806
+ };
1807
+ markerPayload.duration = {
1808
+ mode: "fixed",
1809
+ value: item.media.durationMs
1810
+ };
1811
+ resizeAbsoluteTarget(markerPayload, item.media.durationMs);
1812
+ replaceEntity(draft, target.marker.entityId, {
1813
+ ...target.marker,
1814
+ payload: markerPayload
1815
+ });
1816
+ }
1817
+ const currentCaptionIds = "targetCaptionClipEntityIds" in item ? item.targetCaptionClipEntityIds : [];
1818
+ const itemCaptionIds = [];
1819
+ for (const [captionIndex, caption] of item.captions.entries()) {
1820
+ const durationMs = safeWholeMs(caption.endMs, "Speech Caption endMs") - safeWholeMs(caption.startMs, "Speech Caption startMs");
1821
+ if (durationMs <= 0) throw new Error("Speech Caption must have positive duration");
1822
+ const captionEntity = {
1823
+ entityId: requireAvailableEntityId(draft, stableEffectId("entity", identityScope, `speech:${index}:caption:${captionIndex}`)),
1824
+ entityKind: "caption",
1825
+ payload: {
1826
+ baseEntityIds: [scripts.audioScript.entityId],
1827
+ selection: captionSelection(caption.selection),
1828
+ durationMs
1829
+ }
1830
+ };
1831
+ draft.entities.push(captionEntity);
1832
+ assembleCaptionContent(draft, captionEntity.entityId);
1833
+ const captionTrace = {
1834
+ ...trace,
1835
+ role: "caption-content",
1836
+ captionIndex
1837
+ };
1838
+ let captionClipId;
1839
+ const existingCaptionId = currentCaptionIds[captionIndex];
1840
+ if (!("targetSpeechClipEntityId" in item) || existingCaptionId === void 0) captionClipId = this.insertPlacedClipIntoDraft(draft, {
1841
+ clipEntityId: stableEffectId("entity", identityScope, `speech:${index}:caption:${captionIndex}:clip`),
1842
+ markerEntityId: stableEffectId("entity", identityScope, `speech:${index}:caption:${captionIndex}:marker`),
1843
+ trackEntityId: captionTrack.entityId,
1844
+ contentEntityId: captionEntity.entityId,
1845
+ sourceRange: {
1846
+ start: 0,
1847
+ end: durationMs
1848
+ },
1849
+ duration: {
1850
+ mode: "fixed",
1851
+ value: durationMs
1852
+ },
1853
+ placement: {
1854
+ kind: "absolute",
1855
+ targetRange: {
1856
+ start: startMs + caption.startMs,
1857
+ end: startMs + caption.endMs
1858
+ }
1859
+ },
1860
+ relationTrace: captionTrace,
1861
+ relationIds: {
1862
+ trackClip: stableEffectId("relation", identityScope, `speech:${index}:caption:${captionIndex}:track-clip`),
1863
+ clipMarker: stableEffectId("relation", identityScope, `speech:${index}:caption:${captionIndex}:clip-marker`),
1864
+ markerContent: stableEffectId("relation", identityScope, `speech:${index}:caption:${captionIndex}:marker-content`)
1865
+ }
1866
+ });
1867
+ else {
1868
+ const targetCaption = requireCanonicalClipOnRole(draft, existingCaptionId, "caption");
1869
+ if (targetCaption.trackRelation.endpoint0EntityId !== captionTrack.entityId) throw new Error("Replacement Caption occurrence is not on the frozen Caption Track");
1870
+ captionClipId = targetCaption.clip.entityId;
1871
+ replaceRelationWithTrace(draft, targetCaption.markerContentRelation, targetCaption.marker.entityId, captionEntity.entityId, captionTrace, stableEffectId("relation", identityScope, `speech:${index}:caption:${captionIndex}:marker-content`));
1872
+ replaceEntity(draft, targetCaption.marker.entityId, {
1873
+ ...targetCaption.marker,
1874
+ payload: {
1875
+ ...targetCaption.marker.payload,
1876
+ sourceRange: {
1877
+ start: 0,
1878
+ end: durationMs
1879
+ },
1880
+ duration: {
1881
+ mode: "fixed",
1882
+ value: durationMs
1883
+ },
1884
+ targetRange: {
1885
+ start: startMs + caption.startMs,
1886
+ end: startMs + caption.endMs
1887
+ }
1888
+ }
1889
+ });
1890
+ }
1891
+ itemCaptionIds.push(captionClipId);
1892
+ }
1893
+ for (const retiredCaptionId of currentCaptionIds.slice(item.captions.length)) {
1894
+ const retired = requireCanonicalClipOnRole(draft, retiredCaptionId, "caption");
1895
+ if (retired.trackRelation.endpoint0EntityId !== envelope.decisions.captionTrackEntityId) throw new Error("Retired Caption occurrence is not on the frozen Caption Track");
1896
+ retireClipOccurrence(draft, retired);
1897
+ }
1898
+ speechClipEntityIds.push(speechClipId);
1899
+ speechAudioEntityIds.push(speech.entityId);
1900
+ audioScriptEntityIds.push(scripts.audioScript.entityId);
1901
+ phoneticScriptEntityIds.push(scripts.phonetic.entityId);
1902
+ captionClipEntityIds.push(itemCaptionIds);
1903
+ }
1904
+ return {
1905
+ speechClipEntityIds,
1906
+ speechAudioEntityIds,
1907
+ audioScriptEntityIds,
1908
+ phoneticScriptEntityIds,
1909
+ captionClipEntityIds
1910
+ };
1911
+ });
1912
+ }
1913
+ static compileSpeechAssetsEffect(base, envelope) {
1914
+ assertSpeechAssetsEnvelope(envelope);
1915
+ consumeEffectEnvelope(consumedSpeechEnvelopes, envelope, "Speech");
1916
+ const current = cloneRows(base.snapshot().rows);
1917
+ const replay = resolveSpeechAssetsReplay(current, envelope);
1918
+ if (replay !== void 0) return {
1919
+ result: replay,
1920
+ replayed: true,
1921
+ rows: current
1922
+ };
1923
+ const fingerprint = captionBaselineFingerprint(base);
1924
+ if (fingerprint !== envelope.baselineFingerprint) throw new Error("Speech effect baseline changed; prepare a new effect from the authority");
1925
+ if (canonicalJson(resolveSpeechEffectDecisions(current, envelope.input, envelope.effectId, fingerprint)) !== canonicalJson(envelope.decisions)) throw new Error("Speech effect decisions no longer match the frozen causal baseline");
1926
+ const doc = base.doc.fork();
1927
+ doc.setPeerId(stableEffectPeerId(speechAssetsCommand, envelope.effectId, fingerprint));
1928
+ const staged = new LoroEntityDocument(doc);
1929
+ const editor = new EntityTimelineEditor(staged.snapshot().rows, stableEffectIdFactory(stableEffectScope(speechAssetsCommand, envelope.effectId, fingerprint), "speech-editor"));
1930
+ editor.#applySpeechAssets(envelope);
1931
+ const applied = applyEntityRows(staged, editor.rows());
1932
+ const result = resolveSpeechAssetsReplay(cloneRows(applied.state.rows), envelope);
1933
+ if (result === void 0) throw new Error("Committed Speech effect is missing its complete receipt");
1934
+ return {
1935
+ result,
1936
+ replayed: false,
1937
+ update: applied.update,
1938
+ rows: applied.state.rows
1939
+ };
1940
+ }
1453
1941
  insertPlacedClipIntoDraft(draft, input) {
1454
1942
  const track = requireEntityKind(draft, input.trackEntityId, "track");
1455
1943
  requireTrackTimeline(draft, track.entityId);
1456
1944
  const content = requireSequenceContent(draft, input.contentEntityId);
1457
1945
  const clipId = input.clipEntityId === void 0 ? this.mintEntityId(draft) : requireAvailableEntityId(draft, input.clipEntityId);
1458
- const markerId = this.mintEntityId(draft);
1946
+ const markerId = input.markerEntityId === void 0 ? this.mintEntityId(draft) : requireAvailableEntityId(draft, input.markerEntityId);
1459
1947
  const clipPayload = { ...cloneJsonObject(input.clipPayload ?? {}, "Clip payload") };
1460
1948
  delete clipPayload.order;
1461
1949
  const markerPlacement = applyPlacementPayload(clipPayload, input.placement);
@@ -1474,7 +1962,7 @@ var EntityTimelineEditor = class {
1474
1962
  })
1475
1963
  };
1476
1964
  draft.entities.push(clip, marker);
1477
- draft.relations.push(this.createRelation(draft, "track-clip", track.entityId, clipId), this.createRelation(draft, "clip-marker", clipId, markerId), this.createRelation(draft, "marker-content", markerId, content.entityId));
1965
+ draft.relations.push(this.createRelation(draft, "track-clip", track.entityId, clipId, {}, input.relationTrace, input.relationIds?.trackClip), this.createRelation(draft, "clip-marker", clipId, markerId, {}, input.relationTrace, input.relationIds?.clipMarker), this.createRelation(draft, "marker-content", markerId, content.entityId, {}, input.relationTrace, input.relationIds?.markerContent));
1478
1966
  if (input.placement.kind === "anchored") {
1479
1967
  const host = requireEntityKind(draft, input.placement.hostClipEntityId, "clip");
1480
1968
  if (host.entityId === clipId) throw new Error("A Clip cannot anchor to itself");
@@ -1780,14 +2268,14 @@ var EntityTimelineEditor = class {
1780
2268
  if (draft.entities.some((entity) => entity.entityId === entityId)) throw new Error(`Entity id "${entityId}" already exists`);
1781
2269
  return entityId;
1782
2270
  }
1783
- createRelation(draft, relationKind, endpoint0EntityId, endpoint1EntityId, metadata = {}) {
2271
+ createRelation(draft, relationKind, endpoint0EntityId, endpoint1EntityId, metadata = {}, trace = {}, requestedRelationId) {
1784
2272
  return {
1785
- relationId: this.mintRelationId(draft),
2273
+ relationId: requestedRelationId === void 0 ? this.mintRelationId(draft) : requireAvailableRelationId(draft, requestedRelationId),
1786
2274
  relationKind,
1787
2275
  endpoint0EntityId,
1788
2276
  endpoint1EntityId,
1789
2277
  metadata,
1790
- trace: {}
2278
+ trace
1791
2279
  };
1792
2280
  }
1793
2281
  relinkRelation(draft, relation, endpoints) {
@@ -1806,6 +2294,859 @@ var EntityTimelineEditor = class {
1806
2294
  return relationId;
1807
2295
  }
1808
2296
  };
2297
+ /** Freeze every state-dependent choice once in the sole FE tool-effect handler. */
2298
+ function prepareCaptionAssetsEffect(base, rawInput) {
2299
+ const effectId = requireTrimmed(rawInput.effectId, "Caption effect id");
2300
+ const segments = validateAsrSegments(rawInput.segments);
2301
+ const input = structuredClone({
2302
+ ...rawInput,
2303
+ effectId,
2304
+ segments
2305
+ });
2306
+ const rows = cloneRows(base.snapshot().rows);
2307
+ const signature = captionEffectSignature(input, segments);
2308
+ const baselineFingerprint = captionBaselineFingerprint(base);
2309
+ return deepFreeze({
2310
+ version: 1,
2311
+ baselineFingerprint,
2312
+ effectId,
2313
+ signature,
2314
+ input,
2315
+ decisions: resolveCaptionEffectDecisions(rows, input, stableEffectScope(captionAssetsCommand, effectId, baselineFingerprint), segments)
2316
+ });
2317
+ }
2318
+ /**
2319
+ * Compile only a frozen envelope on its exact causal baseline. Collaborators
2320
+ * receive the resulting Loro update, never the raw effect.
2321
+ */
2322
+ function compileCaptionAssetsEffect(base, envelope) {
2323
+ return EntityTimelineEditor.compileCaptionAssetsEffect(base, envelope);
2324
+ }
2325
+ const captionAssetsCommand = "apply-caption-assets";
2326
+ const generatedVisualsCommand = "add-generated-visuals";
2327
+ const speechAssetsCommand = "apply-speech-assets";
2328
+ const consumedGeneratedVisualEnvelopes = /* @__PURE__ */ new Set();
2329
+ const consumedSpeechEnvelopes = /* @__PURE__ */ new Set();
2330
+ function consumeEffectEnvelope(consumed, envelope, label) {
2331
+ const key = `${envelope.baselineFingerprint}\u0000${envelope.effectId}\u0000${envelope.signature}`;
2332
+ if (consumed.has(key)) throw new Error(`${label} effect envelope is one-shot; retain and retry the compiled Loro update bytes`);
2333
+ consumed.add(key);
2334
+ }
2335
+ /** Freeze the explicit insertion anchor and lineage on one causal baseline. */
2336
+ function prepareGeneratedVisualEffect(base, rawInput) {
2337
+ const effectId = requireTrimmed(rawInput.effectId, "Generated visual effect id");
2338
+ if (rawInput.clips.length === 0) throw new Error("Generated visual effect requires at least one clip");
2339
+ const clips = rawInput.clips.map((clip, index) => {
2340
+ const generationJobId = requireTrimmed(clip.generationJobId, `Generated visual ${index} generation job id`);
2341
+ const durationMs = safeWholeMs(clip.durationMs, `Generated visual ${index} durationMs`);
2342
+ if (durationMs === 0 || clip.media.kind === "video" && durationMs > clip.media.durationMs) throw new Error(`Generated visual ${index} duration must fit its immutable media Sequence`);
2343
+ if (clip.sourceMediaEntityIds.length === 0) throw new Error(`Generated visual ${index} requires explicit source lineage`);
2344
+ const sourceMediaEntityIds = clip.sourceMediaEntityIds.map((sourceId) => requireTrimmed(sourceId, `Generated visual ${index} source media id`));
2345
+ if (new Set(sourceMediaEntityIds).size !== sourceMediaEntityIds.length) throw new Error(`Generated visual ${index} source lineage must be unique`);
2346
+ return {
2347
+ ...structuredClone(clip),
2348
+ durationMs,
2349
+ generationJobId,
2350
+ sourceMediaEntityIds
2351
+ };
2352
+ });
2353
+ const input = structuredClone({
2354
+ ...rawInput,
2355
+ effectId,
2356
+ clips
2357
+ });
2358
+ const rows = cloneRows(base.snapshot().rows);
2359
+ for (const [index, clip] of input.clips.entries()) for (const sourceId of clip.sourceMediaEntityIds) {
2360
+ const source = requireSequenceContent(rows, sourceId);
2361
+ if (![
2362
+ "video",
2363
+ "image",
2364
+ "audio"
2365
+ ].includes(source.entityKind)) throw new Error(`Generated visual ${index} source must be Video, Image, or Audio`);
2366
+ }
2367
+ return deepFreeze({
2368
+ version: 1,
2369
+ baselineFingerprint: captionBaselineFingerprint(base),
2370
+ effectId,
2371
+ signature: generatedVisualSignature(input),
2372
+ input,
2373
+ decisions: resolveGeneratedVisualDecisions(rows, input)
2374
+ });
2375
+ }
2376
+ function prepareContinueVideoEffect(base, input) {
2377
+ const rows = cloneRows(base.snapshot().rows);
2378
+ requireEntityKind(rows, input.sourceMediaEntityId, "video");
2379
+ requireEntityKind(rows, input.tailFrameEntityId, "image");
2380
+ return prepareGeneratedVisualEffect(base, {
2381
+ effectId: input.effectId,
2382
+ timelineEntityId: input.timelineEntityId,
2383
+ afterClipEntityId: input.afterClipEntityId,
2384
+ clips: [{
2385
+ media: input.media,
2386
+ durationMs: input.media.durationMs,
2387
+ generationJobId: input.effectId,
2388
+ sourceMediaEntityIds: [input.sourceMediaEntityId, input.tailFrameEntityId]
2389
+ }]
2390
+ });
2391
+ }
2392
+ /** Compile once at the FE authority; retain the returned update bytes for retry and collaborators. */
2393
+ function compileGeneratedVisualEffect(base, envelope) {
2394
+ return EntityTimelineEditor.compileGeneratedVisualEffect(base, envelope);
2395
+ }
2396
+ function prepareSpeechAssetsEffect(base, rawInput) {
2397
+ for (const item of rawInput.value.items) if (item.source.kind === "audio-script") if (item.source.audioScriptEntityId === void 0) audioScriptSegmentsFromAsr(item.source.segments, false);
2398
+ else validateResolvedAsrSegments(item.source.segments);
2399
+ else validateScriptSegments(item.source.segments);
2400
+ const value = structuredClone(rawInput.value);
2401
+ const effectId = requireTrimmed(value.effectId, "Speech effect id");
2402
+ if (value.items.length === 0) throw new Error("Speech effect requires at least one item");
2403
+ if (new Set(value.items.map((item) => item.media.assetId)).size !== value.items.length) throw new Error("Speech effect media assets must be unique");
2404
+ const input = structuredClone({
2405
+ ...rawInput,
2406
+ value: {
2407
+ ...value,
2408
+ effectId
2409
+ }
2410
+ });
2411
+ const baselineFingerprint = captionBaselineFingerprint(base);
2412
+ return deepFreeze({
2413
+ version: 1,
2414
+ baselineFingerprint,
2415
+ effectId,
2416
+ signature: speechEffectSignature(input),
2417
+ input,
2418
+ decisions: resolveSpeechEffectDecisions(cloneRows(base.snapshot().rows), input, effectId, baselineFingerprint)
2419
+ });
2420
+ }
2421
+ /** Compile once at the FE authority; retain the returned update bytes for retry and collaborators. */
2422
+ function compileSpeechAssetsEffect(base, envelope) {
2423
+ return EntityTimelineEditor.compileSpeechAssetsEffect(base, envelope);
2424
+ }
2425
+ function validateAsrSegments(segments) {
2426
+ if (segments.length === 0) throw new Error("Caption assets require at least one ASR segment");
2427
+ const ids = /* @__PURE__ */ new Set();
2428
+ return segments.map((segment) => {
2429
+ const segmentId = requireTrimmed(segment.segmentId, "ASR segment id");
2430
+ if (ids.has(segmentId)) throw new Error(`Duplicate ASR segment id "${segmentId}"`);
2431
+ ids.add(segmentId);
2432
+ if (typeof segment.text !== "string" || segment.text.trim() === "") throw new Error(`ASR segment "${segmentId}" requires visible text`);
2433
+ const startMs = safeWholeMs(segment.startMs, `ASR segment "${segmentId}" startMs`);
2434
+ const endMs = safeWholeMs(segment.endMs, `ASR segment "${segmentId}" endMs`);
2435
+ if (endMs <= startMs) throw new Error(`ASR segment "${segmentId}" must have positive duration`);
2436
+ const language = segment.language === void 0 ? void 0 : requireTrimmed(segment.language, `ASR segment "${segmentId}" language`);
2437
+ return {
2438
+ segmentId,
2439
+ text: segment.text,
2440
+ startMs,
2441
+ endMs,
2442
+ ...language === void 0 ? {} : { language }
2443
+ };
2444
+ });
2445
+ }
2446
+ function requireCanonicalCaptionTrack(rows, timelineEntityId, trackEntityId) {
2447
+ const timeline = requireEntityKind(rows, timelineEntityId, "timeline");
2448
+ const track = requireEntityKind(rows, trackEntityId, "track");
2449
+ if (track.payload.role !== "caption") throw new Error(`Track "${track.entityId}" must have role "caption"`);
2450
+ const bindings = incidentRelations(rows, track.entityId).filter((relation) => relation.relationKind === "timeline-track");
2451
+ if (bindings.length !== 1) throw new Error(`Caption Track "${track.entityId}" must have one unambiguous Timeline`);
2452
+ const binding = bindings[0];
2453
+ if (binding.endpoint0EntityId !== timeline.entityId || binding.endpoint1EntityId !== track.entityId) throw new Error("timeline-track must use ordered endpoints [Timeline, Track]");
2454
+ return track;
2455
+ }
2456
+ function resolveSourceOccurrence(rows, input, sourceEntityId) {
2457
+ const clip = requireEntityKind(rows, input.sourceOccurrence.clipEntityId, "clip");
2458
+ const marker = requireEntityKind(rows, input.sourceOccurrence.markerEntityId, "sequence-marker");
2459
+ const clipMarkers = incidentRelations(rows, clip.entityId).filter((relation) => relation.relationKind === "clip-marker");
2460
+ if (clipMarkers.length !== 1 || clipMarkers[0].endpoint0EntityId !== clip.entityId || clipMarkers[0].endpoint1EntityId !== marker.entityId) throw new Error("Source occurrence requires one ordered clip-marker [Clip, SequenceMarker]");
2461
+ const contents = incidentRelations(rows, marker.entityId).filter((relation) => relation.relationKind === "marker-content");
2462
+ if (contents.length !== 1 || contents[0].endpoint0EntityId !== marker.entityId || contents[0].endpoint1EntityId !== sourceEntityId) throw new Error("Source occurrence requires one ordered marker-content [SequenceMarker, source Entity]");
2463
+ const trackBindings = incidentRelations(rows, clip.entityId).filter((relation) => relation.relationKind === "track-clip");
2464
+ if (trackBindings.length !== 1 || trackBindings[0].endpoint1EntityId !== clip.entityId) throw new Error("Source occurrence requires one ordered track-clip [Track, Clip]");
2465
+ const sourceTrack = requireEntityKind(rows, trackBindings[0].endpoint0EntityId, "track");
2466
+ const timelineBindings = incidentRelations(rows, sourceTrack.entityId).filter((relation) => relation.relationKind === "timeline-track");
2467
+ if (timelineBindings.length !== 1 || timelineBindings[0].endpoint0EntityId !== input.timelineEntityId || timelineBindings[0].endpoint1EntityId !== sourceTrack.entityId) throw new Error("Source occurrence must be placed on the selected Timeline through [Timeline, Track]");
2468
+ const placement = resolveEntityTimelineLayout(rows).clips.get(clip.entityId);
2469
+ if (placement === void 0 || placement.markerEntityId !== marker.entityId || placement.contentEntityId !== sourceEntityId) throw new Error("Source occurrence is not an unambiguous placed use of the selected source Entity");
2470
+ const sourceRange = requirePositiveRange(marker.payload.sourceRange, "Source occurrence sourceRange");
2471
+ return {
2472
+ sourceRange,
2473
+ timelineStart: placement.start,
2474
+ rate: (sourceRange.end - sourceRange.start) / placement.duration
2475
+ };
2476
+ }
2477
+ function occurrenceTargetRange(occurrence, segment) {
2478
+ if (segment.startMs < occurrence.sourceRange.start || segment.endMs > occurrence.sourceRange.end) throw new Error(`ASR segment "${segment.segmentId}" is outside the selected source occurrence`);
2479
+ const start = Math.round(occurrence.timelineStart + (segment.startMs - occurrence.sourceRange.start) / occurrence.rate);
2480
+ const end = Math.round(occurrence.timelineStart + (segment.endMs - occurrence.sourceRange.start) / occurrence.rate);
2481
+ if (end <= start) throw new Error(`ASR segment "${segment.segmentId}" collapses under the occurrence time mapping`);
2482
+ return {
2483
+ start,
2484
+ end
2485
+ };
2486
+ }
2487
+ function resolveCaptionEffectDecisions(rows, input, identityScope, segments) {
2488
+ const source = requireEntityKind(rows, input.source.entityId, input.source.entityKind);
2489
+ requireCanonicalCaptionTrack(rows, input.timelineEntityId, input.trackEntityId);
2490
+ const occurrence = resolveSourceOccurrence(rows, input, source.entityId);
2491
+ return {
2492
+ sourceOccurrence: {
2493
+ sourceStartMs: occurrence.sourceRange.start,
2494
+ sourceEndMs: occurrence.sourceRange.end,
2495
+ timelineStartMs: occurrence.timelineStart,
2496
+ rate: occurrence.rate
2497
+ },
2498
+ targetRanges: segments.map((segment) => ({
2499
+ segmentId: segment.segmentId,
2500
+ ...occurrenceTargetRange(occurrence, segment)
2501
+ })),
2502
+ captionAsset: resolveCaptionAssetDecision(rows, input, identityScope)
2503
+ };
2504
+ }
2505
+ function resolveCaptionAssetDecision(rows, input, identityScope) {
2506
+ const assetId = requireTrimmed(input.captionAsset.assetId, "Caption asset id");
2507
+ const storageKey = input.captionAsset.storageKey === void 0 ? void 0 : requireTrimmed(input.captionAsset.storageKey, "Caption asset storage key");
2508
+ const matches = rows.entities.filter((row) => row.entityKind === "asset" && row.payload.system === "memota" && row.payload.key === assetId);
2509
+ if (matches.length > 1) throw new Error(`Caption Asset "${assetId}" is ambiguous`);
2510
+ const existing = matches[0];
2511
+ if (existing === void 0) return {
2512
+ mode: "create",
2513
+ resultAssetEntityId: stableEffectId("entity", identityScope, "caption-asset:entity:0"),
2514
+ reboundRelationIds: []
2515
+ };
2516
+ if (storageKey === void 0 || existing.payload.storageKey === storageKey) return {
2517
+ mode: "reuse",
2518
+ priorAssetEntityId: existing.entityId,
2519
+ resultAssetEntityId: existing.entityId,
2520
+ reboundRelationIds: []
2521
+ };
2522
+ if (existing.payload.storageKey !== void 0) throw new Error(`Caption Asset "${assetId}" conflicts with its existing storage key`);
2523
+ const bindings = rows.relations.filter((relation) => relation.relationKind === "from-asset" && (relation.endpoint0EntityId === existing.entityId || relation.endpoint1EntityId === existing.entityId)).map((relation) => String(relation.relationId)).sort();
2524
+ return {
2525
+ mode: "replace",
2526
+ priorAssetEntityId: existing.entityId,
2527
+ resultAssetEntityId: stableEffectId("entity", identityScope, "caption-asset:entity:0"),
2528
+ reboundRelationIds: bindings
2529
+ };
2530
+ }
2531
+ function captionBaselineFingerprint(base) {
2532
+ const causal = bytesToHex(base.doc.oplogVersion().encode());
2533
+ return bytesToHex(sha256(new TextEncoder().encode(canonicalJson({
2534
+ causal,
2535
+ state: base.snapshot()
2536
+ }))));
2537
+ }
2538
+ function resolveSpeechEffectDecisions(rows, input, effectId, baselineFingerprint) {
2539
+ const { value } = input;
2540
+ requireEntityKind(rows, value.timelineEntityId, "timeline");
2541
+ for (const item of value.items) if (item.source.kind === "phonetic-script") requirePersistedPhoneticSourceScript(rows, item.source);
2542
+ else if (item.source.audioScriptEntityId !== void 0) requireAssetlessAsrSourceScript(rows, item.source);
2543
+ const scope = stableEffectScope(speechAssetsCommand, effectId, baselineFingerprint);
2544
+ const speechTrackEntityId = resolveEffectTrackId(rows, value.timelineEntityId, "speech", scope);
2545
+ const captionTrackEntityId = value.items.some((item) => item.captions.length > 0 || "targetCaptionClipEntityIds" in item && item.targetCaptionClipEntityIds.length > 0) ? resolveEffectTrackId(rows, value.timelineEntityId, "caption", scope) : void 0;
2546
+ if (input.mode === "add") return {
2547
+ speechTrackEntityId,
2548
+ ...captionTrackEntityId === void 0 ? {} : { captionTrackEntityId },
2549
+ targetStartsMs: input.value.items.map((item) => safeWholeMs(item.placementStartMs, "Speech placement startMs"))
2550
+ };
2551
+ const targets = input.value.items.map((item) => item.targetSpeechClipEntityId);
2552
+ if (new Set(targets).size !== targets.length) throw new Error("Replacement Speech targets must be unique");
2553
+ const captionTargets = input.value.items.flatMap((item) => item.targetCaptionClipEntityIds);
2554
+ if (new Set(captionTargets).size !== captionTargets.length) throw new Error("Replacement Caption targets must be unique across the effect");
2555
+ const layout = resolveEntityTimelineLayout(rows);
2556
+ const starts = input.value.items.map((item) => {
2557
+ const target = requireCanonicalClipOnRole(rows, item.targetSpeechClipEntityId, "speech");
2558
+ if (target.trackRelation.endpoint0EntityId !== speechTrackEntityId || target.trackRelation.endpoint1EntityId !== target.clip.entityId) throw new Error("Replacement Speech target must use ordered Track/Clip endpoints");
2559
+ for (const captionId of item.targetCaptionClipEntityIds) {
2560
+ const caption = requireCanonicalClipOnRole(rows, captionId, "caption");
2561
+ if (captionTrackEntityId === void 0 || caption.trackRelation.endpoint0EntityId !== captionTrackEntityId || caption.trackRelation.endpoint1EntityId !== caption.clip.entityId) throw new Error("Replacement Caption target must use ordered Track/Clip endpoints");
2562
+ }
2563
+ const placed = layout.clips.get(target.clip.entityId);
2564
+ if (placed === void 0) throw new Error(`Replacement Speech Clip "${target.clip.entityId}" is not placed`);
2565
+ return placed.start;
2566
+ });
2567
+ return {
2568
+ speechTrackEntityId,
2569
+ ...captionTrackEntityId === void 0 ? {} : { captionTrackEntityId },
2570
+ targetStartsMs: starts
2571
+ };
2572
+ }
2573
+ function resolveEffectTrackId(rows, timelineEntityId, role, identityScope) {
2574
+ if (rows.relations.filter((relation) => relation.relationKind === "timeline-track" && relation.endpoint1EntityId === timelineEntityId).length > 0) throw new Error("timeline-track must use ordered endpoints [Timeline, Track]");
2575
+ const candidates = rows.relations.filter((relation) => relation.relationKind === "timeline-track" && relation.endpoint0EntityId === timelineEntityId).map((relation) => requireEntityKind(rows, relation.endpoint1EntityId, "track")).filter((track) => track.payload.role === role);
2576
+ if (candidates.length > 1) throw new Error(`${role} Track is ambiguous`);
2577
+ return candidates[0]?.entityId ?? createEntityId(stableEffectId("entity", identityScope, `track:${role}`));
2578
+ }
2579
+ function ensureEffectRoleTrack(rows, timelineEntityId, role, expectedTrackId, identityScope) {
2580
+ const resolved = resolveEffectTrackId(rows, timelineEntityId, role, identityScope);
2581
+ if (resolved !== expectedTrackId) throw new Error(`Frozen ${role} Track decision changed`);
2582
+ if (rows.entities.find((entity) => entity.entityId === resolved) !== void 0) return requireEntityKind(rows, resolved, "track");
2583
+ const track = {
2584
+ entityId: createEntityId(expectedTrackId),
2585
+ entityKind: "track",
2586
+ payload: {
2587
+ role,
2588
+ order: roleOrder[role]
2589
+ }
2590
+ };
2591
+ rows.entities.push(track);
2592
+ rows.relations.push({
2593
+ relationId: createRelationId(stableEffectId("relation", identityScope, `timeline-track:${role}`)),
2594
+ relationKind: "timeline-track",
2595
+ endpoint0EntityId: createEntityId(timelineEntityId),
2596
+ endpoint1EntityId: track.entityId,
2597
+ metadata: {},
2598
+ trace: {}
2599
+ });
2600
+ return track;
2601
+ }
2602
+ function materializeSpeechSource(rows, item, identityScope, itemIndex, trace) {
2603
+ const source = item.source;
2604
+ const segments = source.kind === "audio-script" ? audioScriptSegmentsFromAsr(source.segments, source.audioScriptEntityId !== void 0) : validateScriptSegments(source.segments);
2605
+ const requestedScriptId = source.audioScriptEntityId === void 0 ? stableEffectId("entity", identityScope, `speech:${itemIndex}:audio-script`) : requireTrimmed(source.audioScriptEntityId, "AudioScript entity id");
2606
+ const existingScript = rows.entities.find((entity) => entity.entityId === requestedScriptId);
2607
+ let audioScript;
2608
+ if (existingScript === void 0) {
2609
+ if (source.kind === "phonetic-script") throw new Error(`Phonetic Speech source AudioScript "${requestedScriptId}" must already exist with an Asset`);
2610
+ audioScript = {
2611
+ entityId: requireAvailableEntityId(rows, requestedScriptId),
2612
+ entityKind: "audio-script",
2613
+ payload: { segments }
2614
+ };
2615
+ rows.entities.push(audioScript);
2616
+ } else {
2617
+ audioScript = requireEntityKind(rows, requestedScriptId, "audio-script");
2618
+ if (canonicalJson(audioScript.payload.segments) !== canonicalJson(segments)) throw new Error(`AudioScript "${requestedScriptId}" conflicts with the immutable Speech source`);
2619
+ if (source.kind === "phonetic-script") requireCanonicalAudioScriptAsset(rows, audioScript.entityId);
2620
+ else requireNoAudioScriptAsset(rows, audioScript.entityId, "ASR-composed");
2621
+ }
2622
+ if (source.kind === "audio-script") {
2623
+ const timed = validateResolvedAsrSegments(source.segments);
2624
+ if (source.sourceMediaEntityIds.length === 0) throw new Error("Audio Speech source requires media lineage");
2625
+ for (const [sourceIndex, sourceId] of source.sourceMediaEntityIds.entries()) {
2626
+ const media = requireSequenceContent(rows, sourceId);
2627
+ if (media.entityKind !== "audio" && media.entityKind !== "video") throw new Error("audio-script-source requires Audio or Video input");
2628
+ const existing = rows.relations.filter((relation) => relation.relationKind === "audio-script-source" && (relation.endpoint0EntityId === audioScript.entityId || relation.endpoint1EntityId === audioScript.entityId));
2629
+ if (existing.some((relation) => relation.endpoint0EntityId !== audioScript.entityId)) throw new Error("audio-script-source must use ordered endpoints [AudioScript, source media]");
2630
+ if (!existing.some((relation) => relation.endpoint1EntityId === media.entityId)) rows.relations.push({
2631
+ relationId: createRelationId(stableEffectId("relation", identityScope, `speech:${itemIndex}:audio-source:${sourceIndex}`)),
2632
+ relationKind: "audio-script-source",
2633
+ endpoint0EntityId: audioScript.entityId,
2634
+ endpoint1EntityId: media.entityId,
2635
+ metadata: {},
2636
+ trace: {
2637
+ ...trace,
2638
+ role: "audio-script-source",
2639
+ sourceIndex
2640
+ }
2641
+ });
2642
+ }
2643
+ const markerLinks = incidentRelations(rows, audioScript.entityId).filter((relation) => relation.relationKind === "audio-script-marker");
2644
+ if (markerLinks.some((relation) => relation.endpoint0EntityId !== audioScript.entityId)) throw new Error("audio-script-marker must use ordered endpoints [AudioScript, annotation SequenceMarker]");
2645
+ if (markerLinks.length > 1) throw new Error(`AudioScript "${audioScript.entityId}" has ambiguous timing annotations`);
2646
+ const segmentRanges = timed.map((segment) => ({
2647
+ segmentId: segment.segmentId,
2648
+ startMs: segment.startMs,
2649
+ endMs: segment.endMs
2650
+ }));
2651
+ if (markerLinks[0] !== void 0) {
2652
+ if (canonicalJson(requireEntityKind(rows, markerLinks[0].endpoint1EntityId, "sequence-marker").payload.segmentRanges) !== canonicalJson(segmentRanges)) throw new Error(`AudioScript "${audioScript.entityId}" timing conflicts with the immutable Speech source`);
2653
+ } else {
2654
+ const markerId = stableEffectId("entity", identityScope, `speech:${itemIndex}:audio-script-marker`);
2655
+ rows.entities.push({
2656
+ entityId: createEntityId(markerId),
2657
+ entityKind: "sequence-marker",
2658
+ payload: {
2659
+ sourceRange: {
2660
+ start: source.sourceStartMs,
2661
+ end: source.sourceStartMs + item.media.durationMs
2662
+ },
2663
+ duration: {
2664
+ mode: "fixed",
2665
+ value: item.media.durationMs
2666
+ },
2667
+ segmentRanges
2668
+ }
2669
+ });
2670
+ rows.relations.push({
2671
+ relationId: createRelationId(stableEffectId("relation", identityScope, `speech:${itemIndex}:script-marker`)),
2672
+ relationKind: "audio-script-marker",
2673
+ endpoint0EntityId: audioScript.entityId,
2674
+ endpoint1EntityId: createEntityId(markerId),
2675
+ metadata: {},
2676
+ trace: {
2677
+ ...trace,
2678
+ role: "audio-script-marker"
2679
+ }
2680
+ });
2681
+ }
2682
+ }
2683
+ const phoneticId = source.kind === "phonetic-script" ? requireTrimmed(source.phoneticScriptEntityId, "PhoneticScript entity id") : stableEffectId("entity", identityScope, `speech:${itemIndex}:phonetic-script`);
2684
+ const existingPhonetic = rows.entities.find((entity) => entity.entityId === phoneticId);
2685
+ const phoneticPayload = {
2686
+ baseEntityIds: [audioScript.entityId],
2687
+ ...source.kind === "phonetic-script" && source.phonemeScript !== void 0 ? { phonemeScript: source.phonemeScript } : {}
2688
+ };
2689
+ let phonetic;
2690
+ if (existingPhonetic === void 0) {
2691
+ phonetic = {
2692
+ entityId: requireAvailableEntityId(rows, phoneticId),
2693
+ entityKind: "phonetic-script",
2694
+ payload: phoneticPayload
2695
+ };
2696
+ rows.entities.push(phonetic);
2697
+ } else {
2698
+ phonetic = requireEntityKind(rows, phoneticId, "phonetic-script");
2699
+ if (canonicalJson(phonetic.payload) !== canonicalJson(phoneticPayload)) throw new Error(`PhoneticScript "${phoneticId}" conflicts with the immutable Speech source`);
2700
+ }
2701
+ assemblePhoneticScriptContent(rows, phonetic.entityId);
2702
+ return {
2703
+ audioScript,
2704
+ phonetic
2705
+ };
2706
+ }
2707
+ function requirePersistedPhoneticSourceScript(rows, source) {
2708
+ const scriptId = requireTrimmed(source.audioScriptEntityId, "AudioScript entity id");
2709
+ const audioScript = requireEntityKind(rows, scriptId, "audio-script");
2710
+ const segments = validateScriptSegments(source.segments);
2711
+ if (canonicalJson(audioScript.payload.segments) !== canonicalJson(segments)) throw new Error(`AudioScript "${scriptId}" conflicts with the immutable Speech source`);
2712
+ requireCanonicalAudioScriptAsset(rows, audioScript.entityId);
2713
+ return audioScript;
2714
+ }
2715
+ function requireAssetlessAsrSourceScript(rows, source) {
2716
+ const scriptId = requireTrimmed(source.audioScriptEntityId, "AudioScript entity id");
2717
+ const audioScript = requireEntityKind(rows, scriptId, "audio-script");
2718
+ const segments = audioScriptSegmentsFromAsr(source.segments, true);
2719
+ if (canonicalJson(audioScript.payload.segments) !== canonicalJson(segments)) throw new Error(`AudioScript "${scriptId}" conflicts with the immutable ASR source`);
2720
+ requireNoAudioScriptAsset(rows, audioScript.entityId, "ASR-composed");
2721
+ return audioScript;
2722
+ }
2723
+ function requireNoAudioScriptAsset(rows, audioScriptEntityId, label) {
2724
+ if (incidentRelations(rows, audioScriptEntityId).filter((relation) => relation.relationKind === "to-asset").length > 0) throw new Error(`${label} AudioScript "${audioScriptEntityId}" must not have an authored Asset snapshot`);
2725
+ }
2726
+ function requireCanonicalAudioScriptAsset(rows, audioScriptEntityId) {
2727
+ const bindings = incidentRelations(rows, audioScriptEntityId).filter((relation) => relation.relationKind === "to-asset");
2728
+ if (bindings.length !== 1) throw new Error(`AudioScript "${audioScriptEntityId}" requires exactly one Asset binding`);
2729
+ const binding = bindings[0];
2730
+ if (binding.endpoint0EntityId !== audioScriptEntityId) throw new Error("to-asset must use ordered endpoints [AudioScript, Asset]");
2731
+ const asset = requireEntityKind(rows, binding.endpoint1EntityId, "asset");
2732
+ if (asset.payload.system !== "memota" || typeof asset.payload.key !== "string" || asset.payload.key.length === 0 || asset.payload.key.trim() !== asset.payload.key) throw new Error(`AudioScript Asset "${asset.entityId}" must state a canonical memota locator`);
2733
+ return asset;
2734
+ }
2735
+ function validateScriptSegments(segments) {
2736
+ if (segments.length === 0) throw new Error("Speech source requires at least one script segment");
2737
+ const ids = /* @__PURE__ */ new Set();
2738
+ return Array.from({ length: segments.length }, (_, index) => {
2739
+ if (!Object.hasOwn(segments, index)) throw new Error("Speech source segments must not be sparse");
2740
+ const value = segments[index];
2741
+ const segment = strictJsonObject(value, `Speech source segment ${index}`);
2742
+ if (typeof segment.segmentId !== "string") throw new Error("Speech source segment id must be a string");
2743
+ const segmentId = requireTrimmed(segment.segmentId, "Speech source segment id");
2744
+ if (ids.has(segmentId)) throw new Error(`Duplicate Speech source segment id "${segmentId}"`);
2745
+ ids.add(segmentId);
2746
+ if (typeof segment.text !== "string" || segment.text.trim() === "") throw new Error("Speech source text is required");
2747
+ if (segment.language !== void 0 && typeof segment.language !== "string") throw new Error("Speech source language must be a string");
2748
+ return {
2749
+ ...segment,
2750
+ segmentId,
2751
+ text: segment.text,
2752
+ ...segment.language === void 0 ? {} : { language: requireTrimmed(segment.language, "Speech source language") }
2753
+ };
2754
+ });
2755
+ }
2756
+ function validateResolvedAsrSegments(segments) {
2757
+ return validateScriptSegments(segments).map((segment) => {
2758
+ const segmentId = segment.segmentId;
2759
+ const startMs = safeWholeMs(segment.startMs, `ASR segment "${segmentId}" startMs`);
2760
+ const endMs = safeWholeMs(segment.endMs, `ASR segment "${segmentId}" endMs`);
2761
+ if (endMs <= startMs) throw new Error(`ASR segment "${segmentId}" must have positive duration`);
2762
+ return {
2763
+ ...segment,
2764
+ segmentId,
2765
+ text: segment.text,
2766
+ startMs,
2767
+ endMs
2768
+ };
2769
+ });
2770
+ }
2771
+ function audioScriptSegmentsFromAsr(segments, preserveResolvedFields) {
2772
+ return validateResolvedAsrSegments(segments).map((timed) => {
2773
+ if (!preserveResolvedFields) {
2774
+ const allowed = new Set([
2775
+ "segmentId",
2776
+ "text",
2777
+ "language",
2778
+ "startMs",
2779
+ "endMs"
2780
+ ]);
2781
+ const extras = Object.keys(timed).filter((key) => !allowed.has(key));
2782
+ if (extras.length > 0) throw new Error(`New ASR segment must not contain host-resolved fields: ${extras.join(", ")}`);
2783
+ return {
2784
+ segmentId: timed.segmentId,
2785
+ text: timed.text,
2786
+ ...timed.language === void 0 ? {} : { language: timed.language }
2787
+ };
2788
+ }
2789
+ const segment = { ...timed };
2790
+ delete segment.startMs;
2791
+ delete segment.endMs;
2792
+ return segment;
2793
+ });
2794
+ }
2795
+ function strictJsonObject(value, label) {
2796
+ const clone = strictJsonValue(value, label, /* @__PURE__ */ new WeakSet());
2797
+ if (!isJsonObject(clone)) throw new Error(`${label} must be a plain JSON object`);
2798
+ return clone;
2799
+ }
2800
+ function strictJsonValue(value, label, seen) {
2801
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
2802
+ if (typeof value === "number") {
2803
+ if (!Number.isFinite(value)) throw new Error(`${label} must not contain non-finite JSON numbers`);
2804
+ return value;
2805
+ }
2806
+ if (Array.isArray(value)) {
2807
+ if (seen.has(value)) throw new Error(`${label} must not contain cyclic JSON values`);
2808
+ seen.add(value);
2809
+ const result = [];
2810
+ for (let index = 0; index < value.length; index += 1) {
2811
+ if (!Object.hasOwn(value, index)) throw new Error(`${label} must not contain sparse JSON arrays`);
2812
+ result.push(strictJsonValue(value[index], `${label}[${index}]`, seen));
2813
+ }
2814
+ seen.delete(value);
2815
+ return result;
2816
+ }
2817
+ if (typeof value !== "object" || value === void 0) throw new Error(`${label} must contain only JSON values`);
2818
+ const prototype = Object.getPrototypeOf(value);
2819
+ if (prototype !== Object.prototype && prototype !== null) throw new Error(`${label} must not contain objects with custom prototypes`);
2820
+ if (seen.has(value)) throw new Error(`${label} must not contain cyclic JSON values`);
2821
+ seen.add(value);
2822
+ const result = {};
2823
+ for (const [key, child] of Object.entries(value)) {
2824
+ if (child === void 0) throw new Error(`${label}.${key} must not be undefined`);
2825
+ result[key] = strictJsonValue(child, `${label}.${key}`, seen);
2826
+ }
2827
+ seen.delete(value);
2828
+ return result;
2829
+ }
2830
+ function replaceRelationWithTrace(rows, previous, endpoint0EntityId, endpoint1EntityId, trace, relationId) {
2831
+ rows.relations = rows.relations.filter((relation) => relation.relationId !== previous.relationId);
2832
+ rows.relations.push({
2833
+ relationId: requireAvailableRelationId(rows, relationId),
2834
+ relationKind: previous.relationKind,
2835
+ endpoint0EntityId,
2836
+ endpoint1EntityId,
2837
+ metadata: previous.metadata,
2838
+ trace
2839
+ });
2840
+ }
2841
+ /** Retire one editor use while retaining its immutable content row and Loro history. */
2842
+ function retireClipOccurrence(rows, topology) {
2843
+ const removedRelations = new Set([
2844
+ topology.trackRelation.relationId,
2845
+ topology.clipMarkerRelation.relationId,
2846
+ topology.markerContentRelation.relationId
2847
+ ]);
2848
+ rows.relations = rows.relations.filter((relation) => !removedRelations.has(relation.relationId));
2849
+ rows.entities = rows.entities.filter((entity) => entity.entityId !== topology.clip.entityId && entity.entityId !== topology.marker.entityId);
2850
+ }
2851
+ function speechEffectSignature(input) {
2852
+ return bytesToHex(sha256(new TextEncoder().encode(canonicalJson(input))));
2853
+ }
2854
+ function speechEffectTrace(envelope, itemIndex) {
2855
+ return {
2856
+ command: speechAssetsCommand,
2857
+ effectId: envelope.effectId,
2858
+ signature: envelope.signature,
2859
+ mode: envelope.input.mode,
2860
+ itemIndex
2861
+ };
2862
+ }
2863
+ function assertSpeechAssetsEnvelope(value) {
2864
+ if (value.version !== 1 || !Object.isFrozen(value) || !Object.isFrozen(value.input) || !Object.isFrozen(value.decisions) || speechEffectSignature(value.input) !== value.signature || value.effectId !== value.input.value.effectId) throw new Error("Speech effect requires a canonical frozen envelope");
2865
+ }
2866
+ function resolveSpeechAssetsReplay(rows, envelope) {
2867
+ const tagged = rows.relations.filter((relation) => relation.trace.command === speechAssetsCommand && relation.trace.effectId === envelope.effectId);
2868
+ if (tagged.length === 0) return void 0;
2869
+ if (tagged.some((relation) => relation.trace.signature !== envelope.signature)) throw new Error(`Speech effect "${envelope.effectId}" was already applied with different input`);
2870
+ const result = {
2871
+ speechClipEntityIds: [],
2872
+ speechAudioEntityIds: [],
2873
+ audioScriptEntityIds: [],
2874
+ phoneticScriptEntityIds: [],
2875
+ captionClipEntityIds: []
2876
+ };
2877
+ for (const [index, item] of envelope.input.value.items.entries()) {
2878
+ const relations = tagged.filter((relation) => relation.trace.itemIndex === index);
2879
+ const renders = relations.filter((relation) => relation.relationKind === "phonetic-script-render");
2880
+ if (renders.length !== 1) throw new Error(`Speech effect item ${index} has an incomplete render receipt`);
2881
+ const render = renders[0];
2882
+ const audio = requireEntityKind(rows, render.endpoint0EntityId, "audio");
2883
+ const phonetic = requireEntityKind(rows, render.endpoint1EntityId, "phonetic-script");
2884
+ const audioScriptId = requireComposedAudioScript(rows, phonetic.entityId);
2885
+ const contentRelations = relations.filter((relation) => relation.relationKind === "marker-content");
2886
+ const speechContent = contentRelations.filter((relation) => relation.trace.role !== "caption-content");
2887
+ if (speechContent.length !== 1 || speechContent[0].endpoint1EntityId !== audio.entityId) throw new Error(`Speech effect item ${index} has an incomplete Speech occurrence receipt`);
2888
+ const speechClip = requireSingleClipForMarker(rows, requireEntityKind(rows, speechContent[0].endpoint0EntityId, "sequence-marker").entityId, "speech");
2889
+ const captionIds = [];
2890
+ for (let captionIndex = 0; captionIndex < item.captions.length; captionIndex += 1) {
2891
+ const matches = contentRelations.filter((relation) => relation.trace.role === "caption-content" && relation.trace.captionIndex === captionIndex);
2892
+ if (matches.length !== 1) throw new Error(`Speech effect item ${index} Caption receipt is incomplete`);
2893
+ if (assembleCaptionContent(rows, requireEntityKind(rows, matches[0].endpoint1EntityId, "caption").entityId).audioScript.entityId !== audioScriptId) throw new Error("Speech Caption must retain the same AudioScript base");
2894
+ captionIds.push(requireSingleClipForMarker(rows, matches[0].endpoint0EntityId, "caption").entityId);
2895
+ }
2896
+ result.speechClipEntityIds.push(speechClip.entityId);
2897
+ result.speechAudioEntityIds.push(audio.entityId);
2898
+ result.audioScriptEntityIds.push(audioScriptId);
2899
+ result.phoneticScriptEntityIds.push(phonetic.entityId);
2900
+ result.captionClipEntityIds.push(captionIds);
2901
+ }
2902
+ return result;
2903
+ }
2904
+ function requireSingleClipForMarker(rows, markerEntityId, role) {
2905
+ const links = incidentRelations(rows, markerEntityId).filter((relation) => relation.relationKind === "clip-marker");
2906
+ if (links.length !== 1 || links[0].endpoint1EntityId !== markerEntityId) throw new Error("clip-marker must use one ordered [Clip, SequenceMarker] relation");
2907
+ return requireClipOnRole(rows, links[0].endpoint0EntityId, role).clip;
2908
+ }
2909
+ function resolveGeneratedVisualDecisions(rows, input) {
2910
+ const timeline = requireEntityKind(rows, input.timelineEntityId, "timeline");
2911
+ const anchorInput = visualInsertionAnchor(input);
2912
+ const anchor = requireCanonicalClipOnRole(rows, anchorInput.clipEntityId, "video_clip");
2913
+ const track = requireEntityKind(rows, anchor.trackRelation.endpoint0EntityId, "track");
2914
+ if (anchor.trackRelation.endpoint1EntityId !== anchor.clip.entityId) throw new Error("track-clip must use ordered endpoints [Track, Clip]");
2915
+ const timelineLinks = incidentRelations(rows, track.entityId).filter((relation) => relation.relationKind === "timeline-track");
2916
+ if (timelineLinks.length !== 1) throw new Error(`Video Track "${track.entityId}" must have one unambiguous Timeline`);
2917
+ const timelineLink = timelineLinks[0];
2918
+ if (timelineLink.endpoint0EntityId !== timeline.entityId || timelineLink.endpoint1EntityId !== track.entityId) throw new Error("timeline-track must use ordered endpoints [Timeline, Track]");
2919
+ const resolvedTrack = resolveEntityTimelineLayout(rows).tracks.find((candidate) => candidate.entityId === track.entityId);
2920
+ const anchorOrder = resolvedTrack?.clips.findIndex((clip) => clip.clipEntityId === anchor.clip.entityId) ?? -1;
2921
+ if (anchorOrder < 0) throw new Error(`Visual anchor Clip "${anchor.clip.entityId}" is not placed on its Track`);
2922
+ if (resolvedTrack.clips.some((clip) => clip.mode !== "sequential")) throw new Error("Generated visual insertion requires a fully sequential Video Track");
2923
+ const insertionIndex = anchorOrder + (anchorInput.position === "after" ? 1 : 0);
2924
+ return {
2925
+ trackEntityId: track.entityId,
2926
+ anchorOrder,
2927
+ anchorPosition: anchorInput.position,
2928
+ insertionOrders: visualInsertionOrders(rows, resolvedTrack.clips.map((clip) => clip.clipEntityId), insertionIndex, input.clips.length)
2929
+ };
2930
+ }
2931
+ function visualInsertionOrders(rows, orderedClipIds, insertionIndex, count) {
2932
+ const orders = orderedClipIds.map((clipId) => {
2933
+ const order = requireEntityKind(rows, clipId, "clip").payload.order;
2934
+ if (typeof order !== "number" || !Number.isFinite(order)) throw new Error(`Sequential Clip "${clipId}" requires a finite order`);
2935
+ return order;
2936
+ });
2937
+ if (orders.some((order, index) => index > 0 && order <= orders[index - 1])) throw new Error("Generated visual insertion requires unambiguous increasing Clip orders");
2938
+ const lower = orders[insertionIndex - 1];
2939
+ const upper = orders[insertionIndex];
2940
+ if (lower === void 0) return Array.from({ length: count }, (_, index) => upper - count + index);
2941
+ if (upper === void 0) return Array.from({ length: count }, (_, index) => lower + index + 1);
2942
+ const gap = (upper - lower) / (count + 1);
2943
+ const result = Array.from({ length: count }, (_, index) => lower + gap * (index + 1));
2944
+ if (result.some((order, index) => !Number.isFinite(order) || order <= (index === 0 ? lower : result[index - 1]) || order >= upper)) throw new Error("Clip order precision is insufficient for generated visual insertion");
2945
+ return result;
2946
+ }
2947
+ function visualInsertionAnchor(input) {
2948
+ const before = input.beforeClipEntityId;
2949
+ const after = input.afterClipEntityId;
2950
+ if (before === void 0 === (after === void 0)) throw new Error("Generated visual effect requires exactly one before or after Clip anchor");
2951
+ return before === void 0 ? {
2952
+ position: "after",
2953
+ clipEntityId: requireTrimmed(after, "After Clip anchor")
2954
+ } : {
2955
+ position: "before",
2956
+ clipEntityId: requireTrimmed(before, "Before Clip anchor")
2957
+ };
2958
+ }
2959
+ function generatedVisualSignature(input) {
2960
+ return bytesToHex(sha256(new TextEncoder().encode(canonicalJson(input))));
2961
+ }
2962
+ function assertGeneratedVisualEnvelope(value) {
2963
+ if (value.version !== 1 || !Object.isFrozen(value) || !Object.isFrozen(value.input) || !Object.isFrozen(value.decisions) || requireTrimmed(value.baselineFingerprint, "Generated visual baseline fingerprint") !== value.baselineFingerprint || requireTrimmed(value.effectId, "Generated visual effect id") !== value.effectId || generatedVisualSignature(value.input) !== value.signature) throw new Error("Generated visual effect requires a canonical frozen envelope");
2964
+ }
2965
+ function generatedVisualTrace(envelope, itemIndex, generationJobId, sourceIndex) {
2966
+ return {
2967
+ command: generatedVisualsCommand,
2968
+ effectId: envelope.effectId,
2969
+ signature: envelope.signature,
2970
+ itemIndex,
2971
+ generationJobId,
2972
+ ...sourceIndex === void 0 ? {} : { sourceIndex }
2973
+ };
2974
+ }
2975
+ function resolveGeneratedVisualReplay(rows, envelope) {
2976
+ const tagged = rows.relations.filter((relation) => relation.trace.command === generatedVisualsCommand && relation.trace.effectId === envelope.effectId);
2977
+ if (tagged.length === 0) return void 0;
2978
+ if (tagged.some((relation) => relation.trace.signature !== envelope.signature)) throw new Error(`Generated visual effect "${envelope.effectId}" was already applied with different input`);
2979
+ const clipEntityIds = [];
2980
+ const mediaEntityIds = [];
2981
+ let expectedCount = 0;
2982
+ for (const [index, clipInput] of envelope.input.clips.entries()) {
2983
+ const item = tagged.filter((relation) => relation.trace.itemIndex === index);
2984
+ const trackLink = requireGeneratedVisualRelation(item, "track-clip", index);
2985
+ if (trackLink.endpoint0EntityId !== envelope.decisions.trackEntityId || requireEntityKind(rows, trackLink.endpoint1EntityId, "clip").entityId !== trackLink.endpoint1EntityId) throw new Error("track-clip must use ordered endpoints [Track, Clip]");
2986
+ const clipEntityId = trackLink.endpoint1EntityId;
2987
+ const markerLink = requireGeneratedVisualRelation(item, "clip-marker", index);
2988
+ if (markerLink.endpoint0EntityId !== clipEntityId) throw new Error("clip-marker must use ordered endpoints [Clip, SequenceMarker]");
2989
+ const marker = requireEntityKind(rows, markerLink.endpoint1EntityId, "sequence-marker");
2990
+ const contentLink = requireGeneratedVisualRelation(item, "marker-content", index);
2991
+ if (contentLink.endpoint0EntityId !== marker.entityId) throw new Error("marker-content must use ordered endpoints [SequenceMarker, media]");
2992
+ const media = requireSequenceContent(rows, contentLink.endpoint1EntityId);
2993
+ if (media.entityKind !== "video" && media.entityKind !== "image") throw new Error("Generated visual receipt must reference Video or Image output");
2994
+ const lineage = item.filter((relation) => relation.relationKind === "generated");
2995
+ if (lineage.length !== clipInput.sourceMediaEntityIds.length) throw new Error(`Generated visual ${index} has incomplete source lineage`);
2996
+ for (const [sourceIndex, sourceId] of clipInput.sourceMediaEntityIds.entries()) {
2997
+ const matches = lineage.filter((relation) => relation.trace.sourceIndex === sourceIndex);
2998
+ if (matches.length !== 1 || matches[0].endpoint0EntityId !== media.entityId || matches[0].endpoint1EntityId !== sourceId) throw new Error("generated must use ordered endpoints [output media, input media]");
2999
+ }
3000
+ expectedCount += 3 + clipInput.sourceMediaEntityIds.length;
3001
+ clipEntityIds.push(clipEntityId);
3002
+ mediaEntityIds.push(media.entityId);
3003
+ }
3004
+ if (tagged.length !== expectedCount) throw new Error(`Generated visual effect "${envelope.effectId}" has an ambiguous relation receipt`);
3005
+ return {
3006
+ clipEntityIds,
3007
+ mediaEntityIds
3008
+ };
3009
+ }
3010
+ function requireGeneratedVisualRelation(relations, kind, itemIndex) {
3011
+ const matches = relations.filter((relation) => relation.relationKind === kind);
3012
+ if (matches.length !== 1) throw new Error(`Generated visual ${itemIndex} must have exactly one ${kind} Relation`);
3013
+ return matches[0];
3014
+ }
3015
+ function assertCaptionAssetsEnvelope(value) {
3016
+ if (value.version !== 1 || !Object.isFrozen(value) || !Object.isFrozen(value.input) || !Object.isFrozen(value.decisions) || requireTrimmed(value.baselineFingerprint, "Caption baseline fingerprint") !== value.baselineFingerprint || requireTrimmed(value.signature, "Caption effect signature") !== value.signature) throw new Error("Caption effect requires a canonical frozen envelope");
3017
+ }
3018
+ function deepFreeze(value) {
3019
+ if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
3020
+ for (const child of Object.values(value)) deepFreeze(child);
3021
+ Object.freeze(value);
3022
+ }
3023
+ return value;
3024
+ }
3025
+ function captionEffectSignature(input, segments) {
3026
+ const value = JSON.stringify({
3027
+ timelineEntityId: input.timelineEntityId,
3028
+ trackEntityId: input.trackEntityId,
3029
+ source: {
3030
+ entityId: input.source.entityId,
3031
+ entityKind: input.source.entityKind
3032
+ },
3033
+ sourceOccurrence: {
3034
+ clipEntityId: input.sourceOccurrence.clipEntityId,
3035
+ markerEntityId: input.sourceOccurrence.markerEntityId
3036
+ },
3037
+ captionAsset: {
3038
+ assetId: input.captionAsset.assetId,
3039
+ ...input.captionAsset.storageKey === void 0 ? {} : { storageKey: input.captionAsset.storageKey }
3040
+ },
3041
+ segments
3042
+ });
3043
+ return bytesToHex(sha256(new TextEncoder().encode(value)));
3044
+ }
3045
+ function effectTrace(effectId, signature, segmentId) {
3046
+ return {
3047
+ command: captionAssetsCommand,
3048
+ effectId,
3049
+ signature,
3050
+ ...segmentId === void 0 ? {} : { segmentId }
3051
+ };
3052
+ }
3053
+ function stableEffectId(kind, effectId, localKey) {
3054
+ return `${kind}_effect_${bytesToHex(sha256(new TextEncoder().encode(`${captionAssetsCommand}\u0000${effectId}\u0000${kind}\u0000${localKey}`))).slice(0, 40)}`;
3055
+ }
3056
+ function stableEffectScope(command, effectId, baselineFingerprint) {
3057
+ return `${command}\u0000${effectId}\u0000${baselineFingerprint}`;
3058
+ }
3059
+ function stableEffectIdFactory(effectId, namespace) {
3060
+ const counters = {
3061
+ entity: 0,
3062
+ relation: 0
3063
+ };
3064
+ return (kind) => stableEffectId(kind, effectId, `${namespace}:${kind}:${counters[kind]++}`);
3065
+ }
3066
+ function stableEffectPeerId(command, effectId, baselineFingerprint) {
3067
+ const digest = sha256(new TextEncoder().encode(`${command}\u0000${effectId}\u0000${baselineFingerprint}\u0000loro-peer`));
3068
+ return BigInt(`0x${bytesToHex(digest).slice(0, 15)}`).toString();
3069
+ }
3070
+ function isCaptionEffectRelation(relation, effectId) {
3071
+ return relation.trace.command === captionAssetsCommand && relation.trace.effectId === effectId;
3072
+ }
3073
+ function resolveCaptionAssetsReplay(rows, input, effectId, signature, segments, sourceEntityId, trackEntityId) {
3074
+ const tagged = rows.relations.filter((relation) => isCaptionEffectRelation(relation, effectId));
3075
+ if (tagged.length === 0) return void 0;
3076
+ if (tagged.some((relation) => relation.trace.signature !== signature)) throw new Error(`Caption effect "${effectId}" was already applied with different input`);
3077
+ const sourceRelations = tagged.filter((relation) => relation.relationKind === "audio-script-source");
3078
+ if (sourceRelations.length !== 1) throw new Error(`Caption effect "${effectId}" has an ambiguous source receipt`);
3079
+ const sourceRelation = sourceRelations[0];
3080
+ if (sourceRelation.endpoint1EntityId !== sourceEntityId) throw new Error("audio-script-source must use ordered endpoints [AudioScript, source media]");
3081
+ const script = requireEntityKind(rows, sourceRelation.endpoint0EntityId, "audio-script");
3082
+ if (!sameScriptSegments(script.payload.segments, segments)) throw new Error(`Caption effect "${effectId}" AudioScript no longer matches its immutable ASR result`);
3083
+ const scriptMarkerRelations = tagged.filter((relation) => relation.relationKind === "audio-script-marker");
3084
+ if (scriptMarkerRelations.length !== 1 || scriptMarkerRelations[0].endpoint0EntityId !== script.entityId) throw new Error("audio-script-marker must use ordered endpoints [AudioScript, annotation SequenceMarker]");
3085
+ const scriptMarker = requireEntityKind(rows, scriptMarkerRelations[0].endpoint1EntityId, "sequence-marker");
3086
+ if (!sameSegmentRanges(scriptMarker.payload.segmentRanges, segments)) throw new Error(`Caption effect "${effectId}" annotation Marker no longer matches its immutable ASR timing`);
3087
+ let assetEntityId;
3088
+ const captionEntityIds = [];
3089
+ const captionClipEntityIds = [];
3090
+ for (const segment of segments) {
3091
+ const relations = tagged.filter((relation) => relation.trace.segmentId === segment.segmentId);
3092
+ const assetLink = requireTaggedRelation(relations, "from-asset", segment.segmentId);
3093
+ const caption = requireEntityKind(rows, assetLink.endpoint0EntityId, "caption");
3094
+ const asset = requireEntityKind(rows, assetLink.endpoint1EntityId, "asset");
3095
+ if (assetEntityId !== void 0 && asset.entityId !== assetEntityId) throw new Error(`Caption effect "${effectId}" references multiple Caption Assets`);
3096
+ assetEntityId = asset.entityId;
3097
+ if (asset.payload.system !== "memota" || asset.payload.key !== input.captionAsset.assetId || input.captionAsset.storageKey !== void 0 && asset.payload.storageKey !== input.captionAsset.storageKey) throw new Error(`Caption effect "${effectId}" Caption Asset does not match its receipt`);
3098
+ const selection = caption.payload.selection;
3099
+ const bases = caption.payload.baseEntityIds;
3100
+ if (caption.payload.durationMs !== segment.endMs - segment.startMs || !isJsonObject(selection) || selection.segmentId !== segment.segmentId || !Array.isArray(bases) || bases.length !== 1 || bases[0] !== script.entityId) throw new Error(`Caption effect "${effectId}" Caption "${caption.entityId}" conflicts with its ASR segment`);
3101
+ const contentLink = requireTaggedRelation(relations, "marker-content", segment.segmentId);
3102
+ if (contentLink.endpoint1EntityId !== caption.entityId) throw new Error("marker-content must use ordered endpoints [SequenceMarker, Caption]");
3103
+ const marker = requireEntityKind(rows, contentLink.endpoint0EntityId, "sequence-marker");
3104
+ const markerLink = requireTaggedRelation(relations, "clip-marker", segment.segmentId);
3105
+ if (markerLink.endpoint1EntityId !== marker.entityId) throw new Error("clip-marker must use ordered endpoints [Clip, SequenceMarker]");
3106
+ const clip = requireEntityKind(rows, markerLink.endpoint0EntityId, "clip");
3107
+ const trackLink = requireTaggedRelation(relations, "track-clip", segment.segmentId);
3108
+ if (trackLink.endpoint0EntityId !== trackEntityId || trackLink.endpoint1EntityId !== clip.entityId) throw new Error("track-clip must use ordered endpoints [Track, Clip]");
3109
+ captionEntityIds.push(caption.entityId);
3110
+ captionClipEntityIds.push(clip.entityId);
3111
+ }
3112
+ if (assetEntityId === void 0 || tagged.length !== 2 + segments.length * 4) throw new Error(`Caption effect "${effectId}" has an incomplete or ambiguous relation receipt`);
3113
+ return {
3114
+ audioScriptEntityId: script.entityId,
3115
+ audioScriptMarkerEntityId: scriptMarker.entityId,
3116
+ captionAssetEntityId: assetEntityId,
3117
+ captionEntityIds,
3118
+ captionClipEntityIds
3119
+ };
3120
+ }
3121
+ function requireTaggedRelation(relations, kind, segmentId) {
3122
+ const matches = relations.filter((relation) => relation.relationKind === kind);
3123
+ if (matches.length !== 1) throw new Error(`ASR segment "${segmentId}" must have exactly one ${kind} Relation`);
3124
+ return matches[0];
3125
+ }
3126
+ function sameScriptSegments(value, segments) {
3127
+ if (!Array.isArray(value) || value.length !== segments.length) return false;
3128
+ return value.every((entry, index) => {
3129
+ if (!isJsonObject(entry)) return false;
3130
+ const expected = segments[index];
3131
+ return entry.segmentId === expected.segmentId && entry.text === expected.text && entry.language === expected.language && Object.keys(entry).every((key) => key === "segmentId" || key === "text" || key === "language");
3132
+ });
3133
+ }
3134
+ function sameSegmentRanges(value, segments) {
3135
+ if (!Array.isArray(value) || value.length !== segments.length) return false;
3136
+ return value.every((entry, index) => {
3137
+ if (!isJsonObject(entry)) return false;
3138
+ const expected = segments[index];
3139
+ return entry.segmentId === expected.segmentId && entry.startMs === expected.startMs && entry.endMs === expected.endMs && Object.keys(entry).every((key) => key === "segmentId" || key === "startMs" || key === "endMs");
3140
+ });
3141
+ }
3142
+ function requireTrimmed(value, label) {
3143
+ if (typeof value !== "string" || value.length === 0 || value.trim() !== value) throw new Error(`${label} must be non-empty and trimmed`);
3144
+ return value;
3145
+ }
3146
+ function safeWholeMs(value, label) {
3147
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error(`${label} must be a non-negative whole millisecond`);
3148
+ return value;
3149
+ }
1809
3150
  function validateFinalRows(rows) {
1810
3151
  decodeEntityRelationRows(rows, numericMarkerValidation);
1811
3152
  assertCanonicalEditorResources(rows);
@@ -1843,6 +3184,16 @@ function requireClipTopology(rows, clipEntityId) {
1843
3184
  markerContentRelation
1844
3185
  };
1845
3186
  }
3187
+ function requireCanonicalClipOnRole(rows, clipEntityId, role) {
3188
+ const topology = requireClipTopology(rows, clipEntityId);
3189
+ if (topology.trackRelation.endpoint1EntityId !== topology.clip.entityId || topology.clipMarkerRelation.endpoint0EntityId !== topology.clip.entityId || topology.clipMarkerRelation.endpoint1EntityId !== topology.marker.entityId || topology.markerContentRelation.endpoint0EntityId !== topology.marker.entityId) throw new Error("Occurrence must use ordered Track→Clip→SequenceMarker→content endpoints");
3190
+ const track = requireEntityKind(rows, topology.trackRelation.endpoint0EntityId, "track");
3191
+ if (track.payload.role !== role) throw new Error(`Clip "${clipEntityId}" must belong to the ${role} Track`);
3192
+ const timelineLinks = incidentRelations(rows, track.entityId).filter((relation) => relation.relationKind === "timeline-track");
3193
+ if (timelineLinks.length !== 1 || timelineLinks[0].endpoint1EntityId !== track.entityId) throw new Error("timeline-track must use one ordered [Timeline, Track] relation");
3194
+ requireEntityKind(rows, timelineLinks[0].endpoint0EntityId, "timeline");
3195
+ return topology;
3196
+ }
1846
3197
  function requireOneRelation(rows, entityId, relationKind) {
1847
3198
  const matches = incidentRelations(rows, entityId).filter((relation) => relation.relationKind === relationKind);
1848
3199
  if (matches.length !== 1) throw new Error(`Entity "${entityId}" must have exactly one ${relationKind} Relation`);
@@ -1894,6 +3245,11 @@ function requireAvailableEntityId(rows, value) {
1894
3245
  if (rows.entities.some((entity) => entity.entityId === entityId)) throw new Error(`Entity id "${entityId}" already exists`);
1895
3246
  return entityId;
1896
3247
  }
3248
+ function requireAvailableRelationId(rows, value) {
3249
+ const relationId = createRelationId(value);
3250
+ if (rows.relations.some((relation) => relation.relationId === relationId)) throw new Error(`Relation id "${relationId}" already exists`);
3251
+ return relationId;
3252
+ }
1897
3253
  function setClipOrder(rows, clipEntityId, order) {
1898
3254
  const clip = requireEntityKind(rows, clipEntityId, "clip");
1899
3255
  replaceEntity(rows, clip.entityId, {
@@ -1969,6 +3325,15 @@ function linearRate(value) {
1969
3325
  if (!isJsonObject(value) || value.kind !== "linear") throw new Error("Only linear Clip time remapping is supported");
1970
3326
  return finitePositive(value.rate, "linear speed rate");
1971
3327
  }
3328
+ function speedModeRate(mode) {
3329
+ switch (mode) {
3330
+ case "0.5x": return .5;
3331
+ case "0.75x": return .75;
3332
+ case "1.0x": return 1;
3333
+ case "1.5x": return 1.5;
3334
+ case "2.0x": return 2;
3335
+ }
3336
+ }
1972
3337
  function resizeAbsoluteTarget(payload, duration) {
1973
3338
  if (payload.targetRange === void 0) return;
1974
3339
  const target = requirePositiveRange(payload.targetRange, "targetRange");
@@ -5145,4 +6510,4 @@ function serverCovers(serverVV, target) {
5145
6510
  return covers(server, target);
5146
6511
  }
5147
6512
  //#endregion
5148
- export { DEFAULT_UNIT_TIME_MS, EntityGraphHttpClient, EntityTimelineEditor, EntityTimelineProjectionError, IMPLEMENTED_SEMANTIC_OP_KINDS, LANE_KINDS_IN_STACK_ORDER, LORO_ENTITY_SCHEMA, LoroEntityDocument, LoroEntityDraft, ManualSyncDoc, MedeoHttpDocStorage, MemoryDocStorage, MengineAckFailedError, MengineDocSession, MengineHttpClient, MengineHttpRequestError, MenginePushRejectedError, MirrorVideoDocumentAdapter, PlainMemoryAdapter, SchemaValidator, ScriptCompositionError, SemanticEditor, TIMELINE_SKELETON_DURATION_MS, ValidationError, VideoDocumentValidationError, applyEntityRows, applyFieldChanges, arrangeMainTrackSeamlessly, assembleCaptionContent, assembleEntityContent, assemblePhoneticScriptContent, assembleScriptText, assertCanonicalEditorResources, assertEntityProjectionPreservesLegacy, assertFieldChanges, assertMediaAssetWritePolicy, assertValidVideoDocument, audioScriptAssetContent, audioScriptAssetFields, audioScriptAssetHash, audioScriptAssetOf, base64ToBytes, buildInitialVideoDocument, buildSpeechHostMap, bytesToBase64, cascadeAfterVideoClipChanges, compileEntityRows, createEditSandbox, createMirrorVideoDocument, createMirrorVideoDocumentAdapter, createPlainMemoryAdapter, decodeDocVersionMark, derivePositionFromAbs, effectiveVideoClipDurationMs, encodeDocVersionMark, ensureEditorFoundation, ensureLaneTrack, fillMainTrackTimeGaps, findComposedAudioScript, findLaneTrack, fromVideoDocument, generatePartId, getAt, hostForAbsMs, importMediaAsset, isEmptyVideoClip, isImplementedSemanticOpKind, isMap, laneTrackId, mainTrackRanges, migrateLegacyTimelineToEntities, partDurationMs, partUnionSchema, phoneticScriptAssetContent, phoneticScriptAssetHash, phoneticScriptAssetOf, prepareCaptionContent, projectEntityTimeline, readDocumentAudioScript, readEntityDocument, readMainTrackItems, readMengineEventStream, readPart, readPartDurationMs, readVideoDocumentFromDraft, reassignSpeechesToVideoClipsByTime, recalculateTimelineDuration, relativePositionForAbs, replayJournal, resolveAllSpeechOverlaps, resolveEntityTimelineLayout, resolveFieldPath, resolveSpeechOverlapByShiftingVideos, safeDurationMs, schemas_exports as schemas, scriptSourceAssetOf, selectAudioScriptSegment, snapshotToPlain, solveVideoDocument, speedOf, syncAggregatedClipsTimePosition, toVideoDocument, validateVideoDocument, videoDocumentMirrorSchema, videoDocumentSchema };
6513
+ export { DEFAULT_UNIT_TIME_MS, EntityGraphHttpClient, EntityTimelineEditor, EntityTimelineProjectionError, IMPLEMENTED_SEMANTIC_OP_KINDS, LANE_KINDS_IN_STACK_ORDER, LORO_ENTITY_SCHEMA, LoroEntityDocument, LoroEntityDraft, ManualSyncDoc, MedeoHttpDocStorage, MemoryDocStorage, MengineAckFailedError, MengineDocSession, MengineHttpClient, MengineHttpRequestError, MenginePushRejectedError, MirrorVideoDocumentAdapter, PlainMemoryAdapter, SchemaValidator, ScriptCompositionError, SemanticEditor, TIMELINE_SKELETON_DURATION_MS, ValidationError, VideoDocumentValidationError, applyEntityRows, applyFieldChanges, arrangeMainTrackSeamlessly, assembleCaptionContent, assembleEntityContent, assemblePhoneticScriptContent, assembleScriptText, assertCanonicalEditorResources, assertEntityProjectionPreservesLegacy, assertFieldChanges, assertMediaAssetWritePolicy, assertValidVideoDocument, audioScriptAssetContent, audioScriptAssetFields, audioScriptAssetHash, audioScriptAssetOf, base64ToBytes, buildInitialVideoDocument, buildSpeechHostMap, bytesToBase64, cascadeAfterVideoClipChanges, compileCaptionAssetsEffect, compileEntityRows, compileGeneratedVisualEffect, compileSpeechAssetsEffect, createEditSandbox, createMirrorVideoDocument, createMirrorVideoDocumentAdapter, createPlainMemoryAdapter, decodeDocVersionMark, derivePositionFromAbs, effectiveVideoClipDurationMs, encodeDocVersionMark, ensureEditorFoundation, ensureLaneTrack, fillMainTrackTimeGaps, findComposedAudioScript, findLaneTrack, fromVideoDocument, generatePartId, getAt, hostForAbsMs, importCaptionAsset, importMediaAsset, isEmptyVideoClip, isImplementedSemanticOpKind, isMap, laneTrackId, mainTrackRanges, migrateLegacyTimelineToEntities, partDurationMs, partUnionSchema, phoneticScriptAssetContent, phoneticScriptAssetHash, phoneticScriptAssetOf, prepareCaptionAssetsEffect, prepareCaptionContent, prepareContinueVideoEffect, prepareGeneratedVisualEffect, prepareSpeechAssetsEffect, projectEntityTimeline, readDocumentAudioScript, readEntityDocument, readMainTrackItems, readMengineEventStream, readPart, readPartDurationMs, readVideoDocumentFromDraft, reassignSpeechesToVideoClipsByTime, recalculateTimelineDuration, relativePositionForAbs, replayJournal, resolveAllSpeechOverlaps, resolveEntityTimelineLayout, resolveFieldPath, resolveSpeechOverlapByShiftingVideos, safeDurationMs, schemas_exports as schemas, scriptSourceAssetOf, selectAudioScriptSegment, snapshotToPlain, solveVideoDocument, speedOf, syncAggregatedClipsTimePosition, toVideoDocument, validateVideoDocument, videoDocumentMirrorSchema, videoDocumentSchema };