@mengine/medeo-client 1.3.1-alpha.9 → 1.4.0

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