@mengine/medeo-client 2.0.1-alpha.1 → 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.
package/dist/index.js CHANGED
@@ -1,7 +1,6 @@
1
- import { t as __exportAll } from "./chunk-D7D4PA-g.js";
2
- import { A as isEmptyVideoClip, C as fillMainTrackTimeGaps, D as resolveSpeechOverlapByShiftingVideos, E as resolveAllSpeechOverlaps, F as partUnionToDraft, I as recordEntries, L as videoDocumentMirrorSchema, M as safeDurationMs, N as DEFAULT_UNIT_TIME_MS, O as syncAggregatedClipsTimePosition, P as effectiveVideoClipDurationMs, R as base64ToBytes, S as arrangeMainTrackSeamlessly, T as recalculateTimelineDuration, _ as ensureLaneTrack, a as DocumentMutationGuard, b as solveVideoDocument, c as derivePositionFromAbs, d as VideoDocumentValidationError, f as assertValidVideoDocument, g as LANE_KINDS_IN_STACK_ORDER, h as videoDocumentSchema, i as readVideoDocumentFromDraft, j as partDurationMs, k as TIMELINE_SKELETON_DURATION_MS, l as fromVideoDocument, m as partUnionSchema, n as createMirrorVideoDocument, o as buildInitialVideoDocument, p as validateVideoDocument, r as createMirrorVideoDocumentAdapter, s as buildSpeechHostMap, t as MirrorVideoDocumentAdapter, u as toVideoDocument, v as findLaneTrack, w as reassignSpeechesToVideoClipsByTime, x as cascadeAfterVideoClipChanges, y as laneTrackId, z as bytesToBase64 } from "./document-CmjJwOba.js";
3
- import { z } from "zod";
4
- import { LoroDoc, UndoManager, VersionVector, decodeImportBlobMeta } from "loro-crdt";
1
+ import { $ as cascadeAfterVideoClipChanges, A as selectAudioScriptSegment, B as derivePositionFromAbs, C as decodeEntityRelationRows, D as assemblePhoneticScriptContent, E as assembleEntityContent, F as createRelationId, G as validateVideoDocument, H as toVideoDocument, I as hasSequence, J as LANE_KINDS_IN_STACK_ORDER, K as partUnionSchema, L as isMediaAssetVariantKind, M as variantBaseEntityIds, N as isJsonObject, O as assembleScriptText, P as createEntityId, Q as solveVideoDocument, R as buildInitialVideoDocument, S as EntityTimelineProjectionError, T as assembleCaptionContent, U as VideoDocumentValidationError, V as fromVideoDocument, W as assertValidVideoDocument, X as findLaneTrack, Y as ensureLaneTrack, Z as laneTrackId, _ as assertFieldChanges, _t as recordEntries, a as applyEntityTimelineProjection, at as resolveSpeechOverlapByShiftingVideos, b as EntityProjectionGraph, bt as bytesToBase64, c as writeVideoDocumentToDraft, ct as isEmptyVideoClip, d as LoroEntityDocument, dt as DEFAULT_UNIT_TIME_MS, et as arrangeMainTrackSeamlessly, f as LoroEntityDraft, ft as ENTITY_TIMELINE_PROJECTION_SCHEMA_VERSION, g as applyFieldChanges, gt as partUnionToDraft, h as equalJson, ht as speedOf, i as MirrorVideoDocumentAdapter, it as resolveAllSpeechOverlaps, j as updateEntityFields, k as findComposedAudioScript, l as readVideoDocumentFromDraft, lt as partDurationMs, m as entityOrderGroups, mt as effectiveVideoClipDurationMs, n as createPlainMemoryAdapter, nt as reassignSpeechesToVideoClipsByTime, o as createMirrorVideoDocument, ot as syncAggregatedClipsTimePosition, p as readEntityDocument, pt as VIDEO_DOCUMENT_SCHEMA_VERSION, q as videoDocumentSchema, r as generatePartId, rt as recalculateTimelineDuration, s as createMirrorVideoDocumentAdapter, st as TIMELINE_SKELETON_DURATION_MS, t as PlainMemoryAdapter, tt as fillMainTrackTimeGaps, u as LORO_ENTITY_SCHEMA, ut as safeDurationMs, v as resolveFieldPath, vt as videoDocumentMirrorSchema, w as ScriptCompositionError, x as resolveEntityTimelineLayout, y as projectEntityTimeline, yt as base64ToBytes, z as buildSpeechHostMap } from "./document-BSAUud6c.js";
2
+ import { addSpeechesInputSchema, addVideoClipsInputSchema, adjustBgmVolumeInputSchema, adjustSpeechVolumeInputSchema, adjustVideoClipDurationInputSchema, adjustVideoClipVolumeInputSchema, changeSpeechScriptInputSchema, changeSpeechVoiceInputSchema, deleteBgmInputSchema, deleteSpeechesInputSchema, deleteVideoClipsInputSchema, moveSpeechesInputSchema, moveVideoClipsByAnchorInputSchema, moveVideoClipsInputSchema, replaceVideoClipContentInputSchema, replaceVideoClipSequenceInputSchema, setBgmInputSchema, setCaptionStyleInputSchema, setCaptionVisibilityInputSchema, setVideoClipSpeedShiftInputSchema, t as schemas_exports } from "./schemas.js";
3
+ import { LoroDoc, VersionVector } from "loro-crdt";
5
4
  import { ClientServerSynchronizer, DocManager } from "@mengine/sync";
6
5
  import { DisposableSet, EventBus, Task } from "@mengine/utils";
7
6
  import { BaseDocStorage, DummyConnection } from "@mengine/storage";
@@ -13,7 +12,7 @@ import { BaseDocStorage, DummyConnection } from "@mengine/storage";
13
12
  * namespace (mirrors the cluster's `/oapi/v1` precedent for an independent
14
13
  * subsystem) rather than folding into the shared `/api/v2/*` space.
15
14
  */
16
- const MENGINE_API_PREFIX = "/api/mengine/v1";
15
+ const MENGINE_API_PREFIX$1 = "/api/mengine/v1";
17
16
  var MengineHttpRequestError = class extends Error {
18
17
  status;
19
18
  payload;
@@ -61,6 +60,12 @@ var MengineHttpClient = class {
61
60
  async fetchSnapshot() {
62
61
  return await this.requestJson("snapshot");
63
62
  }
63
+ async bootstrapSnapshot(snapshot) {
64
+ return await this.requestJson("bootstrap", {
65
+ method: "POST",
66
+ body: JSON.stringify({ snapshot: bytesToBase64(snapshot) })
67
+ });
68
+ }
64
69
  /**
65
70
  * Loro VV-diff pull: send the caller's oplog `VersionVector.encode` as `from`
66
71
  * (omit for a full pull) and receive exactly the updates it is missing plus
@@ -129,12 +134,12 @@ var MengineHttpClient = class {
129
134
  ...init,
130
135
  headers
131
136
  });
132
- const payload = await safeReadJson(response);
137
+ const payload = await safeReadJson$1(response);
133
138
  if (!response.ok) throw new MengineHttpRequestError(response.status, payload);
134
139
  return payload;
135
140
  }
136
141
  endpoint(path) {
137
- return `${this.options.httpOrigin.replace(/\/$/, "")}${MENGINE_API_PREFIX}/docs/${encodeURIComponent(this.options.docId)}/${path}`;
142
+ return `${this.options.httpOrigin.replace(/\/$/, "")}${MENGINE_API_PREFIX$1}/docs/${encodeURIComponent(this.options.docId)}/${path}`;
138
143
  }
139
144
  };
140
145
  /**
@@ -151,7 +156,7 @@ function asPushRejection(error) {
151
156
  if (body.kind !== "rejected" || typeof body.code !== "string") return void 0;
152
157
  return new MenginePushRejectedError(body.code, body.message ?? "", body.server_version, error.status);
153
158
  }
154
- async function safeReadJson(response) {
159
+ async function safeReadJson$1(response) {
155
160
  const text = await response.text();
156
161
  if (text.length === 0) return null;
157
162
  try {
@@ -212,565 +217,2499 @@ function findSseFrameBoundary(buffer) {
212
217
  return Math.min(lf, crlf);
213
218
  }
214
219
  //#endregion
215
- //#region src/editor/id-gen.ts
220
+ //#region src/entity-crdt/compile-rows.ts
221
+ /** Lower a detached ordinary-object edit against its actual causal Loro baseline. */
222
+ function compileEntityRows(snapshot, rows, validate) {
223
+ const doc = new LoroDoc();
224
+ doc.import(snapshot);
225
+ return applyEntityRows(new LoroEntityDocument(doc, validate), rows);
226
+ }
227
+ /** Compile an edit on an existing peer, retaining its native local undo history. */
228
+ function applyEntityRows(editor, rows) {
229
+ const before = editor.snapshot().rows;
230
+ const oldEntities = new Map(before.entities.map((row) => [row.entityId, row]));
231
+ const newEntities = new Map(rows.entities.map((row) => [row.entityId, row]));
232
+ const oldRelations = new Map(before.relations.map((row) => [row.relationId, row]));
233
+ const newRelations = new Map(rows.relations.map((row) => [row.relationId, row]));
234
+ if (newEntities.size !== rows.entities.length || newRelations.size !== rows.relations.length) throw new Error("Duplicate domain identity");
235
+ return {
236
+ update: editor.transact((draft) => {
237
+ for (const row of before.relations) {
238
+ const next = newRelations.get(row.relationId);
239
+ if (!next) draft.unlink(row.relationId);
240
+ else {
241
+ if (next.relationKind !== row.relationKind || next.endpoint0EntityId !== row.endpoint0EntityId || next.endpoint1EntityId !== row.endpoint1EntityId) throw new Error("Relation identity cannot change kind or endpoint positions");
242
+ if (!equalJson(row.metadata, next.metadata) || !equalJson(row.trace, next.trace)) draft.patchRelation(row.relationId, next.metadata, next.trace);
243
+ }
244
+ }
245
+ for (const row of rows.entities) {
246
+ const previous = oldEntities.get(row.entityId);
247
+ if (!previous) draft.create(row);
248
+ else {
249
+ if (previous.entityKind !== row.entityKind) throw new Error("Entity kind cannot change");
250
+ if (!equalJson(previous.payload, row.payload)) draft.replaceOwned(row.entityId, row.payload);
251
+ }
252
+ }
253
+ for (const row of rows.relations) if (!oldRelations.has(row.relationId)) draft.link(row);
254
+ const beforeOrder = entityOrderGroups(before), afterOrder = entityOrderGroups(rows);
255
+ for (const group of new Set([...beforeOrder.keys(), ...afterOrder.keys()])) {
256
+ const next = afterOrder.get(group) ?? [];
257
+ if (!equalJson(beforeOrder.get(group) ?? [], next)) draft.order(group, next);
258
+ }
259
+ for (const row of before.entities) if (!newEntities.has(row.entityId)) draft.delete(row.entityId);
260
+ }),
261
+ state: editor.snapshot()
262
+ };
263
+ }
264
+ //#endregion
265
+ //#region src/entity-editor/document-audio-script.ts
266
+ /** Read only the attached version and preserve every segment; never aggregate other scripts. */
267
+ function readDocumentAudioScript(state) {
268
+ const id = state.audioScriptEntityId;
269
+ if (id === null) throw new EntityTimelineProjectionError("Document AudioScript is not initialized");
270
+ if (typeof id !== "string" || id.trim() !== id || !id) throw new EntityTimelineProjectionError("Invalid document AudioScript identity");
271
+ const entity = state.rows.entities.find((row) => row.entityId === id);
272
+ if (!entity || entity.entityKind !== "audio-script") throw new EntityTimelineProjectionError(`Document AudioScript ${id} must name the project AudioScript`);
273
+ const content = assembleEntityContent(state.rows, createEntityId(id));
274
+ assembleScriptText(content);
275
+ return {
276
+ entityId: id,
277
+ segments: structuredClone(content.payload.segments)
278
+ };
279
+ }
280
+ //#endregion
281
+ //#region src/entity-editor/editor-resources.ts
282
+ const roleOrder$1 = {
283
+ caption: 0,
284
+ video_clip: 1,
285
+ speech: 2,
286
+ bgm: 3
287
+ };
288
+ /**
289
+ * MEngine editor policy, not a cardinality restriction on the general-purpose DSL.
290
+ *
291
+ * Media variants share one entity identity with their Asset: every
292
+ * Image/Video/Audio/Voice Entity must carry its own external locator, every
293
+ * external asset id has exactly one claimant, and no media variant may be
294
+ * bound through a legacy `physical-asset` Relation. Dual-entity media graphs
295
+ * are rejected, not migrated. Caption composes AudioScript text and may associate with a physical text Asset.
296
+ */
297
+ function assertCanonicalEditorResources(rows) {
298
+ if (rows.entities.filter((row) => row.entityKind === "timeline").length > 1) throw new EntityTimelineProjectionError("Editor requires exactly one Timeline");
299
+ for (const role of Object.keys(roleOrder$1)) if (rows.entities.filter((row) => row.entityKind === "track" && row.payload.role === role).length > 1) throw new EntityTimelineProjectionError(`Editor has multiple ${role} Tracks`);
300
+ const identityByAssetKey = /* @__PURE__ */ new Map();
301
+ const kinds = new Map(rows.entities.map((row) => [String(row.entityId), row.entityKind]));
302
+ for (const entity of rows.entities) {
303
+ if (isMediaAssetVariantKind(entity.entityKind) && memotaLocator(entity.payload.external) === void 0) throw new EntityTimelineProjectionError(`Media Entity ${entity.entityId} must carry its own Asset external identity`);
304
+ if (entity.entityKind !== "asset" && !isMediaAssetVariantKind(entity.entityKind)) continue;
305
+ const external = entity.payload.external;
306
+ if (!isJsonObject(external) || external.system !== "memota" && external.system !== "memota-speech" || typeof external.key !== "string") continue;
307
+ const key = JSON.stringify([external.system, external.key]);
308
+ const previous = identityByAssetKey.get(key);
309
+ if (previous !== void 0 && previous !== entity.entityId) throw new EntityTimelineProjectionError(`Duplicate Asset for ${key}; reuse ${previous}`);
310
+ identityByAssetKey.set(key, entity.entityId);
311
+ }
312
+ for (const relation of rows.relations) {
313
+ if (relation.relationKind !== "physical-asset") continue;
314
+ const mediaEndpoint = [relation.endpoint0EntityId, relation.endpoint1EntityId].find((endpoint) => isMediaAssetVariantKind(kinds.get(String(endpoint)) ?? ""));
315
+ if (mediaEndpoint !== void 0) throw new EntityTimelineProjectionError(`Cannot bind media Entity ${mediaEndpoint} through physical-asset Relation ${relation.relationId}; media owns its Asset identity directly`);
316
+ }
317
+ }
216
318
  /**
217
- * Part-id generation, aligned with the online ecosystem.
319
+ * Commit-transition policy shared by the editor, the HTTP commit boundary, the
320
+ * host tool, and the entity stores. It compares the authoritative before and
321
+ * after rows of one CAS commit and enforces the single-identity write rules
322
+ * on the complete after state, with no exemption for historical graphs:
218
323
  *
219
- * The authoritative online producers — agent-harness (`@harness/shared`
220
- * `genObjId`) and director.v2 (`common/obj_id.py` `gen_obj_id`) — both mint part
221
- * ids as `` `${prefix}_${ulid()}` ``, and real captured drafts use exactly that
222
- * shape (`clip_…` / `spe_…` / `cap_…` / `bgm_…`, each a 26-char ULID). The engine
223
- * previously emitted `vc_<base36 timestamp><6 random>`, a different prefix AND a
224
- * different encoding — the sole cross-repo id divergence. This module removes it
225
- * by emitting the same `<prefix>_<ULID>` bytes.
324
+ * 1. every Image/Video/Audio/Voice Entity carries its own Asset `external`
325
+ * identity;
326
+ * 2. no `physical-asset` Relation may bind a media variant;
327
+ * 3. a self-carried media identity is immutable — it cannot be rewritten to
328
+ * another asset id.
226
329
  *
227
- * The ULID is generated inline (Crockford Base32, 48-bit time + 80-bit random)
228
- * rather than pulling the `ulid` npm package: the randomness class matches the
229
- * old generator (both `Math.random`-based) and it keeps `@mengine/medeo-client`
230
- * dependency-free for a purely mechanical id string. Part ids only need to be
231
- * unique and lexicographically time-sortable, which this satisfies.
330
+ * Dual-entity media graphs are rejected instead of being migrated or merged
331
+ * implicitly. Deleting media is explicit and allowed.
232
332
  */
233
- /** Crockford Base32 alphabet (no I, L, O, U), per the ULID spec. */
234
- const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
235
- const TIME_LEN = 10;
236
- const RANDOM_LEN = 16;
237
- function encodeTime(now) {
238
- let out = "";
239
- let ms = now;
240
- for (let i = TIME_LEN - 1; i >= 0; i--) {
241
- const mod = ms % 32;
242
- out = CROCKFORD[mod] + out;
243
- ms = (ms - mod) / 32;
333
+ function assertMediaAssetWritePolicy(before, after) {
334
+ const beforeEntities = new Map(before.entities.map((row) => [String(row.entityId), row]));
335
+ const afterKinds = new Map(after.entities.map((row) => [String(row.entityId), row.entityKind]));
336
+ for (const row of after.entities) {
337
+ if (!isMediaAssetVariantKind(row.entityKind)) continue;
338
+ if (memotaLocator(row.payload.external) === void 0) throw new EntityTimelineProjectionError(`Media Entity ${row.entityId} must carry its own Asset external identity`);
339
+ }
340
+ for (const relation of after.relations) {
341
+ if (relation.relationKind !== "physical-asset") continue;
342
+ const mediaEndpoint = [relation.endpoint0EntityId, relation.endpoint1EntityId].find((endpoint) => isMediaAssetVariantKind(afterKinds.get(String(endpoint)) ?? ""));
343
+ if (mediaEndpoint !== void 0) throw new EntityTimelineProjectionError(`Cannot bind media Entity ${mediaEndpoint} through physical-asset Relation ${relation.relationId}; media owns its Asset identity directly`);
344
+ }
345
+ for (const row of after.entities) {
346
+ if (!isMediaAssetVariantKind(row.entityKind)) continue;
347
+ const priorExternal = memotaLocator(beforeEntities.get(String(row.entityId))?.payload.external);
348
+ if (priorExternal === void 0) continue;
349
+ const nextExternal = memotaLocator(row.payload.external);
350
+ if (nextExternal !== void 0 && (nextExternal.system !== priorExternal.system || nextExternal.key !== priorExternal.key)) throw new EntityTimelineProjectionError(`Media Entity ${row.entityId} cannot rewrite its Asset external identity; create a new Entity instead`);
244
351
  }
245
- return out;
246
352
  }
247
- function encodeRandom() {
248
- let out = "";
249
- for (let i = 0; i < RANDOM_LEN; i++) out += CROCKFORD[Math.floor(Math.random() * 32)];
250
- return out;
353
+ function memotaLocator(value) {
354
+ if (!isJsonObject(value) || value.system !== "memota" && value.system !== "memota-speech" || typeof value.key !== "string" || value.key.trim() === "") return;
355
+ return {
356
+ system: value.system,
357
+ key: value.key
358
+ };
251
359
  }
252
- /** A 26-char Crockford Base32 ULID (10-char time + 16-char random). */
253
- function ulid() {
254
- return encodeTime(Date.now()) + encodeRandom();
360
+ /**
361
+ * Bootstrap an empty script when the foundation has no candidate. Without an
362
+ * explicit project attachment, multiple candidates are ambiguous. Existing
363
+ * content IDs are reused here; Loro editing advances their immutable versions.
364
+ */
365
+ function ensureDocumentAudioScript(entities, idFactory, selectedEntityId) {
366
+ if (selectedEntityId != null) {
367
+ if (!entities.some((row) => row.entityKind === "audio-script" && row.entityId === selectedEntityId)) throw new EntityTimelineProjectionError(`Selected AudioScript ${selectedEntityId} does not exist`);
368
+ return selectedEntityId;
369
+ }
370
+ const scripts = entities.filter((row) => row.entityKind === "audio-script");
371
+ if (scripts.length > 1) throw new EntityTimelineProjectionError("Select an AudioScript for the editor panel when multiple scripts exist");
372
+ const existing = scripts[0];
373
+ if (existing !== void 0) return existing.entityId;
374
+ const id = createEntityId(idFactory("entity"));
375
+ if (entities.some((row) => row.entityId === id)) throw new Error(`Duplicate entity id ${id}`);
376
+ entities.push({
377
+ entityId: id,
378
+ entityKind: "audio-script",
379
+ payload: { segments: [] }
380
+ });
381
+ return id;
255
382
  }
256
- function generatePartId(prefix) {
257
- return `${prefix}_${ulid()}`;
383
+ /** Add only missing editor structure; existing identities and owned settings are never replaced. */
384
+ function ensureEditorFoundation(initial, idFactory = (prefix) => `${prefix}_${globalThis.crypto.randomUUID()}`, timelinePayload = {}, selectedAudioScriptEntityId) {
385
+ const entities = structuredClone([...initial.entities]);
386
+ const relations = structuredClone([...initial.relations]);
387
+ const roots = entities.filter((row) => row.entityKind === "timeline");
388
+ if (roots.length > 1) throw new EntityTimelineProjectionError("Editor requires exactly one Timeline");
389
+ const mintEntity = () => {
390
+ const id = createEntityId(idFactory("entity"));
391
+ if (entities.some((row) => row.entityId === id)) throw new Error(`Duplicate entity id ${id}`);
392
+ return id;
393
+ };
394
+ let timeline = roots[0];
395
+ if (timeline === void 0) {
396
+ timeline = {
397
+ entityId: mintEntity(),
398
+ entityKind: "timeline",
399
+ payload: structuredClone(timelinePayload)
400
+ };
401
+ entities.push(timeline);
402
+ }
403
+ const trackEntityIds = {};
404
+ for (const role of Object.keys(roleOrder$1)) {
405
+ const matches = entities.filter((row) => row.entityKind === "track" && row.payload.role === role);
406
+ if (matches.length > 1) throw new EntityTimelineProjectionError(`Editor has multiple ${role} Tracks`);
407
+ let track = matches[0];
408
+ if (track === void 0) {
409
+ track = {
410
+ entityId: mintEntity(),
411
+ entityKind: "track",
412
+ payload: {
413
+ role,
414
+ order: roleOrder$1[role]
415
+ }
416
+ };
417
+ entities.push(track);
418
+ }
419
+ const bindings = relations.filter((row) => row.relationKind === "timeline-track" && (row.endpoint0EntityId === track.entityId || row.endpoint1EntityId === track.entityId));
420
+ if (bindings.some((row) => row.endpoint0EntityId !== timeline.entityId && row.endpoint1EntityId !== timeline.entityId)) throw new EntityTimelineProjectionError(`Track ${track.entityId} belongs to another Timeline`);
421
+ if (bindings.length === 0) {
422
+ const relationId = createRelationId(idFactory("relation"));
423
+ if (relations.some((row) => row.relationId === relationId)) throw new Error(`Duplicate relation id ${relationId}`);
424
+ relations.push({
425
+ relationId,
426
+ relationKind: "timeline-track",
427
+ endpoint0EntityId: timeline.entityId,
428
+ endpoint1EntityId: track.entityId,
429
+ metadata: {},
430
+ trace: {}
431
+ });
432
+ }
433
+ trackEntityIds[role] = track.entityId;
434
+ }
435
+ const audioScriptEntityId = ensureDocumentAudioScript(entities, idFactory, selectedAudioScriptEntityId);
436
+ return {
437
+ rows: {
438
+ entities,
439
+ relations
440
+ },
441
+ timelineEntityId: timeline.entityId,
442
+ trackEntityIds,
443
+ audioScriptEntityId
444
+ };
258
445
  }
259
446
  //#endregion
260
- //#region src/editor/schemas/shared.ts
261
- const clipIdSchema = z.string().min(1).describe("The clip part ID on the timeline");
262
- const clipIdsSchema = z.array(clipIdSchema).min(1).refine((ids) => new Set(ids).size === ids.length, { message: "Duplicate clip IDs are not allowed" }).describe("List of clip part IDs (no duplicates allowed)");
263
- const mediaIdSchema = z.string().min(1).describe("The media asset ID");
264
- const speechIdSchema = z.string().min(1).describe("The speech part ID on the timeline");
265
- const timelineMsSchema = z.number().int().min(0).describe("Time position in milliseconds on the timeline (>= 0)");
266
- const positiveMsSchema = z.number().int().positive().describe("Duration in milliseconds (> 0)");
267
- const volumeSchema = z.number().min(-60).max(20).describe("Volume in decibels (-60.0 to 20.0; 0.0 = original, -60 = mute, +20 = max)");
268
- const speechIdsSchema = z.array(speechIdSchema).min(1).refine((ids) => new Set(ids).size === ids.length, { message: "Duplicate speech IDs are not allowed" }).describe("List of speech part IDs (no duplicates allowed)");
269
- const tangentHandleSchema = z.object({
270
- x: z.number().finite(),
271
- y: z.number().finite()
272
- }).describe("Bezier tangent handle (x, y)");
273
- const speedKeyframeSchema = z.object({
274
- position: z.number().min(0).max(1),
275
- rate: z.number().min(0),
276
- in_tangent: tangentHandleSchema.optional(),
277
- out_tangent: tangentHandleSchema.optional()
278
- }).describe("A speed keyframe: normalized position (0..1), rate, optional tangents");
279
- /**
280
- * A clip's playback-speed fact, the only thing `SetVideoClipSpeedShift` writes.
281
- * Mirrors the IDL `SpeedShift`: `category` is `linear` | `curve`, and `config`
282
- * is a discriminated union — `{ linear: { speed } }` for a constant multiplier
283
- * (the multiplier projection reads at `config.linear.speed`) or `{ curve: {
284
- * keyframes } }` for a Bezier-controlled variable speed (RFC 02 / `reference/16`
285
- * §0). Exactly one of `linear` / `curve` is present.
286
- */
287
- const speedShiftSchema = z.object({
288
- category: z.enum(["linear", "curve"]),
289
- mode: z.string(),
290
- config: z.union([z.object({ linear: z.object({ speed: z.number().finite().positive() }) }), z.object({ curve: z.object({ keyframes: z.array(speedKeyframeSchema).min(2) }) })])
291
- }).describe("Speed shift: linear multiplier or Bezier curve, mirroring the IDL shape");
292
- const voiceSchema = z.object({
293
- id: z.string().min(1),
294
- name: z.string()
295
- }).describe("TTS voice summary attached to a speech");
447
+ //#region src/entity-editor/entity-graph-http-client.ts
448
+ const MENGINE_API_PREFIX = "/api/mengine/v1";
449
+ const numericMarkerValidation$1 = { compareMarkerPoints: (_marker, _range, left, right) => {
450
+ if (typeof left !== "number" || !Number.isFinite(left) || typeof right !== "number" || !Number.isFinite(right)) throw new Error("entity-state requires finite numeric Marker coordinates");
451
+ return left < right ? -1 : left > right ? 1 : 0;
452
+ } };
453
+ /** Browser-safe authenticated Loro client for a document's Entity graph. */
454
+ var EntityGraphHttpClient = class {
455
+ options;
456
+ transport;
457
+ endpoint;
458
+ constructor(options) {
459
+ this.options = options;
460
+ this.transport = new MengineHttpClient(options);
461
+ const origin = options.httpOrigin.replace(/\/$/, "");
462
+ this.endpoint = `${origin}${MENGINE_API_PREFIX}/docs/${encodeURIComponent(options.docId)}/entity-state`;
463
+ }
464
+ async fetchState() {
465
+ return this.request({ method: "GET" });
466
+ }
467
+ /**
468
+ * Compile edits against the original causal snapshot and publish native Loro operations.
469
+ *
470
+ * Deletion intent is derived from baseline IDs omitted from `nextRows`, so a
471
+ * transient create-then-remove never becomes a request to delete unknown
472
+ * persisted data.
473
+ */
474
+ async commit(baseState, nextRows, options = {}) {
475
+ if (options.migrationBaseVv !== void 0) throw new Error("Legacy entity migration is not supported by the Loro contract");
476
+ const next = cloneAndValidateRows(nextRows);
477
+ assertMediaAssetWritePolicy(baseState.rows, next);
478
+ const compiled = compileEntityRows(base64ToBytes(baseState.loroSnapshot), next);
479
+ return this.commitUpdate(bytesToBase64(compiled.update));
480
+ }
481
+ /** Send the same prepared bytes on retry; never recompile an unconfirmed edit. */
482
+ async commitUpdate(update) {
483
+ return this.request({
484
+ method: "POST",
485
+ body: JSON.stringify({ update })
486
+ });
487
+ }
488
+ async request(init) {
489
+ const response = await this.transport.fetch(this.endpoint, {
490
+ ...init,
491
+ headers: this.transport.headers()
492
+ });
493
+ const payload = await safeReadJson(response);
494
+ if (!response.ok) throw new MengineHttpRequestError(response.status, payload);
495
+ return parseWireState(payload, this.options.docId);
496
+ }
497
+ };
498
+ function parseWireState(value, expectedDocId) {
499
+ if (!isRecord(value) || typeof value.doc_id !== "string" || !isNonNegativeSafeInteger(value.revision)) throw new Error("Invalid entity-state response envelope");
500
+ if (value.doc_id !== expectedDocId) throw new Error(`Entity-state response doc_id mismatch: expected "${expectedDocId}"`);
501
+ const rows = parseWireRows(value.rows);
502
+ decodeEntityRelationRows(rows, numericMarkerValidation$1);
503
+ if (typeof value.audio_script_entity_id !== "string") throw new Error("Document AudioScript is not initialized");
504
+ if (typeof value.loro_snapshot !== "string") throw new Error("Missing causal Loro snapshot");
505
+ const state = {
506
+ revision: value.revision,
507
+ loroSnapshot: value.loro_snapshot,
508
+ rows,
509
+ audioScriptEntityId: value.audio_script_entity_id
510
+ };
511
+ readDocumentAudioScript(state);
512
+ return state;
513
+ }
514
+ function parseWireRows(value) {
515
+ if (!isRecord(value) || !Array.isArray(value.entities) || !Array.isArray(value.relations)) throw new Error("Invalid entity-state response rows");
516
+ return {
517
+ entities: value.entities.map(parseWireEntity),
518
+ relations: value.relations.map(parseWireRelation)
519
+ };
520
+ }
521
+ function parseWireEntity(value) {
522
+ if (!isRecord(value) || !isJsonObject(value.payload)) throw new Error("Invalid Entity row in entity-state response");
523
+ return {
524
+ entityId: createEntityId(requiredString(value.entity_id, "entity_id")),
525
+ entityKind: requiredString(value.entity_kind, "entity_kind"),
526
+ payload: structuredClone(value.payload)
527
+ };
528
+ }
529
+ function parseWireRelation(value) {
530
+ if (!isRecord(value) || !isJsonObject(value.metadata) || !isJsonObject(value.trace)) throw new Error("Invalid Relation row in entity-state response");
531
+ return {
532
+ relationId: createRelationId(requiredString(value.relation_id, "relation_id")),
533
+ relationKind: requiredString(value.relation_kind, "relation_kind"),
534
+ endpoint0EntityId: createEntityId(requiredString(value.endpoint_0_entity_id, "endpoint_0_entity_id")),
535
+ endpoint1EntityId: createEntityId(requiredString(value.endpoint_1_entity_id, "endpoint_1_entity_id")),
536
+ metadata: structuredClone(value.metadata),
537
+ trace: structuredClone(value.trace)
538
+ };
539
+ }
540
+ function cloneAndValidateRows(rows) {
541
+ const clone = structuredClone(rows);
542
+ decodeEntityRelationRows(clone, numericMarkerValidation$1);
543
+ return clone;
544
+ }
545
+ function requiredString(value, field) {
546
+ if (typeof value !== "string" || value.length === 0 || value.trim() !== value) throw new Error(`Invalid ${field} in entity-state response`);
547
+ return value;
548
+ }
549
+ function isRecord(value) {
550
+ return value !== null && typeof value === "object" && !Array.isArray(value);
551
+ }
552
+ function isNonNegativeSafeInteger(value) {
553
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
554
+ }
555
+ async function safeReadJson(response) {
556
+ const text = await response.text();
557
+ if (text.length === 0) return null;
558
+ try {
559
+ return JSON.parse(text);
560
+ } catch {
561
+ return text;
562
+ }
563
+ }
296
564
  //#endregion
297
- //#region src/editor/schemas/speech-assets.ts
565
+ //#region src/entity-editor/media-asset-import.ts
566
+ const numericCoordinates = { compareMarkerPoints: (_marker, _range, left, right) => {
567
+ if (typeof left !== "number" || typeof right !== "number" || !Number.isFinite(left) || !Number.isFinite(right)) throw new Error("Media editor requires numeric coordinates");
568
+ return left - right;
569
+ } };
298
570
  /**
299
- * The materialized TTS result shared by `AddSpeeches` / `ChangeSpeechScript` /
300
- * `ChangeSpeechVoice` (see `results/phase-4-side-effect-payload-contract.md`
301
- * §1/§2). The side effect (TTS/ASR + billing) runs upstream; the op receives the
302
- * stable speech + caption parts and writes them as authoritative facts. No
303
- * cascade runs on write — the projection derives absolute positions on read.
571
+ * Import at the editor boundary, not at asset generation time. Existing
572
+ * provenance is retained.
304
573
  *
305
- * Each speech carries the anchoring fact directly (RFC 02 §4): the host video
306
- * clip `anchor_part_id` and the `offset_ms` within it. The upstream caller
307
- * already knows which clip a speech attaches to, so the op writes
308
- * `{ mode:'anchored', anchorPartId, offsetMs }` verbatim — no write-time
309
- * host-picking. Captions anchor to their speech via the caption part's
310
- * `start_ms` (offset within the speech).
574
+ * A media variant is a logical facet of its Asset and shares one entity
575
+ * identity: the import mints exactly one entity of the media kind that carries
576
+ * the external locator itself, and deduplicates only against existing variants
577
+ * that already carry the same `(system, key)`. Legacy dual-entity graphs
578
+ * (`asset` row plus a `physical-asset` binding) are not reused and are
579
+ * rejected by the canonical resource policy instead of being migrated.
311
580
  */
312
- const speechAssetSchema = z.object({
313
- speech_id: speechIdSchema.describe("The speech part ID (= side-effect speech_parts[].id)"),
314
- anchor_part_id: clipIdSchema.describe("Host video clip part ID the speech anchors to (RFC 02 §4)"),
315
- offset_ms: timelineMsSchema.describe("Offset within the host clip (speech.abs = host.abs + offset_ms)"),
316
- audio_storage_key: z.string().min(1),
317
- duration_ms: positiveMsSchema,
318
- audio_script: z.string(),
319
- volume: volumeSchema,
320
- voice: voiceSchema,
321
- origin_speech_id: z.string().min(1),
322
- caption_ids: z.array(z.string().min(1)).describe("Caption part IDs owned by this speech")
323
- });
324
- const captionAssetSchema = z.object({
325
- caption_id: z.string().min(1).describe("The caption part ID (= side-effect created_caption_parts[].id)"),
326
- speech_part_id: speechIdSchema.describe("The owning speech part ID"),
327
- text: z.string(),
328
- start_ms: timelineMsSchema.describe("Offset within the host speech (caption.abs = speech.abs + start_ms)"),
329
- duration_ms: positiveMsSchema
330
- });
331
- /** A materialized speech-subtree write (speeches + their captions). */
332
- const speechAssetsSchema = z.object({
333
- speeches: z.array(speechAssetSchema).min(1).describe("Materialized speech parts to write"),
334
- captions: z.array(captionAssetSchema).describe("Materialized caption parts owned by the speeches")
335
- });
581
+ function importMediaAsset(initial, fact, idFactory = (prefix) => `${prefix}_${globalThis.crypto.randomUUID()}`) {
582
+ if (!fact.assetId || fact.assetId.trim() !== fact.assetId) throw new Error("Expected an asset id");
583
+ if (![
584
+ "image",
585
+ "video",
586
+ "audio",
587
+ "voice"
588
+ ].includes(fact.kind)) throw new Error("Unsupported media kind");
589
+ if (fact.kind !== "image" && (!Number.isFinite(fact.durationMs) || fact.durationMs <= 0)) throw new Error(`${fact.kind} ${fact.assetId} requires its factual positive duration`);
590
+ if ((fact.kind === "audio" || fact.kind === "voice") && fact.storageKey.trim() === "") throw new Error(`${fact.kind} ${fact.assetId} requires its physical storage key`);
591
+ decodeEntityRelationRows(initial, numericCoordinates);
592
+ assertCanonicalEditorResources(initial);
593
+ const entities = structuredClone([...initial.entities]);
594
+ const relations = structuredClone([...initial.relations]);
595
+ const system = fact.kind === "voice" ? "memota-speech" : "memota";
596
+ const existing = entities.filter((row) => {
597
+ const external = row.payload.external;
598
+ return isMediaAssetVariantKind(row.entityKind) && isJsonObject(external) && external.system === system && external.key === fact.assetId;
599
+ });
600
+ if (existing.length > 1) throw new Error(`Duplicate media identities for ${fact.assetId}; reuse ${existing[0].entityId}`);
601
+ if (existing[0] !== void 0) {
602
+ const variant = requireMatchingVariant(existing[0], fact);
603
+ replaceEntity$1(entities, variant.entityId, variant);
604
+ return {
605
+ rows: {
606
+ entities,
607
+ relations
608
+ },
609
+ contentEntityId: variant.entityId
610
+ };
611
+ }
612
+ const entityId = createEntityId(idFactory("entity"));
613
+ if (entities.some((row) => row.entityId === entityId)) throw new Error(`Duplicate entity id ${entityId}`);
614
+ const variant = {
615
+ entityId,
616
+ entityKind: fact.kind,
617
+ payload: {
618
+ extent: fact.kind === "image" ? {
619
+ kind: "unbounded",
620
+ start: 0
621
+ } : {
622
+ kind: "bounded",
623
+ start: 0,
624
+ end: fact.durationMs
625
+ },
626
+ sampling: fact.kind === "image" ? "constant" : "native",
627
+ coordinateSpace: "milliseconds",
628
+ external: {
629
+ system,
630
+ key: fact.assetId
631
+ },
632
+ ...fact.storageKey === void 0 ? {} : { storageKey: fact.storageKey },
633
+ ...fact.kind === "voice" && fact.voice !== void 0 ? { voice: {
634
+ system: fact.voice.system,
635
+ key: fact.voice.key,
636
+ ...fact.voice.name === void 0 ? {} : { name: fact.voice.name }
637
+ } } : {}
638
+ }
639
+ };
640
+ entities.push(variant);
641
+ const rows = {
642
+ entities,
643
+ relations
644
+ };
645
+ decodeEntityRelationRows(rows, numericCoordinates);
646
+ assertCanonicalEditorResources(rows);
647
+ return {
648
+ rows,
649
+ contentEntityId: entityId
650
+ };
651
+ }
652
+ function requireMatchingVariant(row, fact) {
653
+ const extent = row.payload.extent;
654
+ if (row.entityKind !== fact.kind || fact.kind !== "image" && (!isJsonObject(extent) || extent.start !== 0 || extent.end !== fact.durationMs) || fact.kind === "voice" && !sameVoice(row.payload.voice, fact.voice)) throw new Error(`Media facts conflict with existing identity for ${fact.assetId}`);
655
+ if (fact.storageKey !== void 0 && row.payload.storageKey !== fact.storageKey) {
656
+ if (row.payload.storageKey !== void 0) throw new Error(`Media facts conflict with existing storage key for ${fact.assetId}`);
657
+ return {
658
+ ...row,
659
+ payload: {
660
+ ...row.payload,
661
+ storageKey: fact.storageKey
662
+ }
663
+ };
664
+ }
665
+ return row;
666
+ }
667
+ function replaceEntity$1(entities, entityId, replacement) {
668
+ const index = entities.findIndex((row) => row.entityId === entityId);
669
+ if (index < 0) throw new Error(`Entity id ${entityId} does not exist`);
670
+ entities[index] = replacement;
671
+ }
672
+ function sameVoice(left, right) {
673
+ if (right === void 0) return left === void 0;
674
+ return isJsonObject(left) && left.system === right.system && left.key === right.key && left.name === right.name && Object.keys(left).every((key) => key === "system" || key === "key" || key === "name");
675
+ }
336
676
  //#endregion
337
- //#region src/editor/schemas/add-speeches.ts
677
+ //#region src/entity-editor/entity-timeline-editor.ts
338
678
  /**
339
- * Add speeches (and their captions). TTS runs upstream; the stable speech /
340
- * caption parts arrive materialized (see `speech-assets.ts`). The op writes the
341
- * parts and each speech's `{ mode:'anchored', anchorPartId, offsetMs }` fact
342
- * verbatim — no write-time host-picking, no cascade (RFC 02 §4). The projection
343
- * derives absolute positions on read.
679
+ * Resolve the AudioScript a PhoneticScript composes. The composition is the
680
+ * required text source: a variant without it has no content and fails here.
344
681
  */
345
- const addSpeechesInputSchema = speechAssetsSchema.describe("Materialized speeches + captions to add");
346
- //#endregion
347
- //#region src/editor/schemas/add-video-clips.ts
682
+ function requireComposedAudioScript(rows, phoneticScriptEntityId) {
683
+ return assemblePhoneticScriptContent(rows, phoneticScriptEntityId).audioScript.entityId;
684
+ }
685
+ function captionSelection(selection) {
686
+ return structuredClone(selection);
687
+ }
688
+ function captionBaseIds(ids) {
689
+ if (!Array.isArray(ids) || ids.length === 0) throw new Error("Caption requires non-empty baseEntityIds");
690
+ return ids.map(createEntityId);
691
+ }
692
+ function assertCaptionScript(rows, captionId, scriptId) {
693
+ if (assembleCaptionContent(rows, captionId).audioScript.entityId !== scriptId) throw new Error("Voiceover Caption must compose the same AudioScript as the PhoneticScript");
694
+ }
695
+ const roleOrder = {
696
+ caption: 0,
697
+ video_clip: 1,
698
+ speech: 2,
699
+ bgm: 3
700
+ };
701
+ const defaultIdFactory = (prefix) => `${prefix}_${globalThis.crypto.randomUUID()}`;
348
702
  /**
349
- * Add video clips to a track. Each clip's duration facts are separated so a
350
- * single number is never overloaded (RFC 02 / `reference/16` §0b):
351
- *
352
- * - `media_duration_ms` is the source media's intrinsic full length (a resource
353
- * fact, written to the part);
354
- * - `play_in` / `play_out` are the optional trim window into that media; when
355
- * omitted the whole media is used (`play_in=0`, `play_out=media_duration_ms`).
703
+ * Graph-native timeline authoring over authoritative Medeo Entity and Relation rows.
356
704
  *
357
- * The clip's effective timeline duration is derived by the projection from the
358
- * trim window and `speed_shift` — it is never an input here.
705
+ * Each mutation is applied to a detached graph, validated as a complete DSL set,
706
+ * and committed only after validation succeeds.
359
707
  */
360
- const addVideoClipsInputSchema = z.object({
361
- clips: z.array(z.object({
362
- media_id: mediaIdSchema.describe("The media asset ID for the video clip"),
363
- start_ms: timelineMsSchema.optional().describe("Absolute start time in milliseconds on the timeline"),
364
- media_duration_ms: positiveMsSchema.describe("The source media's intrinsic full length in ms"),
365
- play_in: timelineMsSchema.optional().describe("Trim window start in the media (default 0)"),
366
- play_out: positiveMsSchema.optional().describe("Trim window end in the media (default media_duration_ms)"),
367
- track_id: z.string().min(1).optional().describe("Target track ID (optional, defaults to main track)")
368
- })).min(1).describe("List of video clips to create"),
369
- before_clip_id: z.string().min(1).optional().describe("Insert new clips before this clip ID"),
370
- after_clip_id: z.string().min(1).optional().describe("Insert new clips after this clip ID")
371
- }).superRefine((data, ctx) => {
372
- if (data.before_clip_id != null && data.after_clip_id != null) {
373
- ctx.addIssue({
374
- code: z.ZodIssueCode.custom,
375
- message: "Cannot provide both before_clip_id and after_clip_id"
708
+ var EntityTimelineEditor = class {
709
+ idFactory;
710
+ state;
711
+ constructor(initialRows, idFactory = defaultIdFactory) {
712
+ this.idFactory = idFactory;
713
+ this.state = cloneRows(initialRows);
714
+ }
715
+ rows() {
716
+ return cloneRows(this.state);
717
+ }
718
+ insertClip(input) {
719
+ const requestedOrder = input.clipPayload?.order;
720
+ const order = typeof requestedOrder === "number" ? requestedOrder : nextSequentialOrder(this.state, createEntityId(input.trackEntityId));
721
+ return this.insertPlacedClip({
722
+ trackEntityId: input.trackEntityId,
723
+ contentEntityId: input.contentEntityId,
724
+ sourceRange: input.sourceRange,
725
+ duration: input.duration,
726
+ placement: input.targetRange === void 0 ? {
727
+ kind: "sequential",
728
+ order
729
+ } : {
730
+ kind: "absolute",
731
+ targetRange: input.targetRange
732
+ },
733
+ clipPayload: input.clipPayload
376
734
  });
377
- return;
378
735
  }
379
- const hasRelative = data.before_clip_id != null || data.after_clip_id != null;
380
- for (let i = 0; i < data.clips.length; i++) {
381
- const clip = data.clips[i];
382
- if (hasRelative && clip.start_ms != null) ctx.addIssue({
383
- code: z.ZodIssueCode.custom,
384
- message: `clips[${i}].start_ms must not be provided when using before_clip_id or after_clip_id`,
385
- path: [
386
- "clips",
387
- i,
388
- "start_ms"
389
- ]
736
+ insertPlacedClip(input) {
737
+ return this.transact((draft) => this.insertPlacedClipIntoDraft(draft, input));
738
+ }
739
+ updateClipMarker(input) {
740
+ this.transact((draft) => {
741
+ const { marker } = requireClipTopology(draft, input.clipEntityId);
742
+ const payload = { ...cloneJsonObject(marker.payload, "Sequence Marker payload") };
743
+ if (input.sourceRange !== void 0) payload.sourceRange = cloneJsonValue(input.sourceRange, "sourceRange");
744
+ if (input.duration !== void 0) payload.duration = cloneJsonValue(input.duration, "duration");
745
+ if (Object.hasOwn(input, "targetRange")) if (input.targetRange === void 0) {
746
+ delete payload.targetRange;
747
+ if (!hasOutgoingClipAnchor(draft, input.clipEntityId)) {
748
+ const trackId = otherEndpoint(requireOneRelation(draft, createEntityId(input.clipEntityId), "track-clip"), input.clipEntityId);
749
+ const clipPayload = { ...cloneJsonObject(requireEntityKind(draft, input.clipEntityId, "clip").payload, "Clip payload") };
750
+ clipPayload.order ??= nextSequentialOrder(draft, trackId);
751
+ replaceEntity(draft, createEntityId(input.clipEntityId), {
752
+ ...requireEntityKind(draft, input.clipEntityId, "clip"),
753
+ payload: clipPayload
754
+ });
755
+ }
756
+ } else {
757
+ payload.targetRange = cloneJsonValue(input.targetRange, "targetRange");
758
+ const clip = requireEntityKind(draft, input.clipEntityId, "clip");
759
+ const clipPayload = { ...cloneJsonObject(clip.payload, "Clip payload") };
760
+ delete clipPayload.order;
761
+ replaceEntity(draft, clip.entityId, {
762
+ ...clip,
763
+ payload: clipPayload
764
+ });
765
+ }
766
+ if (Object.hasOwn(input, "timeRemapping")) if (input.timeRemapping === void 0) delete payload.timeRemapping;
767
+ else payload.timeRemapping = cloneJsonValue(input.timeRemapping, "timeRemapping");
768
+ replaceEntity(draft, marker.entityId, {
769
+ ...marker,
770
+ payload
771
+ });
390
772
  });
391
- if (!hasRelative && clip.start_ms == null) ctx.addIssue({
392
- code: z.ZodIssueCode.custom,
393
- message: `clips[${i}].start_ms is required when not using relative positioning`,
394
- path: [
395
- "clips",
396
- i,
397
- "start_ms"
398
- ]
773
+ }
774
+ setClipPlacement(input) {
775
+ this.transact((draft) => this.applyClipPlacement(draft, input.clipEntityId, input.placement));
776
+ }
777
+ moveSequentialClips(input) {
778
+ if (input.clipEntityIds.length === 0) throw new Error("At least one Clip is required");
779
+ this.transact((draft) => {
780
+ const original = resolveEntityTimelineLayout(draft);
781
+ this.normalizeMainSequential(draft);
782
+ const before = resolveEntityTimelineLayout(draft);
783
+ const targetIds = new Set(input.clipEntityIds);
784
+ if (targetIds.size !== input.clipEntityIds.length) throw new Error("Clip ids must be unique");
785
+ const placements = input.clipEntityIds.map((id) => before.clips.get(id));
786
+ if (placements.some((placement) => placement === void 0 || placement.mode !== "sequential")) throw new Error("moveSequentialClips accepts only sequential Clips");
787
+ const trackIds = new Set(placements.map((placement) => placement.trackEntityId));
788
+ if (trackIds.size !== 1) throw new Error("Moved Clips must belong to one Track");
789
+ const trackId = [...trackIds][0];
790
+ const track = before.tracks.find((candidate) => candidate.entityId === trackId);
791
+ if (track?.role !== "video_clip") throw new Error("Only the video_clip Track supports sequential block moves");
792
+ const ordered = track.clips.filter((placement) => placement.mode === "sequential").map((placement) => placement.clipEntityId);
793
+ if (input.anchor.position !== "trackStart" && targetIds.has(input.anchor.clipEntityId)) throw new Error("Move anchor cannot be one of the moved Clips");
794
+ const moved = ordered.filter((id) => targetIds.has(id));
795
+ if (moved.length !== targetIds.size) throw new Error("Every moved Clip must exist on the target Track");
796
+ const remaining = ordered.filter((id) => !targetIds.has(id));
797
+ let insertAt = 0;
798
+ if (input.anchor.position !== "trackStart") {
799
+ const anchorIndex = remaining.indexOf(input.anchor.clipEntityId);
800
+ if (anchorIndex < 0) throw new Error("Move anchor Clip does not exist on the target Track");
801
+ insertAt = anchorIndex + (input.anchor.position === "after" ? 1 : 0);
802
+ }
803
+ [
804
+ ...remaining.slice(0, insertAt),
805
+ ...moved,
806
+ ...remaining.slice(insertAt)
807
+ ].forEach((clipId, order) => setClipOrder(draft, clipId, order));
808
+ if (input.onAnchored === "keepAbsolute") {
809
+ const affected = outgoingAnchorChildren(draft, new Set(track.clips.map((clip) => clip.clipEntityId))).filter((childId) => clipRole(draft, childId) === "speech").map((childId) => {
810
+ const placement = original.clips.get(childId);
811
+ if (placement === void 0) throw new Error(`Anchored child Clip "${childId}" is not placed`);
812
+ return {
813
+ childId,
814
+ start: placement.start
815
+ };
816
+ });
817
+ const after = resolveEntityTimelineLayout(draft);
818
+ for (const child of affected) this.reanchorAtAbsolute(draft, child.childId, child.start, after);
819
+ }
820
+ this.resolveOneVoiceoverOverlap(draft);
399
821
  });
400
- const playIn = clip.play_in ?? 0;
401
- const playOut = clip.play_out ?? clip.media_duration_ms;
402
- if (playOut > clip.media_duration_ms) ctx.addIssue({
403
- code: z.ZodIssueCode.custom,
404
- message: `clips[${i}].play_out ${playOut}ms exceeds media_duration_ms ${clip.media_duration_ms}ms`,
405
- path: [
406
- "clips",
407
- i,
408
- "play_out"
409
- ]
822
+ }
823
+ moveClipsToStarts(input) {
824
+ if (input.moves.length === 0) throw new Error("At least one Clip move is required");
825
+ this.transact((draft) => {
826
+ const original = resolveEntityTimelineLayout(draft);
827
+ const originalVideo = original.tracks.find((track) => track.role === "video_clip");
828
+ if (originalVideo === void 0) throw new Error("The timeline has no video_clip Track");
829
+ const preservedVoiceovers = outgoingAnchorChildren(draft, new Set(originalVideo.clips.map((clip) => clip.clipEntityId))).filter((clipId) => clipRole(draft, clipId) === "speech").map((clipId) => ({
830
+ clipId,
831
+ start: original.clips.get(clipId).start
832
+ }));
833
+ this.normalizeMainSequential(draft);
834
+ for (const move of input.moves) {
835
+ finiteNonNegative(move.newStartMs, "newStartMs");
836
+ requireClipOnRole(draft, move.clipEntityId, "video_clip");
837
+ const track = resolveEntityTimelineLayout(draft).tracks.find((candidate) => candidate.role === "video_clip");
838
+ const ordered = track.clips.map((clip) => clip.clipEntityId);
839
+ const from = ordered.indexOf(move.clipEntityId);
840
+ if (from < 0) throw new Error(`Clip "${move.clipEntityId}" is not on the video_clip Track`);
841
+ const remaining = track.clips.filter((clip) => clip.clipEntityId !== move.clipEntityId);
842
+ let cursor = 0;
843
+ let target = remaining.length;
844
+ for (const [index, clip] of remaining.entries()) {
845
+ if (move.newStartMs <= cursor + clip.duration / 2) {
846
+ target = index;
847
+ break;
848
+ }
849
+ cursor += clip.duration;
850
+ }
851
+ const next = [...ordered];
852
+ next.splice(from, 1);
853
+ next.splice(target, 0, move.clipEntityId);
854
+ next.forEach((clipId, order) => setClipOrder(draft, clipId, order));
855
+ }
856
+ const after = resolveEntityTimelineLayout(draft);
857
+ for (const voiceover of preservedVoiceovers) this.reanchorAtAbsolute(draft, voiceover.clipId, voiceover.start, after);
858
+ this.resolveOneVoiceoverOverlap(draft);
410
859
  });
411
- if (playIn >= playOut) ctx.addIssue({
412
- code: z.ZodIssueCode.custom,
413
- message: `clips[${i}].play_in ${playIn}ms must be less than play_out ${playOut}ms`,
414
- path: [
415
- "clips",
416
- i,
417
- "play_in"
418
- ]
860
+ }
861
+ moveClip(input) {
862
+ this.transact((draft) => {
863
+ const topology = requireClipTopology(draft, input.clipEntityId);
864
+ const track = requireEntityKind(draft, input.trackEntityId, "track");
865
+ requireTrackTimeline(draft, track.entityId);
866
+ this.relinkRelation(draft, topology.trackRelation, {
867
+ endpoint0EntityId: track.entityId,
868
+ endpoint1EntityId: topology.clip.entityId
869
+ });
419
870
  });
420
871
  }
421
- });
422
- //#endregion
423
- //#region src/editor/schemas/adjust-bgm-volume.ts
424
- const adjustBgmVolumeInputSchema = z.object({ bgm: z.array(z.object({
425
- bgm_id: clipIdSchema.describe("The bgm part ID to adjust volume for"),
426
- volume: volumeSchema.describe("Volume in decibels (-60.0 to 20.0; 0.0 = original)")
427
- })).min(1).describe("List of bgm parts with their new volume settings") });
428
- //#endregion
429
- //#region src/editor/schemas/adjust-speech-volume.ts
430
- const adjustSpeechVolumeInputSchema = z.object({ speeches: z.array(z.object({
431
- speech_id: speechIdSchema.describe("The speech part ID to adjust volume for"),
432
- volume: volumeSchema.describe("Volume in decibels (-60.0 to 20.0; 0.0 = original)")
433
- })).min(1).describe("List of speeches with their new volume settings") });
434
- //#endregion
435
- //#region src/editor/schemas/adjust-video-clip-duration.ts
436
- /**
437
- * Re-trim existing video clips (the user-facing "adjust duration" gesture is a
438
- * trim of the source window). The new `play_in` / `play_out` are the facts; the
439
- * effective timeline duration is derived from them and the clip's `speed_shift`,
440
- * and the change reflows downstream clips, speeches, and the timeline inside the
441
- * op's transaction (no caller-materialized cascade).
442
- */
443
- const adjustVideoClipDurationInputSchema = z.object({ clips: z.array(z.object({
444
- clip_id: clipIdSchema.describe("The video clip part ID to re-trim"),
445
- play_in: timelineMsSchema.describe("New trim window start in the source media"),
446
- play_out: positiveMsSchema.describe("New trim window end in the source media")
447
- })).min(1).describe("Video clips with their new trim windows") });
448
- //#endregion
449
- //#region src/editor/schemas/adjust-video-clip-volume.ts
450
- const adjustVideoClipVolumeInputSchema = z.object({ clips: z.array(z.object({
451
- clip_id: clipIdSchema.describe("The video clip part ID to adjust volume for"),
452
- volume: volumeSchema.describe("Volume in decibels (-60.0 to 20.0; 0.0 = original)")
453
- })).min(1).describe("List of video clips with their new volume settings") });
454
- //#endregion
455
- //#region src/editor/schemas/change-speech.ts
456
- /**
457
- * Change a speech's script or voice. Both re-run TTS upstream and return the
458
- * regenerated speech / caption parts in the same materialized shape as
459
- * `AddSpeeches` (`speech-assets.ts`); the op upserts them by id (the speech part
460
- * id is preserved across a re-TTS), re-seats at `start_ms`, and reflows. Old
461
- * caption parts no longer owned by the speech are removed via `caption_ids`.
462
- */
463
- const changeSpeechScriptInputSchema = speechAssetsSchema.describe("Regenerated speeches + captions (new script)");
464
- const changeSpeechVoiceInputSchema = speechAssetsSchema.describe("Regenerated speeches + captions (new voice)");
465
- //#endregion
466
- //#region src/editor/schemas/delete-bgm.ts
467
- /**
468
- * Remove the document BGM. Pure document edit: clears the bgm lane and removes
469
- * the bgm part. Takes no input (a document holds at most one bgm); an empty
470
- * object keeps the op signature uniform with the rest.
471
- */
472
- const deleteBgmInputSchema = z.object({}).describe("Remove the document BGM (no parameters)");
473
- //#endregion
474
- //#region src/editor/schemas/delete-speeches.ts
475
- /**
476
- * Delete speeches with their captions. Pure document edit (no side effect): the
477
- * op removes each speech part, cascade-deletes the captions it owns (via
478
- * `caption_ids` / `speech_part_id`), drops their track items, and reflows.
479
- */
480
- const deleteSpeechesInputSchema = z.object({ speech_ids: speechIdsSchema.describe("Speech part IDs to delete (their captions cascade-delete)") });
481
- //#endregion
482
- //#region src/editor/schemas/delete-video-clips.ts
483
- /**
484
- * How a delete handles the anchored subtree (speeches anchored to a deleted clip,
485
- * and their captions) — a delete-op policy, not a data-model field (reference/17
486
- * §6). `cascade` (default) removes the subtree; `detach` keeps the direct
487
- * anchored children, re-pinning them to `absolute` so they stay on the timeline.
488
- */
489
- const anchoredDeletePolicySchema = z.enum(["cascade", "detach"]);
490
- const deleteVideoClipsInputSchema = z.object({
491
- clip_ids: clipIdsSchema.describe("List of video clip part IDs to delete from the main track"),
492
- on_anchored: anchoredDeletePolicySchema.optional().describe("How to treat anchored children (default cascade)")
493
- });
494
- //#endregion
495
- //#region src/editor/schemas/move-speeches.ts
496
- /**
497
- * Move speeches in time. Pure document edit: the op re-seats each speech at its
498
- * new absolute `start_ms`; the cascade reassigns it to the host video clip,
499
- * resolves overlaps, and reflows. Captions follow their speech.
500
- */
501
- const moveSpeechesInputSchema = z.object({ speeches: z.array(z.object({
502
- speech_id: speechIdSchema.describe("The speech part ID to move"),
503
- new_start_ms: timelineMsSchema.describe("New absolute start time on the timeline")
504
- })).min(1).describe("Speeches to move to new positions") });
505
- //#endregion
506
- //#region src/editor/schemas/move-video-clips-by-anchor.ts
507
- /**
508
- * Where the moved block lands on the main track.
509
- *
510
- * A discriminated union rather than two optional `before_clip_id` /
511
- * `after_clip_id` fields (the shape `addVideoClips` had to use, because there the
512
- * two modes share a whole clip description): here the alternatives carry nothing
513
- * in common, so making them mutually exclusive *by type* removes three runtime
514
- * `superRefine` checks that would otherwise have to be written and tested.
515
- *
516
- * `track_start` is an explicit member, not the absence of an anchor. The
517
- * agent-harness mutation this maps from treats "neither anchor given" as
518
- * "move to the front" (`applyBatchMoveVideoClips` falls back to `insertIndex = 0`),
519
- * which is a default buried in a tool description. Requiring the caller to name
520
- * that intent keeps a forgotten field from silently reordering the timeline.
521
- */
522
- const moveAnchorSchema = z.discriminatedUnion("position", [
523
- z.object({
524
- position: z.literal("before"),
525
- clip_id: clipIdSchema.describe("The moved block lands immediately before this clip")
526
- }),
527
- z.object({
528
- position: z.literal("after"),
529
- clip_id: clipIdSchema.describe("The moved block lands immediately after this clip")
530
- }),
531
- z.object({ position: z.literal("track_start") })
532
- ]).describe("Where the moved block lands: before/after a reference clip, or at the head of the track");
533
- /**
534
- * What happens to the speeches anchored to the clips being moved.
535
- *
536
- * - `follow` keeps each speech anchored where it is, so it travels with its clip
537
- * to the new position. In the anchored model this is the *no-op* branch: a
538
- * speech's authoritative fact is `{ anchorPartId, offsetMs }` and its absolute
539
- * time is derived on read from the host's position, so moving the host moves
540
- * the speech with no write to the speech at all.
541
- * - `keep_absolute` preserves each speech's current absolute landing instead, then
542
- * re-anchors it to whichever clip now covers that time (RFC 02 §9.1/§11.1). This
543
- * is the branch that costs an extra pass, and the one the FE timeline uses.
544
- *
545
- * **Required, with no default**, matching `deleteVideoClips` and
546
- * `replaceVideoClipSequence`. The two branches decide which picture the user's
547
- * narration ends up over, which is too consequential to infer from a missing
548
- * field — and neither branch is "safe enough" to be the implicit one.
549
- */
550
- const movedClipAnchoredPolicySchema = z.enum(["follow", "keep_absolute"]);
551
- /**
552
- * Reorder a set of main-track clips relative to a reference clip.
553
- *
554
- * Distinct from `moveVideoClips`, which positions clips by absolute time
555
- * (`new_start_ms`) and is what the FE timeline dispatches after a drag. Main-track
556
- * clips are `sequential`-positioned, so absolute time is not authoritative state
557
- * there (RFC 02 §4/§7): `moveVideoClips` has to *guess* an index back out of the
558
- * time it was handed, whereas an anchor already is the ordinal fact being changed.
559
- * Keeping them separate also isolates blast radius — this method can diverge on
560
- * speech policy without touching the FE path.
561
- *
562
- * `clip_ids` need not be contiguous. They move as one block, keeping their
563
- * relative order, which is the agent-harness `batch_move_video_clips` contract.
564
- */
565
- const moveVideoClipsByAnchorInputSchema = z.object({
566
- clip_ids: clipIdsSchema.describe("Clips to move as one block, keeping their relative order. Need not be contiguous on the track."),
567
- anchor: moveAnchorSchema,
568
- on_anchored: movedClipAnchoredPolicySchema.describe("What happens to speeches anchored to the moved clips (required — see the policy doc)")
569
- });
570
- //#endregion
571
- //#region src/editor/schemas/move-video-clips.ts
572
- const moveVideoClipsInputSchema = z.object({ clips: z.array(z.object({
573
- clip_id: clipIdSchema.describe("The video clip part ID to move"),
574
- new_start_ms: timelineMsSchema.describe("New absolute start time in milliseconds on the timeline"),
575
- new_track_id: z.string().min(1).optional().describe("Target track ID to move the clip to (optional)")
576
- })).min(1).describe("List of video clips to move to new positions") });
577
- //#endregion
578
- //#region src/editor/schemas/replace-video-clip-content.ts
579
- /**
580
- * Replace the media backing existing video clips. The media import runs upstream
581
- * (Director); its stable result — the new media id, intrinsic length, and the
582
- * reset trim window — arrives materialized (see
583
- * `results/phase-4-side-effect-payload-contract.md` §4). Director resets
584
- * `play_in=0` / `play_out=media_duration_ms` and clears `speed_shift` on
585
- * replacement. The clip `part_id`s (hence their track items) are unchanged; the
586
- * editor reflows the main track from the new effective durations.
587
- */
588
- const replaceVideoClipContentInputSchema = z.object({ clips: z.array(z.object({
589
- clip_id: clipIdSchema.describe("Existing video clip part ID to re-point"),
590
- origin_media_id: mediaIdSchema.describe("The new media asset ID"),
591
- media_duration_ms: positiveMsSchema.describe("The new media's intrinsic full length"),
592
- play_in: timelineMsSchema.describe("Trim window start in the new media (usually 0)"),
593
- play_out: positiveMsSchema.describe("Trim window end in the new media (usually = media_duration_ms)"),
594
- volume: volumeSchema
595
- })).min(1).describe("Video clips whose media is being replaced") });
872
+ replaceClipContent(input) {
873
+ this.transact((draft) => {
874
+ const topology = requireClipTopology(draft, input.clipEntityId);
875
+ const content = requireSequenceContent(draft, input.contentEntityId);
876
+ const payload = {
877
+ ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload"),
878
+ sourceRange: cloneJsonValue(input.sourceRange, "sourceRange"),
879
+ duration: cloneJsonValue(input.duration, "duration")
880
+ };
881
+ delete payload.targetRange;
882
+ delete payload.timeRemapping;
883
+ if (input.targetRange !== void 0) payload.targetRange = cloneJsonValue(input.targetRange, "targetRange");
884
+ if (input.timeRemapping !== void 0) payload.timeRemapping = cloneJsonValue(input.timeRemapping, "timeRemapping");
885
+ replaceEntity(draft, topology.marker.entityId, {
886
+ ...topology.marker,
887
+ payload
888
+ });
889
+ if (!hasOutgoingClipAnchor(draft, topology.clip.entityId)) {
890
+ const clipPayload = { ...cloneJsonObject(topology.clip.payload, "Clip payload") };
891
+ if (input.targetRange === void 0) clipPayload.order ??= nextSequentialOrder(draft, otherEndpoint(topology.trackRelation, topology.clip.entityId));
892
+ else delete clipPayload.order;
893
+ replaceEntity(draft, topology.clip.entityId, {
894
+ ...topology.clip,
895
+ payload: clipPayload
896
+ });
897
+ }
898
+ this.relinkRelation(draft, topology.markerContentRelation, {
899
+ endpoint0EntityId: topology.marker.entityId,
900
+ endpoint1EntityId: content.entityId
901
+ });
902
+ });
903
+ }
904
+ insertMediaClip(input) {
905
+ return this.transact((draft) => {
906
+ if (input.placement.kind === "sequential") this.normalizeMainSequential(draft);
907
+ const imported = importMediaAsset(draft, input.media, this.idFactory);
908
+ replaceRows(draft, imported.rows);
909
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "video_clip");
910
+ const sourceRange = requirePositiveRange(input.sourceRange, "sourceRange");
911
+ const clipId = this.insertPlacedClipIntoDraft(draft, {
912
+ trackEntityId: track.entityId,
913
+ contentEntityId: imported.contentEntityId,
914
+ sourceRange,
915
+ duration: {
916
+ mode: "fixed",
917
+ value: sourceRange.end - sourceRange.start
918
+ },
919
+ placement: input.placement,
920
+ ...input.clipEntityId === void 0 ? {} : { clipEntityId: input.clipEntityId },
921
+ ...input.volume === void 0 ? {} : { clipPayload: { volume: requireVolume(input.volume) } }
922
+ });
923
+ if (input.placement.kind === "sequential") this.resolveOneVoiceoverOverlap(draft);
924
+ return clipId;
925
+ });
926
+ }
927
+ insertMediaClips(input) {
928
+ if (input.clips.length === 0) throw new Error("At least one media Clip is required");
929
+ return this.transact((draft) => {
930
+ this.normalizeMainSequential(draft);
931
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "video_clip");
932
+ const ordered = resolveEntityTimelineLayout(draft).tracks.find((candidate) => candidate.entityId === track.entityId)?.clips ?? [];
933
+ let insertAt = ordered.length;
934
+ const insertion = input.insertion;
935
+ if (insertion.kind === "before" || insertion.kind === "after") {
936
+ const anchorIndex = ordered.findIndex((clip) => clip.clipEntityId === insertion.clipEntityId);
937
+ if (anchorIndex >= 0) insertAt = anchorIndex + (insertion.kind === "after" ? 1 : 0);
938
+ } else {
939
+ const startMs = finiteNonNegative(insertion.startMs, "firstStart.startMs");
940
+ let cursor = 0;
941
+ for (const [index, clip] of ordered.entries()) {
942
+ if (startMs <= cursor + clip.duration / 2) {
943
+ insertAt = index;
944
+ break;
945
+ }
946
+ cursor += clip.duration;
947
+ }
948
+ }
949
+ const created = [];
950
+ for (const [offset, clip] of input.clips.entries()) {
951
+ const imported = importMediaAsset(draft, clip.media, this.idFactory);
952
+ replaceRows(draft, imported.rows);
953
+ const sourceRange = requirePositiveRange(clip.sourceRange, "sourceRange");
954
+ created.push(this.insertPlacedClipIntoDraft(draft, {
955
+ trackEntityId: track.entityId,
956
+ contentEntityId: imported.contentEntityId,
957
+ sourceRange,
958
+ duration: {
959
+ mode: "fixed",
960
+ value: sourceRange.end - sourceRange.start
961
+ },
962
+ placement: {
963
+ kind: "sequential",
964
+ order: ordered.length + offset
965
+ },
966
+ ...clip.clipEntityId === void 0 ? {} : { clipEntityId: clip.clipEntityId },
967
+ ...clip.volume === void 0 ? {} : { clipPayload: { volume: requireVolume(clip.volume) } }
968
+ }));
969
+ }
970
+ const desired = ordered.map((clip) => clip.clipEntityId);
971
+ desired.splice(insertAt, 0, ...created);
972
+ desired.forEach((clipId, order) => setClipOrder(draft, clipId, order));
973
+ this.resolveOneVoiceoverOverlap(draft);
974
+ return created;
975
+ });
976
+ }
977
+ replaceMediaClip(input) {
978
+ this.transact((draft) => {
979
+ this.normalizeMainSequential(draft);
980
+ const topology = requireClipOnRole(draft, input.clipEntityId, "video_clip");
981
+ const imported = importMediaAsset(draft, input.media, this.idFactory);
982
+ replaceRows(draft, imported.rows);
983
+ const sourceRange = requirePositiveRange(input.sourceRange, "sourceRange");
984
+ const markerPayloadValue = {
985
+ ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload"),
986
+ sourceRange,
987
+ duration: {
988
+ mode: "fixed",
989
+ value: sourceRange.end - sourceRange.start
990
+ }
991
+ };
992
+ delete markerPayloadValue.timeRemapping;
993
+ resizeAbsoluteTarget(markerPayloadValue, sourceRange.end - sourceRange.start);
994
+ replaceEntity(draft, topology.marker.entityId, {
995
+ ...topology.marker,
996
+ payload: markerPayloadValue
997
+ });
998
+ this.relinkRelation(draft, topology.markerContentRelation, {
999
+ endpoint0EntityId: topology.marker.entityId,
1000
+ endpoint1EntityId: createEntityId(imported.contentEntityId)
1001
+ });
1002
+ this.resolveOneVoiceoverOverlap(draft);
1003
+ });
1004
+ }
1005
+ setClipVolume(input) {
1006
+ this.transact((draft) => {
1007
+ const topology = requireClipTopology(draft, input.clipEntityId);
1008
+ requireSupportedRole(draft, topology);
1009
+ replaceEntity(draft, topology.clip.entityId, {
1010
+ ...topology.clip,
1011
+ payload: {
1012
+ ...topology.clip.payload,
1013
+ volume: requireVolume(input.volume)
1014
+ }
1015
+ });
1016
+ });
1017
+ }
1018
+ setClipSpeed(input) {
1019
+ this.transact((draft) => {
1020
+ const initialTopology = requireClipOnRole(draft, input.clipEntityId, "video_clip");
1021
+ const content = requireSequenceContent(draft, otherEndpoint(initialTopology.markerContentRelation, initialTopology.marker.entityId));
1022
+ if (content.entityKind !== "video" && content.entityKind !== "image") throw new Error("Clip speed is supported only for Video or Image content");
1023
+ const initialPayload = cloneJsonObject(initialTopology.marker.payload, "Sequence Marker payload");
1024
+ const priorSource = requirePositiveRange(initialPayload.sourceRange, "sourceRange");
1025
+ if (input.timeRemapping === null && initialPayload.timeRemapping === void 0) return;
1026
+ this.normalizeMainSequential(draft);
1027
+ const topology = requireClipTopology(draft, input.clipEntityId);
1028
+ const payload = { ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload") };
1029
+ let sourceRange = priorSource;
1030
+ if (content.entityKind === "image" && initialPayload.timeRemapping === void 0 && input.timeRemapping !== null) sourceRange = {
1031
+ start: 0,
1032
+ end: markerDuration(initialPayload, priorSource)
1033
+ };
1034
+ if (input.timeRemapping === null) {
1035
+ delete payload.timeRemapping;
1036
+ payload.sourceRange = sourceRange;
1037
+ payload.duration = {
1038
+ mode: "fixed",
1039
+ value: sourceRange.end - sourceRange.start
1040
+ };
1041
+ } else {
1042
+ const rate = finitePositive(input.timeRemapping.rate, "linear speed rate");
1043
+ const duration = Math.round((sourceRange.end - sourceRange.start) / rate);
1044
+ if (duration <= 0 || !Number.isSafeInteger(duration)) throw new Error("Linear speed produces an invalid duration");
1045
+ payload.sourceRange = sourceRange;
1046
+ payload.duration = {
1047
+ mode: "fixed",
1048
+ value: duration
1049
+ };
1050
+ payload.timeRemapping = {
1051
+ kind: "linear",
1052
+ rate,
1053
+ ...input.timeRemapping.mode === void 0 ? {} : { mode: input.timeRemapping.mode }
1054
+ };
1055
+ }
1056
+ resizeAbsoluteTarget(payload, markerDuration(payload, sourceRange));
1057
+ replaceEntity(draft, topology.marker.entityId, {
1058
+ ...topology.marker,
1059
+ payload
1060
+ });
1061
+ this.resolveOneVoiceoverOverlap(draft);
1062
+ });
1063
+ }
1064
+ trimClip(input) {
1065
+ this.transact((draft) => {
1066
+ this.normalizeMainSequential(draft);
1067
+ const topology = requireClipOnRole(draft, input.clipEntityId, "video_clip");
1068
+ const content = requireSequenceContent(draft, otherEndpoint(topology.markerContentRelation, topology.marker.entityId));
1069
+ if (content.entityKind !== "video" && content.entityKind !== "image") throw new Error("Clip trimming is supported only for Video or Image content");
1070
+ const sourceRange = requirePositiveRange(input.sourceRange, "sourceRange");
1071
+ const payload = {
1072
+ ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload"),
1073
+ sourceRange
1074
+ };
1075
+ const rate = linearRate(payload.timeRemapping);
1076
+ const duration = Math.round((sourceRange.end - sourceRange.start) / rate);
1077
+ if (duration <= 0 || !Number.isSafeInteger(duration)) throw new Error("Trim produces an invalid duration");
1078
+ payload.duration = {
1079
+ mode: "fixed",
1080
+ value: duration
1081
+ };
1082
+ resizeAbsoluteTarget(payload, duration);
1083
+ replaceEntity(draft, topology.marker.entityId, {
1084
+ ...topology.marker,
1085
+ payload
1086
+ });
1087
+ this.resolveOneVoiceoverOverlap(draft);
1088
+ });
1089
+ }
1090
+ replaceSequentialClips(input) {
1091
+ if (input.oldClipEntityIds.length === 0 || input.newClips.length === 0) throw new Error("Replacement requires at least one old and one new Clip");
1092
+ return this.transact((draft) => {
1093
+ this.normalizeMainSequential(draft);
1094
+ const before = resolveEntityTimelineLayout(draft);
1095
+ const oldIds = new Set(input.oldClipEntityIds);
1096
+ if (oldIds.size !== input.oldClipEntityIds.length) throw new Error("Old Clip ids must be unique");
1097
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "video_clip");
1098
+ const ordered = before.tracks.find((candidate) => candidate.entityId === track.entityId)?.clips.filter((clip) => clip.mode === "sequential").map((clip) => clip.clipEntityId);
1099
+ if (ordered === void 0) throw new Error("The video_clip Track is not present in the current layout");
1100
+ const indexes = input.oldClipEntityIds.map((id) => ordered.indexOf(id));
1101
+ if (indexes.some((index) => index < 0)) throw new Error("Every replaced Clip must be sequential on video_clip");
1102
+ const sortedIndexes = [...indexes].sort((left, right) => left - right);
1103
+ if (sortedIndexes.some((index, offset) => index !== sortedIndexes[0] + offset)) throw new Error("Replaced Clips must form one contiguous timeline run");
1104
+ if (input.oldClipEntityIds.some((id, index) => id !== ordered[sortedIndexes[0] + index])) throw new Error("Replaced Clip ids must be listed in timeline order");
1105
+ const insertOrder = sortedIndexes[0];
1106
+ const temporaryOrder = ordered.length;
1107
+ const created = [];
1108
+ for (const [offset, replacement] of input.newClips.entries()) {
1109
+ if (replacement.clipEntityId !== void 0 && oldIds.has(replacement.clipEntityId)) throw new Error("A replacement Clip id cannot reuse an Entity being removed");
1110
+ const imported = importMediaAsset(draft, replacement.media, this.idFactory);
1111
+ replaceRows(draft, imported.rows);
1112
+ const sourceRange = requirePositiveRange(replacement.sourceRange, "sourceRange");
1113
+ created.push(this.insertPlacedClipIntoDraft(draft, {
1114
+ trackEntityId: track.entityId,
1115
+ contentEntityId: imported.contentEntityId,
1116
+ sourceRange,
1117
+ duration: {
1118
+ mode: "fixed",
1119
+ value: sourceRange.end - sourceRange.start
1120
+ },
1121
+ placement: {
1122
+ kind: "sequential",
1123
+ order: temporaryOrder + offset
1124
+ },
1125
+ ...replacement.clipEntityId === void 0 ? {} : { clipEntityId: replacement.clipEntityId },
1126
+ ...replacement.volume === void 0 ? {} : { clipPayload: { volume: requireVolume(replacement.volume) } }
1127
+ }));
1128
+ }
1129
+ for (const [index, oldId] of input.oldClipEntityIds.entries()) {
1130
+ const children = directAnchorChildren(draft, oldId);
1131
+ if (input.onAnchored === "remap" && created[index] !== void 0) for (const childId of children) this.replaceAnchorHost(draft, childId, created[index]);
1132
+ else {
1133
+ const scheduled = /* @__PURE__ */ new Set();
1134
+ for (const childId of children) {
1135
+ scheduled.add(childId);
1136
+ this.removeAnchoredDescendants(draft, childId, scheduled);
1137
+ this.removeClipGraph(draft, childId);
1138
+ }
1139
+ }
1140
+ }
1141
+ for (const oldId of input.oldClipEntityIds) this.removeClipGraph(draft, oldId);
1142
+ [
1143
+ ...ordered.slice(0, insertOrder),
1144
+ ...created,
1145
+ ...ordered.slice(insertOrder + input.oldClipEntityIds.length)
1146
+ ].forEach((clipId, order) => setClipOrder(draft, clipId, order));
1147
+ this.resolveOneVoiceoverOverlap(draft);
1148
+ return created;
1149
+ });
1150
+ }
1151
+ deleteClip(input) {
1152
+ this.transact((draft) => {
1153
+ const topology = requireClipTopology(draft, input.clipEntityId);
1154
+ assertOnlyStructuralIncidents(draft, topology.clip.entityId, new Set(["track-clip", "clip-marker"]));
1155
+ assertOnlyStructuralIncidents(draft, topology.marker.entityId, new Set(["clip-marker", "marker-content"]));
1156
+ const markerIsExclusive = incidentRelations(draft, topology.marker.entityId).filter((relation) => relation.relationKind === "clip-marker").length === 1;
1157
+ const removedRelationIds = new Set([topology.trackRelation.relationId, topology.clipMarkerRelation.relationId]);
1158
+ if (markerIsExclusive) for (const relation of incidentRelations(draft, topology.marker.entityId)) removedRelationIds.add(relation.relationId);
1159
+ draft.relations = draft.relations.filter((relation) => !removedRelationIds.has(relation.relationId));
1160
+ draft.entities = draft.entities.filter((entity) => entity.entityId !== topology.clip.entityId && (!markerIsExclusive || entity.entityId !== topology.marker.entityId));
1161
+ });
1162
+ }
1163
+ deleteClipTree(input) {
1164
+ if (input.clipEntityIds.length === 0) throw new Error("At least one Clip is required");
1165
+ this.transact((draft) => {
1166
+ const targets = new Set(input.clipEntityIds);
1167
+ if (targets.size !== input.clipEntityIds.length) throw new Error("Clip ids must be unique");
1168
+ for (const target of targets) requireEntityKind(draft, target, "clip");
1169
+ const includesVisual = [...targets].some((target) => clipRole(draft, target) === "video_clip");
1170
+ const original = resolveEntityTimelineLayout(draft);
1171
+ if (includesVisual) this.normalizeMainSequential(draft);
1172
+ if (input.onAnchored === "detach") for (const childId of outgoingAnchorChildren(draft, targets)) {
1173
+ if (targets.has(childId)) continue;
1174
+ const placement = original.clips.get(childId);
1175
+ if (placement === void 0) throw new Error(`Anchored child Clip "${childId}" is not placed`);
1176
+ this.applyClipPlacement(draft, childId, {
1177
+ kind: "absolute",
1178
+ targetRange: {
1179
+ start: placement.start,
1180
+ end: placement.start + placement.duration
1181
+ }
1182
+ });
1183
+ }
1184
+ else for (const target of targets) this.removeAnchoredDescendants(draft, target, targets);
1185
+ for (const target of targets) this.removeClipGraph(draft, target);
1186
+ normalizeSequentialOrders(draft);
1187
+ if (includesVisual) this.resolveOneVoiceoverOverlap(draft);
1188
+ });
1189
+ }
1190
+ updateClip(input) {
1191
+ this.transact((draft) => {
1192
+ const clip = requireEntityKind(draft, input.clipEntityId, "clip");
1193
+ const priorOrder = clip.payload.order;
1194
+ replaceEntity(draft, clip.entityId, {
1195
+ ...clip,
1196
+ payload: {
1197
+ ...cloneJsonObject(input.payload, "Clip payload"),
1198
+ ...priorOrder === void 0 || Object.hasOwn(input.payload, "order") ? {} : { order: priorOrder }
1199
+ }
1200
+ });
1201
+ });
1202
+ }
1203
+ upsertVoiceoverTake(input) {
1204
+ return this.transact((draft) => {
1205
+ this.normalizeMainSequential(draft);
1206
+ const placement = input.placement ?? {
1207
+ kind: "anchored",
1208
+ hostClipEntityId: input.hostClipEntityId,
1209
+ anchorOffset: input.anchorOffset
1210
+ };
1211
+ if (input.placement !== void 0 && (input.hostClipEntityId !== void 0 || input.anchorOffset !== void 0)) throw new Error("Specify Voice placement or hostClipEntityId/anchorOffset, not both");
1212
+ requireVolume(input.volume);
1213
+ const imported = importMediaAsset(draft, input.media, this.idFactory);
1214
+ replaceRows(draft, imported.rows);
1215
+ const voice = requireEntityKind(draft, imported.contentEntityId, "voice");
1216
+ const phonetic = this.requireComposedPhoneticScript(draft, input.phoneticScriptEntityId);
1217
+ this.ensurePhoneticRender(draft, voice.entityId, phonetic.entityId);
1218
+ const speechTrack = this.ensureRoleTrack(draft, input.timelineEntityId, "speech");
1219
+ const existing = draft.entities.find((row) => row.entityId === input.voiceoverClipEntityId);
1220
+ let voiceoverClipEntityId;
1221
+ if (existing === void 0) voiceoverClipEntityId = this.insertPlacedClipIntoDraft(draft, {
1222
+ clipEntityId: input.voiceoverClipEntityId,
1223
+ trackEntityId: speechTrack.entityId,
1224
+ contentEntityId: voice.entityId,
1225
+ sourceRange: {
1226
+ start: 0,
1227
+ end: input.media.durationMs
1228
+ },
1229
+ duration: {
1230
+ mode: "fixed",
1231
+ value: input.media.durationMs
1232
+ },
1233
+ placement,
1234
+ clipPayload: { volume: input.volume }
1235
+ });
1236
+ else {
1237
+ const topology = requireClipOnRole(draft, input.voiceoverClipEntityId, "speech");
1238
+ voiceoverClipEntityId = topology.clip.entityId;
1239
+ replaceEntity(draft, topology.clip.entityId, {
1240
+ ...topology.clip,
1241
+ payload: {
1242
+ ...topology.clip.payload,
1243
+ volume: input.volume
1244
+ }
1245
+ });
1246
+ this.relinkRelation(draft, topology.markerContentRelation, {
1247
+ endpoint0EntityId: topology.marker.entityId,
1248
+ endpoint1EntityId: voice.entityId
1249
+ });
1250
+ this.applyClipPlacement(draft, topology.clip.entityId, placement);
1251
+ const placed = requireClipTopology(draft, topology.clip.entityId);
1252
+ replaceEntity(draft, placed.marker.entityId, {
1253
+ ...placed.marker,
1254
+ payload: {
1255
+ ...placed.marker.payload,
1256
+ sourceRange: {
1257
+ start: 0,
1258
+ end: input.media.durationMs
1259
+ },
1260
+ duration: {
1261
+ mode: "fixed",
1262
+ value: input.media.durationMs
1263
+ }
1264
+ }
1265
+ });
1266
+ }
1267
+ this.reconcileVoiceoverCaptions(draft, voiceoverClipEntityId, voice.entityId, phonetic.entityId, input.captions);
1268
+ this.resolveOneVoiceoverOverlap(draft);
1269
+ return {
1270
+ voiceoverClipEntityId,
1271
+ voiceEntityId: voice.entityId,
1272
+ phoneticScriptEntityId: phonetic.entityId,
1273
+ audioScriptEntityId: requireComposedAudioScript(draft, phonetic.entityId),
1274
+ captionClipEntityIds: input.captions.map((caption) => caption.captionClipEntityId)
1275
+ };
1276
+ });
1277
+ }
1278
+ moveVoiceover(input) {
1279
+ this.transact((draft) => {
1280
+ requireClipOnRole(draft, input.voiceoverClipEntityId, "speech");
1281
+ this.normalizeMainSequential(draft);
1282
+ const layout = resolveEntityTimelineLayout(draft);
1283
+ this.reanchorAtAbsolute(draft, input.voiceoverClipEntityId, finiteNonNegative(input.newStartMs, "newStartMs"), layout);
1284
+ this.resolveOneVoiceoverOverlap(draft);
1285
+ });
1286
+ }
1287
+ deleteVoiceover(input) {
1288
+ this.transact((draft) => {
1289
+ this.normalizeMainSequential(draft);
1290
+ const targets = new Set(input.voiceoverClipEntityIds);
1291
+ if (targets.size !== input.voiceoverClipEntityIds.length) throw new Error("Voiceover Clip ids must be unique");
1292
+ for (const clipId of targets) {
1293
+ requireClipOnRole(draft, clipId, "speech");
1294
+ this.removeAnchoredDescendants(draft, clipId, targets);
1295
+ }
1296
+ for (const clipId of targets) this.removeClipGraph(draft, clipId);
1297
+ this.resolveOneVoiceoverOverlap(draft);
1298
+ });
1299
+ }
1300
+ setBgm(input) {
1301
+ return this.transact((draft) => {
1302
+ const imported = importMediaAsset(draft, input.media, this.idFactory);
1303
+ replaceRows(draft, imported.rows);
1304
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "bgm");
1305
+ const existing = clipsOnTrack(draft, track.entityId);
1306
+ for (const clip of existing) this.removeClipGraph(draft, clip.entityId);
1307
+ const clipId = this.insertPlacedClipIntoDraft(draft, {
1308
+ clipEntityId: input.bgmClipEntityId,
1309
+ trackEntityId: track.entityId,
1310
+ contentEntityId: imported.contentEntityId,
1311
+ sourceRange: {
1312
+ start: 0,
1313
+ end: input.media.durationMs
1314
+ },
1315
+ duration: { mode: "from-source" },
1316
+ placement: {
1317
+ kind: "sequential",
1318
+ order: 0
1319
+ },
1320
+ clipPayload: { volume: requireVolume(input.volume) }
1321
+ });
1322
+ const topology = requireClipTopology(draft, clipId);
1323
+ replaceEntity(draft, topology.marker.entityId, {
1324
+ ...topology.marker,
1325
+ payload: {
1326
+ ...topology.marker.payload,
1327
+ durationPolicy: "timeline"
1328
+ }
1329
+ });
1330
+ return clipId;
1331
+ });
1332
+ }
1333
+ deleteBgm(input) {
1334
+ this.transact((draft) => {
1335
+ const track = findRoleTrack(draft, input.timelineEntityId, "bgm");
1336
+ if (track === void 0) return;
1337
+ for (const clip of clipsOnTrack(draft, track.entityId)) this.removeClipGraph(draft, clip.entityId);
1338
+ });
1339
+ }
1340
+ setCaptionVisibility(input) {
1341
+ this.transact((draft) => {
1342
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "caption");
1343
+ replaceEntity(draft, track.entityId, {
1344
+ ...track,
1345
+ payload: {
1346
+ ...track.payload,
1347
+ hidden: input.hidden
1348
+ }
1349
+ });
1350
+ });
1351
+ }
1352
+ patchCaptionStyle(input) {
1353
+ this.transact((draft) => {
1354
+ const track = findRoleTrack(draft, input.timelineEntityId, "caption");
1355
+ if (track === void 0) return;
1356
+ const patch = cloneJsonObject(input.style, "Caption style");
1357
+ const assembled = new EntityProjectionGraph(draft);
1358
+ for (const clip of clipsOnTrack(draft, track.entityId)) {
1359
+ const topology = requireClipTopology(draft, clip.entityId);
1360
+ const caption = requireEntityKind(draft, otherEndpoint(topology.markerContentRelation, topology.marker.entityId), "caption");
1361
+ const prior = assembled.entity(caption.entityId).payload.style;
1362
+ const style = isJsonObject(prior) ? prior : {};
1363
+ for (const updated of updateEntityFields(draft, caption.entityId, { style: {
1364
+ ...style,
1365
+ ...patch
1366
+ } })) replaceEntity(draft, updated.entityId, updated);
1367
+ }
1368
+ });
1369
+ }
1370
+ /**
1371
+ * Place a Caption as a composed variant of an existing AudioScript: the
1372
+ * entity stores baseEntityIds, selection, optional style, and inherent cue-bounded
1373
+ * Sequence. This helper does not copy base text. The Clip and its display Marker describe this use;
1374
+ * moving or stretching the returned Clip later changes the Clip/Marker,
1375
+ * never the Caption entity or the AudioScript.
1376
+ */
1377
+ insertCaptionClip(input) {
1378
+ return this.transact((draft) => {
1379
+ const durationMs = finitePositive(input.durationMs, "Caption durationMs");
1380
+ const selection = captionSelection(input.selection);
1381
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "caption");
1382
+ const content = {
1383
+ entityId: input.captionEntityId === void 0 ? this.mintEntityId(draft) : requireAvailableEntityId(draft, input.captionEntityId),
1384
+ entityKind: "caption",
1385
+ payload: {
1386
+ extent: {
1387
+ kind: "bounded",
1388
+ start: 0,
1389
+ end: durationMs
1390
+ },
1391
+ sampling: "native",
1392
+ coordinateSpace: "milliseconds",
1393
+ baseEntityIds: captionBaseIds(input.baseEntityIds),
1394
+ selection,
1395
+ ...input.style === void 0 ? {} : { style: cloneJsonObject(input.style, "Caption style") }
1396
+ }
1397
+ };
1398
+ draft.entities.push(content);
1399
+ assembleCaptionContent(draft, content.entityId);
1400
+ return this.insertPlacedClipIntoDraft(draft, {
1401
+ trackEntityId: track.entityId,
1402
+ contentEntityId: content.entityId,
1403
+ sourceRange: {
1404
+ start: 0,
1405
+ end: durationMs
1406
+ },
1407
+ duration: {
1408
+ mode: "fixed",
1409
+ value: durationMs
1410
+ },
1411
+ placement: input.placement,
1412
+ ...input.captionClipEntityId === void 0 ? {} : { clipEntityId: input.captionClipEntityId }
1413
+ });
1414
+ });
1415
+ }
1416
+ insertPlacedClipIntoDraft(draft, input) {
1417
+ const track = requireEntityKind(draft, input.trackEntityId, "track");
1418
+ requireTrackTimeline(draft, track.entityId);
1419
+ const content = requireSequenceContent(draft, input.contentEntityId);
1420
+ const clipId = input.clipEntityId === void 0 ? this.mintEntityId(draft) : requireAvailableEntityId(draft, input.clipEntityId);
1421
+ const markerId = this.mintEntityId(draft);
1422
+ const clipPayload = { ...cloneJsonObject(input.clipPayload ?? {}, "Clip payload") };
1423
+ delete clipPayload.order;
1424
+ const markerPlacement = applyPlacementPayload(clipPayload, input.placement);
1425
+ const clip = {
1426
+ entityId: clipId,
1427
+ entityKind: "clip",
1428
+ payload: clipPayload
1429
+ };
1430
+ const marker = {
1431
+ entityId: markerId,
1432
+ entityKind: "sequence-marker",
1433
+ payload: markerPayload({
1434
+ sourceRange: input.sourceRange,
1435
+ duration: input.duration,
1436
+ ...markerPlacement
1437
+ })
1438
+ };
1439
+ draft.entities.push(clip, marker);
1440
+ draft.relations.push(this.createRelation(draft, "track-clip", track.entityId, clipId), this.createRelation(draft, "clip-marker", clipId, markerId), this.createRelation(draft, "marker-content", markerId, content.entityId));
1441
+ if (input.placement.kind === "anchored") {
1442
+ const host = requireEntityKind(draft, input.placement.hostClipEntityId, "clip");
1443
+ if (host.entityId === clipId) throw new Error("A Clip cannot anchor to itself");
1444
+ draft.relations.push(this.createRelation(draft, "clip-anchor", clipId, host.entityId));
1445
+ }
1446
+ return clipId;
1447
+ }
1448
+ ensureRoleTrack(draft, timelineEntityId, role) {
1449
+ const existing = findRoleTrack(draft, timelineEntityId, role);
1450
+ if (existing !== void 0) {
1451
+ if (existing.payload.order === void 0) {
1452
+ const replacement = {
1453
+ ...existing,
1454
+ payload: {
1455
+ ...existing.payload,
1456
+ order: roleOrder[role]
1457
+ }
1458
+ };
1459
+ replaceEntity(draft, existing.entityId, replacement);
1460
+ return replacement;
1461
+ }
1462
+ return existing;
1463
+ }
1464
+ const timeline = requireEntityKind(draft, timelineEntityId, "timeline");
1465
+ const track = {
1466
+ entityId: this.mintEntityId(draft),
1467
+ entityKind: "track",
1468
+ payload: {
1469
+ role,
1470
+ order: roleOrder[role]
1471
+ }
1472
+ };
1473
+ draft.entities.push(track);
1474
+ draft.relations.push(this.createRelation(draft, "timeline-track", timeline.entityId, track.entityId));
1475
+ return track;
1476
+ }
1477
+ /** The existing pronunciation variant a Voice consumes; composition is required. */
1478
+ requireComposedPhoneticScript(draft, phoneticScriptEntityId) {
1479
+ const phonetic = requireEntityKind(draft, phoneticScriptEntityId, "phonetic-script");
1480
+ requireComposedAudioScript(draft, phonetic.entityId);
1481
+ return phonetic;
1482
+ }
1483
+ /** Preserve the factual synthesis input, regardless of persisted endpoint positions. */
1484
+ ensurePhoneticRender(draft, voiceEntityId, phoneticScriptEntityId) {
1485
+ const renders = draft.relations.filter((relation) => relation.relationKind === "phonetic-script-render" && (relation.endpoint0EntityId === voiceEntityId || relation.endpoint1EntityId === voiceEntityId));
1486
+ if (renders.length > 1) throw new Error(`Voice "${voiceEntityId}" has multiple PhoneticScript render relations`);
1487
+ if (renders[0] !== void 0) {
1488
+ if (otherEndpoint(renders[0], voiceEntityId) === phoneticScriptEntityId) return;
1489
+ throw new Error(`Voice "${voiceEntityId}" already has a different PhoneticScript synthesis input`);
1490
+ }
1491
+ draft.relations.push(this.createRelation(draft, "phonetic-script-render", voiceEntityId, phoneticScriptEntityId));
1492
+ }
1493
+ reconcileVoiceoverCaptions(draft, voiceoverClipEntityId, voiceEntityId, phoneticScriptEntityId, captions) {
1494
+ const audioScriptEntityId = requireComposedAudioScript(draft, phoneticScriptEntityId);
1495
+ const requested = new Set(captions.map((caption) => caption.captionClipEntityId));
1496
+ if (requested.size !== captions.length) throw new Error("Caption Clip ids must be unique within a voiceover take");
1497
+ const existing = directAnchorChildren(draft, voiceoverClipEntityId).filter((clipId) => clipRole(draft, clipId) === "caption");
1498
+ for (const clipId of existing) if (!requested.has(clipId)) this.removeCaptionClipGraph(draft, clipId);
1499
+ const captionTrack = captions.length === 0 ? void 0 : this.ensureRoleTrackForClip(draft, voiceoverClipEntityId, "caption");
1500
+ for (const caption of captions) {
1501
+ const startMs = finiteNonNegative(caption.startMs, "Caption startMs");
1502
+ const durationMs = finitePositive(caption.durationMs, "Caption durationMs");
1503
+ const selection = captionSelection(caption.selection);
1504
+ const baseEntityIds = captionBaseIds(caption.baseEntityIds);
1505
+ if (draft.entities.find((entity) => entity.entityId === caption.captionClipEntityId) === void 0) {
1506
+ const content = {
1507
+ entityId: this.mintEntityId(draft),
1508
+ entityKind: "caption",
1509
+ payload: {
1510
+ extent: {
1511
+ kind: "bounded",
1512
+ start: 0,
1513
+ end: durationMs
1514
+ },
1515
+ sampling: "native",
1516
+ coordinateSpace: "milliseconds",
1517
+ baseEntityIds,
1518
+ selection,
1519
+ ...caption.style === void 0 ? {} : { style: cloneJsonObject(caption.style, "Caption style") }
1520
+ }
1521
+ };
1522
+ draft.entities.push(content);
1523
+ assertCaptionScript(draft, content.entityId, audioScriptEntityId);
1524
+ draft.relations.push(this.createRelation(draft, "caption-alignment", content.entityId, voiceEntityId, { alignment: {
1525
+ start: startMs,
1526
+ end: startMs + durationMs
1527
+ } }));
1528
+ this.insertPlacedClipIntoDraft(draft, {
1529
+ clipEntityId: caption.captionClipEntityId,
1530
+ trackEntityId: captionTrack.entityId,
1531
+ contentEntityId: content.entityId,
1532
+ sourceRange: {
1533
+ start: 0,
1534
+ end: durationMs
1535
+ },
1536
+ duration: {
1537
+ mode: "fixed",
1538
+ value: durationMs
1539
+ },
1540
+ placement: {
1541
+ kind: "anchored",
1542
+ hostClipEntityId: voiceoverClipEntityId,
1543
+ anchorOffset: startMs
1544
+ }
1545
+ });
1546
+ continue;
1547
+ }
1548
+ const topology = requireClipOnRole(draft, caption.captionClipEntityId, "caption");
1549
+ const content = requireEntityKind(draft, otherEndpoint(topology.markerContentRelation, topology.marker.entityId), "caption");
1550
+ const priorStyle = isJsonObject(content.payload.style) ? content.payload.style : {};
1551
+ const style = caption.style === void 0 ? priorStyle : {
1552
+ ...priorStyle,
1553
+ ...cloneJsonObject(caption.style, "Caption style")
1554
+ };
1555
+ replaceEntity(draft, content.entityId, {
1556
+ ...content,
1557
+ payload: {
1558
+ ...content.payload,
1559
+ baseEntityIds,
1560
+ selection,
1561
+ ...Object.keys(style).length === 0 ? {} : { style }
1562
+ }
1563
+ });
1564
+ assertCaptionScript(draft, content.entityId, audioScriptEntityId);
1565
+ this.applyClipPlacement(draft, topology.clip.entityId, {
1566
+ kind: "anchored",
1567
+ hostClipEntityId: voiceoverClipEntityId,
1568
+ anchorOffset: startMs
1569
+ });
1570
+ const placed = requireClipTopology(draft, topology.clip.entityId);
1571
+ replaceEntity(draft, placed.marker.entityId, {
1572
+ ...placed.marker,
1573
+ payload: {
1574
+ ...placed.marker.payload,
1575
+ duration: {
1576
+ mode: "fixed",
1577
+ value: durationMs
1578
+ }
1579
+ }
1580
+ });
1581
+ this.replaceCaptionAlignment(draft, content.entityId, voiceEntityId, startMs, durationMs);
1582
+ }
1583
+ }
1584
+ ensureRoleTrackForClip(draft, clipEntityId, role) {
1585
+ const topology = requireClipTopology(draft, clipEntityId);
1586
+ const track = requireEntityKind(draft, otherEndpoint(topology.trackRelation, topology.clip.entityId), "track");
1587
+ const timeline = requireEntityKind(draft, otherEndpoint(requireOneRelation(draft, track.entityId, "timeline-track"), track.entityId), "timeline");
1588
+ return this.ensureRoleTrack(draft, timeline.entityId, role);
1589
+ }
1590
+ replaceCaptionAlignment(draft, captionEntityId, voiceEntityId, startMs, durationMs) {
1591
+ const removed = new Set(incidentRelations(draft, captionEntityId).filter((relation) => relation.relationKind === "caption-alignment").map((relation) => relation.relationId));
1592
+ draft.relations = draft.relations.filter((relation) => !removed.has(relation.relationId));
1593
+ draft.relations.push(this.createRelation(draft, "caption-alignment", captionEntityId, voiceEntityId, { alignment: {
1594
+ start: startMs,
1595
+ end: startMs + durationMs
1596
+ } }));
1597
+ }
1598
+ /**
1599
+ * Remove one placed Caption use. The composed AudioScript outlives the
1600
+ * caption: it may anchor further captions and remains the text owner.
1601
+ */
1602
+ removeCaptionClipGraph(draft, clipEntityId) {
1603
+ const topology = requireClipOnRole(draft, clipEntityId, "caption");
1604
+ const caption = requireEntityKind(draft, otherEndpoint(topology.markerContentRelation, topology.marker.entityId), "caption");
1605
+ const contentRelations = incidentRelations(draft, caption.entityId);
1606
+ const allowed = new Set(["caption-alignment", "marker-content"]);
1607
+ const unsupported = contentRelations.filter((relation) => !allowed.has(relation.relationKind));
1608
+ if (unsupported.length > 0) throw new Error(`Cannot delete Caption with unsupported Relation ${unsupported[0].relationId}`);
1609
+ this.removeClipGraph(draft, clipEntityId);
1610
+ if (incidentRelations(draft, caption.entityId).some((relation) => relation.relationKind === "marker-content")) return;
1611
+ const removed = new Set(incidentRelations(draft, caption.entityId).map((relation) => relation.relationId));
1612
+ draft.relations = draft.relations.filter((relation) => !removed.has(relation.relationId));
1613
+ draft.entities = draft.entities.filter((entity) => entity.entityId !== caption.entityId);
1614
+ }
1615
+ replaceAnchorHost(draft, childClipEntityId, hostClipEntityId) {
1616
+ const anchors = draft.relations.filter((relation) => relation.relationKind === "clip-anchor" && relation.endpoint0EntityId === childClipEntityId);
1617
+ if (anchors.length !== 1) throw new Error(`Clip "${childClipEntityId}" must have exactly one host`);
1618
+ this.relinkRelation(draft, anchors[0], {
1619
+ endpoint0EntityId: createEntityId(childClipEntityId),
1620
+ endpoint1EntityId: createEntityId(hostClipEntityId)
1621
+ });
1622
+ }
1623
+ /** Rebuild the legacy edit baseline from current visual order before a high-level cascade. */
1624
+ normalizeMainSequential(draft) {
1625
+ const videoTrack = resolveEntityTimelineLayout(draft).tracks.find((track) => track.role === "video_clip");
1626
+ if (videoTrack === void 0) return;
1627
+ videoTrack.clips.forEach((clip, order) => {
1628
+ this.applyClipPlacement(draft, clip.clipEntityId, {
1629
+ kind: "sequential",
1630
+ order
1631
+ });
1632
+ });
1633
+ }
1634
+ resolveOneVoiceoverOverlap(draft) {
1635
+ const layout = resolveEntityTimelineLayout(draft);
1636
+ const speechTrack = layout.tracks.find((track) => track.role === "speech");
1637
+ if (speechTrack === void 0) return;
1638
+ const ranges = speechTrack.clips.map((speech) => {
1639
+ const captions = directAnchorChildren(draft, speech.clipEntityId).filter((clipId) => clipRole(draft, clipId) === "caption").map((clipId) => layout.clips.get(clipId)).filter((value) => value !== void 0);
1640
+ return {
1641
+ speech,
1642
+ start: Math.min(speech.start, ...captions.map((caption) => caption.start)),
1643
+ end: Math.max(speech.start + speech.duration, ...captions.map((caption) => caption.start + caption.duration))
1644
+ };
1645
+ }).sort((left, right) => left.start - right.start || left.speech.clipEntityId.localeCompare(right.speech.clipEntityId));
1646
+ for (let index = 1; index < ranges.length; index += 1) {
1647
+ const prior = ranges[index - 1];
1648
+ const current = ranges[index];
1649
+ if (current.start >= prior.end) continue;
1650
+ const hostId = current.speech.anchorClipEntityId;
1651
+ if (hostId === void 0) continue;
1652
+ const videoTrack = layout.tracks.find((track) => track.role === "video_clip");
1653
+ const hostIndex = videoTrack?.clips.findIndex((clip) => clip.clipEntityId === hostId) ?? -1;
1654
+ if (videoTrack === void 0 || hostIndex < 0) continue;
1655
+ const overlapMs = Math.round(prior.end - current.start);
1656
+ for (const [visualIndex, clip] of videoTrack.clips.entries()) this.applyClipPlacement(draft, clip.clipEntityId, {
1657
+ kind: "absolute",
1658
+ targetRange: {
1659
+ start: clip.start + (visualIndex >= hostIndex ? overlapMs : 0),
1660
+ end: clip.start + clip.duration + (visualIndex >= hostIndex ? overlapMs : 0)
1661
+ }
1662
+ });
1663
+ return;
1664
+ }
1665
+ }
1666
+ applyClipPlacement(draft, clipEntityId, placement) {
1667
+ const topology = requireClipTopology(draft, clipEntityId);
1668
+ const clipPayload = { ...cloneJsonObject(topology.clip.payload, "Clip payload") };
1669
+ const markerPayloadValue = { ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload") };
1670
+ delete clipPayload.order;
1671
+ delete markerPayloadValue.targetRange;
1672
+ delete markerPayloadValue.anchorOffset;
1673
+ const outgoingAnchors = draft.relations.filter((relation) => relation.relationKind === "clip-anchor" && relation.endpoint0EntityId === topology.clip.entityId);
1674
+ const removed = new Set(outgoingAnchors.map((relation) => relation.relationId));
1675
+ draft.relations = draft.relations.filter((relation) => !removed.has(relation.relationId));
1676
+ if (placement.kind === "sequential") clipPayload.order = finiteNumber(placement.order, "Clip order");
1677
+ else if (placement.kind === "absolute") markerPayloadValue.targetRange = cloneJsonValue(placement.targetRange, "targetRange");
1678
+ else {
1679
+ const host = requireEntityKind(draft, placement.hostClipEntityId, "clip");
1680
+ if (host.entityId === topology.clip.entityId) throw new Error("A Clip cannot anchor to itself");
1681
+ markerPayloadValue.anchorOffset = finiteNonNegative(placement.anchorOffset, "anchorOffset");
1682
+ draft.relations.push(this.createRelation(draft, "clip-anchor", topology.clip.entityId, host.entityId));
1683
+ }
1684
+ replaceEntity(draft, topology.clip.entityId, {
1685
+ ...topology.clip,
1686
+ payload: clipPayload
1687
+ });
1688
+ replaceEntity(draft, topology.marker.entityId, {
1689
+ ...topology.marker,
1690
+ payload: markerPayloadValue
1691
+ });
1692
+ }
1693
+ reanchorAtAbsolute(draft, childClipEntityId, absoluteStart, layout) {
1694
+ const hosts = layout.tracks.find((track) => track.role === "video_clip")?.clips.filter((clip) => clip.mode === "sequential") ?? [];
1695
+ if (hosts.length === 0) {
1696
+ const child = layout.clips.get(childClipEntityId);
1697
+ if (child === void 0) throw new Error(`Clip "${childClipEntityId}" is not placed`);
1698
+ this.applyClipPlacement(draft, childClipEntityId, {
1699
+ kind: "absolute",
1700
+ targetRange: {
1701
+ start: absoluteStart,
1702
+ end: absoluteStart + child.duration
1703
+ }
1704
+ });
1705
+ return;
1706
+ }
1707
+ const host = hosts.find((candidate) => candidate.start <= absoluteStart && absoluteStart < candidate.start + candidate.duration) ?? (absoluteStart < hosts[0].start ? hosts[0] : hosts.at(-1));
1708
+ this.applyClipPlacement(draft, childClipEntityId, {
1709
+ kind: "anchored",
1710
+ hostClipEntityId: host.clipEntityId,
1711
+ anchorOffset: Math.max(0, Math.round(absoluteStart - host.start))
1712
+ });
1713
+ }
1714
+ removeAnchoredDescendants(draft, hostClipEntityId, scheduled) {
1715
+ const children = draft.relations.filter((relation) => relation.relationKind === "clip-anchor" && relation.endpoint1EntityId === hostClipEntityId).map((relation) => String(relation.endpoint0EntityId));
1716
+ for (const child of children) {
1717
+ if (scheduled.has(child)) continue;
1718
+ const descendants = new Set(scheduled);
1719
+ descendants.add(child);
1720
+ this.removeAnchoredDescendants(draft, child, descendants);
1721
+ if (clipRole(draft, child) === "caption") this.removeCaptionClipGraph(draft, child);
1722
+ else this.removeClipGraph(draft, child);
1723
+ }
1724
+ }
1725
+ removeClipGraph(draft, clipEntityId) {
1726
+ const topology = requireClipTopology(draft, clipEntityId);
1727
+ assertOnlyStructuralIncidents(draft, topology.clip.entityId, new Set([
1728
+ "track-clip",
1729
+ "clip-marker",
1730
+ "clip-anchor"
1731
+ ]));
1732
+ assertOnlyStructuralIncidents(draft, topology.marker.entityId, new Set(["clip-marker", "marker-content"]));
1733
+ const markerIsExclusive = incidentRelations(draft, topology.marker.entityId).filter((relation) => relation.relationKind === "clip-marker").length === 1;
1734
+ const removed = new Set(incidentRelations(draft, topology.clip.entityId).map((relation) => relation.relationId));
1735
+ if (markerIsExclusive) for (const relation of incidentRelations(draft, topology.marker.entityId)) removed.add(relation.relationId);
1736
+ draft.relations = draft.relations.filter((relation) => !removed.has(relation.relationId));
1737
+ draft.entities = draft.entities.filter((entity) => entity.entityId !== topology.clip.entityId && (!markerIsExclusive || entity.entityId !== topology.marker.entityId));
1738
+ }
1739
+ transact(edit) {
1740
+ const draft = cloneRows(this.state);
1741
+ const result = edit(draft);
1742
+ validateFinalRows(draft);
1743
+ assertMediaAssetWritePolicy(this.state, draft);
1744
+ this.state = draft;
1745
+ return result;
1746
+ }
1747
+ mintEntityId(draft) {
1748
+ const entityId = createEntityId(this.idFactory("entity"));
1749
+ if (draft.entities.some((entity) => entity.entityId === entityId)) throw new Error(`Entity id "${entityId}" already exists`);
1750
+ return entityId;
1751
+ }
1752
+ createRelation(draft, relationKind, endpoint0EntityId, endpoint1EntityId, metadata = {}) {
1753
+ return {
1754
+ relationId: this.mintRelationId(draft),
1755
+ relationKind,
1756
+ endpoint0EntityId,
1757
+ endpoint1EntityId,
1758
+ metadata,
1759
+ trace: {}
1760
+ };
1761
+ }
1762
+ relinkRelation(draft, relation, endpoints) {
1763
+ const relationId = this.mintRelationId(draft);
1764
+ const index = draft.relations.findIndex((candidate) => candidate.relationId === relation.relationId);
1765
+ if (index < 0) throw new Error(`Relation id "${relation.relationId}" does not exist`);
1766
+ draft.relations[index] = {
1767
+ ...relation,
1768
+ ...endpoints,
1769
+ relationId
1770
+ };
1771
+ }
1772
+ mintRelationId(draft) {
1773
+ const relationId = createRelationId(this.idFactory("relation"));
1774
+ if (draft.relations.some((relation) => relation.relationId === relationId)) throw new Error(`Relation id "${relationId}" already exists`);
1775
+ return relationId;
1776
+ }
1777
+ };
1778
+ function validateFinalRows(rows) {
1779
+ decodeEntityRelationRows(rows, numericMarkerValidation);
1780
+ assertCanonicalEditorResources(rows);
1781
+ validateTimelineHierarchy(rows);
1782
+ }
1783
+ function validateTimelineHierarchy(rows) {
1784
+ for (const entity of rows.entities) {
1785
+ if (entity.entityKind === "track") requireTrackTimeline(rows, entity.entityId);
1786
+ if (entity.entityKind !== "clip") continue;
1787
+ const trackRelations = incidentRelations(rows, entity.entityId).filter((relation) => relation.relationKind === "track-clip");
1788
+ if (trackRelations.length !== 1) throw new Error(`Clip Entity "${entity.entityId}" must belong to exactly one Track`);
1789
+ requireEntityKind(rows, otherEndpoint(trackRelations[0], entity.entityId), "track");
1790
+ }
1791
+ }
1792
+ function requireTrackTimeline(rows, trackEntityId) {
1793
+ const timelineRelations = incidentRelations(rows, trackEntityId).filter((relation) => relation.relationKind === "timeline-track");
1794
+ if (timelineRelations.filter((relation) => {
1795
+ const otherId = otherEndpoint(relation, trackEntityId);
1796
+ return rows.entities.some((entity) => entity.entityId === otherId && entity.entityKind === "timeline");
1797
+ }).length !== 1 || timelineRelations.length !== 1) throw new Error(`Track Entity "${trackEntityId}" must belong to exactly one Timeline`);
1798
+ }
1799
+ function requireClipTopology(rows, clipEntityId) {
1800
+ const clip = requireEntityKind(rows, clipEntityId, "clip");
1801
+ const trackRelation = requireOneRelation(rows, clip.entityId, "track-clip");
1802
+ requireEntityKind(rows, otherEndpoint(trackRelation, clip.entityId), "track");
1803
+ const clipMarkerRelation = requireOneRelation(rows, clip.entityId, "clip-marker");
1804
+ const marker = requireEntityKind(rows, otherEndpoint(clipMarkerRelation, clip.entityId), "sequence-marker");
1805
+ const markerContentRelation = requireOneRelation(rows, marker.entityId, "marker-content");
1806
+ requireSequenceContent(rows, otherEndpoint(markerContentRelation, marker.entityId));
1807
+ return {
1808
+ clip,
1809
+ marker,
1810
+ trackRelation,
1811
+ clipMarkerRelation,
1812
+ markerContentRelation
1813
+ };
1814
+ }
1815
+ function requireOneRelation(rows, entityId, relationKind) {
1816
+ const matches = incidentRelations(rows, entityId).filter((relation) => relation.relationKind === relationKind);
1817
+ if (matches.length !== 1) throw new Error(`Entity "${entityId}" must have exactly one ${relationKind} Relation`);
1818
+ return matches[0];
1819
+ }
1820
+ function requireEntityKind(rows, entityIdValue, entityKind) {
1821
+ const entityId = createEntityId(entityIdValue);
1822
+ const entity = rows.entities.find((candidate) => candidate.entityId === entityId);
1823
+ if (entity == null) throw new Error(`Entity id "${entityId}" does not exist`);
1824
+ if (entity.entityKind !== entityKind) throw new Error(`Entity "${entityId}" must have kind "${entityKind}", got "${entity.entityKind}"`);
1825
+ return entity;
1826
+ }
1827
+ function requireSequenceContent(rows, entityIdValue) {
1828
+ if (/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(entityIdValue)) throw new Error("Timeline content must reference an existing Sequence media Entity id; a URL is not allowed");
1829
+ const entityId = createEntityId(entityIdValue);
1830
+ const row = rows.entities.find((candidate) => candidate.entityId === entityId);
1831
+ if (row == null) throw new Error(`Timeline content must reference an existing Sequence media Entity; "${entityId}" was not found`);
1832
+ if (!hasSequence({
1833
+ ...row.payload,
1834
+ entityId: row.entityId,
1835
+ entityKind: row.entityKind
1836
+ })) throw new Error(`Timeline content must reference a Sequence media Entity, but "${entityId}" has kind "${row.entityKind}"`);
1837
+ return row;
1838
+ }
1839
+ function assertOnlyStructuralIncidents(rows, entityId, allowedKinds) {
1840
+ const unsupported = incidentRelations(rows, entityId).filter((relation) => !allowedKinds.has(relation.relationKind));
1841
+ if (unsupported.length === 0) return;
1842
+ throw new Error(`Cannot delete Clip graph: Entity "${entityId}" has unsupported incident Relation id(s): ${unsupported.map((relation) => relation.relationId).sort().join(", ")}`);
1843
+ }
1844
+ function incidentRelations(rows, entityId) {
1845
+ return rows.relations.filter((relation) => relation.endpoint0EntityId === entityId || relation.endpoint1EntityId === entityId);
1846
+ }
1847
+ function hasOutgoingClipAnchor(rows, clipEntityId) {
1848
+ return rows.relations.some((relation) => relation.relationKind === "clip-anchor" && relation.endpoint0EntityId === clipEntityId);
1849
+ }
1850
+ function outgoingAnchorChildren(rows, hostIds) {
1851
+ return rows.relations.filter((relation) => relation.relationKind === "clip-anchor" && hostIds.has(relation.endpoint1EntityId)).map((relation) => String(relation.endpoint0EntityId));
1852
+ }
1853
+ function applyPlacementPayload(clipPayload, placement) {
1854
+ if (placement.kind === "sequential") {
1855
+ clipPayload.order = finiteNumber(placement.order, "Clip order");
1856
+ return {};
1857
+ }
1858
+ if (placement.kind === "absolute") return { targetRange: cloneJsonValue(placement.targetRange, "targetRange") };
1859
+ return { anchorOffset: finiteNonNegative(placement.anchorOffset, "anchorOffset") };
1860
+ }
1861
+ function requireAvailableEntityId(rows, value) {
1862
+ const entityId = createEntityId(value);
1863
+ if (rows.entities.some((entity) => entity.entityId === entityId)) throw new Error(`Entity id "${entityId}" already exists`);
1864
+ return entityId;
1865
+ }
1866
+ function setClipOrder(rows, clipEntityId, order) {
1867
+ const clip = requireEntityKind(rows, clipEntityId, "clip");
1868
+ replaceEntity(rows, clip.entityId, {
1869
+ ...clip,
1870
+ payload: {
1871
+ ...clip.payload,
1872
+ order
1873
+ }
1874
+ });
1875
+ }
1876
+ function normalizeSequentialOrders(rows) {
1877
+ for (const track of rows.entities.filter((entity) => entity.entityKind === "track")) rows.relations.filter((relation) => relation.relationKind === "track-clip" && relation.endpoint0EntityId === track.entityId).map((relation) => rows.entities.find((entity) => entity.entityId === relation.endpoint1EntityId)).filter((entity) => entity?.entityKind === "clip" && typeof entity.payload.order === "number").sort((left, right) => Number(left.payload.order) - Number(right.payload.order)).forEach((clip, order) => setClipOrder(rows, clip.entityId, order));
1878
+ }
1879
+ function findRoleTrack(rows, timelineEntityId, role) {
1880
+ const timeline = requireEntityKind(rows, timelineEntityId, "timeline");
1881
+ const tracks = incidentRelations(rows, timeline.entityId).filter((relation) => relation.relationKind === "timeline-track").map((relation) => requireEntityKind(rows, otherEndpoint(relation, timeline.entityId), "track")).filter((track) => track.payload.role === role);
1882
+ if (tracks.length > 1) throw new Error(`Timeline "${timelineEntityId}" has multiple ${role} Tracks`);
1883
+ return tracks[0];
1884
+ }
1885
+ function clipsOnTrack(rows, trackEntityId) {
1886
+ return incidentRelations(rows, trackEntityId).filter((relation) => relation.relationKind === "track-clip").map((relation) => requireEntityKind(rows, otherEndpoint(relation, trackEntityId), "clip"));
1887
+ }
1888
+ function clipRole(rows, clipEntityId) {
1889
+ const topology = requireClipTopology(rows, clipEntityId);
1890
+ return requireEntityKind(rows, otherEndpoint(topology.trackRelation, topology.clip.entityId), "track").payload.role;
1891
+ }
1892
+ function directAnchorChildren(rows, hostClipEntityId) {
1893
+ return rows.relations.filter((relation) => relation.relationKind === "clip-anchor" && relation.endpoint1EntityId === hostClipEntityId).map((relation) => String(relation.endpoint0EntityId));
1894
+ }
1895
+ function requireSupportedRole(rows, topology) {
1896
+ const role = requireEntityKind(rows, otherEndpoint(topology.trackRelation, topology.clip.entityId), "track").payload.role;
1897
+ if (role !== "video_clip" && role !== "speech" && role !== "caption" && role !== "bgm") throw new Error(`Clip "${topology.clip.entityId}" is not on a supported timeline Track`);
1898
+ return role;
1899
+ }
1900
+ function requireClipOnRole(rows, clipEntityId, role) {
1901
+ const topology = requireClipTopology(rows, clipEntityId);
1902
+ if (requireEntityKind(rows, otherEndpoint(topology.trackRelation, topology.clip.entityId), "track").payload.role !== role) throw new Error(`Clip "${clipEntityId}" must belong to the ${role} Track`);
1903
+ return topology;
1904
+ }
1905
+ function finiteNumber(value, label) {
1906
+ if (!Number.isFinite(value)) throw new Error(`${label} must be finite`);
1907
+ return value;
1908
+ }
1909
+ function finitePositive(value, label) {
1910
+ const result = finiteNumber(value, label);
1911
+ if (result <= 0) throw new Error(`${label} must be positive`);
1912
+ return result;
1913
+ }
1914
+ function requireVolume(value) {
1915
+ const volume = finiteNumber(value, "Clip volume");
1916
+ if (volume < -60 || volume > 20) throw new Error("Clip volume must be between -60 and 20 dB");
1917
+ return volume;
1918
+ }
1919
+ function requirePositiveRange(value, label) {
1920
+ if (!isJsonObject(value)) throw new Error(`${label} must be an object`);
1921
+ const start = finiteNonNegative(value.start, `${label}.start`);
1922
+ const end = finitePositive(value.end, `${label}.end`);
1923
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || end <= start) throw new Error(`${label} must be a positive whole-millisecond range`);
1924
+ return {
1925
+ start,
1926
+ end
1927
+ };
1928
+ }
1929
+ function markerDuration(payload, sourceRange) {
1930
+ const duration = payload.duration;
1931
+ if (!isJsonObject(duration)) throw new Error("Sequence Marker duration must be an object");
1932
+ if (duration.mode === "from-source") return sourceRange.end - sourceRange.start;
1933
+ if (duration.mode !== "fixed") throw new Error("Sequence Marker duration mode is unsupported");
1934
+ return finitePositive(duration.value, "Sequence Marker fixed duration");
1935
+ }
1936
+ function linearRate(value) {
1937
+ if (value === void 0) return 1;
1938
+ if (!isJsonObject(value) || value.kind !== "linear") throw new Error("Only linear Clip time remapping is supported");
1939
+ return finitePositive(value.rate, "linear speed rate");
1940
+ }
1941
+ function resizeAbsoluteTarget(payload, duration) {
1942
+ if (payload.targetRange === void 0) return;
1943
+ const target = requirePositiveRange(payload.targetRange, "targetRange");
1944
+ payload.targetRange = {
1945
+ start: target.start,
1946
+ end: target.start + duration
1947
+ };
1948
+ }
1949
+ function replaceRows(rows, replacement) {
1950
+ rows.entities = structuredClone([...replacement.entities]);
1951
+ rows.relations = structuredClone([...replacement.relations]);
1952
+ }
1953
+ function finiteNonNegative(value, label) {
1954
+ const result = finiteNumber(value, label);
1955
+ if (result < 0) throw new Error(`${label} must be non-negative`);
1956
+ return result;
1957
+ }
1958
+ function nextSequentialOrder(rows, trackEntityId) {
1959
+ const orders = rows.relations.filter((relation) => relation.relationKind === "track-clip" && relation.endpoint0EntityId === trackEntityId).map((relation) => rows.entities.find((entity) => entity.entityId === relation.endpoint1EntityId)?.payload.order).filter((order) => typeof order === "number" && Number.isFinite(order));
1960
+ return orders.length === 0 ? 0 : Math.max(...orders) + 1;
1961
+ }
1962
+ function otherEndpoint(relation, entityId) {
1963
+ if (relation.endpoint0EntityId === entityId) return relation.endpoint1EntityId;
1964
+ if (relation.endpoint1EntityId === entityId) return relation.endpoint0EntityId;
1965
+ throw new Error(`Relation "${relation.relationId}" is not incident to Entity "${entityId}"`);
1966
+ }
1967
+ function replaceEntity(rows, entityId, replacement) {
1968
+ const index = rows.entities.findIndex((entity) => entity.entityId === entityId);
1969
+ if (index < 0) throw new Error(`Entity id "${entityId}" does not exist`);
1970
+ rows.entities[index] = replacement;
1971
+ }
1972
+ function markerPayload(value) {
1973
+ return cloneJsonObject(value, "Sequence Marker payload");
1974
+ }
1975
+ function cloneJsonObject(value, label) {
1976
+ const cloned = structuredClone(value);
1977
+ if (!isJsonObject(cloned)) throw new Error(`${label} must contain only JSON values`);
1978
+ return cloned;
1979
+ }
1980
+ function cloneJsonValue(value, label) {
1981
+ return cloneJsonObject({ value }, label).value;
1982
+ }
1983
+ function cloneRows(rows) {
1984
+ return {
1985
+ entities: rows.entities.map((entity) => structuredClone(entity)),
1986
+ relations: rows.relations.map((relation) => structuredClone(relation))
1987
+ };
1988
+ }
1989
+ const numericMarkerValidation = { compareMarkerPoints: (_marker, _range, left, right) => {
1990
+ if (typeof left !== "number" || !Number.isFinite(left) || typeof right !== "number" || !Number.isFinite(right)) throw new Error("Sequence Marker points must use finite numeric coordinates");
1991
+ return left - right;
1992
+ } };
596
1993
  //#endregion
597
- //#region src/editor/schemas/replace-video-clip-sequence.ts
598
- /**
599
- * What happens to the speeches anchored to the clips being replaced.
600
- *
601
- * - `remap` re-anchors each surviving speech to the new clip in the SAME POSITION
602
- * of the sequence, keeping its offset — old[i]'s children become new[i]'s
603
- * children. An old clip with no counterpart (fewer new clips than old) has its
604
- * subtree deleted, because there is nothing left to anchor to.
605
- * - `cascade` deletes every anchored speech (and its captions) outright, like
606
- * `deleteVideoClips`.
607
- *
608
- * **Required, with no default.** The two branches differ in whether the user's
609
- * narration survives, and the agent tool that drives this op makes its
610
- * `preserve_speeches` flag required for that reason. A default here would let a
611
- * caller that forgot the field silently delete speech.
612
- */
613
- const anchoredReplacePolicySchema = z.enum(["remap", "cascade"]);
614
- /**
615
- * Replace a contiguous run of main-track clips with a new run.
616
- *
617
- * A composite of delete + insert that cannot be expressed as the two ops in
618
- * sequence, because the anchored speeches have to survive *across* the swap: with
619
- * `remap` they are re-anchored positionally, which needs both the old and the new
620
- * ids in the same transaction (ADR 0009 — the cascade stays in the editor, callers
621
- * never re-wire anchors themselves).
622
- *
623
- * Duration facts follow `addVideoClips`: `media_duration_ms` is the source's
624
- * intrinsic length and the trim window defaults to the whole media. The effective
625
- * timeline duration is derived by the projection, never an input.
626
- *
627
- * `media_id` is optional: omitting it creates a **deliberate empty placeholder
628
- * clip** (`origin_media_id: ''`) — structure with no picture. This is the only op
629
- * that can produce one, and it is authoritative state, unlike the gap fillers the
630
- * read-side solve mints (which never enter the document).
631
- */
632
- const replaceVideoClipSequenceInputSchema = z.object({
633
- old_clip_ids: clipIdsSchema.describe("The clips being replaced: a contiguous main-track run, listed in timeline order"),
634
- new_clips: z.array(z.object({
635
- media_id: mediaIdSchema.optional().describe("The replacement media asset ID. Omit to create an empty placeholder clip."),
636
- media_duration_ms: positiveMsSchema.describe("The source media's intrinsic full length in ms"),
637
- play_in: timelineMsSchema.optional().describe("Trim window start in the media (default 0)"),
638
- play_out: positiveMsSchema.optional().describe("Trim window end in the media (default media_duration_ms)")
639
- })).min(1).describe("The replacement clips, in the order they take on the track"),
640
- on_anchored: anchoredReplacePolicySchema.describe("What happens to speeches anchored to the replaced clips (required — see the policy doc)")
641
- }).superRefine((data, ctx) => {
642
- for (let i = 0; i < data.new_clips.length; i++) {
643
- const clip = data.new_clips[i];
644
- const playIn = clip.play_in ?? 0;
645
- const playOut = clip.play_out ?? clip.media_duration_ms;
646
- if (playOut > clip.media_duration_ms) ctx.addIssue({
647
- code: z.ZodIssueCode.custom,
648
- message: `new_clips[${i}].play_out ${playOut}ms exceeds media_duration_ms ${clip.media_duration_ms}ms`,
649
- path: [
650
- "new_clips",
651
- i,
652
- "play_out"
653
- ]
1994
+ //#region src/entity-editor/legacy-entity-migration.ts
1995
+ /** One-time import only. Ordinary editor operations must never reverse-diff a legacy document. */
1996
+ function migrateLegacyTimelineToEntities(legacy, assetFacts, initial = {
1997
+ entities: [],
1998
+ relations: []
1999
+ }, idFactory = (prefix) => `${prefix}_${globalThis.crypto.randomUUID()}`) {
2000
+ assertSupportedLegacy(legacy);
2001
+ if (initial.entities.some((row) => row.entityKind === "timeline")) fail("Timeline already exists; migration is not an editing operation");
2002
+ if (legacy.meta.schema_version === "video-document/entity-projection-v1") fail("An entity projection cannot be migrated as legacy state");
2003
+ const normalizedMainRanges = overlapNormalizedMainRanges(legacy);
2004
+ let entities = structuredClone([...initial.entities]);
2005
+ let relations = structuredClone([...initial.relations]);
2006
+ const documentAudioScriptEntityId = ensureDocumentAudioScript(entities, idFactory);
2007
+ const addEntity = (kind, payload, existingId) => {
2008
+ const entityId = createEntityId(existingId ?? idFactory("entity"));
2009
+ if (entities.some((row) => row.entityId === entityId)) fail(`Migration entity identity collision: ${entityId}`);
2010
+ entities.push({
2011
+ entityId,
2012
+ entityKind: kind,
2013
+ payload
654
2014
  });
655
- if (playIn >= playOut) ctx.addIssue({
656
- code: z.ZodIssueCode.custom,
657
- message: `new_clips[${i}].play_in ${playIn}ms must be less than play_out ${playOut}ms`,
658
- path: [
659
- "new_clips",
660
- i,
661
- "play_in"
662
- ]
2015
+ return entityId;
2016
+ };
2017
+ const link = (kind, from, to, metadata = {}) => {
2018
+ const relationId = createRelationId(idFactory("relation"));
2019
+ if (relations.some((row) => row.relationId === relationId)) fail(`Migration relation identity collision: ${relationId}`);
2020
+ relations.push({
2021
+ relationId,
2022
+ relationKind: kind,
2023
+ endpoint0EntityId: createEntityId(from),
2024
+ endpoint1EntityId: createEntityId(to),
2025
+ metadata,
2026
+ trace: {}
663
2027
  });
2028
+ };
2029
+ const facts = /* @__PURE__ */ new Map();
2030
+ for (const fact of assetFacts) {
2031
+ if (facts.has(fact.assetId)) fail(`Duplicate asset facts for ${fact.assetId}`);
2032
+ facts.set(fact.assetId, fact);
2033
+ }
2034
+ const contentByPartId = /* @__PURE__ */ new Map();
2035
+ for (const track of legacy.tracks ?? []) for (const item of track.items ?? []) {
2036
+ const part = requirePart(legacy, item.part_id);
2037
+ if (part.video_clip !== void 0) {
2038
+ const assetId = part.video_clip.origin_media_id;
2039
+ const fact = facts.get(assetId);
2040
+ if (fact === void 0) fail(`Missing factual media metadata for ${assetId}`);
2041
+ if (fact.kind !== "image" && fact.kind !== "video") fail(`Legacy video Clip ${item.part_id} requires an image or video fact`);
2042
+ const imported = importMediaAsset({
2043
+ entities,
2044
+ relations
2045
+ }, fact, idFactory);
2046
+ entities = [...imported.rows.entities];
2047
+ relations = [...imported.rows.relations];
2048
+ contentByPartId.set(item.part_id, imported.contentEntityId);
2049
+ } else if (part.speech !== void 0) {
2050
+ const speech = part.speech;
2051
+ const imported = importMediaAsset({
2052
+ entities,
2053
+ relations
2054
+ }, {
2055
+ assetId: speech.origin_speech_id,
2056
+ kind: "voice",
2057
+ durationMs: speech.media_duration_ms,
2058
+ storageKey: speech.audio_storage_key,
2059
+ voice: {
2060
+ system: "voice-library",
2061
+ key: speech.voice.id,
2062
+ ...speech.voice.name === void 0 ? {} : { name: speech.voice.name }
2063
+ }
2064
+ }, idFactory);
2065
+ entities = [...imported.rows.entities];
2066
+ relations = [...imported.rows.relations];
2067
+ contentByPartId.set(item.part_id, imported.contentEntityId);
2068
+ const phonemeScript = speech.phoneme_script;
2069
+ ensureSpeechPhoneticChain(imported.contentEntityId, speech.audio_script, typeof phonemeScript === "string" ? phonemeScript : void 0, entities, relations, addEntity, link, documentAudioScriptEntityId);
2070
+ } else if (part.bgm !== void 0) {
2071
+ const bgm = part.bgm;
2072
+ const fact = facts.get(bgm.origin_media_id);
2073
+ if (fact === void 0) fail(`Missing factual media metadata for ${bgm.origin_media_id}`);
2074
+ if (fact.kind !== "audio") fail(`Legacy BGM ${item.part_id} requires an audio fact`);
2075
+ if (fact.storageKey !== bgm.audio_storage_key) fail(`Factual storage key conflicts with legacy BGM ${item.part_id}`);
2076
+ const imported = importMediaAsset({
2077
+ entities,
2078
+ relations
2079
+ }, fact, idFactory);
2080
+ entities = [...imported.rows.entities];
2081
+ relations = [...imported.rows.relations];
2082
+ contentByPartId.set(item.part_id, imported.contentEntityId);
2083
+ }
664
2084
  }
665
- });
666
- //#endregion
667
- //#region src/editor/schemas/set-bgm.ts
668
- /**
669
- * Set the document BGM. The media's stable result (storage key) arrives
670
- * materialized from upstream (see
671
- * `results/phase-4-side-effect-payload-contract.md` §3). The op upserts the bgm
672
- * part and seats it on the bgm lane; its effective length is always the whole
673
- * timeline, derived by the projection on read — so there is no `duration_ms`
674
- * input or fact (RFC 02 / `reference/16` §0b). A `bgm_id` lets the op replace an
675
- * existing bgm part by id.
676
- */
677
- const setBgmInputSchema = z.object({
678
- bgm_id: z.string().min(1).describe("The bgm part ID to write"),
679
- audio_storage_key: z.string().min(1),
680
- origin_media_id: mediaIdSchema,
681
- volume: volumeSchema
682
- });
683
- //#endregion
684
- //#region src/editor/schemas/set-caption-style.ts
685
- /**
686
- * Set the caption visual style. GLOBAL by design: the style applies to every
687
- * caption part in the document — it carries NO `caption_id`. This mirrors the FE,
688
- * whose caption-style store (`caption-style.ts:persistCaptionStylePatch`) iterates
689
- * ALL captions and writes the same normalized style to each; the product has a
690
- * single document-wide caption style, not per-caption styling.
691
- *
692
- * Every field is optional and maps to a `CaptionStyle` attribute (snake_case
693
- * IDL). A field present in the input is written to every caption; a field ABSENT
694
- * from the input is left untouched on each caption (the editor merges the patch
695
- * onto each caption's existing style — this is a value edit, not a full-style
696
- * replace, so a partial patch such as "recolor only" does not wipe font size).
697
- *
698
- * Pure document edit, no cascade — captions keep their positions; only the style
699
- * sub-map of each caption part changes.
700
- */
701
- const setCaptionStyleInputSchema = z.object({
702
- font_id: z.string().min(1).optional().describe("Font ID referencing a font from the font library"),
703
- font_size: z.number().positive().optional().describe("Font size in points"),
704
- font_color: z.string().min(1).optional().describe("Font color as hex string, e.g. \"#FFFFFF\""),
705
- font_weight: z.number().int().optional().describe("Numeric font weight, e.g. 400 or 700"),
706
- entrance_animation: z.string().optional().describe("Entrance animation preset ID, e.g. \"fade\" or \"none\""),
707
- entrance_animation_duration_ms: z.number().min(0).optional().describe("Entrance animation duration in ms"),
708
- stroke_color: z.string().min(1).optional().describe("Outline/stroke color as hex string, e.g. \"#000000\""),
709
- stroke_width: z.number().min(0).optional().describe("Outline/stroke width in pixels"),
710
- position_x: z.number().optional().describe("Caption center X as a fraction (0.0 to 1.0)"),
711
- position_y: z.number().optional().describe("Caption center Y as a fraction (0.0 to 1.0)")
712
- }).describe("Document-wide caption style patch (no caption_id; applies to every caption)");
713
- //#endregion
714
- //#region src/editor/schemas/set-caption-visibility.ts
715
- /**
716
- * Toggle caption visibility (the caption track's `is_hidden` flag). Pure
717
- * document edit, no cascade — captions keep their positions; only the lane's
718
- * hidden flag changes.
719
- */
720
- const setCaptionVisibilityInputSchema = z.object({ is_hidden: z.boolean().describe("Whether the caption track is hidden") });
721
- //#endregion
722
- //#region src/editor/schemas/set-video-clip-speed-shift.ts
2085
+ const timeline = addEntity("timeline", legacy.timeline?.unit_time_ms === void 0 ? {} : { unit_time_ms: legacy.timeline.unit_time_ms });
2086
+ const trackIds = /* @__PURE__ */ new Map();
2087
+ for (const [order, oldTrack] of (legacy.tracks ?? []).entries()) {
2088
+ const track = addEntity("track", {
2089
+ role: oldTrack.parts_kind,
2090
+ order,
2091
+ ...oldTrack.is_hidden === void 0 ? {} : { hidden: oldTrack.is_hidden }
2092
+ }, oldTrack.id);
2093
+ trackIds.set(oldTrack, track);
2094
+ link("timeline-track", timeline, track);
2095
+ }
2096
+ for (const oldTrack of legacy.tracks ?? []) {
2097
+ const track = trackIds.get(oldTrack);
2098
+ for (const [order, item] of (oldTrack.items ?? []).entries()) {
2099
+ const part = requirePart(legacy, item.part_id);
2100
+ const role = oldTrack.parts_kind;
2101
+ const volume = part.video_clip?.volume ?? part.speech?.volume ?? part.bgm?.volume;
2102
+ const clip = addEntity("clip", {
2103
+ ...volume === void 0 ? {} : { volume },
2104
+ ...item.time_position.mode === "sequential" && !(role === "video_clip" && normalizedMainRanges !== void 0) || role === "bgm" ? { order: role === "bgm" ? 0 : order } : {}
2105
+ }, item.part_id);
2106
+ let content = contentByPartId.get(item.part_id);
2107
+ let duration;
2108
+ let markerPayload;
2109
+ if (part.video_clip !== void 0) {
2110
+ const video = part.video_clip;
2111
+ duration = effectiveVideoClipDurationMs(video);
2112
+ const fact = facts.get(video.origin_media_id);
2113
+ const rate = speedOf(video.speed_shift);
2114
+ markerPayload = {
2115
+ sourceRange: {
2116
+ start: video.play_in,
2117
+ end: video.play_out
2118
+ },
2119
+ duration: {
2120
+ mode: "fixed",
2121
+ value: duration
2122
+ },
2123
+ ...(fact.kind === "image" || fact.kind === "video") && video.speed_shift !== void 0 ? { timeRemapping: {
2124
+ kind: "linear",
2125
+ mode: video.speed_shift?.mode ?? "constant",
2126
+ rate
2127
+ } } : {}
2128
+ };
2129
+ } else if (part.speech !== void 0) {
2130
+ duration = part.speech.media_duration_ms;
2131
+ markerPayload = {
2132
+ sourceRange: {
2133
+ start: 0,
2134
+ end: duration
2135
+ },
2136
+ duration: {
2137
+ mode: "fixed",
2138
+ value: duration
2139
+ }
2140
+ };
2141
+ } else if (part.caption !== void 0) {
2142
+ const caption = part.caption;
2143
+ duration = caption.initial_duration_ms;
2144
+ const voice = contentByPartId.get(caption.speech_part_id);
2145
+ const render = relations.find((relation) => relation.relationKind === "phonetic-script-render" && relation.endpoint0EntityId === voice);
2146
+ const phonetic = entities.find((entity) => entity.entityId === render?.endpoint1EntityId);
2147
+ const script = phonetic === void 0 ? void 0 : composedAudioScript(phonetic, entities);
2148
+ if (script === void 0) fail("Legacy Caption has no composed AudioScript");
2149
+ const sourceText = scriptText(script);
2150
+ const captionText = caption.text;
2151
+ const offset = sourceText.indexOf(captionText);
2152
+ if (!captionText.trim() || offset < 0 || sourceText.indexOf(captionText, offset + 1) >= 0) fail("Legacy Caption needs explicit unambiguous AudioScript selection before cutover");
2153
+ const selection = {
2154
+ segmentId: "segment-0",
2155
+ ...sourceText === captionText ? {} : { textRange: {
2156
+ start: Array.from(sourceText.slice(0, offset)).length,
2157
+ end: Array.from(sourceText.slice(0, offset + captionText.length)).length
2158
+ } }
2159
+ };
2160
+ content = addEntity("caption", {
2161
+ extent: {
2162
+ kind: "bounded",
2163
+ start: 0,
2164
+ end: duration
2165
+ },
2166
+ sampling: "native",
2167
+ coordinateSpace: "milliseconds",
2168
+ baseEntityIds: [script.entityId],
2169
+ selection,
2170
+ ...caption.style === void 0 ? {} : { style: toEntityCaptionStyle(caption.style) }
2171
+ });
2172
+ link("caption-alignment", content, voice, { alignment: {
2173
+ start: caption.start_ms,
2174
+ end: caption.start_ms + duration
2175
+ } });
2176
+ markerPayload = {
2177
+ sourceRange: {
2178
+ start: 0,
2179
+ end: duration
2180
+ },
2181
+ duration: {
2182
+ mode: "fixed",
2183
+ value: duration
2184
+ }
2185
+ };
2186
+ } else {
2187
+ const bgm = part.bgm;
2188
+ const fact = facts.get(bgm.origin_media_id);
2189
+ if (fact.kind !== "audio") fail(`Legacy BGM ${item.part_id} requires an audio fact`);
2190
+ duration = fact.durationMs;
2191
+ markerPayload = {
2192
+ sourceRange: {
2193
+ start: 0,
2194
+ end: duration
2195
+ },
2196
+ duration: { mode: "from-source" },
2197
+ durationPolicy: "timeline"
2198
+ };
2199
+ }
2200
+ if (content === void 0) fail(`Migration could not resolve content for ${item.part_id}`);
2201
+ const normalizedMainRange = role === "video_clip" ? normalizedMainRanges?.get(item.part_id) : void 0;
2202
+ if (normalizedMainRange !== void 0) markerPayload = {
2203
+ ...markerPayload,
2204
+ targetRange: normalizedMainRange
2205
+ };
2206
+ else if (item.time_position.mode === "absolute" && role !== "bgm") markerPayload = {
2207
+ ...markerPayload,
2208
+ targetRange: {
2209
+ start: item.time_position.offsetMs,
2210
+ end: item.time_position.offsetMs + duration
2211
+ }
2212
+ };
2213
+ else if (item.time_position.mode === "anchored") markerPayload = {
2214
+ ...markerPayload,
2215
+ anchorOffset: item.time_position.offsetMs
2216
+ };
2217
+ const marker = addEntity("sequence-marker", markerPayload);
2218
+ link("track-clip", track, clip);
2219
+ link("clip-marker", clip, marker);
2220
+ link("marker-content", marker, content);
2221
+ if (item.time_position.mode === "anchored") link("clip-anchor", clip, item.time_position.anchorPartId);
2222
+ }
2223
+ }
2224
+ const rows = {
2225
+ entities,
2226
+ relations
2227
+ };
2228
+ assertEntityProjectionPreservesLegacy(legacy, projectEntityTimeline(rows, legacy.meta), rows);
2229
+ return rows;
2230
+ }
2231
+ /** Server gate: a cutover may change representation, never the existing render facts. */
2232
+ function assertEntityProjectionPreservesLegacy(legacy, projection, rows) {
2233
+ assertSupportedLegacy(legacy);
2234
+ if (projection.meta.schema_version !== "video-document/entity-projection-v1") fail("Expected an entity projection for migration");
2235
+ const normalizedMainRanges = overlapNormalizedMainRanges(legacy);
2236
+ const compatibilityFacts = (document) => {
2237
+ const { version: _version, ...view } = fromVideoDocument(document);
2238
+ for (const part of Object.values(view.part_library ?? {})) {
2239
+ const speech = part.speech;
2240
+ if (speech?.phoneme_script === null) delete speech.phoneme_script;
2241
+ }
2242
+ const { schema_version: _schemaVersion, version: _metaVersion, ...meta } = document.meta;
2243
+ return {
2244
+ meta,
2245
+ view
2246
+ };
2247
+ };
2248
+ if (canonical(compatibilityFacts(legacy)) !== canonical(compatibilityFacts(projection))) fail("Entity migration must preserve all existing timeline facts; edit after cutover");
2249
+ const trackOrders = [];
2250
+ for (const oldTrack of legacy.tracks ?? []) {
2251
+ const candidates = rows.entities.filter((row) => row.entityKind === "track" && (oldTrack.id === void 0 ? row.payload.role === oldTrack.parts_kind : row.entityId === oldTrack.id));
2252
+ if (candidates.length !== 1) fail("Migration must preserve every Track identity");
2253
+ const track = candidates[0];
2254
+ if (track.payload.role !== oldTrack.parts_kind || (track.payload.hidden ?? false) !== (oldTrack.is_hidden ?? false)) fail("Migration must preserve Track role and visibility");
2255
+ if (typeof track.payload.order !== "number" || !Number.isFinite(track.payload.order)) fail("Migration must preserve Track order");
2256
+ trackOrders.push(track.payload.order);
2257
+ const sequentialOrders = [];
2258
+ for (const item of oldTrack.items ?? []) {
2259
+ const clip = rows.entities.find((row) => row.entityId === item.part_id && row.entityKind === "clip");
2260
+ const binding = rows.relations.filter((row) => row.relationKind === "clip-marker" && row.endpoint0EntityId === item.part_id && rows.entities.some((entity) => entity.entityId === row.endpoint1EntityId && entity.entityKind === "sequence-marker"));
2261
+ const marker = rows.entities.find((row) => row.entityId === binding[0]?.endpoint1EntityId && row.entityKind === "sequence-marker");
2262
+ if (clip === void 0 || binding.length !== 1 || marker === void 0) fail("Migration must preserve Clip/Marker placement identity");
2263
+ const anchors = rows.relations.filter((row) => row.relationKind === "clip-anchor" && row.endpoint0EntityId === clip.entityId);
2264
+ const normalizedMainRange = oldTrack.parts_kind === "video_clip" ? normalizedMainRanges?.get(item.part_id) : void 0;
2265
+ if (normalizedMainRange !== void 0) {
2266
+ if (clip.payload.order !== void 0 || !isExactRange(marker.payload.targetRange, normalizedMainRange) || marker.payload.anchorOffset !== void 0 || anchors.length !== 0) fail("Migration must preserve the legacy overlap-normalized main Track");
2267
+ } else if (oldTrack.parts_kind === "bgm") {
2268
+ if (clip.payload.order !== 0 || marker.payload.targetRange !== void 0 || marker.payload.anchorOffset !== void 0 || marker.payload.durationPolicy !== "timeline" || anchors.length !== 0) fail("Migration must preserve timeline-filling BGM semantics");
2269
+ } else if (item.time_position.mode === "sequential") {
2270
+ if (marker.payload.targetRange !== void 0 || marker.payload.anchorOffset !== void 0 || typeof clip.payload.order !== "number" || !Number.isFinite(clip.payload.order) || anchors.length !== 0) fail("Migration must preserve sequential placement semantics");
2271
+ sequentialOrders.push(clip.payload.order);
2272
+ } else if (item.time_position.mode === "absolute") {
2273
+ const target = marker.payload.targetRange;
2274
+ if (clip.payload.order !== void 0 || !isRangeStartingAt(target, item.time_position.offsetMs) || marker.payload.anchorOffset !== void 0 || anchors.length !== 0) fail("Migration must preserve absolute placement semantics");
2275
+ } else if (clip.payload.order !== void 0 || marker.payload.targetRange !== void 0 || marker.payload.anchorOffset !== item.time_position.offsetMs || anchors.length !== 1 || anchors[0].endpoint1EntityId !== item.time_position.anchorPartId) fail("Migration must preserve anchored placement semantics");
2276
+ }
2277
+ if (sequentialOrders.some((order, index) => index > 0 && order <= sequentialOrders[index - 1])) fail("Migration must preserve sequential Clip order");
2278
+ }
2279
+ if (trackOrders.some((order, index) => index > 0 && order <= trackOrders[index - 1])) fail("Migration must preserve Track stacking order");
2280
+ }
2281
+ function assertSupportedLegacy(document) {
2282
+ assertValidVideoDocument(document);
2283
+ const tracks = document.tracks ?? [];
2284
+ assertKnownFields(document.timeline ?? {}, ["unit_time_ms"], "Timeline");
2285
+ if (document.timeline?.unit_time_ms !== void 0 && (typeof document.timeline.unit_time_ms !== "number" || !Number.isFinite(document.timeline.unit_time_ms) || document.timeline.unit_time_ms <= 0)) fail("Migration requires a positive finite unit_time_ms");
2286
+ const seenRoles = /* @__PURE__ */ new Set();
2287
+ const placed = /* @__PURE__ */ new Map();
2288
+ for (const track of tracks) {
2289
+ const role = track.parts_kind;
2290
+ if (role === void 0 || ![
2291
+ "video_clip",
2292
+ "speech",
2293
+ "caption",
2294
+ "bgm"
2295
+ ].includes(role)) fail("Every legacy Track requires a supported role");
2296
+ if (seenRoles.has(role)) fail(`The compatibility editor supports only one ${role} Track`);
2297
+ seenRoles.add(role);
2298
+ if (track.id !== void 0 && (track.id.trim() === "" || track.id.trim() !== track.id)) fail("Migration requires trimmed Track identities");
2299
+ for (const item of track.items ?? []) {
2300
+ if (item.part_id.trim() === "" || item.part_id.trim() !== item.part_id) fail("Migration requires trimmed Clip identities");
2301
+ if (placed.has(item.part_id)) fail(`Legacy part ${item.part_id} is placed more than once`);
2302
+ placed.set(item.part_id, {
2303
+ track,
2304
+ item
2305
+ });
2306
+ assertKnownFields(item.time_position, item.time_position.mode === "sequential" ? ["mode"] : [
2307
+ "mode",
2308
+ "anchorPartId",
2309
+ "offsetMs"
2310
+ ], "placement");
2311
+ if (item.time_position.mode === "absolute") requireMilliseconds(item.time_position.offsetMs, "absolute offset");
2312
+ if (item.time_position.mode === "anchored") {
2313
+ if (item.time_position.anchorPartId.trim() === "" || item.time_position.anchorPartId.trim() !== item.time_position.anchorPartId) fail("Migration requires a trimmed anchor identity");
2314
+ requireMilliseconds(item.time_position.offsetMs, "anchor offset");
2315
+ }
2316
+ if (item.fallback_abs_ms !== void 0) requireMilliseconds(item.fallback_abs_ms, "anchor fallback");
2317
+ assertKnownFields(item, [
2318
+ "part_id",
2319
+ "time_position",
2320
+ "fallback_abs_ms"
2321
+ ], "TrackItem");
2322
+ }
2323
+ assertKnownFields(track, [
2324
+ "id",
2325
+ "parts_kind",
2326
+ "is_hidden",
2327
+ "items"
2328
+ ], "Track");
2329
+ }
2330
+ for (const [id, part] of Object.entries(document.part_library ?? {})) {
2331
+ const placement = placed.get(id);
2332
+ if (placement === void 0) fail(`Cannot discard unplaced legacy part ${id}`);
2333
+ assertPartSupported(id, part, placement.track.parts_kind);
2334
+ }
2335
+ for (const id of placed.keys()) if (document.part_library?.[id] === void 0) fail(`Placed Clip ${id} has no part payload`);
2336
+ assertLegacyRelations(document, placed);
2337
+ }
2338
+ function assertPartSupported(id, part, role) {
2339
+ assertKnownFields(part, [
2340
+ "video_clip",
2341
+ "speech",
2342
+ "caption",
2343
+ "bgm"
2344
+ ], "Part");
2345
+ const present = [
2346
+ "video_clip",
2347
+ "speech",
2348
+ "caption",
2349
+ "bgm"
2350
+ ].filter((kind) => part[kind] !== void 0);
2351
+ if (present.length !== 1 || present[0] !== role) fail(`Legacy part ${id} must match its ${role} Track`);
2352
+ if (part.video_clip !== void 0) {
2353
+ const clip = part.video_clip;
2354
+ if (clip.id !== id || clip.kind !== "video_clip" || !trimmed(clip.origin_media_id) || clip.play_in === void 0 || clip.play_out === void 0) fail("Migration requires complete Clip identity, media and trim facts");
2355
+ requireMilliseconds(clip.play_in, "Clip play_in");
2356
+ requireMilliseconds(clip.play_out, "Clip play_out");
2357
+ if (clip.play_out <= clip.play_in) fail("Migration requires a non-empty Clip trim window");
2358
+ requireFinite(clip.volume, "Clip volume");
2359
+ const speed = clip.speed_shift;
2360
+ if (speed !== void 0 && (speed.category !== "linear" || speed.config?.linear === void 0 || speed.mode !== void 0 && typeof speed.mode !== "string")) fail("Nonlinear speed requires an entity remapping adapter");
2361
+ if (speed !== void 0) {
2362
+ const rate = speed.config?.linear?.speed;
2363
+ if (typeof rate !== "number" || !Number.isFinite(rate) || rate <= 0) fail("Migration requires a positive finite speed");
2364
+ assertKnownFields(speed, [
2365
+ "category",
2366
+ "mode",
2367
+ "config"
2368
+ ], "speed_shift");
2369
+ assertKnownFields(speed.config, ["linear"], "speed config");
2370
+ assertKnownFields(speed.config.linear, ["speed"], "linear speed");
2371
+ }
2372
+ assertKnownFields(clip, [
2373
+ "id",
2374
+ "kind",
2375
+ "origin_media_id",
2376
+ "play_in",
2377
+ "play_out",
2378
+ "volume",
2379
+ "speed_shift"
2380
+ ], "Clip");
2381
+ } else if (part.speech !== void 0) {
2382
+ const speech = part.speech;
2383
+ const phonemeScript = speech.phoneme_script;
2384
+ if (speech.id !== id || speech.kind !== "speech" || !trimmed(speech.origin_speech_id) || !trimmed(speech.audio_storage_key) || typeof speech.audio_script !== "string") fail("Migration requires complete Speech identity and physical take facts");
2385
+ requirePositiveMilliseconds(speech.media_duration_ms, "Speech duration");
2386
+ requireFinite(speech.volume, "Speech volume");
2387
+ if (!trimmed(speech.voice?.id)) fail("Migration requires an explicit voice-library identity");
2388
+ if (speech.voice?.name !== void 0 && typeof speech.voice.name !== "string") fail("Migration requires a string voice name when present");
2389
+ if (!Array.isArray(speech.caption_ids) || speech.caption_ids.some((captionId) => !trimmed(captionId))) fail("Migration requires explicit Speech caption identities");
2390
+ if (new Set(speech.caption_ids).size !== speech.caption_ids.length) fail("Migration requires unique Speech caption identities");
2391
+ if (phonemeScript !== void 0 && phonemeScript !== null && typeof phonemeScript !== "string") fail("Migration requires a string phoneme_script when present");
2392
+ assertKnownFields(speech.voice, ["id", "name"], "voice");
2393
+ assertKnownFields(speech, [
2394
+ "id",
2395
+ "kind",
2396
+ "media_duration_ms",
2397
+ "audio_script",
2398
+ "volume",
2399
+ "audio_storage_key",
2400
+ "origin_speech_id",
2401
+ "voice",
2402
+ "caption_ids",
2403
+ "phoneme_script"
2404
+ ], "Speech");
2405
+ } else if (part.caption !== void 0) {
2406
+ const caption = part.caption;
2407
+ if (caption.id !== id || caption.kind !== "caption" || !trimmed(caption.speech_part_id) || typeof caption.text !== "string") fail("Migration requires complete Caption identity, Speech provenance and text");
2408
+ requireMilliseconds(caption.start_ms, "Caption source offset");
2409
+ requirePositiveMilliseconds(caption.initial_duration_ms, "Caption duration");
2410
+ if (caption.style !== void 0) assertCaptionStyle(caption.style);
2411
+ assertKnownFields(caption, [
2412
+ "id",
2413
+ "kind",
2414
+ "initial_duration_ms",
2415
+ "speech_part_id",
2416
+ "text",
2417
+ "start_ms",
2418
+ "style"
2419
+ ], "Caption");
2420
+ } else if (part.bgm !== void 0) {
2421
+ const bgm = part.bgm;
2422
+ if (bgm.id !== id || bgm.kind !== "bgm" || !trimmed(bgm.origin_media_id) || !trimmed(bgm.audio_storage_key)) fail("Migration requires complete BGM identity and physical media facts");
2423
+ requireFinite(bgm.volume, "BGM volume");
2424
+ assertKnownFields(bgm, [
2425
+ "id",
2426
+ "kind",
2427
+ "audio_storage_key",
2428
+ "volume",
2429
+ "origin_media_id"
2430
+ ], "BGM");
2431
+ }
2432
+ }
2433
+ function assertLegacyRelations(document, placed) {
2434
+ const captionIdsBySpeech = /* @__PURE__ */ new Map();
2435
+ for (const track of document.tracks ?? []) {
2436
+ if (track.parts_kind === "bgm" && (track.items?.length ?? 0) > 1) fail("The compatibility editor supports only one BGM Clip");
2437
+ for (const item of track.items ?? []) {
2438
+ const part = requirePart(document, item.part_id);
2439
+ const position = item.time_position;
2440
+ if (track.parts_kind === "video_clip" && position.mode === "anchored") fail("Anchored video Clips require an overlay adapter");
2441
+ if (track.parts_kind === "bgm") {
2442
+ if (position.mode !== "absolute" || position.offsetMs !== 0) fail("Legacy BGM must start at the Timeline origin");
2443
+ } else if (position.mode === "anchored") {
2444
+ const host = placed.get(position.anchorPartId);
2445
+ if (host === void 0) fail(`Legacy anchor ${position.anchorPartId} is not placed`);
2446
+ if (track.parts_kind === "speech" && host.track.parts_kind !== "video_clip") fail("Speech may only anchor to a video Clip");
2447
+ if (track.parts_kind === "caption") {
2448
+ if (host.track.parts_kind !== "speech") fail("Caption may only anchor to a Speech Clip");
2449
+ const caption = part.caption;
2450
+ if (position.anchorPartId !== caption.speech_part_id || position.offsetMs !== caption.start_ms) fail("Caption placement must agree with its Speech provenance and source offset");
2451
+ }
2452
+ } else if (track.parts_kind === "caption") fail("Caption placement requires an explicit Speech anchor");
2453
+ if (part.caption !== void 0) {
2454
+ const ids = captionIdsBySpeech.get(part.caption.speech_part_id) ?? [];
2455
+ ids.push(item.part_id);
2456
+ captionIdsBySpeech.set(part.caption.speech_part_id, ids);
2457
+ }
2458
+ }
2459
+ }
2460
+ for (const [id, placement] of placed) {
2461
+ const speech = requirePart(document, id).speech;
2462
+ if (speech === void 0) continue;
2463
+ const expected = captionIdsBySpeech.get(id) ?? [];
2464
+ if (canonical(speech.caption_ids) !== canonical(expected)) fail(`Speech ${id} caption_ids must agree with the Caption Track order`);
2465
+ if (placement.item.time_position.mode === "anchored") continue;
2466
+ if (placement.item.time_position.mode !== "absolute") fail("Speech placement must be anchored or absolute");
2467
+ }
2468
+ const intervals = (fromVideoDocument(document).main_track?.items ?? []).map((item) => {
2469
+ const clip = document.part_library?.[item.part_id]?.video_clip;
2470
+ if (clip === void 0) fail("Projection must preserve every video Clip");
2471
+ return {
2472
+ start: item.abs_time_position ?? 0,
2473
+ end: (item.abs_time_position ?? 0) + effectiveVideoClipDurationMs(clip)
2474
+ };
2475
+ }).sort((left, right) => left.start - right.start);
2476
+ if (intervals.some((interval, index) => index > 0 && interval.start < intervals[index - 1].end)) fail("Overlapping video Clips require an overlay adapter");
2477
+ }
723
2478
  /**
724
- * Set the playback speed of existing video clips. Per the speed-shift decision
725
- * (`reference/16` §0): the op writes only the `speed_shift` fact — it does NOT
726
- * store an effective `duration_ms` (projection derives it from the trim window /
727
- * speed) and does NOT scale anchored speeches' relative offsets (offsets stay
728
- * put; the cascade reflows absolute positions). A `null` speed_shift clears the
729
- * speed back to original (1×).
2479
+ * Legacy reads perform one speech-overlap pass after laying the visual lane out
2480
+ * sequentially. Entity reads deliberately do not run that hidden cascade. When
2481
+ * the pass moved any visual Clip, cutover therefore records the complete solved
2482
+ * visual lane as explicit target ranges. Mixing absolute and sequential Clips
2483
+ * would create two unrelated placement chains and could reorder the lane.
730
2484
  */
731
- const setVideoClipSpeedShiftInputSchema = z.object({ clips: z.array(z.object({
732
- clip_id: clipIdSchema.describe("The video clip part ID to set speed for"),
733
- speed_shift: speedShiftSchema.nullable().describe("The new speed setting, or null to reset to 1×")
734
- })).min(1).describe("Video clips with their new speed settings") });
2485
+ function overlapNormalizedMainRanges(document) {
2486
+ const track = document.tracks?.find((candidate) => candidate.parts_kind === "video_clip");
2487
+ if (track === void 0 || (track.items?.length ?? 0) === 0) return void 0;
2488
+ const solved = fromVideoDocument(document).main_track?.items ?? [];
2489
+ const starts = new Map(solved.map((item) => [item.part_id, requireMilliseconds(item.abs_time_position, `Solved position for ${item.part_id ?? "unknown Clip"}`)]));
2490
+ let cursor = 0;
2491
+ let moved = false;
2492
+ const ranges = /* @__PURE__ */ new Map();
2493
+ for (const item of track.items ?? []) {
2494
+ const part = requirePart(document, item.part_id).video_clip;
2495
+ if (part === void 0) fail(`Projection must preserve video Clip ${item.part_id}`);
2496
+ const duration = effectiveVideoClipDurationMs(part);
2497
+ const start = starts.get(item.part_id);
2498
+ if (start === void 0) fail(`Projection must preserve video Clip ${item.part_id}`);
2499
+ if (start !== cursor) moved = true;
2500
+ const end = start + duration;
2501
+ requireMilliseconds(end, `Solved end for ${item.part_id}`);
2502
+ ranges.set(item.part_id, {
2503
+ start,
2504
+ end
2505
+ });
2506
+ cursor += duration;
2507
+ }
2508
+ return moved ? ranges : void 0;
2509
+ }
2510
+ function requirePart(document, partId) {
2511
+ const part = document.part_library?.[partId];
2512
+ if (part === void 0) fail(`Placed Clip ${partId} has no part payload`);
2513
+ return part;
2514
+ }
2515
+ function ensureSpeechPhoneticChain(voiceEntityId, audioScriptText, phonemeScript, entities, relations, addEntity, link, documentAudioScriptEntityId) {
2516
+ const renders = relations.filter((relation) => relation.relationKind === "phonetic-script-render" && relation.endpoint0EntityId === voiceEntityId);
2517
+ if (renders.length > 1) fail(`Voice ${voiceEntityId} has ambiguous PhoneticScript provenance`);
2518
+ if (renders.length === 1) {
2519
+ const phonetic = entities.find((entity) => entity.entityId === renders[0].endpoint1EntityId && entity.entityKind === "phonetic-script");
2520
+ if (phonetic === void 0) fail(`Voice ${voiceEntityId} has a dangling PhoneticScript render`);
2521
+ const script = composedAudioScript(phonetic, entities);
2522
+ if (script === void 0 || scriptText(script) !== audioScriptText) fail(`Voice ${voiceEntityId} conflicts with the legacy Speech script`);
2523
+ return phonetic.entityId;
2524
+ }
2525
+ const script = entities.find((entity) => entity.entityId === documentAudioScriptEntityId);
2526
+ if (script === void 0 || script.entityKind !== "audio-script") fail("Migration must carry the fixed document AudioScript");
2527
+ const segments = script.payload.segments;
2528
+ if (Array.isArray(segments) && segments.length > 0) {
2529
+ if (scriptText(script) !== audioScriptText) fail(`Voice ${voiceEntityId} conflicts with the project AudioScript text`);
2530
+ } else {
2531
+ const scriptIndex = entities.findIndex((row) => row.entityId === script.entityId);
2532
+ entities[scriptIndex] = {
2533
+ ...script,
2534
+ payload: { segments: [{
2535
+ segmentId: "segment-0",
2536
+ text: audioScriptText
2537
+ }] }
2538
+ };
2539
+ }
2540
+ const phonetic = addEntity("phonetic-script", {
2541
+ baseEntityIds: [script.entityId],
2542
+ ...phonemeScript === void 0 ? {} : { phonemeScript }
2543
+ });
2544
+ link("phonetic-script-render", voiceEntityId, phonetic);
2545
+ return phonetic;
2546
+ }
2547
+ function composedAudioScript(phonetic, entities) {
2548
+ return findComposedAudioScript({
2549
+ entities,
2550
+ relations: []
2551
+ }, phonetic.entityId, "phonetic-script");
2552
+ }
2553
+ function scriptText(script) {
2554
+ const segments = script.payload.segments;
2555
+ if (!Array.isArray(segments)) fail("AudioScript requires segments");
2556
+ return segments.map((segment) => {
2557
+ if (segment === null || typeof segment !== "object" || Array.isArray(segment) || typeof segment.text !== "string") fail("AudioScript segment requires text");
2558
+ return segment.text;
2559
+ }).join("");
2560
+ }
2561
+ function toEntityCaptionStyle(style) {
2562
+ return {
2563
+ ...style.font_id === void 0 ? {} : { font: {
2564
+ system: "font-library",
2565
+ key: style.font_id
2566
+ } },
2567
+ ...style.font_size === void 0 ? {} : { fontSize: style.font_size },
2568
+ ...style.font_color === void 0 ? {} : { fontColor: style.font_color },
2569
+ ...style.font_weight === void 0 ? {} : { fontWeight: style.font_weight },
2570
+ ...style.entrance_animation === void 0 ? {} : { entranceAnimation: style.entrance_animation },
2571
+ ...style.entrance_animation_duration_ms === void 0 ? {} : { entranceAnimationDurationMs: style.entrance_animation_duration_ms },
2572
+ ...style.stroke_color === void 0 ? {} : { strokeColor: style.stroke_color },
2573
+ ...style.stroke_width === void 0 ? {} : { strokeWidth: style.stroke_width },
2574
+ ...style.position_x === void 0 ? {} : { positionX: style.position_x },
2575
+ ...style.position_y === void 0 ? {} : { positionY: style.position_y }
2576
+ };
2577
+ }
2578
+ function assertCaptionStyle(style) {
2579
+ if (style.font_id !== void 0 && !trimmed(style.font_id)) fail("Caption font_id must be a trimmed identity");
2580
+ for (const value of [
2581
+ style.font_size,
2582
+ style.font_weight,
2583
+ style.entrance_animation_duration_ms,
2584
+ style.stroke_width,
2585
+ style.position_x,
2586
+ style.position_y
2587
+ ]) if (value !== void 0) requireFinite(value, "Caption style number");
2588
+ for (const value of [
2589
+ style.font_color,
2590
+ style.entrance_animation,
2591
+ style.stroke_color
2592
+ ]) if (value !== void 0 && typeof value !== "string") fail("Caption style text must be a string");
2593
+ assertKnownFields(style, [
2594
+ "font_id",
2595
+ "font_size",
2596
+ "font_color",
2597
+ "font_weight",
2598
+ "entrance_animation",
2599
+ "entrance_animation_duration_ms",
2600
+ "stroke_color",
2601
+ "stroke_width",
2602
+ "position_x",
2603
+ "position_y"
2604
+ ], "Caption style");
2605
+ }
2606
+ function isRangeStartingAt(value, expectedStart) {
2607
+ return value !== null && typeof value === "object" && !Array.isArray(value) && value.start === expectedStart;
2608
+ }
2609
+ function isExactRange(value, expected) {
2610
+ return value !== null && typeof value === "object" && !Array.isArray(value) && value.start === expected.start && value.end === expected.end;
2611
+ }
2612
+ function requireFinite(value, label) {
2613
+ if (typeof value !== "number" || !Number.isFinite(value)) fail(`${label} must be finite`);
2614
+ return value;
2615
+ }
2616
+ function requireMilliseconds(value, label) {
2617
+ const result = requireFinite(value, label);
2618
+ if (!Number.isSafeInteger(result) || result < 0) fail(`${label} must be non-negative whole milliseconds`);
2619
+ return result;
2620
+ }
2621
+ function requirePositiveMilliseconds(value, label) {
2622
+ const result = requireMilliseconds(value, label);
2623
+ if (result <= 0) fail(`${label} must be positive`);
2624
+ return result;
2625
+ }
2626
+ function trimmed(value) {
2627
+ return typeof value === "string" && value.trim() !== "" && value.trim() === value;
2628
+ }
2629
+ function assertKnownFields(value, fields, label) {
2630
+ if (Object.entries(value).some(([key, field]) => field !== void 0 && !fields.includes(key))) fail(`Unknown legacy ${label} fields require an explicit migration adapter`);
2631
+ }
2632
+ function canonical(value) {
2633
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
2634
+ if (value !== null && typeof value === "object") return `{${Object.entries(value).filter(([, field]) => field !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, field]) => `${JSON.stringify(key)}:${canonical(field)}`).join(",")}}`;
2635
+ return JSON.stringify(value) ?? "undefined";
2636
+ }
2637
+ function fail(message) {
2638
+ throw new EntityTimelineProjectionError(message);
2639
+ }
735
2640
  //#endregion
736
- //#region src/editor/schemas/index.ts
737
- var schemas_exports = /* @__PURE__ */ __exportAll({
738
- addSpeechesInputSchema: () => addSpeechesInputSchema,
739
- addVideoClipsInputSchema: () => addVideoClipsInputSchema,
740
- adjustBgmVolumeInputSchema: () => adjustBgmVolumeInputSchema,
741
- adjustSpeechVolumeInputSchema: () => adjustSpeechVolumeInputSchema,
742
- adjustVideoClipDurationInputSchema: () => adjustVideoClipDurationInputSchema,
743
- adjustVideoClipVolumeInputSchema: () => adjustVideoClipVolumeInputSchema,
744
- anchoredDeletePolicySchema: () => anchoredDeletePolicySchema,
745
- anchoredReplacePolicySchema: () => anchoredReplacePolicySchema,
746
- changeSpeechScriptInputSchema: () => changeSpeechScriptInputSchema,
747
- changeSpeechVoiceInputSchema: () => changeSpeechVoiceInputSchema,
748
- clipIdSchema: () => clipIdSchema,
749
- clipIdsSchema: () => clipIdsSchema,
750
- deleteBgmInputSchema: () => deleteBgmInputSchema,
751
- deleteSpeechesInputSchema: () => deleteSpeechesInputSchema,
752
- deleteVideoClipsInputSchema: () => deleteVideoClipsInputSchema,
753
- mediaIdSchema: () => mediaIdSchema,
754
- moveAnchorSchema: () => moveAnchorSchema,
755
- moveSpeechesInputSchema: () => moveSpeechesInputSchema,
756
- moveVideoClipsByAnchorInputSchema: () => moveVideoClipsByAnchorInputSchema,
757
- moveVideoClipsInputSchema: () => moveVideoClipsInputSchema,
758
- movedClipAnchoredPolicySchema: () => movedClipAnchoredPolicySchema,
759
- positiveMsSchema: () => positiveMsSchema,
760
- replaceVideoClipContentInputSchema: () => replaceVideoClipContentInputSchema,
761
- replaceVideoClipSequenceInputSchema: () => replaceVideoClipSequenceInputSchema,
762
- setBgmInputSchema: () => setBgmInputSchema,
763
- setCaptionStyleInputSchema: () => setCaptionStyleInputSchema,
764
- setCaptionVisibilityInputSchema: () => setCaptionVisibilityInputSchema,
765
- setVideoClipSpeedShiftInputSchema: () => setVideoClipSpeedShiftInputSchema,
766
- speechAssetsSchema: () => speechAssetsSchema,
767
- speechIdSchema: () => speechIdSchema,
768
- speechIdsSchema: () => speechIdsSchema,
769
- speedShiftSchema: () => speedShiftSchema,
770
- timelineMsSchema: () => timelineMsSchema,
771
- voiceSchema: () => voiceSchema,
772
- volumeSchema: () => volumeSchema
773
- });
2641
+ //#region src/entity-editor/caption-content.ts
2642
+ /** Author Caption content from semantic intent; callers never reconcile variant bases or assembled fields. */
2643
+ function prepareCaptionContent(rows, input) {
2644
+ const entityId = createEntityId(input.contentEntityId);
2645
+ const scriptId = createEntityId(input.audioScriptEntityId);
2646
+ if (!Number.isFinite(input.durationMs) || input.durationMs <= 0) throw new Error("Caption duration must be positive");
2647
+ const previous = rows.entities.find((row) => row.entityId === entityId);
2648
+ if (previous !== void 0 && previous.entityKind !== "caption") throw new Error("Caption content identity has a different kind");
2649
+ let baseEntityIds = [scriptId];
2650
+ if (previous !== void 0) {
2651
+ const source = assembleCaptionContent(rows, entityId).audioScript.entityId;
2652
+ const bases = variantBaseEntityIds(previous);
2653
+ if (source !== scriptId && !bases.includes(source)) throw new Error("Replacing an indirectly composed AudioScript requires an explicit composition change");
2654
+ baseEntityIds = bases.map((id) => id === source ? scriptId : id);
2655
+ }
2656
+ const candidate = {
2657
+ entityId,
2658
+ entityKind: "caption",
2659
+ payload: {
2660
+ ...previous?.payload,
2661
+ baseEntityIds,
2662
+ extent: previous?.payload.extent ?? {
2663
+ kind: "bounded",
2664
+ start: 0,
2665
+ end: input.durationMs
2666
+ },
2667
+ sampling: previous?.payload.sampling ?? "native",
2668
+ coordinateSpace: previous?.payload.coordinateSpace ?? "milliseconds"
2669
+ }
2670
+ };
2671
+ const graph = {
2672
+ ...rows,
2673
+ entities: [...rows.entities.filter((row) => row.entityId !== entityId), candidate]
2674
+ };
2675
+ const textSource = {
2676
+ ...assembleEntityContent(graph, entityId),
2677
+ entityKind: "audio-script"
2678
+ };
2679
+ const selected = {
2680
+ ...candidate,
2681
+ payload: {
2682
+ ...candidate.payload,
2683
+ selection: structuredClone(input.selection ?? selectCaptionText(textSource, input.text))
2684
+ }
2685
+ };
2686
+ if (assembleCaptionContent({
2687
+ ...graph,
2688
+ entities: graph.entities.map((row) => row.entityId === entityId ? selected : row)
2689
+ }, entityId).text !== input.text) throw new Error("Caption review text differs from its assembled variant content");
2690
+ return selected;
2691
+ }
2692
+ function selectCaptionText(script, text) {
2693
+ if (!text.trim()) throw new Error("Caption text selection must not be blank");
2694
+ const segments = script.payload.segments;
2695
+ const matches = [];
2696
+ for (const segment of segments) {
2697
+ let offset = segment.text.indexOf(text);
2698
+ while (offset !== -1) {
2699
+ const start = Array.from(segment.text.slice(0, offset)).length;
2700
+ matches.push({
2701
+ segmentId: segment.segmentId,
2702
+ textRange: {
2703
+ start,
2704
+ end: start + Array.from(text).length
2705
+ }
2706
+ });
2707
+ offset = segment.text.indexOf(text, offset + 1);
2708
+ }
2709
+ }
2710
+ if (matches.length !== 1) throw new Error("Caption text must select a unique AudioScript range; provide explicit selection");
2711
+ return matches[0];
2712
+ }
774
2713
  //#endregion
775
2714
  //#region src/editor/snapshot-utils.ts
776
2715
  function isMap(value) {
@@ -1120,9 +3059,11 @@ function readPartLibrary(draft) {
1120
3059
  var SemanticEditor = class {
1121
3060
  doc;
1122
3061
  validator;
1123
- constructor(doc, validator = new SchemaValidator()) {
3062
+ idFactory;
3063
+ constructor(doc, validator = new SchemaValidator(), idFactory = generatePartId) {
1124
3064
  this.doc = doc;
1125
3065
  this.validator = validator;
3066
+ this.idFactory = idFactory;
1126
3067
  }
1127
3068
  async moveVideoClips(input, options) {
1128
3069
  this.validator.validateMoveVideoClips(input, this.doc);
@@ -1202,7 +3143,7 @@ var SemanticEditor = class {
1202
3143
  track.items ??= [];
1203
3144
  let at = insertIndex;
1204
3145
  for (const clip of input.clips) {
1205
- const partId = generatePartId("clip");
3146
+ const partId = this.idFactory("clip");
1206
3147
  setPart(draft, partId, { video_clip: {
1207
3148
  id: partId,
1208
3149
  kind: "video_clip",
@@ -1249,7 +3190,7 @@ var SemanticEditor = class {
1249
3190
  const newItems = [];
1250
3191
  const newClipIds = [];
1251
3192
  for (const clip of input.new_clips) {
1252
- const partId = generatePartId("clip");
3193
+ const partId = this.idFactory("clip");
1253
3194
  setPart(draft, partId, { video_clip: {
1254
3195
  id: partId,
1255
3196
  kind: "video_clip",
@@ -1707,7 +3648,7 @@ function writeSpeechAssets(draft, assets) {
1707
3648
  if (caption == null) continue;
1708
3649
  const priorCaption = draft.part_library?.[captionId]?.caption;
1709
3650
  setPart(draft, captionId, { caption: {
1710
- ...priorCaption ?? { style: {} },
3651
+ ...priorCaption,
1711
3652
  id: captionId,
1712
3653
  kind: "caption",
1713
3654
  initial_duration_ms: caption.duration_ms,
@@ -1869,6 +3810,111 @@ function deleteAnchoredSubtree(draft, clipId) {
1869
3810
  for (const speechId of anchored) deleteSpeechSubtree(draft, speechId);
1870
3811
  }
1871
3812
  //#endregion
3813
+ //#region src/editor/journal.ts
3814
+ /**
3815
+ * Wire a plain-memory adapter + editor that share a recording id factory, so
3816
+ * every mutating transact lands in `journal` with ordered `generated_ids`.
3817
+ */
3818
+ function createEditSandbox(document, options) {
3819
+ const adapter = createPlainMemoryAdapter(document, options);
3820
+ return {
3821
+ adapter,
3822
+ editor: new SemanticEditor(adapter, new SchemaValidator(), adapter.idFactory),
3823
+ journal: adapter.journal
3824
+ };
3825
+ }
3826
+ /**
3827
+ * Re-drive `doc` from a recorded journal, forcing each entry's `generated_ids`
3828
+ * through a queue-backed id factory. Never mints fresh ids: an empty queue on
3829
+ * demand throws `unrecorded id`; leftover ids after an entry throws
3830
+ * `unconsumed ids`. Legacy entries without `generated_ids` are treated as `[]`.
3831
+ */
3832
+ async function replayJournal(doc, journal) {
3833
+ const queue = [];
3834
+ const idFactory = (_prefix) => {
3835
+ const id = queue.shift();
3836
+ if (id == null) throw new Error("unrecorded id");
3837
+ return id;
3838
+ };
3839
+ const editor = new SemanticEditor(doc, new SchemaValidator(), idFactory);
3840
+ for (const entry of journal) {
3841
+ queue.push(...entry.generated_ids ?? []);
3842
+ await dispatchEntry(editor, entry);
3843
+ if (queue.length > 0) throw new Error("unconsumed ids");
3844
+ }
3845
+ }
3846
+ /** Dispatch one journal entry to the matching editor method; payload is passed through. */
3847
+ async function dispatchEntry(editor, entry) {
3848
+ const payload = entry.payload;
3849
+ const options = entry.intent != null ? { intent: entry.intent } : void 0;
3850
+ switch (entry.kind) {
3851
+ case "MoveVideoClips":
3852
+ await editor.moveVideoClips(payload, options);
3853
+ return;
3854
+ case "MoveVideoClipsByAnchor":
3855
+ await editor.moveVideoClipsByAnchor(payload, options);
3856
+ return;
3857
+ case "DeleteVideoClips":
3858
+ await editor.deleteVideoClips(payload, options);
3859
+ return;
3860
+ case "AddVideoClips":
3861
+ await editor.addVideoClips(payload, options);
3862
+ return;
3863
+ case "AdjustVideoClipVolume":
3864
+ await editor.adjustVideoClipVolume(payload, options);
3865
+ return;
3866
+ case "SetVideoClipSpeedShift":
3867
+ await editor.setVideoClipSpeedShift(payload, options);
3868
+ return;
3869
+ case "ReplaceVideoClipContent":
3870
+ await editor.replaceVideoClipContent(payload, options);
3871
+ return;
3872
+ case "ReplaceVideoClipSequence":
3873
+ await editor.replaceVideoClipSequence(payload, options);
3874
+ return;
3875
+ case "AdjustVideoClipDuration":
3876
+ await editor.adjustVideoClipDuration(payload, options);
3877
+ return;
3878
+ case "AddSpeeches":
3879
+ await editor.addSpeeches(payload, options);
3880
+ return;
3881
+ case "DeleteSpeeches":
3882
+ await editor.deleteSpeeches(payload, options);
3883
+ return;
3884
+ case "MoveSpeeches":
3885
+ await editor.moveSpeeches(payload, options);
3886
+ return;
3887
+ case "ChangeSpeechScript":
3888
+ await editor.changeSpeechScript(payload, options);
3889
+ return;
3890
+ case "ChangeSpeechVoice":
3891
+ await editor.changeSpeechVoice(payload, options);
3892
+ return;
3893
+ case "AdjustSpeechVolume":
3894
+ await editor.adjustSpeechVolume(payload, options);
3895
+ return;
3896
+ case "SetCaptionVisibility":
3897
+ await editor.setCaptionVisibility(payload, options);
3898
+ return;
3899
+ case "SetCaptionStyle":
3900
+ await editor.setCaptionStyle(payload, options);
3901
+ return;
3902
+ case "SetBgm":
3903
+ await editor.setBgm(payload, options);
3904
+ return;
3905
+ case "DeleteBgm":
3906
+ await editor.deleteBgm(payload, options);
3907
+ return;
3908
+ case "AdjustBgmVolume":
3909
+ await editor.adjustBgmVolume(payload, options);
3910
+ return;
3911
+ default: {
3912
+ const _exhaustive = entry.kind;
3913
+ throw new Error(`replayJournal: unsupported kind ${String(_exhaustive)}`);
3914
+ }
3915
+ }
3916
+ }
3917
+ //#endregion
1872
3918
  //#region src/editor/types.ts
1873
3919
  /** Runtime list of the frozen, implemented kinds (for guards / introspection). */
1874
3920
  const IMPLEMENTED_SEMANTIC_OP_KINDS = [
@@ -2029,24 +4075,17 @@ var ManualSyncDoc = class ManualSyncDoc {
2029
4075
  * Fetches the snapshot up front rather than starting empty and converging: the
2030
4076
  * agent's first act is to read the document, so there is no useful state before
2031
4077
  * the snapshot lands. This also fails fast and loudly on a document that does
2032
- * not exist or whose first snapshot is incomplete or invalid.
4078
+ * not exist, instead of `MengineDocSession.waitForContent()`'s behavior of
4079
+ * waiting forever for content that will never arrive.
2033
4080
  */
2034
4081
  static async open(options) {
2035
- const response = await options.client.fetchSnapshot();
2036
4082
  const doc = new LoroDoc();
2037
- let manualSyncDoc;
2038
- try {
2039
- if (options.peerId != null) doc.setPeerId(options.peerId);
2040
- if (doc.import(base64ToBytes(response.snapshot)).pending != null) throw new Error("Initial mengine snapshot has missing dependencies");
2041
- manualSyncDoc = new ManualSyncDoc(options.client, doc);
2042
- assertValidVideoDocument(manualSyncDoc.snapshot());
2043
- manualSyncDoc.watermark = manualSyncDoc.serverVVFrom(response.version.server_vv) ?? doc.oplogVersion();
2044
- return manualSyncDoc;
2045
- } catch (error) {
2046
- manualSyncDoc?.adapter.dispose();
2047
- doc.free();
2048
- throw error;
2049
- }
4083
+ if (options.peerId != null) doc.setPeerId(options.peerId);
4084
+ const response = await options.client.fetchSnapshot();
4085
+ doc.import(base64ToBytes(response.snapshot));
4086
+ const manualSyncDoc = new ManualSyncDoc(options.client, doc);
4087
+ manualSyncDoc.watermark = manualSyncDoc.serverVVFrom(response.version.server_vv) ?? doc.oplogVersion();
4088
+ return manualSyncDoc;
2050
4089
  }
2051
4090
  /** Current document read model (authoritative shape). */
2052
4091
  snapshot() {
@@ -2065,18 +4104,31 @@ var ManualSyncDoc = class ManualSyncDoc {
2065
4104
  editorPeerId() {
2066
4105
  return this.doc.peerIdStr;
2067
4106
  }
2068
- /** Current content projected into the compatible track and part read shape. */
2069
- content() {
4107
+ /** Current document projected to the legacy `VideoDraft` read shape. */
4108
+ draft() {
2070
4109
  return fromVideoDocument(this.adapter.snapshot());
2071
4110
  }
2072
4111
  /**
4112
+ * Replay a deterministic sandbox journal into this document.
4113
+ *
4114
+ * The adapter stays private so callers cannot bypass the manual-sync
4115
+ * lifecycle; journal replay is the one host-side operation that needs the
4116
+ * adapter's transaction boundary and recorded id queue. Durability is still
4117
+ * explicit: call {@link push} after replay and report success only from its
4118
+ * verdict.
4119
+ */
4120
+ async replayJournal(journal) {
4121
+ await replayJournal(this.adapter, journal);
4122
+ }
4123
+ /**
2073
4124
  * Mark the document state the caller has just observed, for a later
2074
4125
  * {@link hasChangedSince}.
2075
4126
  *
2076
4127
  * This pair replaces the legacy integer-version comparison that
2077
4128
  * `DraftVersionDetector` used to tell the LLM "the draft was modified
2078
- * externally, reload before editing". Comparing Loro version vectors covers
2079
- * all collaborative edits without a business revision field in the document.
4129
+ * externally, reload before editing". Under mengine `meta.version` never
4130
+ * changes, so that detector would go permanently silent; comparing version
4131
+ * vectors restores the same capability.
2080
4132
  *
2081
4133
  * Same capability, not a stronger one: like the legacy detector, this only
2082
4134
  * reports what changed between two moments the caller chose to sample.
@@ -2160,7 +4212,6 @@ var ManualSyncDoc = class ManualSyncDoc {
2160
4212
  if (serverVV != null) this.watermark = serverVV;
2161
4213
  return {
2162
4214
  kind: response.kind,
2163
- mengineUpdateSeq: response.version?.update_seq ?? response.update_seq ?? void 0,
2164
4215
  updateSeq: response.update_seq ?? void 0,
2165
4216
  collaborated: serverVV != null && !covers(localVersion, serverVV)
2166
4217
  };
@@ -2279,7 +4330,6 @@ var SseConnection = class {
2279
4330
  for (const update of event.updates) this.onUpdate(update);
2280
4331
  }
2281
4332
  });
2282
- if (!signal.aborted) this.setStatus("connecting", /* @__PURE__ */ new Error("SSE stream closed"));
2283
4333
  } catch (error) {
2284
4334
  if (signal.aborted) break;
2285
4335
  this.setStatus("connecting", error instanceof Error ? error : new Error(String(error)));
@@ -2332,7 +4382,6 @@ var MedeoHttpDocStorage = class {
2332
4382
  async getDoc(docId) {
2333
4383
  this.assertDocId(docId);
2334
4384
  const snapshot = await this.client.fetchSnapshot();
2335
- this.reportServerVersion(snapshot.version?.server_vv);
2336
4385
  const now = /* @__PURE__ */ new Date();
2337
4386
  return {
2338
4387
  docId,
@@ -2344,7 +4393,6 @@ var MedeoHttpDocStorage = class {
2344
4393
  async getDocDiff(docId, knownVersion) {
2345
4394
  this.assertDocId(docId);
2346
4395
  const response = await this.client.sync(knownVersion);
2347
- this.reportServerVersion(response.server_vv);
2348
4396
  return {
2349
4397
  docId,
2350
4398
  missing: base64ToBytes(response.update),
@@ -2375,7 +4423,7 @@ var MedeoHttpDocStorage = class {
2375
4423
  if (update.data.byteLength === 0) return {};
2376
4424
  try {
2377
4425
  const response = await this.client.pushUpdate(update.data);
2378
- const serverVV = this.reportServerVersion(response.version?.server_vv);
4426
+ const serverVV = decodeServerVV(response.version?.server_vv);
2379
4427
  this.events.emit("pushOutcome", {
2380
4428
  kind: response.kind,
2381
4429
  updateSeq: response.update_seq ?? void 0,
@@ -2403,15 +4451,6 @@ var MedeoHttpDocStorage = class {
2403
4451
  subscribePushOutcome(callback) {
2404
4452
  return this.events.on("pushOutcome", callback);
2405
4453
  }
2406
- /** Authoritative HTTP reads and accepted pushes, never inferred from SSE bytes. */
2407
- subscribeServerVersion(callback) {
2408
- return this.events.on("serverVersion", callback);
2409
- }
2410
- reportServerVersion(encoded) {
2411
- const version = decodeServerVV(encoded);
2412
- if (version != null) this.events.emit("serverVersion", version);
2413
- return version;
2414
- }
2415
4454
  async deleteDoc(_docId) {
2416
4455
  throw new Error("MedeoHttpDocStorage does not support deleteDoc");
2417
4456
  }
@@ -2528,118 +4567,6 @@ var MemoryDocStorage = class extends BaseDocStorage {
2528
4567
  }
2529
4568
  };
2530
4569
  //#endregion
2531
- //#region src/session/document-undo-manager.ts
2532
- /**
2533
- * Tracks the shared LoroDoc independently of semantic editing. Undo/redo use
2534
- * the same mutation guard as the adapter and publish settled availability.
2535
- */
2536
- var DocumentUndoManager = class {
2537
- doc;
2538
- mutationGuard;
2539
- onChange;
2540
- manager;
2541
- unsubscribe;
2542
- disposed = false;
2543
- notificationQueued = false;
2544
- published = {
2545
- canUndo: false,
2546
- canRedo: false
2547
- };
2548
- activeSource = null;
2549
- constructor(doc, mutationGuard, onChange) {
2550
- this.doc = doc;
2551
- this.mutationGuard = mutationGuard;
2552
- this.onChange = onChange;
2553
- const peer = doc.peerIdStr;
2554
- this.manager = new UndoManager(doc, {
2555
- mergeInterval: 0,
2556
- maxUndoSteps: 100,
2557
- excludeOriginPrefixes: ["mengine.bootstrap", "mengine.initialize"],
2558
- onPush: (_isUndo, range) => {
2559
- this.scheduleNotification();
2560
- return {
2561
- value: this.activeSource ?? {
2562
- peer,
2563
- counter: range.start
2564
- },
2565
- cursors: []
2566
- };
2567
- },
2568
- onPop: () => this.scheduleNotification()
2569
- });
2570
- this.unsubscribe = doc.subscribe(() => this.scheduleNotification());
2571
- }
2572
- getState() {
2573
- this.assertActive();
2574
- return {
2575
- canUndo: this.manager.canUndo(),
2576
- canRedo: this.manager.canRedo()
2577
- };
2578
- }
2579
- undo(options) {
2580
- return this.applyUndoRedo("Undo", options);
2581
- }
2582
- redo(options) {
2583
- return this.applyUndoRedo("Redo", options);
2584
- }
2585
- beginGroup() {
2586
- this.assertActive();
2587
- this.mutationGuard.run(() => this.manager.groupStart());
2588
- }
2589
- endGroup() {
2590
- this.assertActive();
2591
- this.mutationGuard.run(() => this.manager.groupEnd());
2592
- this.scheduleNotification();
2593
- }
2594
- applyUndoRedo(kind, options) {
2595
- this.assertActive();
2596
- return this.mutationGuard.run(() => {
2597
- if (kind === "Undo" ? !this.manager.canUndo() : !this.manager.canRedo()) return false;
2598
- this.activeSource = kind === "Undo" ? this.manager.topUndoValue() : this.manager.topRedoValue();
2599
- try {
2600
- this.doc.setNextCommitOptions({ message: JSON.stringify({
2601
- semantic_op: kind,
2602
- payload: { source: this.activeSource },
2603
- intent: options?.intent ?? null,
2604
- actor: options?.actor ?? null
2605
- }) });
2606
- const before = this.doc.oplogFrontiers();
2607
- return (kind === "Undo" ? this.manager.undo() : this.manager.redo()) && this.doc.cmpWithFrontiers(before) !== 0;
2608
- } finally {
2609
- this.doc.clearNextCommitOptions();
2610
- this.activeSource = null;
2611
- this.scheduleNotification();
2612
- }
2613
- });
2614
- }
2615
- dispose() {
2616
- if (this.disposed) return;
2617
- this.disposed = true;
2618
- this.unsubscribe();
2619
- this.manager.setOnPush(void 0);
2620
- this.manager.setOnPop(void 0);
2621
- this.manager.free();
2622
- }
2623
- scheduleNotification() {
2624
- if (this.notificationQueued || this.disposed) return;
2625
- this.notificationQueued = true;
2626
- queueMicrotask(() => {
2627
- this.notificationQueued = false;
2628
- if (!this.disposed) this.publish();
2629
- });
2630
- }
2631
- publish() {
2632
- if (this.disposed) return;
2633
- const state = this.getState();
2634
- if (state.canUndo === this.published.canUndo && state.canRedo === this.published.canRedo) return;
2635
- this.published = state;
2636
- this.onChange();
2637
- }
2638
- assertActive() {
2639
- if (this.disposed) throw new Error("mengine doc undo manager is disposed");
2640
- }
2641
- };
2642
- //#endregion
2643
4570
  //#region src/session/mengine-doc-session.ts
2644
4571
  /**
2645
4572
  * Raised by {@link MengineDocSession.waitForServerAck} when the local edits it
@@ -2675,9 +4602,13 @@ var MengineAckFailedError = class extends Error {
2675
4602
  * A live editing session for one Medeo document — the single entry point clients
2676
4603
  * (FE draft driver, Agent, embeds) use to open, edit, and observe a document.
2677
4604
  *
2678
- * SemanticEditor writes through MirrorVideoDocumentAdapter directly, while
2679
- * DocumentUndoManager observes the same LoroDoc independently. Both mutation
2680
- * paths use the session's DocumentMutationGuard, closed before teardown.
4605
+ * It assembles the engine sync stack around one Medeo document:
4606
+ *
4607
+ * local DocStorage ─┐
4608
+ * ├─ ClientServerSynchronizer ── DocManager ── LoroDoc
4609
+ * MedeoHttpDocStorage┘ │
4610
+ * (remote = Rust mengine-server) ▼
4611
+ * MirrorVideoDocumentAdapter + SemanticEditor
2681
4612
  *
2682
4613
  * `DocManager` owns the `LoroDoc`: local edits committed on the adapter are
2683
4614
  * picked up via `subscribeLocalUpdates`, saved to local storage, then pushed to
@@ -2698,21 +4629,11 @@ var MengineDocSession = class {
2698
4629
  manager;
2699
4630
  events = new EventBus();
2700
4631
  disposables = new DisposableSet();
2701
- mutationGuard = new DocumentMutationGuard();
2702
4632
  adapterValue = null;
2703
4633
  editorValue = null;
2704
- undoManagerValue = null;
2705
4634
  started = false;
2706
- startTask = null;
2707
- destroyed = false;
2708
- closeTask = null;
2709
- lifetime = null;
2710
- hasConnected = false;
2711
- initialVersionValue = null;
2712
- localVersionValue = null;
2713
- pushErrorValue = null;
2714
4635
  /**
2715
- * Latest server oplog version seen on an authoritative HTTP response. Lets `waitForServerAck`
4636
+ * Latest server oplog version seen on a push outcome. Lets `waitForServerAck`
2716
4637
  * return without waiting when the server is already known to cover the local
2717
4638
  * doc (e.g. nothing was edited since the last confirmed push).
2718
4639
  */
@@ -2724,7 +4645,8 @@ var MengineDocSession = class {
2724
4645
  this.server = new MedeoHttpDocStorage({
2725
4646
  docId: options.docId,
2726
4647
  client: options.client,
2727
- sseReconnectDelayMs: options.sseReconnectDelayMs
4648
+ sseReconnectDelayMs: options.sseReconnectDelayMs,
4649
+ readonlyMode: options.readonlyMode
2728
4650
  });
2729
4651
  this.synchronizer = new ClientServerSynchronizer(this.local, this.server);
2730
4652
  this.manager = new DocManager(this.local, this.synchronizer);
@@ -2740,14 +4662,14 @@ var MengineDocSession = class {
2740
4662
  return this.server.subscribePushOutcome(callback);
2741
4663
  }
2742
4664
  /**
2743
- * Resolve once the server has durably accepted the local commits as of
4665
+ * Resolve once the server has durably accepted the local document state as of
2744
4666
  * *now* — the capability an Agent tool needs to answer "did my edit land?"
2745
4667
  * before reporting success.
2746
4668
  *
2747
4669
  * Call it right after the editor ops whose durability matters. It snapshots the
2748
- * latest local commit's version (or the loaded baseline before any edit) and
2749
- * resolves when an authoritative server version covers it. Remote-only
2750
- * imports do not extend this target, matching the displayed confirmation state.
4670
+ * local doc's current version and resolves on the first push outcome whose
4671
+ * `serverVV` covers that version, i.e. the server log is at least as advanced as
4672
+ * the local doc was when this was called.
2751
4673
  *
2752
4674
  * Version coverage, not byte identity, is the acceptance test — for two reasons:
2753
4675
  * the ops may reach the server inside a merged blob rather than as the exact
@@ -2762,39 +4684,31 @@ var MengineDocSession = class {
2762
4684
  * @throws {MengineAckFailedError} on timeout, rejection, or transport failure.
2763
4685
  */
2764
4686
  async waitForServerAck(options = {}) {
2765
- if (this.adapterValue == null || this.lifetime == null) throw new Error("mengine doc session is not started");
4687
+ if (this.adapterValue == null) throw new Error("mengine doc session is not started");
2766
4688
  const timeoutMs = options.timeoutMs ?? 15e3;
2767
- const target = this.confirmationTarget() ?? this.manager.connectDoc(this.docId).version();
2768
- const signal = this.lifetime.signal;
4689
+ const target = this.manager.connectDoc(this.docId).version();
2769
4690
  if (this.serverVVValue != null && serverCovers(this.serverVVValue, target)) return;
2770
4691
  await new Promise((resolve, reject) => {
2771
- const cleanup = [];
4692
+ let off = () => {};
2772
4693
  let done = false;
2773
4694
  const settle = (error) => {
2774
4695
  if (done) return;
2775
4696
  done = true;
2776
4697
  clearTimeout(timer);
2777
- cleanup.forEach((off) => off());
4698
+ off();
2778
4699
  if (error == null) resolve();
2779
4700
  else reject(error);
2780
4701
  };
2781
4702
  const timer = setTimeout(() => {
2782
4703
  settle(new MengineAckFailedError("timeout", void 0, void 0, `mengine did not acknowledge the update within ${timeoutMs}ms`));
2783
4704
  }, timeoutMs);
2784
- const onAbort = () => settle(new MengineAckFailedError("failed", void 0, void 0, "mengine doc session destroyed"));
2785
- signal.addEventListener("abort", onAbort, { once: true });
2786
- cleanup.push(() => signal.removeEventListener("abort", onAbort));
2787
- cleanup.push(this.events.on("syncState", () => {
2788
- if (this.serverVVValue != null && serverCovers(this.serverVVValue, target)) settle(void 0);
2789
- }));
2790
- cleanup.push(this.server.subscribePushOutcome((outcome) => {
4705
+ off = this.server.subscribePushOutcome((outcome) => {
2791
4706
  if (outcome.kind === "rejected" || outcome.kind === "failed") {
2792
4707
  settle(new MengineAckFailedError(outcome.kind, outcome.code, outcome.error, outcome.error?.message ?? `mengine push ${outcome.kind}`));
2793
4708
  return;
2794
4709
  }
2795
- }));
2796
- if (signal.aborted) onAbort();
2797
- else this.synchronizer.requestSync(this.docId);
4710
+ if (outcome.serverVV != null && serverCovers(outcome.serverVV, target)) settle(void 0);
4711
+ });
2798
4712
  });
2799
4713
  }
2800
4714
  /**
@@ -2807,207 +4721,67 @@ var MengineDocSession = class {
2807
4721
  if (this.editorValue == null) throw new Error("mengine doc session is not started");
2808
4722
  return this.editorValue;
2809
4723
  }
2810
- /** Current document snapshot (read model). */
2811
- snapshot() {
2812
- if (this.adapterValue == null) throw new Error("mengine doc session is not started");
2813
- return this.adapterValue.snapshot();
2814
- }
2815
- /** Current-session undo/redo availability. Loading and closed sessions report false. */
2816
- getUndoState() {
2817
- return this.undoManagerValue?.getState() ?? {
2818
- canUndo: false,
2819
- canRedo: false
2820
- };
2821
- }
2822
- /**
2823
- * Supplies current availability immediately, then coalesces stack changes in a
2824
- * microtask. Session teardown publishes empty availability synchronously.
2825
- */
2826
- subscribeUndoState(cb) {
2827
- const notify = () => cb(this.getUndoState());
2828
- const off = this.destroyed ? () => {} : this.events.on("undoState", notify);
2829
- notify();
2830
- return off;
2831
- }
2832
- /**
2833
- * Undo a local edit immediately; server confirmation remains asynchronous.
2834
- * On a shared LWW field this writes its prior value, potentially overwriting a
2835
- * later remote edit to that same field. Returns false if no update is produced.
2836
- */
2837
- undo(options) {
2838
- if (this.undoManagerValue == null) throw new Error("mengine doc undo manager is not ready");
2839
- return this.undoManagerValue.undo(options);
2840
- }
2841
4724
  /**
2842
- * Restore the state visible before undo without rerunning external side effects.
2843
- * Returns false if no update is produced; durable confirmation is separate.
4725
+ * Opaque version token of the local oplog (base64 `VersionVector.encode`).
4726
+ * Equality-comparable only: equal means no observed change (local or
4727
+ * remote-arrived) since the token was taken. Throws when not started.
2844
4728
  */
2845
- redo(options) {
2846
- if (this.undoManagerValue == null) throw new Error("mengine doc undo manager is not ready");
2847
- return this.undoManagerValue.redo(options);
4729
+ version() {
4730
+ if (this.adapterValue == null) throw new Error("mengine doc session is not started");
4731
+ return bytesToBase64(this.adapterValue.doc.oplogVersion().encode());
2848
4732
  }
2849
4733
  /**
2850
- * Combine existing semantic operations (e.g. trim a clip and adjust its volume)
2851
- * or repeated commits during one drag gesture into a single undo step. A gesture
2852
- * that only previews locally and commits once on release needs no group.
2853
- * Each commit is immediately visible locally and enters sync independently;
2854
- * a later failure does not roll it back.
2855
- * Always pair with endUndoGroup in a finally block. Conflicting remote imports
2856
- * can end/split the group early, and unrelated local edits would join it.
2857
- * Complete asynchronous asset preparation before opening the group.
4734
+ * The live document adapter, exposed for journal replay (commit channel).
4735
+ * Replaying through it still goes SemanticEditor → Loro → mengine-server —
4736
+ * no write bypass. Typed by the narrow interface on purpose.
2858
4737
  */
2859
- beginUndoGroup() {
2860
- if (this.undoManagerValue == null) throw new Error("mengine doc undo manager is not ready");
2861
- this.undoManagerValue.beginGroup();
4738
+ get documentAdapter() {
4739
+ if (this.adapterValue == null) throw new Error("mengine doc session is not started");
4740
+ return this.adapterValue;
2862
4741
  }
2863
- /** End a gesture, including one already split by a conflicting remote import. */
2864
- endUndoGroup() {
2865
- if (this.undoManagerValue == null) throw new Error("mengine doc undo manager is not ready");
2866
- this.undoManagerValue.endGroup();
4742
+ /** Current document snapshot (read model). */
4743
+ snapshot() {
4744
+ if (this.adapterValue == null) throw new Error("mengine doc session is not started");
4745
+ return this.adapterValue.snapshot();
2867
4746
  }
2868
4747
  /**
2869
4748
  * Start the sync stack and connect the document.
2870
4749
  *
2871
- * Returns after DocManager loads a local snapshot, or after the first remote
2872
- * sync when no local snapshot exists. A valid empty document is ready too.
2873
- * Cached documents can open before SSE connects; subsequent remote changes
2874
- * surface through `subscribe`.
4750
+ * Returns once the local snapshot has loaded into the Loro doc so callers can
4751
+ * read an initial snapshot. Remote convergence continues in the background and
4752
+ * surfaces through `subscribe`.
2875
4753
  */
2876
- start() {
2877
- if (this.destroyed) return Promise.reject(/* @__PURE__ */ new Error("mengine doc session destroyed"));
2878
- if (this.startTask != null) return this.startTask;
4754
+ async start() {
4755
+ if (this.started) return this.snapshot();
2879
4756
  this.started = true;
2880
- this.lifetime = new AbortController();
2881
- this.startTask = this.open().catch((error) => {
2882
- const wasDestroyed = this.destroyed;
2883
- this.destroy();
2884
- if (wasDestroyed) throw new Error("mengine doc session destroyed");
2885
- throw error;
2886
- });
2887
- return this.startTask;
2888
- }
2889
- async open() {
2890
- this.disposables.add(this.server.subscribeServerVersion((version) => {
2891
- this.serverVVValue = version;
2892
- if (this.getSyncState().confirmation === "confirmed") this.pushErrorValue = null;
2893
- this.emitSyncState();
2894
- }));
2895
- this.disposables.add(this.server.subscribePushOutcome((outcome) => {
2896
- this.pushErrorValue = outcome.kind === "failed" || outcome.kind === "rejected" ? outcome.error ?? /* @__PURE__ */ new Error(`mengine push ${outcome.kind}`) : null;
2897
- this.emitSyncState();
2898
- }));
2899
- this.disposables.add(this.server.connection.onStatusChanged((status) => {
2900
- if (status === "connected") this.hasConnected = true;
2901
- this.emitSyncState();
2902
- }));
2903
- this.disposables.add(() => this.local.connection.disconnect());
2904
- this.disposables.add(() => this.server.connection.disconnect());
2905
4757
  this.local.connection.connect();
2906
- await this.local.connection.waitForConnected().abortOn(this.lifetime.signal);
2907
- if (this.destroyed) throw new Error("mengine doc session destroyed");
2908
- if (this.options.initialSnapshot) {
2909
- await this.local.pushDocUpdate({
2910
- docId: this.docId,
2911
- data: this.options.initialSnapshot
2912
- }, "initial-snapshot");
2913
- if (this.destroyed) throw new Error("mengine doc session destroyed");
2914
- }
2915
4758
  this.server.connection.connect();
4759
+ this.disposables.add(() => this.local.connection.disconnect());
4760
+ this.disposables.add(() => this.server.connection.disconnect());
2916
4761
  this.synchronizer.start();
2917
4762
  this.manager.start();
2918
4763
  this.disposables.add(() => this.synchronizer.stop());
2919
4764
  this.disposables.add(() => this.manager.stop());
2920
4765
  const doc = this.manager.connectDoc(this.docId);
2921
- this.disposables.add(() => this.manager.disconnectDoc(this.docId));
2922
4766
  if (this.options.peerId != null) doc.setPeerId(this.options.peerId);
2923
- this.adapterValue = new MirrorVideoDocumentAdapter(doc, this.mutationGuard);
4767
+ this.adapterValue = new MirrorVideoDocumentAdapter(doc);
4768
+ this.editorValue = new SemanticEditor(this.adapterValue);
4769
+ this.disposables.add(() => this.manager.disconnectDoc(this.docId));
2924
4770
  const unsubscribe = doc.subscribe((event) => {
2925
4771
  if (this.adapterValue == null) return;
2926
- if (event.by === "local") this.trackLocalVersion(doc.version());
2927
- this.emitSyncState();
2928
4772
  this.events.emit("update", {
2929
4773
  source: event.by === "local" ? "local" : "remote",
2930
4774
  snapshot: this.adapterValue.snapshot()
2931
4775
  });
2932
4776
  });
2933
4777
  this.disposables.add(unsubscribe);
2934
- this.disposables.add(this.manager.onLocalUpdateReceived(this.docId, (update) => {
2935
- this.trackLocalVersion(decodeImportBlobMeta(update, true).partialEndVersionVector);
2936
- this.emitSyncState();
2937
- }));
2938
- this.disposables.add(this.manager.onDocStateChange(this.docId, (state) => {
2939
- this.events.emit("state", state);
2940
- this.emitSyncState();
4778
+ this.disposables.add(this.manager.onDocStateChange(this.docId, (state) => this.events.emit("state", state)));
4779
+ this.disposables.add(this.server.subscribePushOutcome((outcome) => {
4780
+ if (outcome.serverVV != null) this.serverVVValue = outcome.serverVV;
2941
4781
  }));
2942
- await this.waitForInitialLoad();
2943
- if (this.destroyed) throw new Error("mengine doc session destroyed");
2944
- assertValidVideoDocument(this.snapshot());
2945
- this.undoManagerValue = new DocumentUndoManager(doc, this.mutationGuard, () => this.events.emit("undoState"));
2946
- this.editorValue = new SemanticEditor(this.adapterValue);
2947
- this.initialVersionValue = doc.version();
2948
- if (this.localVersionValue) this.trackLocalVersion(this.initialVersionValue);
2949
- this.emitSyncState();
4782
+ await this.waitForContent();
2950
4783
  return this.snapshot();
2951
4784
  }
2952
- getLocalSaveState() {
2953
- return this.getState().localSave;
2954
- }
2955
- /** Immediately reports local transaction state; independent of server confirmation. */
2956
- subscribeLocalSaveState(cb) {
2957
- const off = this.events.on("state", () => cb(this.getLocalSaveState()));
2958
- cb(this.getLocalSaveState());
2959
- return off;
2960
- }
2961
- /** Waits for commits present now to reach local storage. Does not wait for the network. */
2962
- async waitForLocalSave(options = {}) {
2963
- if (!this.editorValue || this.destroyed) throw new Error("mengine doc session is not started");
2964
- await this.manager.waitForLocalSave(this.docId).timeout(options.timeoutMs ?? 15e3);
2965
- }
2966
- /** Stop accepting edits and drain local persistence before releasing resources.
2967
- * A failed local write keeps retrying, even after the host has unmounted.
2968
- * Hosts should use this for normal teardown; destroy() is immediate cancellation. */
2969
- close() {
2970
- if (this.closeTask) return this.closeTask;
2971
- if (this.destroyed || !this.editorValue) {
2972
- this.destroy();
2973
- return Promise.resolve();
2974
- }
2975
- this.mutationGuard.close();
2976
- this.synchronizer.stop();
2977
- this.server.connection.disconnect();
2978
- this.closeTask = this.manager.waitForLocalSave(this.docId).then(() => this.destroy());
2979
- return this.closeTask;
2980
- }
2981
- getSyncState() {
2982
- const state = this.getState();
2983
- const target = this.confirmationTarget();
2984
- const confirmation = this.serverVVValue == null || target == null ? this.localVersionValue == null ? "unknown" : "pending" : serverCovers(this.serverVVValue, target) ? "confirmed" : "pending";
2985
- const connection = !this.started ? "disconnected" : this.server.connection.status === "connected" ? "connected" : this.hasConnected || this.server.connection.error != null ? "disconnected" : "connecting";
2986
- return {
2987
- confirmation,
2988
- phase: connection === "disconnected" ? "offline" : this.pushErrorValue != null || state.error != null ? "failed" : connection === "connecting" ? "connecting" : state.syncing ? "syncing" : "idle"
2989
- };
2990
- }
2991
- trackLocalVersion(version) {
2992
- const target = VersionVector.parseJSON(this.confirmationTarget()?.toJSON() ?? /* @__PURE__ */ new Map());
2993
- for (const [peer, counter] of version.toJSON()) if ((target.get(peer) ?? 0) < counter) target.setEnd({
2994
- peer,
2995
- counter
2996
- });
2997
- this.localVersionValue = target;
2998
- }
2999
- confirmationTarget() {
3000
- return this.localVersionValue ?? this.initialVersionValue;
3001
- }
3002
- /** Immediately supplies current state; unsubscribe when the host changes docs. */
3003
- subscribeSyncState(cb) {
3004
- const off = this.events.on("syncState", cb);
3005
- cb(this.getSyncState());
3006
- return off;
3007
- }
3008
- emitSyncState() {
3009
- this.events.emit("syncState", this.getSyncState());
3010
- }
3011
4785
  subscribe(cb) {
3012
4786
  return this.events.on("update", cb);
3013
4787
  }
@@ -3018,48 +4792,40 @@ var MengineDocSession = class {
3018
4792
  return this.manager.getDocState(this.docId);
3019
4793
  }
3020
4794
  destroy() {
3021
- if (this.destroyed) return;
3022
- this.destroyed = true;
3023
- this.mutationGuard.close();
3024
- this.started = false;
3025
- this.lifetime?.abort();
3026
- this.undoManagerValue?.dispose();
3027
- this.undoManagerValue = null;
3028
- this.events.emit("undoState");
3029
4795
  this.disposables.dispose();
3030
- this.emitSyncState();
3031
4796
  this.events.clearAll();
3032
- this.adapterValue?.dispose();
3033
4797
  this.adapterValue = null;
3034
4798
  this.editorValue = null;
3035
4799
  this.started = false;
3036
4800
  }
3037
- /** Local absence needs a remote sync; empty business content does not. */
3038
- async waitForInitialLoad() {
3039
- const signal = this.lifetime.signal;
3040
- await new Promise((resolve, reject) => {
3041
- let off = () => {};
3042
- let offConnection = () => {};
3043
- const finish = (error) => {
3044
- off();
3045
- offConnection();
3046
- signal.removeEventListener("abort", onAbort);
3047
- if (error != null) reject(error);
3048
- else resolve();
3049
- };
3050
- const onAbort = () => finish(/* @__PURE__ */ new Error("mengine doc session destroyed"));
3051
- const check = (state) => {
3052
- if (state.loaded && (state.loadedFromLocal || state.synced)) finish();
3053
- else if (state.error != null) finish(new Error(state.error));
3054
- else if (state.loaded && this.server.connection.error != null) finish(this.server.connection.error);
3055
- };
3056
- off = this.onStateChange(check);
3057
- offConnection = this.server.connection.onStatusChanged(() => check(this.getState()));
3058
- signal.addEventListener("abort", onAbort, { once: true });
3059
- if (signal.aborted) onAbort();
3060
- else check(this.getState());
4801
+ /**
4802
+ * Resolve once the Loro doc holds the document root.
4803
+ *
4804
+ * `DocManager` loads from local storage, which starts empty for a fresh
4805
+ * client; the server snapshot arrives asynchronously via the first sync job.
4806
+ * `loaded` only means the local load ran, so we wait for actual content
4807
+ * (populated schema roots) instead, surfaced by the doc subscription set up
4808
+ * in `start()`.
4809
+ */
4810
+ async waitForContent() {
4811
+ if (this.hasContent()) return;
4812
+ await new Promise((resolve) => {
4813
+ const off = this.events.on("update", () => {
4814
+ if (this.hasContent()) {
4815
+ off();
4816
+ resolve();
4817
+ }
4818
+ });
3061
4819
  });
3062
4820
  }
4821
+ hasContent() {
4822
+ if (this.adapterValue == null) return false;
4823
+ try {
4824
+ return this.adapterValue.hasContent();
4825
+ } catch {
4826
+ return false;
4827
+ }
4828
+ }
3063
4829
  };
3064
4830
  /**
3065
4831
  * True when the *encoded* server version `serverVV` includes everything in
@@ -3083,4 +4849,4 @@ function serverCovers(serverVV, target) {
3083
4849
  return covers(server, target);
3084
4850
  }
3085
4851
  //#endregion
3086
- export { DEFAULT_UNIT_TIME_MS, IMPLEMENTED_SEMANTIC_OP_KINDS, LANE_KINDS_IN_STACK_ORDER, ManualSyncDoc, MedeoHttpDocStorage, MemoryDocStorage, MengineAckFailedError, MengineDocSession, MengineHttpClient, MengineHttpRequestError, MenginePushRejectedError, MirrorVideoDocumentAdapter, SchemaValidator, SemanticEditor, TIMELINE_SKELETON_DURATION_MS, ValidationError, VideoDocumentValidationError, arrangeMainTrackSeamlessly, assertValidVideoDocument, base64ToBytes, buildInitialVideoDocument, buildSpeechHostMap, bytesToBase64, cascadeAfterVideoClipChanges, createMirrorVideoDocument, createMirrorVideoDocumentAdapter, decodeDocVersionMark, derivePositionFromAbs, encodeDocVersionMark, ensureLaneTrack, fillMainTrackTimeGaps, findLaneTrack, fromVideoDocument, generatePartId, getAt, hostForAbsMs, isEmptyVideoClip, isImplementedSemanticOpKind, isMap, laneTrackId, mainTrackRanges, partDurationMs, partUnionSchema, readMainTrackItems, readMengineEventStream, readPart, readPartDurationMs, readVideoDocumentFromDraft, reassignSpeechesToVideoClipsByTime, recalculateTimelineDuration, relativePositionForAbs, resolveAllSpeechOverlaps, resolveSpeechOverlapByShiftingVideos, safeDurationMs, schemas_exports as schemas, snapshotToPlain, solveVideoDocument, syncAggregatedClipsTimePosition, toVideoDocument, validateVideoDocument, videoDocumentMirrorSchema, videoDocumentSchema };
4852
+ export { DEFAULT_UNIT_TIME_MS, ENTITY_TIMELINE_PROJECTION_SCHEMA_VERSION, EntityGraphHttpClient, EntityTimelineEditor, EntityTimelineProjectionError, IMPLEMENTED_SEMANTIC_OP_KINDS, LANE_KINDS_IN_STACK_ORDER, LORO_ENTITY_SCHEMA, LoroEntityDocument, LoroEntityDraft, ManualSyncDoc, MedeoHttpDocStorage, MemoryDocStorage, MengineAckFailedError, MengineDocSession, MengineHttpClient, MengineHttpRequestError, MenginePushRejectedError, MirrorVideoDocumentAdapter, PlainMemoryAdapter, SchemaValidator, ScriptCompositionError, SemanticEditor, TIMELINE_SKELETON_DURATION_MS, VIDEO_DOCUMENT_SCHEMA_VERSION, ValidationError, VideoDocumentValidationError, applyEntityRows, applyEntityTimelineProjection, applyFieldChanges, arrangeMainTrackSeamlessly, assembleCaptionContent, assembleEntityContent, assemblePhoneticScriptContent, assembleScriptText, assertCanonicalEditorResources, assertEntityProjectionPreservesLegacy, assertFieldChanges, assertMediaAssetWritePolicy, assertValidVideoDocument, base64ToBytes, buildInitialVideoDocument, buildSpeechHostMap, bytesToBase64, cascadeAfterVideoClipChanges, compileEntityRows, createEditSandbox, createMirrorVideoDocument, createMirrorVideoDocumentAdapter, createPlainMemoryAdapter, decodeDocVersionMark, derivePositionFromAbs, effectiveVideoClipDurationMs, encodeDocVersionMark, ensureEditorFoundation, ensureLaneTrack, fillMainTrackTimeGaps, findComposedAudioScript, findLaneTrack, fromVideoDocument, generatePartId, getAt, hostForAbsMs, importMediaAsset, isEmptyVideoClip, isImplementedSemanticOpKind, isMap, laneTrackId, mainTrackRanges, migrateLegacyTimelineToEntities, partDurationMs, partUnionSchema, prepareCaptionContent, projectEntityTimeline, readDocumentAudioScript, readEntityDocument, readMainTrackItems, readMengineEventStream, readPart, readPartDurationMs, readVideoDocumentFromDraft, reassignSpeechesToVideoClipsByTime, recalculateTimelineDuration, relativePositionForAbs, replayJournal, resolveAllSpeechOverlaps, resolveEntityTimelineLayout, resolveFieldPath, resolveSpeechOverlapByShiftingVideos, safeDurationMs, schemas_exports as schemas, selectAudioScriptSegment, snapshotToPlain, solveVideoDocument, speedOf, syncAggregatedClipsTimePosition, toVideoDocument, validateVideoDocument, videoDocumentMirrorSchema, videoDocumentSchema, writeVideoDocumentToDraft };