@mengine/medeo-client 2.0.1-alpha.0 → 2.0.1-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1628 +0,0 @@
1
- import { Mirror, schema, validateSchema } from "loro-mirror";
2
- import { z } from "zod";
3
- import { LoroDoc } from "loro-crdt";
4
- //#region src/client/base64.ts
5
- function bytesToBase64(bytes) {
6
- let binary = "";
7
- for (const byte of bytes) binary += String.fromCharCode(byte);
8
- return btoa(binary);
9
- }
10
- function base64ToBytes(base64) {
11
- const binary = atob(base64);
12
- const bytes = new Uint8Array(binary.length);
13
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
14
- return bytes;
15
- }
16
- //#endregion
17
- //#region src/document/mirror-schema.ts
18
- /**
19
- * Declarative `loro-mirror` schema for `VideoDocument` — the canonical structural
20
- * SSOT and live storage wire (replaces the hand-rolled `@mengine/schema`
21
- * definition + adapter, see ADR 0008).
22
- *
23
- * Mirror gives an in-memory immutable state synced to the Loro doc by declarative
24
- * diff, so the storage layer no longer hand-writes per-region reconcile or a
25
- * transaction state machine. The shapes here store only authoritative facts
26
- * (RFC 02 §6): per-item absolute time, `part_aggregations`, and total duration
27
- * are projection-derived (cascade-solved at read time), so they are absent here.
28
- *
29
- * - tracks live in a single `tracks` `LoroMovableList` keyed by track id
30
- * (reference/17 §4). Lane is expressed by each track's `parts_kind`, not by
31
- * which container it lives in; order is the movable-list order itself. There is
32
- * no `lane` / `lane_order` field, so two peers inserting tracks never collide
33
- * on an order integer — list moves are conflict-free (RFC 03 §4). The legacy
34
- * keyed-map (`LoroMapRecord` + an integer `lane_order`) and the prior three
35
- * named containers are gone; the `main` / `above` / `below` three-pane view is
36
- * rebuilt by the projection from `parts_kind`.
37
- * - each track's `items` is a `LoroMovableList` keyed by `part_id`: a part is
38
- * placed at most once per lane, so `part_id` is the stable placement identity.
39
- * Reorder diffs to a real Loro `move`, preserving per-item CRDT identity on
40
- * every lane (main and secondary alike).
41
- * - `time_position` is the authoritative positioning fact (RFC 02 §4,
42
- * reference/17 §3), carried as an opaque JSON blob string (a whole tagged-union
43
- * value, last-writer-wins). The derived `fallback_abs_ms` snapshot sits beside
44
- * it as its own number field — a separate LWW unit so a projection refresh
45
- * never clobbers a `time_position` edit.
46
- * - `part_library` values are nested `LoroMap`s: the value is a `LoroMap` with
47
- * four mutually-exclusive optional part sub-maps (`video_clip` / `speech` /
48
- * `caption` / `bgm`), each a `LoroMap` whose fields are stored as real Loro
49
- * sub-keys. This makes each field its own CRDT unit, so two peers editing
50
- * different fields of the same part (e.g. one volume, one play_out) merge
51
- * field-by-field instead of one whole-value overwrite. Field `required` mirrors
52
- * the Smithy `@required` contract (see `video_draft_comp.smithy`). `kind` is not
53
- * stored (the present sub-key names the kind); `duration_ms` is not stored (it
54
- * is derived, reference/17 §5). Nested values that the engine does not edit
55
- * field-by-field — `speed_shift` (a tagged union), `voice`, `caption_ids` — stay
56
- * as opaque JSON-blob sub-keys via `transform`. The four sub-keys are optional,
57
- * so the "exactly one part kind" union invariant is not enforced by the schema
58
- * type; it is rebuilt by `draftToPartUnion` on read and gated by zod on write.
59
- * - a caption's `style` is a mergeable child map for independent style fields.
60
- * Creation paths materialize it with the caption, even when empty, so undoing
61
- * a later style edit never removes the parent reference. Other nested maps
62
- * keep their regular container identities from creation.
63
- */
64
- /**
65
- * JSON-blob transform for an opaque, last-writer-wins value carried in a Loro
66
- * string. The field must be declared `required: false`: an absent field decodes
67
- * to `undefined` (mirror never calls `decode`/`encode` for null/undefined),
68
- * which is how we represent "no value" instead of encoding a `null` sentinel.
69
- */
70
- function jsonTransform() {
71
- return {
72
- decode: (value) => JSON.parse(value),
73
- encode: (value) => JSON.stringify(value),
74
- isEqual: "encoded-value-equality"
75
- };
76
- }
77
- const trackItem = schema.LoroMap({
78
- part_id: schema.String(),
79
- time_position: schema.String().transform(jsonTransform()),
80
- fallback_abs_ms: schema.Number({ required: false })
81
- });
82
- const track = schema.LoroMap({
83
- id: schema.String(),
84
- parts_kind: schema.String({ required: false }),
85
- is_hidden: schema.Boolean({ required: false }),
86
- items: schema.LoroMovableList(trackItem, (item) => item.part_id)
87
- });
88
- const videoClipPart = schema.LoroMap({
89
- id: schema.String(),
90
- play_in: schema.Number(),
91
- play_out: schema.Number(),
92
- volume: schema.Number(),
93
- origin_media_id: schema.String(),
94
- speed_shift: schema.String({ required: false }).transform(jsonTransform())
95
- }, { required: false });
96
- const speechPart = schema.LoroMap({
97
- id: schema.String(),
98
- media_duration_ms: schema.Number(),
99
- audio_script: schema.String(),
100
- volume: schema.Number(),
101
- audio_storage_key: schema.String(),
102
- origin_speech_id: schema.String(),
103
- voice: schema.String().transform(jsonTransform()),
104
- caption_ids: schema.String().transform(jsonTransform())
105
- }, { required: false });
106
- const captionStyle = schema.LoroMap({
107
- font_id: schema.String({ required: false }),
108
- font_size: schema.Number({ required: false }),
109
- font_color: schema.String({ required: false }),
110
- font_weight: schema.Number({ required: false }),
111
- entrance_animation: schema.String({ required: false }),
112
- entrance_animation_duration_ms: schema.Number({ required: false }),
113
- stroke_color: schema.String({ required: false }),
114
- stroke_width: schema.Number({ required: false }),
115
- position_x: schema.Number({ required: false }),
116
- position_y: schema.Number({ required: false })
117
- }, { required: false });
118
- const captionPart = schema.LoroMap({
119
- id: schema.String(),
120
- initial_duration_ms: schema.Number(),
121
- speech_part_id: schema.String(),
122
- text: schema.String(),
123
- start_ms: schema.Number(),
124
- style: captionStyle
125
- }, {
126
- required: false,
127
- mergeableMapChildContainers: true
128
- });
129
- const bgmPart = schema.LoroMap({
130
- id: schema.String(),
131
- audio_storage_key: schema.String(),
132
- volume: schema.Number(),
133
- origin_media_id: schema.String()
134
- }, { required: false });
135
- const partValue = schema.LoroMap({
136
- video_clip: videoClipPart,
137
- speech: speechPart,
138
- caption: captionPart,
139
- bgm: bgmPart
140
- });
141
- const videoDocumentMirrorSchema = schema({
142
- timeline: schema.LoroMap({ unit_time_ms: schema.Number({ required: false }) }),
143
- tracks: schema.LoroMovableList(track, (t) => t.id),
144
- part_library: schema.LoroMapRecord(partValue)
145
- });
146
- /** Project a discriminated `PartUnion` into the draft's four-optional shape. */
147
- function partUnionToDraft(part) {
148
- if (part.video_clip != null) return { video_clip: omitKind(part.video_clip) };
149
- if (part.speech != null) return { speech: omitKind(part.speech) };
150
- if (part.caption != null) return { caption: omitKind(part.caption) };
151
- return { bgm: omitKind(part.bgm) };
152
- }
153
- /**
154
- * Rebuild a discriminated `PartUnion` from a draft part value: pick the one
155
- * present sub-key, restore its `kind`, and drop the `$cid`. Returns `undefined`
156
- * when no part sub-key is present (an empty/placeholder value).
157
- */
158
- function draftToPartUnion(value) {
159
- if (value == null) return void 0;
160
- const v = value;
161
- if (v.video_clip != null) return { video_clip: withKind(v.video_clip, "video_clip") };
162
- if (v.speech != null) return { speech: withKind(v.speech, "speech") };
163
- if (v.caption != null) return { caption: withKind(v.caption, "caption") };
164
- if (v.bgm != null) return { bgm: withKind(v.bgm, "bgm") };
165
- }
166
- /** Drop `kind` (not stored) and `$cid` from a part payload for the draft. */
167
- function omitKind(part) {
168
- const { kind: _kind, $cid: _cid, ...rest } = part;
169
- return rest;
170
- }
171
- /** Restore `kind` (and drop `$cid`) on a part sub-map read from the draft. */
172
- function withKind(part, kind) {
173
- const { $cid: _cid, ...rest } = part;
174
- return {
175
- ...rest,
176
- kind
177
- };
178
- }
179
- /** Entries of a draft record (e.g. `tracks`) with `$cid` stripped. */
180
- function recordEntries(record) {
181
- if (record == null) return [];
182
- const out = [];
183
- for (const [key, value] of Object.entries(record)) {
184
- if (key === "$cid") continue;
185
- out.push([key, value]);
186
- }
187
- return out;
188
- }
189
- //#endregion
190
- //#region src/document/types.ts
191
- /** The linear speed multiplier of a `speed_shift`, defaulting to 1 (original). */
192
- function speedOf(speedShift) {
193
- const speed = speedShift?.config?.linear?.speed;
194
- return typeof speed === "number" && Number.isFinite(speed) && speed > 0 ? speed : 1;
195
- }
196
- /**
197
- * A video clip's effective timeline duration, derived from authoritative facts
198
- * (RFC 02, `reference/16` §4, reference/17 §5): the trim window
199
- * `play_out - play_in` divided by the speed multiplier, rounded to integer ms.
200
- * `play_in` / `play_out` are optional in the IDL but every write path sets them
201
- * (defaulting to the whole media), and the legacy-ingest projection backfills the
202
- * window from a legacy `duration_ms` — so an authoritative clip always carries a
203
- * trim window and there is no stored `duration_ms` to fall back to. A clip with
204
- * neither bound yields 0. Speeds the clip up (>1× → shorter) or down (<1×).
205
- */
206
- function effectiveVideoClipDurationMs(clip) {
207
- const speed = speedOf(clip.speed_shift);
208
- const sourceMs = (clip.play_out ?? 0) - (clip.play_in ?? 0);
209
- const effective = Math.round(sourceMs / speed);
210
- return Number.isFinite(effective) && effective > 0 ? effective : 0;
211
- }
212
- /**
213
- * The `timeline.unit_time_ms` the read-view states when the document states none.
214
- *
215
- * One frame at 30fps. A document legitimately has no such fact (display
216
- * granularity is the editor's, not the timeline's), but the read-view IDL marks
217
- * the field `@required`, so the projection has to name a value. This one is a
218
- * usable granularity; `0` — which a downstream consumer had been defaulting to —
219
- * is not, and passes any `>= 0` guard on its way to an editor that cannot use it.
220
- */
221
- const DEFAULT_UNIT_TIME_MS = 33.333;
222
- //#endregion
223
- //#region src/timeline-core/types.ts
224
- /** Total document duration when there is no real content (matches FE bgm fallback). */
225
- const TIMELINE_SKELETON_DURATION_MS = 2e4;
226
- /** Empty placeholder clip marker: a video_clip part with no backing media. */
227
- function isEmptyVideoClip(part) {
228
- const clip = part?.video_clip;
229
- if (clip == null) return false;
230
- return clip.origin_media_id == null || clip.origin_media_id === "";
231
- }
232
- /** Clamp a duration to a non-negative integer (NaN/Infinity/negative → 0). */
233
- function safeDurationMs(value) {
234
- const n = Number(value);
235
- if (!Number.isFinite(n) || n <= 0) return 0;
236
- return Math.round(n);
237
- }
238
- function partDurationMs(doc, partId) {
239
- const part = doc.part_library[partId];
240
- if (part?.video_clip != null) return safeDurationMs(effectiveVideoClipDurationMs(part.video_clip));
241
- if (part?.bgm != null) return doc.timeline.duration_ms > 0 ? doc.timeline.duration_ms : TIMELINE_SKELETON_DURATION_MS;
242
- if (part?.speech != null) return safeDurationMs(part.speech.media_duration_ms);
243
- if (part?.caption != null) return safeDurationMs(part.caption.initial_duration_ms);
244
- return 0;
245
- }
246
- //#endregion
247
- //#region src/timeline-core/cascade.ts
248
- /**
249
- * Canonical timeline cascade primitives (ADR 0009).
250
- *
251
- * Single source of truth for "how an edit's connected regions move": main-track
252
- * seamless layout, aggregation position sync + reassignment, total-duration
253
- * recompute, speech-overlap resolution, gap filling. Reconciled per ADR 0009 §4:
254
- *
255
- * - product behavior follows the FE current implementation;
256
- * - all times are integer ms — positions/durations are rounded, never floated;
257
- * - function decomposition follows agent-harness (the Python-derived structure).
258
- *
259
- * Every function mutates the `TimelineDoc` in place (the editor runs them inside
260
- * one immer `transact`, so in-place edits diff correctly).
261
- */
262
- /**
263
- * Lay the main track out head-to-tail from 0, rewriting each item's
264
- * `abs_time_position`. Items whose part is missing from the library are dropped.
265
- */
266
- function arrangeMainTrackSeamlessly(doc) {
267
- const kept = [];
268
- let cursor = 0;
269
- for (const item of doc.main_track) {
270
- if (doc.part_library[item.part_id] == null) continue;
271
- item.abs_time_position = cursor;
272
- cursor += partDurationMs(doc, item.part_id);
273
- kept.push(item);
274
- }
275
- doc.main_track = kept;
276
- }
277
- /**
278
- * Sync attached parts' absolute positions from their host:
279
- * speech.abs = host_video.abs + relative_time_position
280
- * caption.abs = speech.abs + caption.start_ms
281
- */
282
- function syncAggregatedClipsTimePosition(doc) {
283
- const videoByPart = indexByPart(doc.main_track);
284
- const speechByPart = indexByPart(doc.speech_track);
285
- for (const aggregation of doc.aggregations) {
286
- const videoItem = videoByPart.get(aggregation.body_part_id);
287
- if (videoItem == null) continue;
288
- for (const attachment of aggregation.attachments) {
289
- const speechItem = speechByPart.get(attachment.part_id);
290
- if (speechItem == null) continue;
291
- speechItem.abs_time_position = videoItem.abs_time_position + attachment.relative_time_position;
292
- }
293
- }
294
- for (const captionItem of doc.caption_track) {
295
- const captionPart = doc.part_library[captionItem.part_id]?.caption;
296
- if (captionPart == null) continue;
297
- const speechItem = captionPart.speech_part_id == null ? void 0 : speechByPart.get(captionPart.speech_part_id);
298
- if (speechItem == null) continue;
299
- captionItem.abs_time_position = speechItem.abs_time_position + safeDurationMs(captionPart.start_ms);
300
- }
301
- }
302
- /**
303
- * Reassign each speech to the video clip whose time range contains its start,
304
- * rebuilding `aggregations`. A speech before the first clip or after the last
305
- * falls back to the first / last clip respectively (FE: see §4 note — FE falls
306
- * back to last only; we keep the harness two-sided fallback because a speech
307
- * dragged before clip 0 belonging to the last clip is clearly wrong, and the FE
308
- * single-sided rule is an acknowledged rough edge). `relative_time_position` is
309
- * clamped to a non-negative integer.
310
- */
311
- function reassignSpeechesToVideoClipsByTime(doc) {
312
- const ranges = doc.main_track.filter((item) => doc.part_library[item.part_id] != null).map((item) => ({
313
- part_id: item.part_id,
314
- start: item.abs_time_position,
315
- end: item.abs_time_position + partDurationMs(doc, item.part_id)
316
- }));
317
- if (ranges.length === 0) {
318
- doc.aggregations = [];
319
- return;
320
- }
321
- const rebuilt = /* @__PURE__ */ new Map();
322
- for (const speechItem of doc.speech_track) {
323
- const start = speechItem.abs_time_position;
324
- const targetRange = ranges.find((r) => r.start <= start && start < r.end) ?? (start < ranges[0].start ? ranges[0] : ranges[ranges.length - 1]);
325
- const relative = Math.max(0, Math.round(start - targetRange.start));
326
- const targetId = targetRange.part_id;
327
- let aggregation = rebuilt.get(targetId);
328
- if (aggregation == null) {
329
- aggregation = {
330
- body_part_id: targetId,
331
- attachments: []
332
- };
333
- rebuilt.set(targetId, aggregation);
334
- }
335
- aggregation.attachments.push({
336
- part_id: speechItem.part_id,
337
- relative_time_position: relative
338
- });
339
- }
340
- doc.aggregations = ranges.map((r) => rebuilt.get(r.part_id)).filter((a) => a != null);
341
- }
342
- /**
343
- * Recompute `timeline.duration_ms` as the max end (abs + duration) across main,
344
- * speech, and caption lanes (BGM does not extend the timeline).
345
- *
346
- * BGM has no authoritative duration (RFC 02 / `reference/16` §0b): its effective
347
- * length is always the timeline total, so it is not written back here — the
348
- * projection derives it from `timeline.duration_ms` on read (`partDurationMs`
349
- * returns the timeline total for a bgm part). The empty-document 20s skeleton is
350
- * applied at that read step, not stored.
351
- */
352
- function recalculateTimelineDuration(doc) {
353
- const max = Math.max(laneEndMs(doc, doc.main_track), laneEndMs(doc, doc.speech_track), laneEndMs(doc, doc.caption_track));
354
- doc.timeline.duration_ms = max;
355
- }
356
- /**
357
- * Resolve one speech overlap by shifting the overlapping speech's host video
358
- * (and every clip after it) right. Returns true when one overlap was resolved;
359
- * callers loop until it returns false. The compared range is the speech merged
360
- * with its captions: start = min(speech.start, captions.start) (FE behavior),
361
- * end = max(speech.end, captions.end).
362
- */
363
- function resolveSpeechOverlapByShiftingVideos(doc) {
364
- const speeches = doc.speech_track;
365
- for (let i = 1; i < speeches.length; i++) {
366
- const prev = speechWithCaptionsRange(doc, speeches[i - 1]);
367
- const curr = speechWithCaptionsRange(doc, speeches[i]);
368
- if (prev == null || curr == null) continue;
369
- if (curr.start >= prev.end) continue;
370
- const overlapMs = Math.round(prev.end - curr.start);
371
- const hostId = hostVideoOf(doc, speeches[i].part_id);
372
- if (hostId == null) continue;
373
- const fromIndex = doc.main_track.findIndex((item) => item.part_id === hostId);
374
- if (fromIndex < 0) continue;
375
- for (let idx = fromIndex; idx < doc.main_track.length; idx++) doc.main_track[idx].abs_time_position += overlapMs;
376
- syncAggregatedClipsTimePosition(doc);
377
- return true;
378
- }
379
- return false;
380
- }
381
- /**
382
- * Resolve speech overlaps for one cascade pass. Mirrors the authoritative FE
383
- * `ensureNoOverlappingClips`, which is documented to resolve AT MOST ONE overlap
384
- * per cascade and is invoked exactly once at every FE call site — the supported
385
- * ops each produce at most one new overlap. It is NOT a fixpoint loop: shifting a
386
- * host right also moves every speech anchored to it, so two speeches sharing a
387
- * host can never be separated by shifting. Looping to a "fixed point" there does
388
- * not converge — it accumulates the same overlap every iteration and pushes the
389
- * clip arbitrarily far right (e.g. a sped-up clip landing at ~287k ms instead of
390
- * its seamless slot). A single pass matches FE product behavior and terminates.
391
- */
392
- function resolveAllSpeechOverlaps(doc) {
393
- resolveSpeechOverlapByShiftingVideos(doc);
394
- }
395
- /**
396
- * Make the main track gapless by adjusting/merging empty placeholder clips or
397
- * inserting new ones between real clips. Mirrors the harness four-case rule, but
398
- * the merge of two adjacent empty clips keeps the earlier clip (harness Case 4).
399
- * Requires `makeEmptyPart` to mint a placeholder part (the editor supplies an
400
- * id generator).
401
- */
402
- function fillMainTrackTimeGaps(doc, makeEmptyPart) {
403
- const items = doc.main_track;
404
- let i = 0;
405
- while (i < items.length) {
406
- const current = items[i];
407
- const currentPart = doc.part_library[current.part_id];
408
- if (currentPart == null) {
409
- i += 1;
410
- continue;
411
- }
412
- const currentEnd = current.abs_time_position + partDurationMs(doc, current.part_id);
413
- if (i + 1 >= items.length) break;
414
- const next = items[i + 1];
415
- const nextPart = doc.part_library[next.part_id];
416
- if (nextPart == null) {
417
- i += 1;
418
- continue;
419
- }
420
- const gap = next.abs_time_position - currentEnd;
421
- if (gap > 0) {
422
- if (isEmptyVideoClip(currentPart)) {
423
- extendEmptyClip(currentPart.video_clip, gap);
424
- continue;
425
- }
426
- if (isEmptyVideoClip(nextPart)) {
427
- next.abs_time_position -= gap;
428
- extendEmptyClip(nextPart.video_clip, gap);
429
- i += 1;
430
- continue;
431
- }
432
- const { partId } = makeEmptyPart(gap);
433
- doc.part_library[partId] = { video_clip: {
434
- id: partId,
435
- kind: "video_clip",
436
- play_in: 0,
437
- play_out: gap,
438
- volume: 0,
439
- origin_media_id: ""
440
- } };
441
- items.splice(i + 1, 0, {
442
- part_id: partId,
443
- time_position: { mode: "sequential" },
444
- abs_time_position: currentEnd
445
- });
446
- i += 1;
447
- continue;
448
- }
449
- if (gap === 0 && isEmptyVideoClip(currentPart) && isEmptyVideoClip(nextPart)) {
450
- extendEmptyClip(currentPart.video_clip, partDurationMs(doc, next.part_id));
451
- items.splice(i + 1, 1);
452
- delete doc.part_library[next.part_id];
453
- continue;
454
- }
455
- i += 1;
456
- }
457
- }
458
- function indexByPart(items) {
459
- const map = /* @__PURE__ */ new Map();
460
- for (const item of items) map.set(item.part_id, item);
461
- return map;
462
- }
463
- function laneEndMs(doc, items) {
464
- let max = 0;
465
- for (const item of items) {
466
- if (doc.part_library[item.part_id] == null) continue;
467
- const end = item.abs_time_position + partDurationMs(doc, item.part_id);
468
- if (end > max) max = end;
469
- }
470
- return max;
471
- }
472
- function extendEmptyClip(clip, byMs) {
473
- clip.play_out = safeDurationMs(clip.play_out) + byMs;
474
- }
475
- /** speech merged with its captions: start = min, end = max. */
476
- function speechWithCaptionsRange(doc, speechItem) {
477
- const speech = doc.part_library[speechItem.part_id]?.speech;
478
- if (speech == null) return null;
479
- let start = speechItem.abs_time_position;
480
- let end = speechItem.abs_time_position + safeDurationMs(speech.media_duration_ms);
481
- for (const captionId of captionIdsOf(speech)) {
482
- const captionItem = doc.caption_track.find((item) => item.part_id === captionId);
483
- const captionPart = doc.part_library[captionId]?.caption;
484
- if (captionItem == null || captionPart == null) continue;
485
- const cStart = captionItem.abs_time_position;
486
- const cEnd = captionItem.abs_time_position + safeDurationMs(captionPart.initial_duration_ms);
487
- if (cStart < start) start = cStart;
488
- if (cEnd > end) end = cEnd;
489
- }
490
- return {
491
- start,
492
- end
493
- };
494
- }
495
- function captionIdsOf(speech) {
496
- return (speech.caption_ids ?? []).filter((id) => id != null);
497
- }
498
- function hostVideoOf(doc, speechPartId) {
499
- for (const aggregation of doc.aggregations) if (aggregation.attachments.some((att) => att.part_id === speechPartId)) return aggregation.body_part_id;
500
- return null;
501
- }
502
- //#endregion
503
- //#region src/timeline-core/entrypoints.ts
504
- /**
505
- * The full solve pipeline: arrange → sync → reassign → resolve-overlap →
506
- * fill-gaps → recalc. The single cascade the read-side projection runs; ops
507
- * never call it (they write only facts — RFC 02 §7/§10).
508
- */
509
- function cascadeAfterVideoClipChanges(doc, makeEmptyPart) {
510
- arrangeMainTrackSeamlessly(doc);
511
- syncAggregatedClipsTimePosition(doc);
512
- reassignSpeechesToVideoClipsByTime(doc);
513
- resolveAllSpeechOverlaps(doc);
514
- fillMainTrackTimeGaps(doc, makeEmptyPart);
515
- recalculateTimelineDuration(doc);
516
- }
517
- //#endregion
518
- //#region src/timeline-core/bridge.ts
519
- /**
520
- * Solve a `VideoDocument` (authoritative, position-only) into its derived
521
- * read-view: absolute time per item, `part_aggregations`, and total duration.
522
- * This is the read side of the single-directional flow — never written back.
523
- */
524
- function solveVideoDocument(document) {
525
- const doc = videoDocumentToTimelineDoc(document);
526
- let counter = 0;
527
- const derivedFillerPartIds = /* @__PURE__ */ new Set();
528
- cascadeAfterVideoClipChanges(doc, () => {
529
- const partId = `empty_${counter++}`;
530
- derivedFillerPartIds.add(partId);
531
- return { partId };
532
- });
533
- const absByPartId = /* @__PURE__ */ new Map();
534
- for (const item of doc.main_track) absByPartId.set(item.part_id, item.abs_time_position);
535
- for (const item of doc.speech_track) absByPartId.set(item.part_id, item.abs_time_position);
536
- for (const item of doc.caption_track) absByPartId.set(item.part_id, item.abs_time_position);
537
- for (const item of doc.bgm_track) absByPartId.set(item.part_id, item.abs_time_position);
538
- return {
539
- absByPartId,
540
- aggregations: doc.aggregations.map((aggregation) => ({
541
- body_part_id: aggregation.body_part_id,
542
- attachments: aggregation.attachments.map((a) => ({
543
- part_id: a.part_id,
544
- relative_time_position: a.relative_time_position
545
- }))
546
- })),
547
- durationMs: doc.timeline.duration_ms,
548
- partLibrary: doc.part_library,
549
- derivedFillerPartIds
550
- };
551
- }
552
- function videoDocumentToTimelineDoc(document) {
553
- const partLibrary = {};
554
- for (const [partId, part] of Object.entries(document.part_library ?? {})) partLibrary[partId] = part;
555
- const laneItems = (track) => (track?.items ?? []).map((item) => ({
556
- part_id: item.part_id,
557
- time_position: item.time_position,
558
- abs_time_position: seedAbs(item.time_position, item.fallback_abs_ms),
559
- fallback_abs_ms: item.fallback_abs_ms
560
- }));
561
- const tracks = document.tracks ?? [];
562
- let mainItems = [];
563
- let speechItems = [];
564
- let bgmItems = [];
565
- let captionItems = [];
566
- for (const t of tracks) switch (t.parts_kind) {
567
- case "video_clip":
568
- mainItems = mainItems.concat(laneItems(t));
569
- break;
570
- case "speech":
571
- speechItems = speechItems.concat(laneItems(t));
572
- break;
573
- case "bgm":
574
- bgmItems = bgmItems.concat(laneItems(t));
575
- break;
576
- case "caption":
577
- captionItems = captionItems.concat(laneItems(t));
578
- break;
579
- }
580
- return {
581
- main_track: mainItems,
582
- speech_track: speechItems,
583
- caption_track: captionItems,
584
- bgm_track: bgmItems,
585
- part_library: partLibrary,
586
- aggregations: seedAggregations(mainItems, speechItems),
587
- timeline: {
588
- duration_ms: 0,
589
- unit_time_ms: document.timeline?.unit_time_ms ?? 0
590
- }
591
- };
592
- }
593
- /**
594
- * Seed an item's solve-variable `abs_time_position` from its `time_position` (and
595
- * the `fallback_abs_ms` snapshot carried beside it): `absolute` → `offsetMs`;
596
- * `anchored` → `fallbackAbsMs` (last solved position, also the orphan-recovery
597
- * anchor when the host is gone); `sequential` → 0 (the cascade lays the main
598
- * track out head-to-tail). The cascade then resolves anchored items against their
599
- * host, so this seed only needs to put each item somewhere plausible for the
600
- * first reassign/overlap pass.
601
- */
602
- function seedAbs(position, fallbackAbsMs) {
603
- switch (position.mode) {
604
- case "absolute": return Math.round(position.offsetMs);
605
- case "anchored": return Math.round(fallbackAbsMs ?? 0);
606
- case "sequential": return 0;
607
- }
608
- }
609
- /**
610
- * Build the cascade `aggregations` parent-map from anchored items: an anchored
611
- * item's `anchorPartId` is the host's `part_id` (= `body_part_id`), `offsetMs`
612
- * is `relative_time_position`. Only main-track (video) hosts form aggregations;
613
- * caption→speech relations are recomputed by the cascade from `caption.start_ms`.
614
- */
615
- function seedAggregations(mainItems, speechItems) {
616
- const mainPartIds = new Set(mainItems.map((item) => item.part_id));
617
- const byHost = /* @__PURE__ */ new Map();
618
- const order = [];
619
- for (const speech of speechItems) {
620
- if (speech.time_position.mode !== "anchored") continue;
621
- const host = speech.time_position.anchorPartId;
622
- if (!mainPartIds.has(host)) continue;
623
- let aggregation = byHost.get(host);
624
- if (aggregation == null) {
625
- aggregation = {
626
- body_part_id: host,
627
- attachments: []
628
- };
629
- byHost.set(host, aggregation);
630
- order.push(host);
631
- }
632
- aggregation.attachments.push({
633
- part_id: speech.part_id,
634
- relative_time_position: speech.time_position.offsetMs
635
- });
636
- }
637
- return order.map((host) => byHost.get(host));
638
- }
639
- /**
640
- * The four lanes in top-to-bottom stack order — the order a `tracks` list holds
641
- * them in (see {@link laneRank}).
642
- *
643
- * Exported so a document can be seeded with all four lanes up front. That seed is
644
- * not cosmetic: {@link ensureLaneTrack} is find-then-mint over a `LoroMovableList`,
645
- * so two concurrent writers that each mint the same absent lane both keep their
646
- * row, and the merged document holds two tracks for one lane. For the main lane
647
- * that is fatal — `videoDocumentSchema` allows at most one `video_clip` track, so
648
- * the merged document stops being projectable at all, symmetrically on both
649
- * replicas. Pre-seeding every lane makes `ensureLaneTrack` always take its find
650
- * branch, which removes the race by construction rather than by detection.
651
- *
652
- * What closes the race is that a track with the lane's `parts_kind` EXISTS — the
653
- * lookup is by kind, not by id. So a seed is only safe if it covers every lane:
654
- * a partial seed leaves the uncovered lanes exactly as exposed as before.
655
- */
656
- const LANE_KINDS_IN_STACK_ORDER = [
657
- "caption",
658
- "video_clip",
659
- "speech",
660
- "bgm"
661
- ];
662
- /**
663
- * The conventional track id for a lane (`main_track`, `<kind>_track`). Shared by
664
- * the up-front seed and {@link ensureLaneTrack}'s lazy mint so a document's lane
665
- * ids do not depend on which of the two created the track.
666
- *
667
- * Ids are cosmetic to the merge itself — lane lookup goes by `parts_kind`, so
668
- * drifting them apart would not reopen the concurrent-mint race. They matter to
669
- * readers that address a lane by id (the FE editor's panes, fixtures), which is
670
- * why there is one convention rather than two.
671
- */
672
- function laneTrackId(kind) {
673
- return kind === "video_clip" ? "main_track" : `${kind}_track`;
674
- }
675
- /**
676
- * Lane-stacking rank for the single `tracks` list (reference/17 §4): caption
677
- * (above) sits before the video_clip main track, which sits before speech / bgm
678
- * (below). The `tracks` array is kept in this top-to-bottom order so a freshly
679
- * minted track lands in the right place and the projection's three-pane rebuild
680
- * stays deterministic.
681
- */
682
- function laneRank(kind) {
683
- switch (kind) {
684
- case "caption": return 0;
685
- case "video_clip": return 1;
686
- case "speech":
687
- case "bgm": return 2;
688
- default: return 3;
689
- }
690
- }
691
- /**
692
- * Insert a freshly-minted track into `tracks` at the position that keeps the
693
- * lane-stacking order (caption → main → speech/bgm). Inserts before the first
694
- * track whose rank is strictly greater, so same-rank tracks keep insertion order.
695
- */
696
- function insertTrackByLaneOrder(tracks, track) {
697
- const rank = laneRank(track.parts_kind);
698
- const at = tracks.findIndex((t) => laneRank(t?.parts_kind) > rank);
699
- if (at < 0) tracks.push(track);
700
- else tracks.splice(at, 0, track);
701
- }
702
- /**
703
- * Locate a lane's track row in the single `tracks` list by kind, minting an empty
704
- * row in lane-stacking order if absent (reference/17 §4: lane = `parts_kind`).
705
- * Ops use this to write authoritative items onto the right lane. The track id
706
- * comes from {@link laneTrackId}, shared with the up-front seed.
707
- *
708
- * The mint branch is a concurrency hazard, not a convenience: see
709
- * {@link LANE_KINDS_IN_STACK_ORDER}. A document seeded with all four lanes never
710
- * reaches it.
711
- */
712
- function ensureLaneTrack(draft, kind) {
713
- draft.tracks ??= [];
714
- let track = draft.tracks.find((t) => t?.parts_kind === kind);
715
- if (track == null) {
716
- track = {
717
- id: laneTrackId(kind),
718
- parts_kind: kind,
719
- is_hidden: void 0,
720
- items: []
721
- };
722
- insertTrackByLaneOrder(draft.tracks, track);
723
- }
724
- track.items ??= [];
725
- return track;
726
- }
727
- /** Find a secondary lane's track row without minting it. */
728
- function findLaneTrack(draft, kind) {
729
- return (draft.tracks ?? []).find((t) => t?.parts_kind === kind);
730
- }
731
- //#endregion
732
- //#region src/document/zod-schema.ts
733
- const partKindSchema = z.enum([
734
- "video_clip",
735
- "speech",
736
- "caption",
737
- "bgm"
738
- ]);
739
- const finiteNumber = z.number().finite();
740
- const trackItemTimePositionSchema = z.discriminatedUnion("mode", [
741
- z.object({ mode: z.literal("sequential") }).passthrough(),
742
- z.object({
743
- mode: z.literal("anchored"),
744
- anchorPartId: z.string(),
745
- offsetMs: finiteNumber
746
- }).passthrough(),
747
- z.object({
748
- mode: z.literal("absolute"),
749
- offsetMs: finiteNumber
750
- }).passthrough()
751
- ]);
752
- const trackItemSchema = z.object({
753
- part_id: z.string(),
754
- time_position: trackItemTimePositionSchema,
755
- fallback_abs_ms: finiteNumber.optional()
756
- }).passthrough();
757
- const trackSchema = z.object({
758
- id: z.string().optional(),
759
- parts_kind: partKindSchema.optional(),
760
- is_hidden: z.boolean().optional(),
761
- items: z.array(trackItemSchema).optional()
762
- }).passthrough();
763
- const speedShiftSchema = z.object({
764
- category: z.string().optional(),
765
- mode: z.string().optional(),
766
- config: z.object({ linear: z.object({ speed: finiteNumber.optional() }).passthrough().optional() }).passthrough().optional()
767
- }).passthrough();
768
- const videoClipPartSchema = z.object({
769
- id: z.string().optional(),
770
- kind: z.literal("video_clip"),
771
- duration_ms: finiteNumber.optional(),
772
- play_in: finiteNumber,
773
- play_out: finiteNumber,
774
- volume: finiteNumber,
775
- origin_media_id: z.string(),
776
- speed_shift: speedShiftSchema.optional()
777
- }).passthrough();
778
- const speechPartSchema = z.object({
779
- id: z.string().optional(),
780
- kind: z.literal("speech"),
781
- media_duration_ms: finiteNumber,
782
- duration_ms: finiteNumber.optional(),
783
- audio_script: z.string(),
784
- volume: finiteNumber,
785
- audio_storage_key: z.string(),
786
- origin_speech_id: z.string(),
787
- voice: z.unknown(),
788
- caption_ids: z.array(z.string())
789
- }).passthrough();
790
- const captionPartSchema = z.object({
791
- id: z.string().optional(),
792
- kind: z.literal("caption"),
793
- initial_duration_ms: finiteNumber,
794
- speech_part_id: z.string(),
795
- text: z.string(),
796
- start_ms: finiteNumber,
797
- style: z.object({
798
- font_id: z.string().optional(),
799
- font_size: finiteNumber.optional(),
800
- font_color: z.string().optional(),
801
- font_weight: finiteNumber.optional(),
802
- entrance_animation: z.string().optional(),
803
- entrance_animation_duration_ms: finiteNumber.optional(),
804
- stroke_color: z.string().optional(),
805
- stroke_width: finiteNumber.optional(),
806
- position_x: finiteNumber.optional(),
807
- position_y: finiteNumber.optional()
808
- }).passthrough().optional()
809
- }).passthrough();
810
- const bgmPartSchema = z.object({
811
- id: z.string().optional(),
812
- kind: z.literal("bgm"),
813
- audio_storage_key: z.string(),
814
- volume: finiteNumber,
815
- origin_media_id: z.string()
816
- }).passthrough();
817
- const partUnionSchema = z.union([
818
- z.object({ video_clip: videoClipPartSchema }).passthrough(),
819
- z.object({ speech: speechPartSchema }).passthrough(),
820
- z.object({ caption: captionPartSchema }).passthrough(),
821
- z.object({ bgm: bgmPartSchema }).passthrough()
822
- ]).refine((part) => {
823
- const p = part;
824
- return [
825
- "video_clip",
826
- "speech",
827
- "caption",
828
- "bgm"
829
- ].filter((k) => p[k] != null).length === 1;
830
- }, { message: "A part_library value must have exactly one of video_clip / speech / caption / bgm" });
831
- const videoDocumentSchema = z.object({
832
- timeline: z.object({ unit_time_ms: finiteNumber.optional() }).passthrough().optional(),
833
- tracks: z.array(trackSchema).optional(),
834
- part_library: z.record(z.string(), partUnionSchema).optional()
835
- }).passthrough().refine((doc) => (doc.tracks ?? []).filter((t) => t.parts_kind === "video_clip").length <= 1, {
836
- message: "A VideoDocument may have at most one video_clip (main) track",
837
- path: ["tracks"]
838
- });
839
- //#endregion
840
- //#region src/document/validation.ts
841
- /**
842
- * Business-level schema guard for `VideoDocument` (RFC 03 §9). It is the gate
843
- * that decides whether an arbitrary value is a *legal* `VideoDocument` before it
844
- * is written into Loro — distinct from two neighbours:
845
- *
846
- * - `zod-schema.ts` (`videoDocumentSchema`) checks structure/shape only; this
847
- * file layers the business rules on top (part-kind match, reference integrity,
848
- * `position.anchorPartId` targets, value ranges, identity uniqueness).
849
- * - loro-mirror's own `validateSchema` (run on every `setState`) only checks the
850
- * storage structure, never these business invariants.
851
- *
852
- * Projection (`projection.ts`) calls `assertValidVideoDocument` before solving a
853
- * document into the legacy `VideoDraft`.
854
- */
855
- var VideoDocumentValidationError = class extends Error {
856
- issues;
857
- constructor(issues) {
858
- super(`Invalid VideoDocument: ${issues.map((issue) => issue.message).join("; ")}`);
859
- this.issues = issues;
860
- this.name = "VideoDocumentValidationError";
861
- }
862
- };
863
- /**
864
- * Assert the document is legal enough to project. Only `error`-severity issues
865
- * hard-reject; `recoverable` ones (dangling anchor / orphan, RFC 02 §11.1) are
866
- * left for the projection to heal on read and do NOT throw. Use
867
- * `validateVideoDocument` directly to inspect recoverable issues too.
868
- */
869
- function assertValidVideoDocument(document) {
870
- const blocking = validateVideoDocument(document).filter((issue) => (issue.severity ?? "error") === "error");
871
- if (blocking.length > 0) throw new VideoDocumentValidationError(blocking);
872
- }
873
- function validateVideoDocument(document) {
874
- const parsed = videoDocumentSchema.safeParse(document);
875
- if (!parsed.success) return parsed.error.issues.map((issue) => ({
876
- code: "invalid_schema",
877
- path: zodPath(issue.path),
878
- message: issue.message
879
- }));
880
- const doc = parsed.data;
881
- const issues = [];
882
- const partLibrary = doc.part_library ?? {};
883
- for (const [partId, part] of Object.entries(partLibrary)) {
884
- if (!partUnionSchema.safeParse(part).success) {
885
- issues.push({
886
- code: "unknown_part_kind",
887
- path: `/part_library/${partId}`,
888
- message: `Part "${partId}" is not a supported part union`
889
- });
890
- continue;
891
- }
892
- const wrapperKind = getPartUnionKind(part);
893
- const innerKind = getPartKind(part);
894
- if (wrapperKind != null && innerKind != null && wrapperKind !== innerKind) issues.push({
895
- code: "part_kind_mismatch",
896
- path: `/part_library/${partId}`,
897
- message: `Part "${partId}" wrapper kind "${wrapperKind}" does not match inner kind "${innerKind}"`
898
- });
899
- validatePartValues(partId, part, issues);
900
- }
901
- for (const [idx, track] of (doc.tracks ?? []).entries()) validateTrack(track, `tracks/${idx}`, partLibrary, issues, track.parts_kind === "video_clip");
902
- validateLaneTrackUniqueness(doc, issues);
903
- validateSpeechCaptionReferences(partLibrary, issues);
904
- validatePositionReferences(doc, partLibrary, issues);
905
- return issues;
906
- }
907
- /**
908
- * Report a duplicated lane: two tracks sharing the same `id`, or two secondary
909
- * tracks of the same `parts_kind`.
910
- *
911
- * Found by the Phase 6 M0/S2 concurrency probe. `ensureLaneTrack` locates a lane
912
- * by `parts_kind` and mints `<kind>_track` when absent, so two replicas that both
913
- * start without (say) a caption track each create one; `tracks` is a
914
- * `LoroMovableList`, so the merge keeps BOTH. The lane is then split across two
915
- * same-id tracks, and the projection's `find`-by-kind returns only one of them —
916
- * so an item can be authoritative yet invisible in the pane a reader looks at.
917
- *
918
- * Flagged **recoverable**, not `error`, for two reasons. It is a reachable
919
- * outcome of ordinary concurrent editing, and hard-rejecting would make an
920
- * unavoidable merge result un-projectable — the same argument §11.1 makes for
921
- * orphans. And the projection already tolerates it: `solveVideoDocument`
922
- * concatenates every track of a kind, so the cascade sees all items regardless.
923
- * The defect is a *reader-visible* split, so the right response is to surface it
924
- * (loudly, in a channel someone reads), not to block the document.
925
- *
926
- * The main track is exempt from the kind check: `parts_kind === 'video_clip'` may
927
- * legitimately appear on several tracks (the projection treats only the first as
928
- * the main pane), so only its `id` collision is reported.
929
- */
930
- function validateLaneTrackUniqueness(doc, issues) {
931
- const tracks = doc.tracks ?? [];
932
- const seenIds = /* @__PURE__ */ new Set();
933
- const seenSecondaryKinds = /* @__PURE__ */ new Set();
934
- for (const [idx, track] of tracks.entries()) {
935
- const id = track?.id;
936
- if (id != null && id !== "") if (seenIds.has(id)) issues.push({
937
- code: "duplicate_lane_track",
938
- path: `/tracks/${idx}/id`,
939
- message: `Track "tracks/${idx}" reuses track id "${id}"`,
940
- severity: "recoverable"
941
- });
942
- else seenIds.add(id);
943
- const kind = track?.parts_kind;
944
- if (kind == null || kind === "video_clip") continue;
945
- if (seenSecondaryKinds.has(kind)) issues.push({
946
- code: "duplicate_lane_track",
947
- path: `/tracks/${idx}/parts_kind`,
948
- message: `Lane "${kind}" is split across more than one track (at "tracks/${idx}")`,
949
- severity: "recoverable"
950
- });
951
- else seenSecondaryKinds.add(kind);
952
- }
953
- }
954
- /**
955
- * An `anchored` item whose `anchorPartId` no longer exists in the library is the
956
- * orphan condition (RFC 02 §4/§11.1) — e.g. a speech whose host video, or a
957
- * caption whose host speech, was concurrently deleted while this item was being
958
- * reparented in. This is flagged as a **recoverable** issue, NOT a hard error:
959
- * the projection heals it on read (the item's `fallback_abs_ms` snapshot seeds
960
- * its absolute position, then the cascade reassigns it to the nearest available
961
- * host, or it stays put as an absolute item). Reporting it here keeps the orphan
962
- * observable without blocking projection — the opposite of a hard reject, which
963
- * would make an inevitable concurrent-delete outcome un-projectable (§11.1).
964
- */
965
- function validatePositionReferences(doc, partLibrary, issues) {
966
- const tracks = (doc.tracks ?? []).map((track, idx) => ({
967
- track,
968
- path: `tracks/${idx}`
969
- }));
970
- for (const { track, path } of tracks) for (const [idx, item] of (track?.items ?? []).entries()) {
971
- if (item.time_position.mode !== "anchored") continue;
972
- if (partLibrary[item.time_position.anchorPartId] == null) issues.push({
973
- code: "invalid_position_anchor",
974
- path: `/${path}/items/${idx}/time_position/anchorPartId`,
975
- message: `Track item "${path}/${idx}" anchors to missing part "${item.time_position.anchorPartId}"`,
976
- severity: "recoverable"
977
- });
978
- }
979
- }
980
- function validatePartValues(partId, part, issues) {
981
- const payload = part.video_clip ?? part.speech ?? part.caption ?? part.bgm ?? void 0;
982
- if (payload == null) return;
983
- if ("duration_ms" in payload && payload.duration_ms != null && payload.duration_ms < 0) issues.push({
984
- code: "invalid_part_value",
985
- path: `/part_library/${partId}/duration_ms`,
986
- message: `Part "${partId}" has negative duration_ms`
987
- });
988
- if ("volume" in payload && payload.volume != null && !Number.isFinite(payload.volume)) issues.push({
989
- code: "invalid_part_value",
990
- path: `/part_library/${partId}/volume`,
991
- message: `Part "${partId}" has non-finite volume`
992
- });
993
- if (part.video_clip != null) {
994
- const { play_in, play_out } = part.video_clip;
995
- if (play_in != null && play_in < 0) issues.push({
996
- code: "invalid_part_value",
997
- path: `/part_library/${partId}/play_in`,
998
- message: `Video clip "${partId}" has negative play_in`
999
- });
1000
- if (play_out != null && play_in != null && play_out < play_in) issues.push({
1001
- code: "invalid_part_value",
1002
- path: `/part_library/${partId}/play_out`,
1003
- message: `Video clip "${partId}" has play_out before play_in`
1004
- });
1005
- }
1006
- }
1007
- function validateTrack(track, path, partLibrary, issues, isMainTrack) {
1008
- if (track == null) return;
1009
- const seenPartIds = /* @__PURE__ */ new Set();
1010
- for (const [idx, item] of (track.items ?? []).entries()) {
1011
- const partId = item.part_id;
1012
- if (partId != null && partId !== "") if (seenPartIds.has(partId)) issues.push({
1013
- code: "duplicate_track_item_identity",
1014
- path: `/${path}/items/${idx}/part_id`,
1015
- message: `Track item "${path}/${idx}" reuses part_id "${partId}"`
1016
- });
1017
- else seenPartIds.add(partId);
1018
- if (partId == null || partId === "") {
1019
- issues.push({
1020
- code: "missing_part_reference",
1021
- path: `/${path}/items/${idx}/part_id`,
1022
- message: `Track item "${path}/${idx}" has no part_id`
1023
- });
1024
- continue;
1025
- }
1026
- const part = partLibrary[partId];
1027
- if (part == null) {
1028
- issues.push({
1029
- code: "missing_part_reference",
1030
- path: `/${path}/items/${idx}/part_id`,
1031
- message: `Track item "${path}/${idx}" references missing part "${partId}"`
1032
- });
1033
- continue;
1034
- }
1035
- const partKind = getPartKind(part);
1036
- if (isMainTrack && partKind !== "video_clip") issues.push({
1037
- code: "main_track_non_video_clip",
1038
- path: `/${path}/items/${idx}/part_id`,
1039
- message: `Main track item "${path}/${idx}" references non-video part "${partId}"`
1040
- });
1041
- if (track.parts_kind != null && partKind != null && track.parts_kind !== partKind) issues.push({
1042
- code: "track_kind_mismatch",
1043
- path: `/${path}/items/${idx}/part_id`,
1044
- message: `Track "${path}" expects "${track.parts_kind}" but part "${partId}" is "${partKind}"`
1045
- });
1046
- }
1047
- }
1048
- /**
1049
- * Check speech↔caption references. A reference to a *missing* part (speech's
1050
- * caption_ids → deleted caption, or caption's speech_part_id → deleted speech)
1051
- * is the orphan condition (RFC 02 §11.1): reported as **recoverable** so the
1052
- * projection can heal it on read, not block. A *back-pointer mismatch* (caption
1053
- * exists but does not point back) is data corruption, kept as a hard error.
1054
- */
1055
- function validateSpeechCaptionReferences(partLibrary, issues) {
1056
- for (const [partId, part] of Object.entries(partLibrary)) {
1057
- if (part.speech != null) for (const captionId of part.speech.caption_ids ?? []) {
1058
- const caption = partLibrary[captionId]?.caption;
1059
- if (caption == null) {
1060
- issues.push({
1061
- code: "invalid_speech_caption_reference",
1062
- path: `/part_library/${partId}/speech/caption_ids`,
1063
- message: `Speech "${partId}" references missing caption "${captionId}"`,
1064
- severity: "recoverable"
1065
- });
1066
- continue;
1067
- }
1068
- if (caption.speech_part_id !== partId) issues.push({
1069
- code: "invalid_speech_caption_reference",
1070
- path: `/part_library/${captionId}/caption/speech_part_id`,
1071
- message: `Caption "${captionId}" does not point back to speech "${partId}"`
1072
- });
1073
- }
1074
- if (part.caption != null) {
1075
- const speechId = part.caption.speech_part_id;
1076
- if (speechId != null && partLibrary[speechId]?.speech == null) issues.push({
1077
- code: "invalid_speech_caption_reference",
1078
- path: `/part_library/${partId}/caption/speech_part_id`,
1079
- message: `Caption "${partId}" references missing speech "${speechId}"`,
1080
- severity: "recoverable"
1081
- });
1082
- }
1083
- }
1084
- }
1085
- function getPartUnionKind(part) {
1086
- if (part.video_clip != null) return "video_clip";
1087
- if (part.speech != null) return "speech";
1088
- if (part.caption != null) return "caption";
1089
- if (part.bgm != null) return "bgm";
1090
- }
1091
- function getPartKind(part) {
1092
- return part.video_clip?.kind ?? part.speech?.kind ?? part.caption?.kind ?? part.bgm?.kind;
1093
- }
1094
- function zodPath(path) {
1095
- if (path.length === 0) return "/";
1096
- return `/${path.map(String).join("/")}`;
1097
- }
1098
- //#endregion
1099
- //#region src/document/projection.ts
1100
- /**
1101
- * Projection between authoritative `VideoDocument` and compatible content
1102
- * layouts (RFC 02 §5/§7). Both directions live here:
1103
- *
1104
- * - `toVideoDocument` ingests a `VideoDraft`, deriving each item's `position`
1105
- * from the legacy absolute layout + aggregations; derived values (abs time,
1106
- * `part_aggregations`, total duration) are dropped.
1107
- * - `fromVideoDocument` solves a `VideoDocument` into `VideoDraftContent` via the
1108
- * timeline-core cascade, re-deriving exactly those values.
1109
- *
1110
- * Business validation lives in `validation.ts`; `fromVideoDocument` asserts a
1111
- * valid document before solving.
1112
- */
1113
- /**
1114
- * Ingest the legacy `VideoDraft` into the authoritative `VideoDocument`,
1115
- * deriving each item's `time_position` from the legacy absolute layout +
1116
- * aggregations (RFC 02 §4/§5). Absolute time, `part_aggregations`, and total
1117
- * duration are dropped — they are re-derived by the projection.
1118
- */
1119
- function toVideoDocument(draft) {
1120
- const speechHost = buildSpeechHostMap(draft.part_aggregations);
1121
- const partLibrary = draft.part_library ?? {};
1122
- const toTrack = (track, isMain) => {
1123
- if (track == null) return void 0;
1124
- return {
1125
- id: track.id,
1126
- parts_kind: track.parts_kind,
1127
- is_hidden: track.is_hidden,
1128
- items: (track.items ?? []).map((item) => deriveItem(item, isMain, speechHost, partLibrary))
1129
- };
1130
- };
1131
- const mainTrack = toTrack(draft.main_track, true);
1132
- const tracks = [
1133
- ...(draft.above_main_tracks ?? []).map((t) => toTrack(t, false)),
1134
- ...mainTrack == null ? [] : [mainTrack],
1135
- ...(draft.below_main_tracks ?? []).map((t) => toTrack(t, false))
1136
- ];
1137
- return {
1138
- timeline: draft.timeline == null ? void 0 : { unit_time_ms: draft.timeline.unit_time_ms },
1139
- tracks,
1140
- part_library: toAuthoritativePartLibrary(draft.part_library)
1141
- };
1142
- }
1143
- /**
1144
- * Map the legacy `VideoDraft` part library into the authoritative shape
1145
- * (reference/17 §5): the authoritative parts store no derived part-level
1146
- * duration, so the read-view `duration_ms` is dropped from video / speech / bgm.
1147
- * For a caption the legacy `duration_ms` is the generation-time length, stored
1148
- * authoritatively as `initial_duration_ms`.
1149
- */
1150
- function toAuthoritativePartLibrary(partLibrary) {
1151
- if (partLibrary == null) return void 0;
1152
- const out = {};
1153
- for (const [partId, part] of Object.entries(partLibrary)) {
1154
- if (typeof part !== "object" || part == null) continue;
1155
- if (part.video_clip != null) out[partId] = { video_clip: withTrimWindowFromDuration(part.video_clip) };
1156
- else if (part.speech != null) {
1157
- const { duration_ms, rest } = splitDurationMs(part.speech);
1158
- out[partId] = { speech: {
1159
- ...rest,
1160
- media_duration_ms: rest.media_duration_ms ?? duration_ms
1161
- } };
1162
- } else if (part.caption != null) {
1163
- const { duration_ms, rest } = splitDurationMs(part.caption);
1164
- out[partId] = { caption: {
1165
- ...rest,
1166
- initial_duration_ms: rest.initial_duration_ms ?? duration_ms
1167
- } };
1168
- } else if (part.bgm != null) out[partId] = { bgm: omitDurationMs(part.bgm) };
1169
- }
1170
- return out;
1171
- }
1172
- /**
1173
- * Build a speech-host map from a part_aggregations list. Used by
1174
- * `toVideoDocument` (legacy VideoDraft → VideoDocument) to recover each speech's
1175
- * host video clip and relative offset. Aggregation items with null ids are
1176
- * skipped (malformed input tolerance).
1177
- */
1178
- function buildSpeechHostMap(aggregations) {
1179
- const map = /* @__PURE__ */ new Map();
1180
- for (const aggregation of aggregations ?? []) {
1181
- const host = aggregation.body_part_id;
1182
- if (host == null) continue;
1183
- for (const attachment of aggregation.attachments ?? []) {
1184
- if (attachment.part_id == null) continue;
1185
- map.set(attachment.part_id, {
1186
- hostPartId: host,
1187
- offsetMs: Math.round(attachment.relative_time_position ?? 0)
1188
- });
1189
- }
1190
- }
1191
- return map;
1192
- }
1193
- /**
1194
- * Derive `time_position` (and `fallbackAbsMs` for anchored items) from a legacy
1195
- * absolute time + pre-built speech-host map + part library. The three-branch
1196
- * rule (RFC 02 §4/§5, reference/17 §3):
1197
- *
1198
- * 1. main-track → `sequential`
1199
- * 2. speech/attachment (part_id in speechHost) → `anchored(host, offsetMs)`
1200
- * 3. caption (part has `speech_part_id`) → `anchored(speech, start_ms)`
1201
- * 4. everything else → `absolute(abs)`
1202
- *
1203
- * `partLibrary` values may be `PartUnion | string | undefined` (draft raw
1204
- * form); only object-typed entries are inspected for `caption`.
1205
- */
1206
- function derivePositionFromAbs(partId, abs, isMain, speechHost, partLibrary) {
1207
- if (isMain) return { timePosition: { mode: "sequential" } };
1208
- const host = speechHost.get(partId);
1209
- if (host != null) return {
1210
- timePosition: {
1211
- mode: "anchored",
1212
- anchorPartId: host.hostPartId,
1213
- offsetMs: host.offsetMs
1214
- },
1215
- fallbackAbsMs: abs
1216
- };
1217
- const part = partLibrary[partId];
1218
- const captionPart = typeof part === "object" && part != null ? part.caption : void 0;
1219
- const speechId = captionPart?.speech_part_id ?? void 0;
1220
- if (speechId != null) return {
1221
- timePosition: {
1222
- mode: "anchored",
1223
- anchorPartId: speechId,
1224
- offsetMs: Math.round(captionPart?.start_ms ?? 0)
1225
- },
1226
- fallbackAbsMs: abs
1227
- };
1228
- return { timePosition: {
1229
- mode: "absolute",
1230
- offsetMs: abs
1231
- } };
1232
- }
1233
- /** Derive one item's authoritative `time_position` from its legacy abs + aggregation. */
1234
- function deriveItem(item, isMain, speechHost, partLibrary) {
1235
- const partId = item.part_id ?? "";
1236
- const { timePosition, fallbackAbsMs } = derivePositionFromAbs(partId, Math.round(item.abs_time_position ?? 0), isMain, speechHost, partLibrary);
1237
- return fallbackAbsMs == null ? {
1238
- part_id: partId,
1239
- time_position: timePosition
1240
- } : {
1241
- part_id: partId,
1242
- time_position: timePosition,
1243
- fallback_abs_ms: fallbackAbsMs
1244
- };
1245
- }
1246
- /**
1247
- * Project `VideoDocument` into `VideoDraftContent`, solving each item's
1248
- * absolute position, the `part_aggregations`, and
1249
- * the total duration via the timeline-core cascade.
1250
- *
1251
- * The read-view is a compatibility contract, and the IDL declares
1252
- * `Timeline.unit_time_ms` and `Track.is_hidden` `@required`
1253
- * (`video_draft_comp.smithy`) — so a projection that omitted them handed every
1254
- * consumer a payload that violated the shape it claims to satisfy, leaving each
1255
- * one to invent its own default. Two already had, and they disagreed: the agent
1256
- * harness used `unit_time_ms: 0`, director used a frame at 30fps. Defaulting here
1257
- * makes the contract true at the one place that produces it.
1258
- *
1259
- * These two are defaultable because the projection knows their values on its own:
1260
- * absent `unit_time_ms` means "no display granularity was ever stated" and absent
1261
- * `is_hidden` means "this track was never hidden". `version` is NOT defaultable
1262
- * here — it belongs to Director assembly using the server envelope update_seq.
1263
- * Neither business metadata nor a revision counter belongs in content projection.
1264
- */
1265
- function fromVideoDocument(document) {
1266
- assertValidVideoDocument(document);
1267
- const view = solveVideoDocument(document);
1268
- const tracks = document.tracks ?? [];
1269
- const mainTrack = tracks.find((t) => t.parts_kind === "video_clip");
1270
- const aboveTracks = tracks.filter((t) => t.parts_kind === "caption");
1271
- const belowTracks = tracks.filter((t) => t.parts_kind === "speech" || t.parts_kind === "bgm");
1272
- return {
1273
- timeline: {
1274
- duration_ms: view.durationMs,
1275
- unit_time_ms: document.timeline?.unit_time_ms ?? 33.333
1276
- },
1277
- main_track: draftTrack(mainTrack, view.absByPartId),
1278
- above_main_tracks: aboveTracks.map((t) => draftTrack(t, view.absByPartId)),
1279
- below_main_tracks: belowTracks.map((t) => draftTrack(t, view.absByPartId)),
1280
- part_aggregations: view.aggregations,
1281
- part_library: toReadViewPartLibrary(view.partLibrary, view.durationMs, view.derivedFillerPartIds)
1282
- };
1283
- }
1284
- /**
1285
- * Map the authoritative part library into the `VideoDraft` read-view shape,
1286
- * re-injecting the derived effective `duration_ms` downstream expects
1287
- * (reference/17 §5/§7) — the authoritative parts store no part-level duration:
1288
- *
1289
- * - video clip → `(play_out - play_in) / speed` (`effectiveVideoClipDurationMs`)
1290
- * - speech → its intrinsic `media_duration_ms` (no trim/speed)
1291
- * - caption → its generation-time `initial_duration_ms`
1292
- * - bgm → the timeline total (`durationMs`)
1293
- *
1294
- * Parts are deep-cloned; the engine extensions (`media_duration_ms`,
1295
- * `initial_duration_ms`) are kept alongside the injected `duration_ms`.
1296
- *
1297
- * `derivedFillerPartIds` are skipped: the solve minted them to lay the track out
1298
- * and they are not part of the document (see `fromVideoDocument`). An empty clip a
1299
- * writer placed deliberately is NOT in that set and is projected normally.
1300
- */
1301
- function toReadViewPartLibrary(partLibrary, durationMs, derivedFillerPartIds) {
1302
- const out = {};
1303
- for (const [partId, part] of Object.entries(partLibrary)) {
1304
- if (derivedFillerPartIds.has(partId)) continue;
1305
- if (part.video_clip != null) {
1306
- const clip = clone(part.video_clip);
1307
- out[partId] = { video_clip: {
1308
- ...clip,
1309
- duration_ms: effectiveVideoClipDurationMs(clip)
1310
- } };
1311
- } else if (part.speech != null) {
1312
- const speech = clone(part.speech);
1313
- out[partId] = { speech: {
1314
- ...speech,
1315
- duration_ms: speech.media_duration_ms
1316
- } };
1317
- } else if (part.caption != null) {
1318
- const caption = clone(part.caption);
1319
- out[partId] = { caption: {
1320
- ...caption,
1321
- duration_ms: caption.initial_duration_ms
1322
- } };
1323
- } else if (part.bgm != null) out[partId] = { bgm: {
1324
- ...clone(part.bgm),
1325
- duration_ms: durationMs
1326
- } };
1327
- }
1328
- return out;
1329
- }
1330
- /** Deep-clone a part payload, dropping the derived read-view `duration_ms`. */
1331
- function omitDurationMs(part) {
1332
- const { duration_ms: _drop, ...rest } = clone(part);
1333
- return rest;
1334
- }
1335
- /**
1336
- * Migrate a legacy video clip into the authoritative trim-window-only shape: the
1337
- * authoritative part stores no `duration_ms`, so it is dropped — but a legacy
1338
- * clip with no explicit trim window (`play_in` / `play_out` absent) would then
1339
- * compute an effective length of 0 and vanish from the layout. When that clip
1340
- * carried a legacy `duration_ms`, backfill it as the trim window (`play_in` 0,
1341
- * `play_out = duration_ms`, no speed) so the effective length is preserved, then
1342
- * drop `duration_ms`. A clip that already has a trim window keeps it verbatim.
1343
- */
1344
- function withTrimWindowFromDuration(clip) {
1345
- const stripped = omitDurationMs(clip);
1346
- if (clip.play_in != null || clip.play_out != null) return stripped;
1347
- const legacyDuration = clip.duration_ms;
1348
- if (legacyDuration == null || !Number.isFinite(legacyDuration)) return stripped;
1349
- return {
1350
- ...stripped,
1351
- play_in: 0,
1352
- play_out: legacyDuration
1353
- };
1354
- }
1355
- /** Deep-clone a part payload, returning its `duration_ms` separately from the rest. */
1356
- function splitDurationMs(part) {
1357
- const { duration_ms, ...rest } = clone(part);
1358
- return {
1359
- duration_ms,
1360
- rest
1361
- };
1362
- }
1363
- function draftTrack(track, absByPartId) {
1364
- if (track == null) return void 0;
1365
- return {
1366
- id: track.id,
1367
- parts_kind: track.parts_kind,
1368
- is_hidden: track.is_hidden ?? false,
1369
- items: (track.items ?? []).map((item) => ({
1370
- part_id: item.part_id,
1371
- abs_time_position: absByPartId.get(item.part_id) ?? 0
1372
- }))
1373
- };
1374
- }
1375
- function clone(value) {
1376
- if (Array.isArray(value)) return value.map((item) => clone(item));
1377
- if (value != null && typeof value === "object") {
1378
- const result = {};
1379
- for (const [key, child] of Object.entries(value)) result[key] = clone(child);
1380
- return result;
1381
- }
1382
- return value;
1383
- }
1384
- //#endregion
1385
- //#region src/document/initial-document.ts
1386
- /**
1387
- * Build the `VideoDocument` a newly created project starts from: the caller's
1388
- * no parts and one empty track per lane. Business facts remain in Director.
1389
- *
1390
- * The empty lane tracks are the reason this function exists rather than callers
1391
- * assembling a document inline. Lane tracks are otherwise minted lazily by the
1392
- * first op that needs one (`ensureLaneTrack`), which is find-then-mint over a
1393
- * CRDT list — so if the Agent's first generation and a user edit race on an
1394
- * empty document, each mints its own copy of the same lane and the merge keeps
1395
- * both. Two video_clip tracks violate the at-most-one-main-track rule, and the
1396
- * merged document becomes unprojectable for *every* reader (editor, render,
1397
- * share) with no winning replica to fall back on. Seeding all four lanes up
1398
- * front means `ensureLaneTrack` only ever finds, never mints, so the race cannot
1399
- * happen on a document created here.
1400
- *
1401
- * All four, not just the main lane: the secondary lanes fail less loudly (a
1402
- * duplicate pane rather than an unreadable document), but they fail by the same
1403
- * mechanism, and covering only the fatal one would leave three live races.
1404
- *
1405
- * `timeline` is left absent: `unit_time_ms` is a display concern the editor
1406
- * supplies, and total duration is derived on read (RFC 02 §6), so a new document
1407
- * has no timeline fact to state.
1408
- */
1409
- function buildInitialVideoDocument() {
1410
- return {
1411
- timeline: void 0,
1412
- tracks: emptyLaneTracks(),
1413
- part_library: {}
1414
- };
1415
- }
1416
- /** One empty track per lane, in lane-stacking order, with the conventional ids. */
1417
- function emptyLaneTracks() {
1418
- return LANE_KINDS_IN_STACK_ORDER.map((kind) => ({
1419
- id: laneTrackId(kind),
1420
- parts_kind: kind,
1421
- is_hidden: void 0,
1422
- items: []
1423
- }));
1424
- }
1425
- //#endregion
1426
- //#region src/document/document-mutation-guard.ts
1427
- /**
1428
- * @internal
1429
- * Shared by synchronous mutation entry points for one document. The session
1430
- * closes it before teardown callbacks can attempt another write.
1431
- */
1432
- var DocumentMutationGuard = class {
1433
- running = false;
1434
- closed = false;
1435
- run(mutation) {
1436
- if (this.closed) throw new Error("mengine document is disposed");
1437
- if (this.running) throw new Error("mengine document mutation is already running");
1438
- this.running = true;
1439
- try {
1440
- return mutation();
1441
- } finally {
1442
- this.running = false;
1443
- }
1444
- }
1445
- close() {
1446
- this.closed = true;
1447
- }
1448
- };
1449
- //#endregion
1450
- //#region src/document/mirror-read.ts
1451
- /**
1452
- * Project the mirror state (`VideoDocumentDraft`) into the authoritative
1453
- * `VideoDocument`. The storage shape is isomorphic to the domain shape (RFC 03
1454
- * §4, reference/17 §4: timeline + a single `tracks` list + part_library), so this
1455
- * is a near-identity — it reads `time_position` / `fallback_abs_ms` JSON blobs
1456
- * back into structured values and selects content fields. Legacy meta is ignored.
1457
- *
1458
- * It maps only authoritative facts (RFC 02 §6): `part_id` + `time_position`. The
1459
- * projection-derived `VideoDraft` read-view (absolute time, `part_aggregations`,
1460
- * total duration) is solved separately by the cascade, not here.
1461
- *
1462
- * It reads in-memory mirror state (O(n) over the document), not a Loro
1463
- * `toJSON()` FFI rebuild — the cost the prior schema adapter paid on every
1464
- * `snapshot()`.
1465
- */
1466
- function readVideoDocumentFromDraft(draft) {
1467
- const partLibrary = {};
1468
- for (const [partId, payload] of recordEntries(draft.part_library)) {
1469
- const part = draftToPartUnion(payload);
1470
- if (part != null) partLibrary[partId] = part;
1471
- }
1472
- const timeline = draft.timeline;
1473
- return {
1474
- timeline: timeline?.unit_time_ms != null ? { unit_time_ms: timeline.unit_time_ms } : void 0,
1475
- tracks: rowsToTracks(draft.tracks),
1476
- part_library: partLibrary
1477
- };
1478
- }
1479
- /** Map a movable-list of track rows (`$cid`-bearing) into domain tracks, dropping empty-id placeholders. */
1480
- function rowsToTracks(rows) {
1481
- return (rows ?? []).filter((row) => row.id != null && row.id !== "").map(rowToTrack);
1482
- }
1483
- function rowToTrack(row) {
1484
- return {
1485
- id: row.id,
1486
- parts_kind: row.parts_kind ?? void 0,
1487
- is_hidden: row.is_hidden ?? void 0,
1488
- items: (row.items ?? []).map((item) => {
1489
- const result = {
1490
- part_id: item.part_id ?? "",
1491
- time_position: item.time_position
1492
- };
1493
- if (item.fallback_abs_ms != null) result.fallback_abs_ms = item.fallback_abs_ms;
1494
- return result;
1495
- })
1496
- };
1497
- }
1498
- //#endregion
1499
- //#region src/document/mirror-adapter.ts
1500
- /**
1501
- * Storage-layer adapter that backs a `VideoDocument` with `loro-mirror` (ADR
1502
- * 0008). The mirror holds an in-memory immutable state synced to the `LoroDoc`
1503
- * by declarative diff, replacing the hand-rolled `@mengine/schema` adapter:
1504
- *
1505
- * - `snapshot()` projects the mirror's in-memory state to the read model — no
1506
- * per-call `toJSON()` FFI rebuild.
1507
- * - `transact(edit, audit)` runs the whole op in one `mirror.setState` callback:
1508
- * one diff, one `doc.commit` carrying the audit message. The callback edits an
1509
- * immer draft, so a throw inside it discards the draft and never touches Loro
1510
- * (natural rollback) without a document checkout or compensating commit.
1511
- * - mirror's `idSelector` (track items keyed by `part_id`) diffs reorders to
1512
- * real Loro `move` ops on every lane, so per-item CRDT identity survives on
1513
- * main and secondary tracks alike.
1514
- */
1515
- var MirrorVideoDocumentAdapter = class {
1516
- doc;
1517
- mutationGuard;
1518
- mirror;
1519
- disposed = false;
1520
- constructor(doc, mutationGuard = new DocumentMutationGuard()) {
1521
- this.doc = doc;
1522
- this.mutationGuard = mutationGuard;
1523
- this.mirror = new Mirror({
1524
- doc,
1525
- schema: videoDocumentMirrorSchema,
1526
- validateUpdates: false
1527
- });
1528
- }
1529
- snapshot() {
1530
- this.assertActive();
1531
- return readVideoDocumentFromDraft(this.mirror.getState());
1532
- }
1533
- /**
1534
- * Release mirror subscriptions; do not reuse this adapter afterwards.
1535
- * The caller still owns the borrowed LoroDoc.
1536
- */
1537
- dispose() {
1538
- if (this.disposed) return;
1539
- this.disposed = true;
1540
- this.mirror.dispose();
1541
- }
1542
- /**
1543
- * Apply one op as a single transaction. `edit` mutates the immer draft; mirror
1544
- * diffs the result and commits once with the audit `message`. A throw in `edit`
1545
- * discards the draft (Loro untouched). When `edit` produces no change, mirror
1546
- * skips the commit — matching the prior "empty op leaves no audit" behavior.
1547
- */
1548
- transact(edit, audit) {
1549
- this.assertActive();
1550
- this.mutationGuard.run(() => {
1551
- this.mirror.setState((draft) => {
1552
- edit(draft);
1553
- const result = validateSchema(videoDocumentMirrorSchema, {
1554
- timeline: draft.timeline,
1555
- tracks: draft.tracks,
1556
- part_library: draft.part_library
1557
- });
1558
- if (!result.valid) throw new Error(`Invalid content update: ${result.errors?.join("; ")}`);
1559
- }, {
1560
- origin: "mengine.semantic_editor",
1561
- message: JSON.stringify({
1562
- semantic_op: audit.kind,
1563
- payload: audit.payload,
1564
- intent: audit.intent ?? null,
1565
- actor: audit.actor ?? null
1566
- })
1567
- });
1568
- });
1569
- }
1570
- assertActive() {
1571
- if (this.disposed) throw new Error("mengine document adapter is disposed");
1572
- }
1573
- };
1574
- /** Build a fresh Loro doc seeded with `document` through the mirror. */
1575
- function createMirrorVideoDocument(document, options = {}) {
1576
- assertValidVideoDocument(document);
1577
- const doc = new LoroDoc();
1578
- try {
1579
- if (options.peerId != null) doc.setPeerId(options.peerId);
1580
- const mirror = new Mirror({
1581
- doc,
1582
- schema: videoDocumentMirrorSchema
1583
- });
1584
- try {
1585
- mirror.setState((draft) => {
1586
- seedDraft(draft, document);
1587
- }, { origin: options.origin ?? "mengine.bootstrap" });
1588
- return doc;
1589
- } finally {
1590
- mirror.dispose();
1591
- }
1592
- } catch (error) {
1593
- doc.free();
1594
- throw error;
1595
- }
1596
- }
1597
- /** Build a `MirrorVideoDocumentAdapter` over a fresh doc seeded with `document`. */
1598
- function createMirrorVideoDocumentAdapter(document, options) {
1599
- return new MirrorVideoDocumentAdapter(createMirrorVideoDocument(document, options));
1600
- }
1601
- /** Write a whole `VideoDocument` into the mirror draft (used to seed a fresh doc). */
1602
- function seedDraft(draft, document) {
1603
- draft.timeline = { unit_time_ms: document.timeline?.unit_time_ms ?? void 0 };
1604
- draft.tracks = (document.tracks ?? []).map(toTrackRow);
1605
- draft.part_library = {};
1606
- for (const [partId, part] of Object.entries(document.part_library ?? {})) {
1607
- const createdPart = part.caption != null ? { caption: {
1608
- ...part.caption,
1609
- style: part.caption.style ?? {}
1610
- } } : part;
1611
- draft.part_library[partId] = partUnionToDraft(createdPart);
1612
- }
1613
- }
1614
- /** Map a domain `Track` to a draft track row (no lane/lane_order — see schema). */
1615
- function toTrackRow(track) {
1616
- return {
1617
- id: track.id ?? "",
1618
- parts_kind: track.parts_kind ?? void 0,
1619
- is_hidden: track.is_hidden ?? void 0,
1620
- items: (track.items ?? []).map((item) => ({
1621
- part_id: item.part_id,
1622
- time_position: item.time_position,
1623
- fallback_abs_ms: item.fallback_abs_ms
1624
- }))
1625
- };
1626
- }
1627
- //#endregion
1628
- export { isEmptyVideoClip as A, fillMainTrackTimeGaps as C, resolveSpeechOverlapByShiftingVideos as D, resolveAllSpeechOverlaps as E, partUnionToDraft as F, recordEntries as I, videoDocumentMirrorSchema as L, safeDurationMs as M, DEFAULT_UNIT_TIME_MS as N, syncAggregatedClipsTimePosition as O, effectiveVideoClipDurationMs as P, base64ToBytes as R, arrangeMainTrackSeamlessly as S, recalculateTimelineDuration as T, ensureLaneTrack as _, DocumentMutationGuard as a, solveVideoDocument as b, derivePositionFromAbs as c, VideoDocumentValidationError as d, assertValidVideoDocument as f, LANE_KINDS_IN_STACK_ORDER as g, videoDocumentSchema as h, readVideoDocumentFromDraft as i, partDurationMs as j, TIMELINE_SKELETON_DURATION_MS as k, fromVideoDocument as l, partUnionSchema as m, createMirrorVideoDocument as n, buildInitialVideoDocument as o, validateVideoDocument as p, createMirrorVideoDocumentAdapter as r, buildSpeechHostMap as s, MirrorVideoDocumentAdapter as t, toVideoDocument as u, findLaneTrack as v, reassignSpeechesToVideoClipsByTime as w, cascadeAfterVideoClipChanges as x, laneTrackId as y, bytesToBase64 as z };