@mengine/medeo-client 1.3.0 → 1.3.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,5 @@
1
- import { t as __exportAll } from "./chunk-D7D4PA-g.js";
2
- import { A as partDurationMs, C as reassignSpeechesToVideoClipsByTime, D as syncAggregatedClipsTimePosition, E as resolveSpeechOverlapByShiftingVideos, F as partUnionToDraft, I as recordEntries, L as videoDocumentMirrorSchema, M as DEFAULT_UNIT_TIME_MS, N as VIDEO_DOCUMENT_SCHEMA_VERSION, O as TIMELINE_SKELETON_DURATION_MS, P as effectiveVideoClipDurationMs, R as base64ToBytes, S as fillMainTrackTimeGaps, T as resolveAllSpeechOverlaps, _ as findLaneTrack, a as buildInitialVideoDocument, b as cascadeAfterVideoClipChanges, c as fromVideoDocument, d as assertValidVideoDocument, f as validateVideoDocument, g as ensureLaneTrack, h as LANE_KINDS_IN_STACK_ORDER, i as readVideoDocumentFromDraft, j as safeDurationMs, k as isEmptyVideoClip, l as toVideoDocument, m as videoDocumentSchema, n as createMirrorVideoDocument, o as buildSpeechHostMap, p as partUnionSchema, r as createMirrorVideoDocumentAdapter, s as derivePositionFromAbs, t as MirrorVideoDocumentAdapter, u as VideoDocumentValidationError, v as laneTrackId, w as recalculateTimelineDuration, x as arrangeMainTrackSeamlessly, y as solveVideoDocument, z as bytesToBase64 } from "./document-C0o_cjAH.js";
3
- import { z } from "zod";
1
+ import { $ as videoDocumentMirrorSchema, A as ensureLaneTrack, B as resolveSpeechOverlapByShiftingVideos, C as toVideoDocument, D as partUnionSchema, E as validateVideoDocument, F as arrangeMainTrackSeamlessly, G as safeDurationMs, H as TIMELINE_SKELETON_DURATION_MS, I as fillMainTrackTimeGaps, J as VIDEO_DOCUMENT_SCHEMA_VERSION, K as DEFAULT_UNIT_TIME_MS, L as reassignSpeechesToVideoClipsByTime, M as laneTrackId, N as solveVideoDocument, O as videoDocumentSchema, P as cascadeAfterVideoClipChanges, Q as recordEntries, R as recalculateTimelineDuration, S as fromVideoDocument, T as assertValidVideoDocument, U as isEmptyVideoClip, V as syncAggregatedClipsTimePosition, W as partDurationMs, X as speedOf, Y as effectiveVideoClipDurationMs, Z as partUnionToDraft, _ as hasSequence, a as applyEntityTimelineProjection, b as buildSpeechHostMap, c as writeVideoDocumentToDraft, d as resolveEntityTimelineLayout, et as base64ToBytes, f as EntityTimelineProjectionError, g as createRelationId, h as createEntityId, i as MirrorVideoDocumentAdapter, j as findLaneTrack, k as LANE_KINDS_IN_STACK_ORDER, l as readVideoDocumentFromDraft, m as isJsonObject, n as createPlainMemoryAdapter, o as createMirrorVideoDocument, p as decodeEntityRelationRows, q as ENTITY_TIMELINE_PROJECTION_SCHEMA_VERSION, r as generatePartId, s as createMirrorVideoDocumentAdapter, t as PlainMemoryAdapter, tt as bytesToBase64, u as projectEntityTimeline, v as isMediaAssetVariantKind, w as VideoDocumentValidationError, x as derivePositionFromAbs, y as buildInitialVideoDocument, z as resolveAllSpeechOverlaps } from "./document-Caidonf8.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";
4
3
  import { LoroDoc, VersionVector } from "loro-crdt";
5
4
  import { ClientServerSynchronizer, DocManager } from "@mengine/sync";
6
5
  import { DisposableSet, EventBus, Task } from "@mengine/utils";
@@ -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;
@@ -135,12 +134,12 @@ var MengineHttpClient = class {
135
134
  ...init,
136
135
  headers
137
136
  });
138
- const payload = await safeReadJson(response);
137
+ const payload = await safeReadJson$1(response);
139
138
  if (!response.ok) throw new MengineHttpRequestError(response.status, payload);
140
139
  return payload;
141
140
  }
142
141
  endpoint(path) {
143
- 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}`;
144
143
  }
145
144
  };
146
145
  /**
@@ -157,7 +156,7 @@ function asPushRejection(error) {
157
156
  if (body.kind !== "rejected" || typeof body.code !== "string") return void 0;
158
157
  return new MenginePushRejectedError(body.code, body.message ?? "", body.server_version, error.status);
159
158
  }
160
- async function safeReadJson(response) {
159
+ async function safeReadJson$1(response) {
161
160
  const text = await response.text();
162
161
  if (text.length === 0) return null;
163
162
  try {
@@ -195,588 +194,2377 @@ async function readMengineEventStream(options) {
195
194
  }
196
195
  }
197
196
  }
198
- function handleSseFrame(frame, onUpdate) {
199
- const event = parseSseFrame(frame);
200
- if (event.event !== "update" || event.data.length === 0) return;
201
- onUpdate(JSON.parse(event.data.join("\n")));
197
+ function handleSseFrame(frame, onUpdate) {
198
+ const event = parseSseFrame(frame);
199
+ if (event.event !== "update" || event.data.length === 0) return;
200
+ onUpdate(JSON.parse(event.data.join("\n")));
201
+ }
202
+ function parseSseFrame(frame) {
203
+ let event = null;
204
+ const data = [];
205
+ for (const line of frame.split(/\r?\n/)) if (line.startsWith("event:")) event = line.slice(6).trim();
206
+ else if (line.startsWith("data:")) data.push(line.slice(5).trimStart());
207
+ return {
208
+ event,
209
+ data
210
+ };
211
+ }
212
+ function findSseFrameBoundary(buffer) {
213
+ const lf = buffer.indexOf("\n\n");
214
+ const crlf = buffer.indexOf("\r\n\r\n");
215
+ if (lf < 0) return crlf;
216
+ if (crlf < 0) return lf;
217
+ return Math.min(lf, crlf);
218
+ }
219
+ //#endregion
220
+ //#region src/entity-editor/editor-resources.ts
221
+ const roleOrder$1 = {
222
+ caption: 0,
223
+ video_clip: 1,
224
+ speech: 2,
225
+ bgm: 3
226
+ };
227
+ /**
228
+ * MEngine editor policy, not a cardinality restriction on the general-purpose DSL.
229
+ *
230
+ * Media variants share one entity identity with their Asset: every
231
+ * Image/Video/Audio/Voice Entity must carry its own external locator, every
232
+ * external asset id has exactly one claimant, and no media variant may be
233
+ * bound through a legacy `physical-asset` Relation. Dual-entity media graphs
234
+ * are rejected, not migrated. Caption inline text keeps its inline Asset and
235
+ * `physical-asset` binding.
236
+ */
237
+ function assertCanonicalEditorResources(rows) {
238
+ if (rows.entities.filter((row) => row.entityKind === "timeline").length > 1) throw new EntityTimelineProjectionError("Editor requires exactly one Timeline");
239
+ 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`);
240
+ const identityByAssetKey = /* @__PURE__ */ new Map();
241
+ const kinds = new Map(rows.entities.map((row) => [String(row.entityId), row.entityKind]));
242
+ for (const entity of rows.entities) {
243
+ if (isMediaAssetVariantKind(entity.entityKind) && memotaLocator(entity.payload.external) === void 0) throw new EntityTimelineProjectionError(`Media Entity ${entity.entityId} must carry its own Asset external identity`);
244
+ if (entity.entityKind !== "asset" && !isMediaAssetVariantKind(entity.entityKind)) continue;
245
+ const external = entity.payload.external;
246
+ if (!isJsonObject(external) || external.system !== "memota" && external.system !== "memota-speech" || typeof external.key !== "string") continue;
247
+ const key = JSON.stringify([external.system, external.key]);
248
+ const previous = identityByAssetKey.get(key);
249
+ if (previous !== void 0 && previous !== entity.entityId) throw new EntityTimelineProjectionError(`Duplicate Asset for ${key}; reuse ${previous}`);
250
+ identityByAssetKey.set(key, entity.entityId);
251
+ }
252
+ for (const relation of rows.relations) {
253
+ if (relation.relationKind !== "physical-asset") continue;
254
+ const mediaEndpoint = [relation.endpoint0EntityId, relation.endpoint1EntityId].find((endpoint) => isMediaAssetVariantKind(kinds.get(String(endpoint)) ?? ""));
255
+ if (mediaEndpoint !== void 0) throw new EntityTimelineProjectionError(`Cannot bind media Entity ${mediaEndpoint} through physical-asset Relation ${relation.relationId}; media owns its Asset identity directly`);
256
+ }
257
+ }
258
+ /**
259
+ * Commit-transition policy shared by the editor, the HTTP commit boundary, the
260
+ * host tool, and the entity stores. It compares the authoritative before and
261
+ * after rows of one CAS commit and enforces the single-identity write rules
262
+ * on the complete after state, with no exemption for historical graphs:
263
+ *
264
+ * 1. every Image/Video/Audio/Voice Entity carries its own Asset `external`
265
+ * identity;
266
+ * 2. no `physical-asset` Relation may bind a media variant (Caption inline
267
+ * text keeps its inline Asset and binding);
268
+ * 3. a self-carried media identity is immutable — it cannot be rewritten to
269
+ * another asset id.
270
+ *
271
+ * Dual-entity media graphs are rejected instead of being migrated or merged
272
+ * implicitly. Deleting media is explicit and allowed.
273
+ */
274
+ function assertMediaAssetWritePolicy(before, after) {
275
+ const beforeEntities = new Map(before.entities.map((row) => [String(row.entityId), row]));
276
+ const afterKinds = new Map(after.entities.map((row) => [String(row.entityId), row.entityKind]));
277
+ for (const row of after.entities) {
278
+ if (!isMediaAssetVariantKind(row.entityKind)) continue;
279
+ if (memotaLocator(row.payload.external) === void 0) throw new EntityTimelineProjectionError(`Media Entity ${row.entityId} must carry its own Asset external identity`);
280
+ }
281
+ for (const relation of after.relations) {
282
+ if (relation.relationKind !== "physical-asset") continue;
283
+ const mediaEndpoint = [relation.endpoint0EntityId, relation.endpoint1EntityId].find((endpoint) => isMediaAssetVariantKind(afterKinds.get(String(endpoint)) ?? ""));
284
+ if (mediaEndpoint !== void 0) throw new EntityTimelineProjectionError(`Cannot bind media Entity ${mediaEndpoint} through physical-asset Relation ${relation.relationId}; media owns its Asset identity directly`);
285
+ }
286
+ for (const row of after.entities) {
287
+ if (!isMediaAssetVariantKind(row.entityKind)) continue;
288
+ const priorExternal = memotaLocator(beforeEntities.get(String(row.entityId))?.payload.external);
289
+ if (priorExternal === void 0) continue;
290
+ const nextExternal = memotaLocator(row.payload.external);
291
+ 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`);
292
+ }
293
+ }
294
+ function memotaLocator(value) {
295
+ if (!isJsonObject(value) || value.system !== "memota" && value.system !== "memota-speech" || typeof value.key !== "string" || value.key.trim() === "") return;
296
+ return {
297
+ system: value.system,
298
+ key: value.key
299
+ };
300
+ }
301
+ /** Add only missing editor structure; existing identities and owned settings are never replaced. */
302
+ function ensureEditorFoundation(initial, idFactory = (prefix) => `${prefix}_${globalThis.crypto.randomUUID()}`, timelinePayload = {}) {
303
+ const entities = structuredClone([...initial.entities]);
304
+ const relations = structuredClone([...initial.relations]);
305
+ const roots = entities.filter((row) => row.entityKind === "timeline");
306
+ if (roots.length > 1) throw new EntityTimelineProjectionError("Editor requires exactly one Timeline");
307
+ const mintEntity = () => {
308
+ const id = createEntityId(idFactory("entity"));
309
+ if (entities.some((row) => row.entityId === id)) throw new Error(`Duplicate entity id ${id}`);
310
+ return id;
311
+ };
312
+ let timeline = roots[0];
313
+ if (timeline === void 0) {
314
+ timeline = {
315
+ entityId: mintEntity(),
316
+ entityKind: "timeline",
317
+ payload: structuredClone(timelinePayload)
318
+ };
319
+ entities.push(timeline);
320
+ }
321
+ const trackEntityIds = {};
322
+ for (const role of Object.keys(roleOrder$1)) {
323
+ const matches = entities.filter((row) => row.entityKind === "track" && row.payload.role === role);
324
+ if (matches.length > 1) throw new EntityTimelineProjectionError(`Editor has multiple ${role} Tracks`);
325
+ let track = matches[0];
326
+ if (track === void 0) {
327
+ track = {
328
+ entityId: mintEntity(),
329
+ entityKind: "track",
330
+ payload: {
331
+ role,
332
+ order: roleOrder$1[role]
333
+ }
334
+ };
335
+ entities.push(track);
336
+ }
337
+ const bindings = relations.filter((row) => row.relationKind === "timeline-track" && (row.endpoint0EntityId === track.entityId || row.endpoint1EntityId === track.entityId));
338
+ if (bindings.some((row) => row.endpoint0EntityId !== timeline.entityId && row.endpoint1EntityId !== timeline.entityId)) throw new EntityTimelineProjectionError(`Track ${track.entityId} belongs to another Timeline`);
339
+ if (bindings.length === 0) {
340
+ const relationId = createRelationId(idFactory("relation"));
341
+ if (relations.some((row) => row.relationId === relationId)) throw new Error(`Duplicate relation id ${relationId}`);
342
+ relations.push({
343
+ relationId,
344
+ relationKind: "timeline-track",
345
+ endpoint0EntityId: timeline.entityId,
346
+ endpoint1EntityId: track.entityId,
347
+ metadata: {},
348
+ trace: {}
349
+ });
350
+ }
351
+ trackEntityIds[role] = track.entityId;
352
+ }
353
+ return {
354
+ rows: {
355
+ entities,
356
+ relations
357
+ },
358
+ timelineEntityId: timeline.entityId,
359
+ trackEntityIds
360
+ };
361
+ }
362
+ //#endregion
363
+ //#region src/entity-editor/entity-graph-http-client.ts
364
+ const MENGINE_API_PREFIX = "/api/mengine/v1";
365
+ const numericMarkerValidation$1 = { compareMarkerPoints: (_marker, _range, left, right) => {
366
+ if (typeof left !== "number" || !Number.isFinite(left) || typeof right !== "number" || !Number.isFinite(right)) throw new Error("entity-state requires finite numeric Marker coordinates");
367
+ return left < right ? -1 : left > right ? 1 : 0;
368
+ } };
369
+ /** Browser-safe authenticated CAS client for a document's Entity graph. */
370
+ var EntityGraphHttpClient = class {
371
+ options;
372
+ transport;
373
+ endpoint;
374
+ constructor(options) {
375
+ this.options = options;
376
+ this.transport = new MengineHttpClient(options);
377
+ const origin = options.httpOrigin.replace(/\/$/, "");
378
+ this.endpoint = `${origin}${MENGINE_API_PREFIX}/docs/${encodeURIComponent(options.docId)}/entity-state`;
379
+ }
380
+ async fetchState() {
381
+ return this.request({ method: "GET" });
382
+ }
383
+ /**
384
+ * Replace the complete Entity graph under the baseline revision.
385
+ *
386
+ * Deletion intent is derived from baseline IDs omitted from `nextRows`, so a
387
+ * transient create-then-remove never becomes a request to delete unknown
388
+ * persisted data.
389
+ */
390
+ async commit(baseState, nextRows, options = {}) {
391
+ if (!isNonNegativeSafeInteger(baseState.revision)) throw new Error("Entity graph revision must be a non-negative safe integer");
392
+ const baseRows = cloneAndValidateRows(baseState.rows);
393
+ const next = cloneAndValidateRows(nextRows);
394
+ assertMediaAssetWritePolicy(baseRows, next);
395
+ const nextEntityIds = new Set(next.entities.map((row) => row.entityId));
396
+ const nextRelationIds = new Set(next.relations.map((row) => row.relationId));
397
+ const deletedEntityIds = baseRows.entities.map((row) => row.entityId).filter((entityId) => !nextEntityIds.has(entityId)).sort();
398
+ const deletedRelationIds = baseRows.relations.map((row) => row.relationId).filter((relationId) => !nextRelationIds.has(relationId)).sort();
399
+ return this.request({
400
+ method: "POST",
401
+ body: JSON.stringify({
402
+ expected_revision: baseState.revision,
403
+ rows: toWireRows(next),
404
+ deleted_entity_ids: deletedEntityIds,
405
+ deleted_relation_ids: deletedRelationIds,
406
+ ...options.migrationBaseVv === void 0 ? {} : { migration_base_vv: options.migrationBaseVv }
407
+ })
408
+ });
409
+ }
410
+ async request(init) {
411
+ const response = await this.transport.fetch(this.endpoint, {
412
+ ...init,
413
+ headers: this.transport.headers()
414
+ });
415
+ const payload = await safeReadJson(response);
416
+ if (!response.ok) throw new MengineHttpRequestError(response.status, payload);
417
+ return parseWireState(payload, this.options.docId);
418
+ }
419
+ };
420
+ function parseWireState(value, expectedDocId) {
421
+ if (!isRecord(value) || typeof value.doc_id !== "string" || !isNonNegativeSafeInteger(value.revision)) throw new Error("Invalid entity-state response envelope");
422
+ if (value.doc_id !== expectedDocId) throw new Error(`Entity-state response doc_id mismatch: expected "${expectedDocId}"`);
423
+ const rows = parseWireRows(value.rows);
424
+ decodeEntityRelationRows(rows, numericMarkerValidation$1);
425
+ return {
426
+ revision: value.revision,
427
+ rows
428
+ };
429
+ }
430
+ function parseWireRows(value) {
431
+ if (!isRecord(value) || !Array.isArray(value.entities) || !Array.isArray(value.relations)) throw new Error("Invalid entity-state response rows");
432
+ return {
433
+ entities: value.entities.map(parseWireEntity),
434
+ relations: value.relations.map(parseWireRelation)
435
+ };
436
+ }
437
+ function parseWireEntity(value) {
438
+ if (!isRecord(value) || !isJsonObject(value.payload)) throw new Error("Invalid Entity row in entity-state response");
439
+ return {
440
+ entityId: createEntityId(requiredString(value.entity_id, "entity_id")),
441
+ entityKind: requiredString(value.entity_kind, "entity_kind"),
442
+ payload: structuredClone(value.payload)
443
+ };
444
+ }
445
+ function parseWireRelation(value) {
446
+ if (!isRecord(value) || !isJsonObject(value.metadata) || !isJsonObject(value.trace)) throw new Error("Invalid Relation row in entity-state response");
447
+ return {
448
+ relationId: createRelationId(requiredString(value.relation_id, "relation_id")),
449
+ relationKind: requiredString(value.relation_kind, "relation_kind"),
450
+ endpoint0EntityId: createEntityId(requiredString(value.endpoint_0_entity_id, "endpoint_0_entity_id")),
451
+ endpoint1EntityId: createEntityId(requiredString(value.endpoint_1_entity_id, "endpoint_1_entity_id")),
452
+ metadata: structuredClone(value.metadata),
453
+ trace: structuredClone(value.trace)
454
+ };
455
+ }
456
+ function cloneAndValidateRows(rows) {
457
+ const clone = structuredClone(rows);
458
+ decodeEntityRelationRows(clone, numericMarkerValidation$1);
459
+ return clone;
460
+ }
461
+ function toWireRows(rows) {
462
+ return {
463
+ entities: rows.entities.map((row) => ({
464
+ entity_id: row.entityId,
465
+ entity_kind: row.entityKind,
466
+ payload: row.payload
467
+ })),
468
+ relations: rows.relations.map((row) => ({
469
+ relation_id: row.relationId,
470
+ relation_kind: row.relationKind,
471
+ endpoint_0_entity_id: row.endpoint0EntityId,
472
+ endpoint_1_entity_id: row.endpoint1EntityId,
473
+ metadata: row.metadata,
474
+ trace: row.trace
475
+ }))
476
+ };
477
+ }
478
+ function requiredString(value, field) {
479
+ if (typeof value !== "string" || value.length === 0 || value.trim() !== value) throw new Error(`Invalid ${field} in entity-state response`);
480
+ return value;
481
+ }
482
+ function isRecord(value) {
483
+ return value !== null && typeof value === "object" && !Array.isArray(value);
484
+ }
485
+ function isNonNegativeSafeInteger(value) {
486
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
487
+ }
488
+ async function safeReadJson(response) {
489
+ const text = await response.text();
490
+ if (text.length === 0) return null;
491
+ try {
492
+ return JSON.parse(text);
493
+ } catch {
494
+ return text;
495
+ }
496
+ }
497
+ //#endregion
498
+ //#region src/entity-editor/media-asset-import.ts
499
+ const numericCoordinates = { compareMarkerPoints: (_marker, _range, left, right) => {
500
+ if (typeof left !== "number" || typeof right !== "number" || !Number.isFinite(left) || !Number.isFinite(right)) throw new Error("Media editor requires numeric coordinates");
501
+ return left - right;
502
+ } };
503
+ /**
504
+ * Import at the editor boundary, not at asset generation time. Existing
505
+ * provenance is retained.
506
+ *
507
+ * A media variant is a logical facet of its Asset and shares one entity
508
+ * identity: the import mints exactly one entity of the media kind that carries
509
+ * the external locator itself, and deduplicates only against existing variants
510
+ * that already carry the same `(system, key)`. Legacy dual-entity graphs
511
+ * (`asset` row plus a `physical-asset` binding) are not reused and are
512
+ * rejected by the canonical resource policy instead of being migrated.
513
+ */
514
+ function importMediaAsset(initial, fact, idFactory = (prefix) => `${prefix}_${globalThis.crypto.randomUUID()}`) {
515
+ if (!fact.assetId || fact.assetId.trim() !== fact.assetId) throw new Error("Expected an asset id");
516
+ if (![
517
+ "image",
518
+ "video",
519
+ "audio",
520
+ "voice"
521
+ ].includes(fact.kind)) throw new Error("Unsupported media kind");
522
+ if (fact.kind !== "image" && (!Number.isFinite(fact.durationMs) || fact.durationMs <= 0)) throw new Error(`${fact.kind} ${fact.assetId} requires its factual positive duration`);
523
+ if ((fact.kind === "audio" || fact.kind === "voice") && fact.storageKey.trim() === "") throw new Error(`${fact.kind} ${fact.assetId} requires its physical storage key`);
524
+ decodeEntityRelationRows(initial, numericCoordinates);
525
+ assertCanonicalEditorResources(initial);
526
+ const entities = structuredClone([...initial.entities]);
527
+ const relations = structuredClone([...initial.relations]);
528
+ const system = fact.kind === "voice" ? "memota-speech" : "memota";
529
+ const existing = entities.filter((row) => {
530
+ const external = row.payload.external;
531
+ return isMediaAssetVariantKind(row.entityKind) && isJsonObject(external) && external.system === system && external.key === fact.assetId;
532
+ });
533
+ if (existing.length > 1) throw new Error(`Duplicate media identities for ${fact.assetId}; reuse ${existing[0].entityId}`);
534
+ if (existing[0] !== void 0) {
535
+ const variant = requireMatchingVariant(existing[0], fact);
536
+ replaceEntity$1(entities, variant.entityId, variant);
537
+ return {
538
+ rows: {
539
+ entities,
540
+ relations
541
+ },
542
+ contentEntityId: variant.entityId
543
+ };
544
+ }
545
+ const entityId = createEntityId(idFactory("entity"));
546
+ if (entities.some((row) => row.entityId === entityId)) throw new Error(`Duplicate entity id ${entityId}`);
547
+ const variant = {
548
+ entityId,
549
+ entityKind: fact.kind,
550
+ payload: {
551
+ extent: fact.kind === "image" ? {
552
+ kind: "unbounded",
553
+ start: 0
554
+ } : {
555
+ kind: "bounded",
556
+ start: 0,
557
+ end: fact.durationMs
558
+ },
559
+ sampling: fact.kind === "image" ? "constant" : "native",
560
+ coordinateSpace: "milliseconds",
561
+ external: {
562
+ system,
563
+ key: fact.assetId
564
+ },
565
+ ...fact.storageKey === void 0 ? {} : { storageKey: fact.storageKey },
566
+ ...fact.kind === "voice" && fact.voice !== void 0 ? { voice: {
567
+ system: fact.voice.system,
568
+ key: fact.voice.key,
569
+ ...fact.voice.name === void 0 ? {} : { name: fact.voice.name }
570
+ } } : {}
571
+ }
572
+ };
573
+ entities.push(variant);
574
+ const rows = {
575
+ entities,
576
+ relations
577
+ };
578
+ decodeEntityRelationRows(rows, numericCoordinates);
579
+ assertCanonicalEditorResources(rows);
580
+ return {
581
+ rows,
582
+ contentEntityId: entityId
583
+ };
584
+ }
585
+ function requireMatchingVariant(row, fact) {
586
+ const extent = row.payload.extent;
587
+ 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}`);
588
+ if (fact.storageKey !== void 0 && row.payload.storageKey !== fact.storageKey) {
589
+ if (row.payload.storageKey !== void 0) throw new Error(`Media facts conflict with existing storage key for ${fact.assetId}`);
590
+ return {
591
+ ...row,
592
+ payload: {
593
+ ...row.payload,
594
+ storageKey: fact.storageKey
595
+ }
596
+ };
597
+ }
598
+ return row;
599
+ }
600
+ function replaceEntity$1(entities, entityId, replacement) {
601
+ const index = entities.findIndex((row) => row.entityId === entityId);
602
+ if (index < 0) throw new Error(`Entity id ${entityId} does not exist`);
603
+ entities[index] = replacement;
604
+ }
605
+ function sameVoice(left, right) {
606
+ if (right === void 0) return left === void 0;
607
+ 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");
608
+ }
609
+ //#endregion
610
+ //#region src/entity-editor/entity-timeline-editor.ts
611
+ const roleOrder = {
612
+ caption: 0,
613
+ video_clip: 1,
614
+ speech: 2,
615
+ bgm: 3
616
+ };
617
+ const defaultIdFactory = (prefix) => `${prefix}_${globalThis.crypto.randomUUID()}`;
618
+ /**
619
+ * Graph-native timeline authoring over authoritative Medeo Entity and Relation rows.
620
+ *
621
+ * Each mutation is applied to a detached graph, validated as a complete DSL set,
622
+ * and committed only after validation succeeds.
623
+ */
624
+ var EntityTimelineEditor = class {
625
+ idFactory;
626
+ state;
627
+ constructor(initialRows, idFactory = defaultIdFactory) {
628
+ this.idFactory = idFactory;
629
+ this.state = cloneRows(initialRows);
630
+ }
631
+ rows() {
632
+ return cloneRows(this.state);
633
+ }
634
+ insertClip(input) {
635
+ const requestedOrder = input.clipPayload?.order;
636
+ const order = typeof requestedOrder === "number" ? requestedOrder : nextSequentialOrder(this.state, createEntityId(input.trackEntityId));
637
+ return this.insertPlacedClip({
638
+ trackEntityId: input.trackEntityId,
639
+ contentEntityId: input.contentEntityId,
640
+ sourceRange: input.sourceRange,
641
+ duration: input.duration,
642
+ placement: input.targetRange === void 0 ? {
643
+ kind: "sequential",
644
+ order
645
+ } : {
646
+ kind: "absolute",
647
+ targetRange: input.targetRange
648
+ },
649
+ clipPayload: input.clipPayload
650
+ });
651
+ }
652
+ insertPlacedClip(input) {
653
+ return this.transact((draft) => this.insertPlacedClipIntoDraft(draft, input));
654
+ }
655
+ updateClipMarker(input) {
656
+ this.transact((draft) => {
657
+ const { marker } = requireClipTopology(draft, input.clipEntityId);
658
+ const payload = { ...cloneJsonObject(marker.payload, "Sequence Marker payload") };
659
+ if (input.sourceRange !== void 0) payload.sourceRange = cloneJsonValue(input.sourceRange, "sourceRange");
660
+ if (input.duration !== void 0) payload.duration = cloneJsonValue(input.duration, "duration");
661
+ if (Object.hasOwn(input, "targetRange")) if (input.targetRange === void 0) {
662
+ delete payload.targetRange;
663
+ if (!hasOutgoingClipAnchor(draft, input.clipEntityId)) {
664
+ const trackId = otherEndpoint(requireOneRelation(draft, createEntityId(input.clipEntityId), "track-clip"), input.clipEntityId);
665
+ const clipPayload = { ...cloneJsonObject(requireEntityKind(draft, input.clipEntityId, "clip").payload, "Clip payload") };
666
+ clipPayload.order ??= nextSequentialOrder(draft, trackId);
667
+ replaceEntity(draft, createEntityId(input.clipEntityId), {
668
+ ...requireEntityKind(draft, input.clipEntityId, "clip"),
669
+ payload: clipPayload
670
+ });
671
+ }
672
+ } else {
673
+ payload.targetRange = cloneJsonValue(input.targetRange, "targetRange");
674
+ const clip = requireEntityKind(draft, input.clipEntityId, "clip");
675
+ const clipPayload = { ...cloneJsonObject(clip.payload, "Clip payload") };
676
+ delete clipPayload.order;
677
+ replaceEntity(draft, clip.entityId, {
678
+ ...clip,
679
+ payload: clipPayload
680
+ });
681
+ }
682
+ if (Object.hasOwn(input, "timeRemapping")) if (input.timeRemapping === void 0) delete payload.timeRemapping;
683
+ else payload.timeRemapping = cloneJsonValue(input.timeRemapping, "timeRemapping");
684
+ replaceEntity(draft, marker.entityId, {
685
+ ...marker,
686
+ payload
687
+ });
688
+ });
689
+ }
690
+ setClipPlacement(input) {
691
+ this.transact((draft) => this.applyClipPlacement(draft, input.clipEntityId, input.placement));
692
+ }
693
+ moveSequentialClips(input) {
694
+ if (input.clipEntityIds.length === 0) throw new Error("At least one Clip is required");
695
+ this.transact((draft) => {
696
+ const original = resolveEntityTimelineLayout(draft);
697
+ this.normalizeMainSequential(draft);
698
+ const before = resolveEntityTimelineLayout(draft);
699
+ const targetIds = new Set(input.clipEntityIds);
700
+ if (targetIds.size !== input.clipEntityIds.length) throw new Error("Clip ids must be unique");
701
+ const placements = input.clipEntityIds.map((id) => before.clips.get(id));
702
+ if (placements.some((placement) => placement === void 0 || placement.mode !== "sequential")) throw new Error("moveSequentialClips accepts only sequential Clips");
703
+ const trackIds = new Set(placements.map((placement) => placement.trackEntityId));
704
+ if (trackIds.size !== 1) throw new Error("Moved Clips must belong to one Track");
705
+ const trackId = [...trackIds][0];
706
+ const track = before.tracks.find((candidate) => candidate.entityId === trackId);
707
+ if (track?.role !== "video_clip") throw new Error("Only the video_clip Track supports sequential block moves");
708
+ const ordered = track.clips.filter((placement) => placement.mode === "sequential").map((placement) => placement.clipEntityId);
709
+ if (input.anchor.position !== "trackStart" && targetIds.has(input.anchor.clipEntityId)) throw new Error("Move anchor cannot be one of the moved Clips");
710
+ const moved = ordered.filter((id) => targetIds.has(id));
711
+ if (moved.length !== targetIds.size) throw new Error("Every moved Clip must exist on the target Track");
712
+ const remaining = ordered.filter((id) => !targetIds.has(id));
713
+ let insertAt = 0;
714
+ if (input.anchor.position !== "trackStart") {
715
+ const anchorIndex = remaining.indexOf(input.anchor.clipEntityId);
716
+ if (anchorIndex < 0) throw new Error("Move anchor Clip does not exist on the target Track");
717
+ insertAt = anchorIndex + (input.anchor.position === "after" ? 1 : 0);
718
+ }
719
+ [
720
+ ...remaining.slice(0, insertAt),
721
+ ...moved,
722
+ ...remaining.slice(insertAt)
723
+ ].forEach((clipId, order) => setClipOrder(draft, clipId, order));
724
+ if (input.onAnchored === "keepAbsolute") {
725
+ const affected = outgoingAnchorChildren(draft, new Set(track.clips.map((clip) => clip.clipEntityId))).filter((childId) => clipRole(draft, childId) === "speech").map((childId) => {
726
+ const placement = original.clips.get(childId);
727
+ if (placement === void 0) throw new Error(`Anchored child Clip "${childId}" is not placed`);
728
+ return {
729
+ childId,
730
+ start: placement.start
731
+ };
732
+ });
733
+ const after = resolveEntityTimelineLayout(draft);
734
+ for (const child of affected) this.reanchorAtAbsolute(draft, child.childId, child.start, after);
735
+ }
736
+ this.resolveOneVoiceoverOverlap(draft);
737
+ });
738
+ }
739
+ moveClipsToStarts(input) {
740
+ if (input.moves.length === 0) throw new Error("At least one Clip move is required");
741
+ this.transact((draft) => {
742
+ const original = resolveEntityTimelineLayout(draft);
743
+ const originalVideo = original.tracks.find((track) => track.role === "video_clip");
744
+ if (originalVideo === void 0) throw new Error("The timeline has no video_clip Track");
745
+ const preservedVoiceovers = outgoingAnchorChildren(draft, new Set(originalVideo.clips.map((clip) => clip.clipEntityId))).filter((clipId) => clipRole(draft, clipId) === "speech").map((clipId) => ({
746
+ clipId,
747
+ start: original.clips.get(clipId).start
748
+ }));
749
+ this.normalizeMainSequential(draft);
750
+ for (const move of input.moves) {
751
+ finiteNonNegative(move.newStartMs, "newStartMs");
752
+ requireClipOnRole(draft, move.clipEntityId, "video_clip");
753
+ const track = resolveEntityTimelineLayout(draft).tracks.find((candidate) => candidate.role === "video_clip");
754
+ const ordered = track.clips.map((clip) => clip.clipEntityId);
755
+ const from = ordered.indexOf(move.clipEntityId);
756
+ if (from < 0) throw new Error(`Clip "${move.clipEntityId}" is not on the video_clip Track`);
757
+ const remaining = track.clips.filter((clip) => clip.clipEntityId !== move.clipEntityId);
758
+ let cursor = 0;
759
+ let target = remaining.length;
760
+ for (const [index, clip] of remaining.entries()) {
761
+ if (move.newStartMs <= cursor + clip.duration / 2) {
762
+ target = index;
763
+ break;
764
+ }
765
+ cursor += clip.duration;
766
+ }
767
+ const next = [...ordered];
768
+ next.splice(from, 1);
769
+ next.splice(target, 0, move.clipEntityId);
770
+ next.forEach((clipId, order) => setClipOrder(draft, clipId, order));
771
+ }
772
+ const after = resolveEntityTimelineLayout(draft);
773
+ for (const voiceover of preservedVoiceovers) this.reanchorAtAbsolute(draft, voiceover.clipId, voiceover.start, after);
774
+ this.resolveOneVoiceoverOverlap(draft);
775
+ });
776
+ }
777
+ moveClip(input) {
778
+ this.transact((draft) => {
779
+ const topology = requireClipTopology(draft, input.clipEntityId);
780
+ const track = requireEntityKind(draft, input.trackEntityId, "track");
781
+ requireTrackTimeline(draft, track.entityId);
782
+ this.relinkRelation(draft, topology.trackRelation, {
783
+ endpoint0EntityId: track.entityId,
784
+ endpoint1EntityId: topology.clip.entityId
785
+ });
786
+ });
787
+ }
788
+ replaceClipContent(input) {
789
+ this.transact((draft) => {
790
+ const topology = requireClipTopology(draft, input.clipEntityId);
791
+ const content = requireSequenceContent(draft, input.contentEntityId);
792
+ const payload = {
793
+ ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload"),
794
+ sourceRange: cloneJsonValue(input.sourceRange, "sourceRange"),
795
+ duration: cloneJsonValue(input.duration, "duration")
796
+ };
797
+ delete payload.targetRange;
798
+ delete payload.timeRemapping;
799
+ if (input.targetRange !== void 0) payload.targetRange = cloneJsonValue(input.targetRange, "targetRange");
800
+ if (input.timeRemapping !== void 0) payload.timeRemapping = cloneJsonValue(input.timeRemapping, "timeRemapping");
801
+ replaceEntity(draft, topology.marker.entityId, {
802
+ ...topology.marker,
803
+ payload
804
+ });
805
+ if (!hasOutgoingClipAnchor(draft, topology.clip.entityId)) {
806
+ const clipPayload = { ...cloneJsonObject(topology.clip.payload, "Clip payload") };
807
+ if (input.targetRange === void 0) clipPayload.order ??= nextSequentialOrder(draft, otherEndpoint(topology.trackRelation, topology.clip.entityId));
808
+ else delete clipPayload.order;
809
+ replaceEntity(draft, topology.clip.entityId, {
810
+ ...topology.clip,
811
+ payload: clipPayload
812
+ });
813
+ }
814
+ this.relinkRelation(draft, topology.markerContentRelation, {
815
+ endpoint0EntityId: topology.marker.entityId,
816
+ endpoint1EntityId: content.entityId
817
+ });
818
+ });
819
+ }
820
+ insertMediaClip(input) {
821
+ return this.transact((draft) => {
822
+ if (input.placement.kind === "sequential") this.normalizeMainSequential(draft);
823
+ const imported = importMediaAsset(draft, input.media, this.idFactory);
824
+ replaceRows(draft, imported.rows);
825
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "video_clip");
826
+ const sourceRange = requirePositiveRange(input.sourceRange, "sourceRange");
827
+ const clipId = this.insertPlacedClipIntoDraft(draft, {
828
+ trackEntityId: track.entityId,
829
+ contentEntityId: imported.contentEntityId,
830
+ sourceRange,
831
+ duration: {
832
+ mode: "fixed",
833
+ value: sourceRange.end - sourceRange.start
834
+ },
835
+ placement: input.placement,
836
+ ...input.clipEntityId === void 0 ? {} : { clipEntityId: input.clipEntityId },
837
+ ...input.volume === void 0 ? {} : { clipPayload: { volume: requireVolume(input.volume) } }
838
+ });
839
+ if (input.placement.kind === "sequential") this.resolveOneVoiceoverOverlap(draft);
840
+ return clipId;
841
+ });
842
+ }
843
+ insertMediaClips(input) {
844
+ if (input.clips.length === 0) throw new Error("At least one media Clip is required");
845
+ return this.transact((draft) => {
846
+ this.normalizeMainSequential(draft);
847
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "video_clip");
848
+ const ordered = resolveEntityTimelineLayout(draft).tracks.find((candidate) => candidate.entityId === track.entityId)?.clips ?? [];
849
+ let insertAt = ordered.length;
850
+ const insertion = input.insertion;
851
+ if (insertion.kind === "before" || insertion.kind === "after") {
852
+ const anchorIndex = ordered.findIndex((clip) => clip.clipEntityId === insertion.clipEntityId);
853
+ if (anchorIndex >= 0) insertAt = anchorIndex + (insertion.kind === "after" ? 1 : 0);
854
+ } else {
855
+ const startMs = finiteNonNegative(insertion.startMs, "firstStart.startMs");
856
+ let cursor = 0;
857
+ for (const [index, clip] of ordered.entries()) {
858
+ if (startMs <= cursor + clip.duration / 2) {
859
+ insertAt = index;
860
+ break;
861
+ }
862
+ cursor += clip.duration;
863
+ }
864
+ }
865
+ const created = [];
866
+ for (const [offset, clip] of input.clips.entries()) {
867
+ const imported = importMediaAsset(draft, clip.media, this.idFactory);
868
+ replaceRows(draft, imported.rows);
869
+ const sourceRange = requirePositiveRange(clip.sourceRange, "sourceRange");
870
+ created.push(this.insertPlacedClipIntoDraft(draft, {
871
+ trackEntityId: track.entityId,
872
+ contentEntityId: imported.contentEntityId,
873
+ sourceRange,
874
+ duration: {
875
+ mode: "fixed",
876
+ value: sourceRange.end - sourceRange.start
877
+ },
878
+ placement: {
879
+ kind: "sequential",
880
+ order: ordered.length + offset
881
+ },
882
+ ...clip.clipEntityId === void 0 ? {} : { clipEntityId: clip.clipEntityId },
883
+ ...clip.volume === void 0 ? {} : { clipPayload: { volume: requireVolume(clip.volume) } }
884
+ }));
885
+ }
886
+ const desired = ordered.map((clip) => clip.clipEntityId);
887
+ desired.splice(insertAt, 0, ...created);
888
+ desired.forEach((clipId, order) => setClipOrder(draft, clipId, order));
889
+ this.resolveOneVoiceoverOverlap(draft);
890
+ return created;
891
+ });
892
+ }
893
+ replaceMediaClip(input) {
894
+ this.transact((draft) => {
895
+ this.normalizeMainSequential(draft);
896
+ const topology = requireClipOnRole(draft, input.clipEntityId, "video_clip");
897
+ const imported = importMediaAsset(draft, input.media, this.idFactory);
898
+ replaceRows(draft, imported.rows);
899
+ const sourceRange = requirePositiveRange(input.sourceRange, "sourceRange");
900
+ const markerPayloadValue = {
901
+ ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload"),
902
+ sourceRange,
903
+ duration: {
904
+ mode: "fixed",
905
+ value: sourceRange.end - sourceRange.start
906
+ }
907
+ };
908
+ delete markerPayloadValue.timeRemapping;
909
+ resizeAbsoluteTarget(markerPayloadValue, sourceRange.end - sourceRange.start);
910
+ replaceEntity(draft, topology.marker.entityId, {
911
+ ...topology.marker,
912
+ payload: markerPayloadValue
913
+ });
914
+ this.relinkRelation(draft, topology.markerContentRelation, {
915
+ endpoint0EntityId: topology.marker.entityId,
916
+ endpoint1EntityId: createEntityId(imported.contentEntityId)
917
+ });
918
+ this.resolveOneVoiceoverOverlap(draft);
919
+ });
920
+ }
921
+ setClipVolume(input) {
922
+ this.transact((draft) => {
923
+ const topology = requireClipTopology(draft, input.clipEntityId);
924
+ requireSupportedRole(draft, topology);
925
+ replaceEntity(draft, topology.clip.entityId, {
926
+ ...topology.clip,
927
+ payload: {
928
+ ...topology.clip.payload,
929
+ volume: requireVolume(input.volume)
930
+ }
931
+ });
932
+ });
933
+ }
934
+ setClipSpeed(input) {
935
+ this.transact((draft) => {
936
+ const initialTopology = requireClipOnRole(draft, input.clipEntityId, "video_clip");
937
+ const content = requireSequenceContent(draft, otherEndpoint(initialTopology.markerContentRelation, initialTopology.marker.entityId));
938
+ if (content.entityKind !== "video" && content.entityKind !== "image") throw new Error("Clip speed is supported only for Video or Image content");
939
+ const initialPayload = cloneJsonObject(initialTopology.marker.payload, "Sequence Marker payload");
940
+ const priorSource = requirePositiveRange(initialPayload.sourceRange, "sourceRange");
941
+ if (input.timeRemapping === null && initialPayload.timeRemapping === void 0) return;
942
+ this.normalizeMainSequential(draft);
943
+ const topology = requireClipTopology(draft, input.clipEntityId);
944
+ const payload = { ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload") };
945
+ let sourceRange = priorSource;
946
+ if (content.entityKind === "image" && initialPayload.timeRemapping === void 0 && input.timeRemapping !== null) sourceRange = {
947
+ start: 0,
948
+ end: markerDuration(initialPayload, priorSource)
949
+ };
950
+ if (input.timeRemapping === null) {
951
+ delete payload.timeRemapping;
952
+ payload.sourceRange = sourceRange;
953
+ payload.duration = {
954
+ mode: "fixed",
955
+ value: sourceRange.end - sourceRange.start
956
+ };
957
+ } else {
958
+ const rate = finitePositive(input.timeRemapping.rate, "linear speed rate");
959
+ const duration = Math.round((sourceRange.end - sourceRange.start) / rate);
960
+ if (duration <= 0 || !Number.isSafeInteger(duration)) throw new Error("Linear speed produces an invalid duration");
961
+ payload.sourceRange = sourceRange;
962
+ payload.duration = {
963
+ mode: "fixed",
964
+ value: duration
965
+ };
966
+ payload.timeRemapping = {
967
+ kind: "linear",
968
+ rate,
969
+ ...input.timeRemapping.mode === void 0 ? {} : { mode: input.timeRemapping.mode }
970
+ };
971
+ }
972
+ resizeAbsoluteTarget(payload, markerDuration(payload, sourceRange));
973
+ replaceEntity(draft, topology.marker.entityId, {
974
+ ...topology.marker,
975
+ payload
976
+ });
977
+ this.resolveOneVoiceoverOverlap(draft);
978
+ });
979
+ }
980
+ trimClip(input) {
981
+ this.transact((draft) => {
982
+ this.normalizeMainSequential(draft);
983
+ const topology = requireClipOnRole(draft, input.clipEntityId, "video_clip");
984
+ const content = requireSequenceContent(draft, otherEndpoint(topology.markerContentRelation, topology.marker.entityId));
985
+ if (content.entityKind !== "video" && content.entityKind !== "image") throw new Error("Clip trimming is supported only for Video or Image content");
986
+ const sourceRange = requirePositiveRange(input.sourceRange, "sourceRange");
987
+ const payload = {
988
+ ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload"),
989
+ sourceRange
990
+ };
991
+ const rate = linearRate(payload.timeRemapping);
992
+ const duration = Math.round((sourceRange.end - sourceRange.start) / rate);
993
+ if (duration <= 0 || !Number.isSafeInteger(duration)) throw new Error("Trim produces an invalid duration");
994
+ payload.duration = {
995
+ mode: "fixed",
996
+ value: duration
997
+ };
998
+ resizeAbsoluteTarget(payload, duration);
999
+ replaceEntity(draft, topology.marker.entityId, {
1000
+ ...topology.marker,
1001
+ payload
1002
+ });
1003
+ this.resolveOneVoiceoverOverlap(draft);
1004
+ });
1005
+ }
1006
+ replaceSequentialClips(input) {
1007
+ if (input.oldClipEntityIds.length === 0 || input.newClips.length === 0) throw new Error("Replacement requires at least one old and one new Clip");
1008
+ return this.transact((draft) => {
1009
+ this.normalizeMainSequential(draft);
1010
+ const before = resolveEntityTimelineLayout(draft);
1011
+ const oldIds = new Set(input.oldClipEntityIds);
1012
+ if (oldIds.size !== input.oldClipEntityIds.length) throw new Error("Old Clip ids must be unique");
1013
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "video_clip");
1014
+ const ordered = before.tracks.find((candidate) => candidate.entityId === track.entityId)?.clips.filter((clip) => clip.mode === "sequential").map((clip) => clip.clipEntityId);
1015
+ if (ordered === void 0) throw new Error("The video_clip Track is not present in the current layout");
1016
+ const indexes = input.oldClipEntityIds.map((id) => ordered.indexOf(id));
1017
+ if (indexes.some((index) => index < 0)) throw new Error("Every replaced Clip must be sequential on video_clip");
1018
+ const sortedIndexes = [...indexes].sort((left, right) => left - right);
1019
+ if (sortedIndexes.some((index, offset) => index !== sortedIndexes[0] + offset)) throw new Error("Replaced Clips must form one contiguous timeline run");
1020
+ if (input.oldClipEntityIds.some((id, index) => id !== ordered[sortedIndexes[0] + index])) throw new Error("Replaced Clip ids must be listed in timeline order");
1021
+ const insertOrder = sortedIndexes[0];
1022
+ const temporaryOrder = ordered.length;
1023
+ const created = [];
1024
+ for (const [offset, replacement] of input.newClips.entries()) {
1025
+ if (replacement.clipEntityId !== void 0 && oldIds.has(replacement.clipEntityId)) throw new Error("A replacement Clip id cannot reuse an Entity being removed");
1026
+ const imported = importMediaAsset(draft, replacement.media, this.idFactory);
1027
+ replaceRows(draft, imported.rows);
1028
+ const sourceRange = requirePositiveRange(replacement.sourceRange, "sourceRange");
1029
+ created.push(this.insertPlacedClipIntoDraft(draft, {
1030
+ trackEntityId: track.entityId,
1031
+ contentEntityId: imported.contentEntityId,
1032
+ sourceRange,
1033
+ duration: {
1034
+ mode: "fixed",
1035
+ value: sourceRange.end - sourceRange.start
1036
+ },
1037
+ placement: {
1038
+ kind: "sequential",
1039
+ order: temporaryOrder + offset
1040
+ },
1041
+ ...replacement.clipEntityId === void 0 ? {} : { clipEntityId: replacement.clipEntityId },
1042
+ ...replacement.volume === void 0 ? {} : { clipPayload: { volume: requireVolume(replacement.volume) } }
1043
+ }));
1044
+ }
1045
+ for (const [index, oldId] of input.oldClipEntityIds.entries()) {
1046
+ const children = directAnchorChildren(draft, oldId);
1047
+ if (input.onAnchored === "remap" && created[index] !== void 0) for (const childId of children) this.replaceAnchorHost(draft, childId, created[index]);
1048
+ else {
1049
+ const scheduled = /* @__PURE__ */ new Set();
1050
+ for (const childId of children) {
1051
+ scheduled.add(childId);
1052
+ this.removeAnchoredDescendants(draft, childId, scheduled);
1053
+ this.removeClipGraph(draft, childId);
1054
+ }
1055
+ }
1056
+ }
1057
+ for (const oldId of input.oldClipEntityIds) this.removeClipGraph(draft, oldId);
1058
+ [
1059
+ ...ordered.slice(0, insertOrder),
1060
+ ...created,
1061
+ ...ordered.slice(insertOrder + input.oldClipEntityIds.length)
1062
+ ].forEach((clipId, order) => setClipOrder(draft, clipId, order));
1063
+ this.resolveOneVoiceoverOverlap(draft);
1064
+ return created;
1065
+ });
1066
+ }
1067
+ deleteClip(input) {
1068
+ this.transact((draft) => {
1069
+ const topology = requireClipTopology(draft, input.clipEntityId);
1070
+ assertOnlyStructuralIncidents(draft, topology.clip.entityId, new Set(["track-clip", "clip-marker"]));
1071
+ assertOnlyStructuralIncidents(draft, topology.marker.entityId, new Set(["clip-marker", "marker-content"]));
1072
+ const markerIsExclusive = incidentRelations(draft, topology.marker.entityId).filter((relation) => relation.relationKind === "clip-marker").length === 1;
1073
+ const removedRelationIds = new Set([topology.trackRelation.relationId, topology.clipMarkerRelation.relationId]);
1074
+ if (markerIsExclusive) for (const relation of incidentRelations(draft, topology.marker.entityId)) removedRelationIds.add(relation.relationId);
1075
+ draft.relations = draft.relations.filter((relation) => !removedRelationIds.has(relation.relationId));
1076
+ draft.entities = draft.entities.filter((entity) => entity.entityId !== topology.clip.entityId && (!markerIsExclusive || entity.entityId !== topology.marker.entityId));
1077
+ });
1078
+ }
1079
+ deleteClipTree(input) {
1080
+ if (input.clipEntityIds.length === 0) throw new Error("At least one Clip is required");
1081
+ this.transact((draft) => {
1082
+ const targets = new Set(input.clipEntityIds);
1083
+ if (targets.size !== input.clipEntityIds.length) throw new Error("Clip ids must be unique");
1084
+ for (const target of targets) requireEntityKind(draft, target, "clip");
1085
+ const includesVisual = [...targets].some((target) => clipRole(draft, target) === "video_clip");
1086
+ const original = resolveEntityTimelineLayout(draft);
1087
+ if (includesVisual) this.normalizeMainSequential(draft);
1088
+ if (input.onAnchored === "detach") for (const childId of outgoingAnchorChildren(draft, targets)) {
1089
+ if (targets.has(childId)) continue;
1090
+ const placement = original.clips.get(childId);
1091
+ if (placement === void 0) throw new Error(`Anchored child Clip "${childId}" is not placed`);
1092
+ this.applyClipPlacement(draft, childId, {
1093
+ kind: "absolute",
1094
+ targetRange: {
1095
+ start: placement.start,
1096
+ end: placement.start + placement.duration
1097
+ }
1098
+ });
1099
+ }
1100
+ else for (const target of targets) this.removeAnchoredDescendants(draft, target, targets);
1101
+ for (const target of targets) this.removeClipGraph(draft, target);
1102
+ normalizeSequentialOrders(draft);
1103
+ if (includesVisual) this.resolveOneVoiceoverOverlap(draft);
1104
+ });
1105
+ }
1106
+ updateClip(input) {
1107
+ this.transact((draft) => {
1108
+ const clip = requireEntityKind(draft, input.clipEntityId, "clip");
1109
+ const priorOrder = clip.payload.order;
1110
+ replaceEntity(draft, clip.entityId, {
1111
+ ...clip,
1112
+ payload: {
1113
+ ...cloneJsonObject(input.payload, "Clip payload"),
1114
+ ...priorOrder === void 0 || Object.hasOwn(input.payload, "order") ? {} : { order: priorOrder }
1115
+ }
1116
+ });
1117
+ });
1118
+ }
1119
+ upsertVoiceoverTake(input) {
1120
+ return this.transact((draft) => {
1121
+ this.normalizeMainSequential(draft);
1122
+ const placement = input.placement ?? {
1123
+ kind: "anchored",
1124
+ hostClipEntityId: input.hostClipEntityId,
1125
+ anchorOffset: input.anchorOffset
1126
+ };
1127
+ if (input.placement !== void 0 && (input.hostClipEntityId !== void 0 || input.anchorOffset !== void 0)) throw new Error("Specify Voice placement or hostClipEntityId/anchorOffset, not both");
1128
+ requireVolume(input.volume);
1129
+ const imported = importMediaAsset(draft, input.media, this.idFactory);
1130
+ replaceRows(draft, imported.rows);
1131
+ const voice = requireEntityKind(draft, imported.contentEntityId, "voice");
1132
+ const script = this.ensureAudioScript(draft, voice.entityId, input.scriptText);
1133
+ const speechTrack = this.ensureRoleTrack(draft, input.timelineEntityId, "speech");
1134
+ const existing = draft.entities.find((row) => row.entityId === input.voiceoverClipEntityId);
1135
+ let voiceoverClipEntityId;
1136
+ if (existing === void 0) voiceoverClipEntityId = this.insertPlacedClipIntoDraft(draft, {
1137
+ clipEntityId: input.voiceoverClipEntityId,
1138
+ trackEntityId: speechTrack.entityId,
1139
+ contentEntityId: voice.entityId,
1140
+ sourceRange: {
1141
+ start: 0,
1142
+ end: input.media.durationMs
1143
+ },
1144
+ duration: {
1145
+ mode: "fixed",
1146
+ value: input.media.durationMs
1147
+ },
1148
+ placement,
1149
+ clipPayload: { volume: input.volume }
1150
+ });
1151
+ else {
1152
+ const topology = requireClipOnRole(draft, input.voiceoverClipEntityId, "speech");
1153
+ voiceoverClipEntityId = topology.clip.entityId;
1154
+ replaceEntity(draft, topology.clip.entityId, {
1155
+ ...topology.clip,
1156
+ payload: {
1157
+ ...topology.clip.payload,
1158
+ volume: input.volume
1159
+ }
1160
+ });
1161
+ this.relinkRelation(draft, topology.markerContentRelation, {
1162
+ endpoint0EntityId: topology.marker.entityId,
1163
+ endpoint1EntityId: voice.entityId
1164
+ });
1165
+ this.applyClipPlacement(draft, topology.clip.entityId, placement);
1166
+ const placed = requireClipTopology(draft, topology.clip.entityId);
1167
+ replaceEntity(draft, placed.marker.entityId, {
1168
+ ...placed.marker,
1169
+ payload: {
1170
+ ...placed.marker.payload,
1171
+ sourceRange: {
1172
+ start: 0,
1173
+ end: input.media.durationMs
1174
+ },
1175
+ duration: {
1176
+ mode: "fixed",
1177
+ value: input.media.durationMs
1178
+ }
1179
+ }
1180
+ });
1181
+ }
1182
+ this.reconcileVoiceoverCaptions(draft, voiceoverClipEntityId, voice.entityId, script.entityId, input.captions);
1183
+ this.resolveOneVoiceoverOverlap(draft);
1184
+ return {
1185
+ voiceoverClipEntityId,
1186
+ voiceEntityId: voice.entityId,
1187
+ audioScriptEntityId: script.entityId,
1188
+ captionClipEntityIds: input.captions.map((caption) => caption.captionClipEntityId)
1189
+ };
1190
+ });
1191
+ }
1192
+ moveVoiceover(input) {
1193
+ this.transact((draft) => {
1194
+ requireClipOnRole(draft, input.voiceoverClipEntityId, "speech");
1195
+ this.normalizeMainSequential(draft);
1196
+ const layout = resolveEntityTimelineLayout(draft);
1197
+ this.reanchorAtAbsolute(draft, input.voiceoverClipEntityId, finiteNonNegative(input.newStartMs, "newStartMs"), layout);
1198
+ this.resolveOneVoiceoverOverlap(draft);
1199
+ });
1200
+ }
1201
+ deleteVoiceover(input) {
1202
+ this.transact((draft) => {
1203
+ this.normalizeMainSequential(draft);
1204
+ const targets = new Set(input.voiceoverClipEntityIds);
1205
+ if (targets.size !== input.voiceoverClipEntityIds.length) throw new Error("Voiceover Clip ids must be unique");
1206
+ for (const clipId of targets) {
1207
+ requireClipOnRole(draft, clipId, "speech");
1208
+ this.removeAnchoredDescendants(draft, clipId, targets);
1209
+ }
1210
+ for (const clipId of targets) this.removeClipGraph(draft, clipId);
1211
+ this.resolveOneVoiceoverOverlap(draft);
1212
+ });
1213
+ }
1214
+ setBgm(input) {
1215
+ return this.transact((draft) => {
1216
+ const imported = importMediaAsset(draft, input.media, this.idFactory);
1217
+ replaceRows(draft, imported.rows);
1218
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "bgm");
1219
+ const existing = clipsOnTrack(draft, track.entityId);
1220
+ for (const clip of existing) this.removeClipGraph(draft, clip.entityId);
1221
+ const clipId = this.insertPlacedClipIntoDraft(draft, {
1222
+ clipEntityId: input.bgmClipEntityId,
1223
+ trackEntityId: track.entityId,
1224
+ contentEntityId: imported.contentEntityId,
1225
+ sourceRange: {
1226
+ start: 0,
1227
+ end: input.media.durationMs
1228
+ },
1229
+ duration: { mode: "from-source" },
1230
+ placement: {
1231
+ kind: "sequential",
1232
+ order: 0
1233
+ },
1234
+ clipPayload: { volume: requireVolume(input.volume) }
1235
+ });
1236
+ const topology = requireClipTopology(draft, clipId);
1237
+ replaceEntity(draft, topology.marker.entityId, {
1238
+ ...topology.marker,
1239
+ payload: {
1240
+ ...topology.marker.payload,
1241
+ durationPolicy: "timeline"
1242
+ }
1243
+ });
1244
+ return clipId;
1245
+ });
1246
+ }
1247
+ deleteBgm(input) {
1248
+ this.transact((draft) => {
1249
+ const track = findRoleTrack(draft, input.timelineEntityId, "bgm");
1250
+ if (track === void 0) return;
1251
+ for (const clip of clipsOnTrack(draft, track.entityId)) this.removeClipGraph(draft, clip.entityId);
1252
+ });
1253
+ }
1254
+ setCaptionVisibility(input) {
1255
+ this.transact((draft) => {
1256
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "caption");
1257
+ replaceEntity(draft, track.entityId, {
1258
+ ...track,
1259
+ payload: {
1260
+ ...track.payload,
1261
+ hidden: input.hidden
1262
+ }
1263
+ });
1264
+ });
1265
+ }
1266
+ patchCaptionStyle(input) {
1267
+ this.transact((draft) => {
1268
+ const track = findRoleTrack(draft, input.timelineEntityId, "caption");
1269
+ if (track === void 0) return;
1270
+ const patch = cloneJsonObject(input.style, "Caption style");
1271
+ for (const clip of clipsOnTrack(draft, track.entityId)) {
1272
+ const topology = requireClipTopology(draft, clip.entityId);
1273
+ const caption = requireEntityKind(draft, otherEndpoint(topology.markerContentRelation, topology.marker.entityId), "caption");
1274
+ const prior = caption.payload.style;
1275
+ const style = isJsonObject(prior) ? prior : {};
1276
+ replaceEntity(draft, caption.entityId, {
1277
+ ...caption,
1278
+ payload: {
1279
+ ...caption.payload,
1280
+ style: {
1281
+ ...style,
1282
+ ...patch
1283
+ }
1284
+ }
1285
+ });
1286
+ }
1287
+ });
1288
+ }
1289
+ /**
1290
+ * Place an independent Caption: its own content entity, inline text Asset,
1291
+ * and Clip with a display Marker. No Voice, provenance, or alignment is
1292
+ * required — the placement describes only this use. Moving or stretching
1293
+ * the returned Clip later changes the Clip/Marker, never the Caption entity.
1294
+ */
1295
+ insertCaptionClip(input) {
1296
+ return this.transact((draft) => {
1297
+ const durationMs = finitePositive(input.durationMs, "Caption durationMs");
1298
+ const track = this.ensureRoleTrack(draft, input.timelineEntityId, "caption");
1299
+ const content = {
1300
+ entityId: this.mintEntityId(draft),
1301
+ entityKind: "caption",
1302
+ payload: {
1303
+ extent: {
1304
+ kind: "bounded",
1305
+ start: 0,
1306
+ end: durationMs
1307
+ },
1308
+ sampling: "native",
1309
+ coordinateSpace: "milliseconds",
1310
+ text: input.text,
1311
+ ...input.style === void 0 ? {} : { style: cloneJsonObject(input.style, "Caption style") }
1312
+ }
1313
+ };
1314
+ const asset = {
1315
+ entityId: this.mintEntityId(draft),
1316
+ entityKind: "asset",
1317
+ payload: { inline: {
1318
+ mediaType: "text/plain",
1319
+ text: input.text
1320
+ } }
1321
+ };
1322
+ draft.entities.push(content, asset);
1323
+ draft.relations.push(this.createRelation(draft, "physical-asset", content.entityId, asset.entityId));
1324
+ return this.insertPlacedClipIntoDraft(draft, {
1325
+ trackEntityId: track.entityId,
1326
+ contentEntityId: content.entityId,
1327
+ sourceRange: {
1328
+ start: 0,
1329
+ end: durationMs
1330
+ },
1331
+ duration: {
1332
+ mode: "fixed",
1333
+ value: durationMs
1334
+ },
1335
+ placement: input.placement,
1336
+ ...input.captionClipEntityId === void 0 ? {} : { clipEntityId: input.captionClipEntityId }
1337
+ });
1338
+ });
1339
+ }
1340
+ insertPlacedClipIntoDraft(draft, input) {
1341
+ const track = requireEntityKind(draft, input.trackEntityId, "track");
1342
+ requireTrackTimeline(draft, track.entityId);
1343
+ const content = requireSequenceContent(draft, input.contentEntityId);
1344
+ const clipId = input.clipEntityId === void 0 ? this.mintEntityId(draft) : requireAvailableEntityId(draft, input.clipEntityId);
1345
+ const markerId = this.mintEntityId(draft);
1346
+ const clipPayload = { ...cloneJsonObject(input.clipPayload ?? {}, "Clip payload") };
1347
+ delete clipPayload.order;
1348
+ const markerPlacement = applyPlacementPayload(clipPayload, input.placement);
1349
+ const clip = {
1350
+ entityId: clipId,
1351
+ entityKind: "clip",
1352
+ payload: clipPayload
1353
+ };
1354
+ const marker = {
1355
+ entityId: markerId,
1356
+ entityKind: "sequence-marker",
1357
+ payload: markerPayload({
1358
+ sourceRange: input.sourceRange,
1359
+ duration: input.duration,
1360
+ ...markerPlacement
1361
+ })
1362
+ };
1363
+ draft.entities.push(clip, marker);
1364
+ 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));
1365
+ if (input.placement.kind === "anchored") {
1366
+ const host = requireEntityKind(draft, input.placement.hostClipEntityId, "clip");
1367
+ if (host.entityId === clipId) throw new Error("A Clip cannot anchor to itself");
1368
+ draft.relations.push(this.createRelation(draft, "clip-anchor", clipId, host.entityId));
1369
+ }
1370
+ return clipId;
1371
+ }
1372
+ ensureRoleTrack(draft, timelineEntityId, role) {
1373
+ const existing = findRoleTrack(draft, timelineEntityId, role);
1374
+ if (existing !== void 0) {
1375
+ if (existing.payload.order === void 0) {
1376
+ const replacement = {
1377
+ ...existing,
1378
+ payload: {
1379
+ ...existing.payload,
1380
+ order: roleOrder[role]
1381
+ }
1382
+ };
1383
+ replaceEntity(draft, existing.entityId, replacement);
1384
+ return replacement;
1385
+ }
1386
+ return existing;
1387
+ }
1388
+ const timeline = requireEntityKind(draft, timelineEntityId, "timeline");
1389
+ const track = {
1390
+ entityId: this.mintEntityId(draft),
1391
+ entityKind: "track",
1392
+ payload: {
1393
+ role,
1394
+ order: roleOrder[role]
1395
+ }
1396
+ };
1397
+ draft.entities.push(track);
1398
+ draft.relations.push(this.createRelation(draft, "timeline-track", timeline.entityId, track.entityId));
1399
+ return track;
1400
+ }
1401
+ ensureAudioScript(draft, voiceEntityId, text) {
1402
+ const renders = draft.relations.filter((relation) => relation.relationKind === "audio-script-render" && relation.endpoint0EntityId === voiceEntityId);
1403
+ if (renders.length > 1) throw new Error(`Voice "${voiceEntityId}" has multiple AudioScript relations`);
1404
+ if (renders[0] !== void 0) {
1405
+ const script = requireEntityKind(draft, renders[0].endpoint1EntityId, "audio-script");
1406
+ const replacement = {
1407
+ ...script,
1408
+ payload: { segments: [{
1409
+ segmentId: "segment-0",
1410
+ text
1411
+ }] }
1412
+ };
1413
+ replaceEntity(draft, script.entityId, replacement);
1414
+ return replacement;
1415
+ }
1416
+ const script = {
1417
+ entityId: this.mintEntityId(draft),
1418
+ entityKind: "audio-script",
1419
+ payload: { segments: [{
1420
+ segmentId: "segment-0",
1421
+ text
1422
+ }] }
1423
+ };
1424
+ draft.entities.push(script);
1425
+ draft.relations.push(this.createRelation(draft, "audio-script-render", voiceEntityId, script.entityId));
1426
+ return script;
1427
+ }
1428
+ reconcileVoiceoverCaptions(draft, voiceoverClipEntityId, voiceEntityId, scriptEntityId, captions) {
1429
+ const requested = new Set(captions.map((caption) => caption.captionClipEntityId));
1430
+ if (requested.size !== captions.length) throw new Error("Caption Clip ids must be unique within a voiceover take");
1431
+ const existing = directAnchorChildren(draft, voiceoverClipEntityId).filter((clipId) => clipRole(draft, clipId) === "caption");
1432
+ for (const clipId of existing) if (!requested.has(clipId)) this.removeCaptionClipGraph(draft, clipId);
1433
+ const captionTrack = captions.length === 0 ? void 0 : this.ensureRoleTrackForClip(draft, voiceoverClipEntityId, "caption");
1434
+ for (const caption of captions) {
1435
+ const startMs = finiteNonNegative(caption.startMs, "Caption startMs");
1436
+ const durationMs = finitePositive(caption.durationMs, "Caption durationMs");
1437
+ if (draft.entities.find((entity) => entity.entityId === caption.captionClipEntityId) === void 0) {
1438
+ const content = {
1439
+ entityId: this.mintEntityId(draft),
1440
+ entityKind: "caption",
1441
+ payload: {
1442
+ extent: {
1443
+ kind: "bounded",
1444
+ start: 0,
1445
+ end: durationMs
1446
+ },
1447
+ sampling: "native",
1448
+ coordinateSpace: "milliseconds",
1449
+ text: caption.text,
1450
+ ...caption.style === void 0 ? {} : { style: cloneJsonObject(caption.style, "Caption style") }
1451
+ }
1452
+ };
1453
+ const asset = {
1454
+ entityId: this.mintEntityId(draft),
1455
+ entityKind: "asset",
1456
+ payload: { inline: {
1457
+ mediaType: "text/plain",
1458
+ text: caption.text
1459
+ } }
1460
+ };
1461
+ draft.entities.push(content, asset);
1462
+ draft.relations.push(this.createRelation(draft, "physical-asset", content.entityId, asset.entityId), this.createRelation(draft, "caption-alignment", content.entityId, voiceEntityId, { alignment: {
1463
+ start: startMs,
1464
+ end: startMs + durationMs
1465
+ } }), this.createRelation(draft, "caption-provenance", content.entityId, scriptEntityId, { segmentAlignment: [] }));
1466
+ this.insertPlacedClipIntoDraft(draft, {
1467
+ clipEntityId: caption.captionClipEntityId,
1468
+ trackEntityId: captionTrack.entityId,
1469
+ contentEntityId: content.entityId,
1470
+ sourceRange: {
1471
+ start: 0,
1472
+ end: durationMs
1473
+ },
1474
+ duration: {
1475
+ mode: "fixed",
1476
+ value: durationMs
1477
+ },
1478
+ placement: {
1479
+ kind: "anchored",
1480
+ hostClipEntityId: voiceoverClipEntityId,
1481
+ anchorOffset: startMs
1482
+ }
1483
+ });
1484
+ continue;
1485
+ }
1486
+ const topology = requireClipOnRole(draft, caption.captionClipEntityId, "caption");
1487
+ const content = requireEntityKind(draft, otherEndpoint(topology.markerContentRelation, topology.marker.entityId), "caption");
1488
+ const priorStyle = isJsonObject(content.payload.style) ? content.payload.style : {};
1489
+ const style = caption.style === void 0 ? priorStyle : {
1490
+ ...priorStyle,
1491
+ ...cloneJsonObject(caption.style, "Caption style")
1492
+ };
1493
+ replaceEntity(draft, content.entityId, {
1494
+ ...content,
1495
+ payload: {
1496
+ ...content.payload,
1497
+ extent: {
1498
+ kind: "bounded",
1499
+ start: 0,
1500
+ end: durationMs
1501
+ },
1502
+ text: caption.text,
1503
+ ...Object.keys(style).length === 0 ? {} : { style }
1504
+ }
1505
+ });
1506
+ const asset = requireEntityKind(draft, otherEndpoint(requireOneRelation(draft, content.entityId, "physical-asset"), content.entityId), "asset");
1507
+ if (asset.payload.inline === void 0) throw new Error(`Caption "${caption.captionClipEntityId}" is not inline`);
1508
+ replaceEntity(draft, asset.entityId, {
1509
+ ...asset,
1510
+ payload: {
1511
+ ...asset.payload,
1512
+ inline: {
1513
+ mediaType: "text/plain",
1514
+ text: caption.text
1515
+ }
1516
+ }
1517
+ });
1518
+ this.applyClipPlacement(draft, topology.clip.entityId, {
1519
+ kind: "anchored",
1520
+ hostClipEntityId: voiceoverClipEntityId,
1521
+ anchorOffset: startMs
1522
+ });
1523
+ const placed = requireClipTopology(draft, topology.clip.entityId);
1524
+ replaceEntity(draft, placed.marker.entityId, {
1525
+ ...placed.marker,
1526
+ payload: {
1527
+ ...placed.marker.payload,
1528
+ sourceRange: {
1529
+ start: 0,
1530
+ end: durationMs
1531
+ },
1532
+ duration: {
1533
+ mode: "fixed",
1534
+ value: durationMs
1535
+ }
1536
+ }
1537
+ });
1538
+ this.replaceCaptionSemanticRelations(draft, content.entityId, voiceEntityId, scriptEntityId, startMs, durationMs);
1539
+ }
1540
+ }
1541
+ ensureRoleTrackForClip(draft, clipEntityId, role) {
1542
+ const topology = requireClipTopology(draft, clipEntityId);
1543
+ const track = requireEntityKind(draft, otherEndpoint(topology.trackRelation, topology.clip.entityId), "track");
1544
+ const timeline = requireEntityKind(draft, otherEndpoint(requireOneRelation(draft, track.entityId, "timeline-track"), track.entityId), "timeline");
1545
+ return this.ensureRoleTrack(draft, timeline.entityId, role);
1546
+ }
1547
+ replaceCaptionSemanticRelations(draft, captionEntityId, voiceEntityId, scriptEntityId, startMs, durationMs) {
1548
+ const removed = new Set(incidentRelations(draft, captionEntityId).filter((relation) => relation.relationKind === "caption-alignment" || relation.relationKind === "caption-provenance").map((relation) => relation.relationId));
1549
+ draft.relations = draft.relations.filter((relation) => !removed.has(relation.relationId));
1550
+ draft.relations.push(this.createRelation(draft, "caption-alignment", captionEntityId, voiceEntityId, { alignment: {
1551
+ start: startMs,
1552
+ end: startMs + durationMs
1553
+ } }), this.createRelation(draft, "caption-provenance", captionEntityId, scriptEntityId, { segmentAlignment: [] }));
1554
+ }
1555
+ removeCaptionClipGraph(draft, clipEntityId) {
1556
+ const topology = requireClipOnRole(draft, clipEntityId, "caption");
1557
+ const caption = requireEntityKind(draft, otherEndpoint(topology.markerContentRelation, topology.marker.entityId), "caption");
1558
+ const asset = requireEntityKind(draft, otherEndpoint(requireOneRelation(draft, caption.entityId, "physical-asset"), caption.entityId), "asset");
1559
+ const contentRelations = incidentRelations(draft, caption.entityId);
1560
+ const allowed = new Set([
1561
+ "physical-asset",
1562
+ "caption-alignment",
1563
+ "caption-provenance",
1564
+ "marker-content"
1565
+ ]);
1566
+ const unsupported = contentRelations.filter((relation) => !allowed.has(relation.relationKind));
1567
+ if (unsupported.length > 0) throw new Error(`Cannot delete Caption with unsupported Relation ${unsupported[0].relationId}`);
1568
+ this.removeClipGraph(draft, clipEntityId);
1569
+ if (incidentRelations(draft, caption.entityId).some((relation) => relation.relationKind === "marker-content")) return;
1570
+ const removed = new Set(incidentRelations(draft, caption.entityId).map((relation) => relation.relationId));
1571
+ const assetIncidents = incidentRelations(draft, asset.entityId);
1572
+ const deleteAsset = asset.payload.inline !== void 0 && assetIncidents.every((relation) => removed.has(relation.relationId));
1573
+ draft.relations = draft.relations.filter((relation) => !removed.has(relation.relationId));
1574
+ draft.entities = draft.entities.filter((entity) => entity.entityId !== caption.entityId && (!deleteAsset || entity.entityId !== asset.entityId));
1575
+ }
1576
+ replaceAnchorHost(draft, childClipEntityId, hostClipEntityId) {
1577
+ const anchors = draft.relations.filter((relation) => relation.relationKind === "clip-anchor" && relation.endpoint0EntityId === childClipEntityId);
1578
+ if (anchors.length !== 1) throw new Error(`Clip "${childClipEntityId}" must have exactly one host`);
1579
+ this.relinkRelation(draft, anchors[0], {
1580
+ endpoint0EntityId: createEntityId(childClipEntityId),
1581
+ endpoint1EntityId: createEntityId(hostClipEntityId)
1582
+ });
1583
+ }
1584
+ /** Rebuild the legacy edit baseline from current visual order before a high-level cascade. */
1585
+ normalizeMainSequential(draft) {
1586
+ const videoTrack = resolveEntityTimelineLayout(draft).tracks.find((track) => track.role === "video_clip");
1587
+ if (videoTrack === void 0) return;
1588
+ videoTrack.clips.forEach((clip, order) => {
1589
+ this.applyClipPlacement(draft, clip.clipEntityId, {
1590
+ kind: "sequential",
1591
+ order
1592
+ });
1593
+ });
1594
+ }
1595
+ resolveOneVoiceoverOverlap(draft) {
1596
+ const layout = resolveEntityTimelineLayout(draft);
1597
+ const speechTrack = layout.tracks.find((track) => track.role === "speech");
1598
+ if (speechTrack === void 0) return;
1599
+ const ranges = speechTrack.clips.map((speech) => {
1600
+ const captions = directAnchorChildren(draft, speech.clipEntityId).filter((clipId) => clipRole(draft, clipId) === "caption").map((clipId) => layout.clips.get(clipId)).filter((value) => value !== void 0);
1601
+ return {
1602
+ speech,
1603
+ start: Math.min(speech.start, ...captions.map((caption) => caption.start)),
1604
+ end: Math.max(speech.start + speech.duration, ...captions.map((caption) => caption.start + caption.duration))
1605
+ };
1606
+ }).sort((left, right) => left.start - right.start || left.speech.clipEntityId.localeCompare(right.speech.clipEntityId));
1607
+ for (let index = 1; index < ranges.length; index += 1) {
1608
+ const prior = ranges[index - 1];
1609
+ const current = ranges[index];
1610
+ if (current.start >= prior.end) continue;
1611
+ const hostId = current.speech.anchorClipEntityId;
1612
+ if (hostId === void 0) continue;
1613
+ const videoTrack = layout.tracks.find((track) => track.role === "video_clip");
1614
+ const hostIndex = videoTrack?.clips.findIndex((clip) => clip.clipEntityId === hostId) ?? -1;
1615
+ if (videoTrack === void 0 || hostIndex < 0) continue;
1616
+ const overlapMs = Math.round(prior.end - current.start);
1617
+ for (const [visualIndex, clip] of videoTrack.clips.entries()) this.applyClipPlacement(draft, clip.clipEntityId, {
1618
+ kind: "absolute",
1619
+ targetRange: {
1620
+ start: clip.start + (visualIndex >= hostIndex ? overlapMs : 0),
1621
+ end: clip.start + clip.duration + (visualIndex >= hostIndex ? overlapMs : 0)
1622
+ }
1623
+ });
1624
+ return;
1625
+ }
1626
+ }
1627
+ applyClipPlacement(draft, clipEntityId, placement) {
1628
+ const topology = requireClipTopology(draft, clipEntityId);
1629
+ const clipPayload = { ...cloneJsonObject(topology.clip.payload, "Clip payload") };
1630
+ const markerPayloadValue = { ...cloneJsonObject(topology.marker.payload, "Sequence Marker payload") };
1631
+ delete clipPayload.order;
1632
+ delete markerPayloadValue.targetRange;
1633
+ delete markerPayloadValue.anchorOffset;
1634
+ const outgoingAnchors = draft.relations.filter((relation) => relation.relationKind === "clip-anchor" && relation.endpoint0EntityId === topology.clip.entityId);
1635
+ const removed = new Set(outgoingAnchors.map((relation) => relation.relationId));
1636
+ draft.relations = draft.relations.filter((relation) => !removed.has(relation.relationId));
1637
+ if (placement.kind === "sequential") clipPayload.order = finiteNumber(placement.order, "Clip order");
1638
+ else if (placement.kind === "absolute") markerPayloadValue.targetRange = cloneJsonValue(placement.targetRange, "targetRange");
1639
+ else {
1640
+ const host = requireEntityKind(draft, placement.hostClipEntityId, "clip");
1641
+ if (host.entityId === topology.clip.entityId) throw new Error("A Clip cannot anchor to itself");
1642
+ markerPayloadValue.anchorOffset = finiteNonNegative(placement.anchorOffset, "anchorOffset");
1643
+ draft.relations.push(this.createRelation(draft, "clip-anchor", topology.clip.entityId, host.entityId));
1644
+ }
1645
+ replaceEntity(draft, topology.clip.entityId, {
1646
+ ...topology.clip,
1647
+ payload: clipPayload
1648
+ });
1649
+ replaceEntity(draft, topology.marker.entityId, {
1650
+ ...topology.marker,
1651
+ payload: markerPayloadValue
1652
+ });
1653
+ }
1654
+ reanchorAtAbsolute(draft, childClipEntityId, absoluteStart, layout) {
1655
+ const hosts = layout.tracks.find((track) => track.role === "video_clip")?.clips.filter((clip) => clip.mode === "sequential") ?? [];
1656
+ if (hosts.length === 0) {
1657
+ const child = layout.clips.get(childClipEntityId);
1658
+ if (child === void 0) throw new Error(`Clip "${childClipEntityId}" is not placed`);
1659
+ this.applyClipPlacement(draft, childClipEntityId, {
1660
+ kind: "absolute",
1661
+ targetRange: {
1662
+ start: absoluteStart,
1663
+ end: absoluteStart + child.duration
1664
+ }
1665
+ });
1666
+ return;
1667
+ }
1668
+ const host = hosts.find((candidate) => candidate.start <= absoluteStart && absoluteStart < candidate.start + candidate.duration) ?? (absoluteStart < hosts[0].start ? hosts[0] : hosts.at(-1));
1669
+ this.applyClipPlacement(draft, childClipEntityId, {
1670
+ kind: "anchored",
1671
+ hostClipEntityId: host.clipEntityId,
1672
+ anchorOffset: Math.max(0, Math.round(absoluteStart - host.start))
1673
+ });
1674
+ }
1675
+ removeAnchoredDescendants(draft, hostClipEntityId, scheduled) {
1676
+ const children = draft.relations.filter((relation) => relation.relationKind === "clip-anchor" && relation.endpoint1EntityId === hostClipEntityId).map((relation) => String(relation.endpoint0EntityId));
1677
+ for (const child of children) {
1678
+ if (scheduled.has(child)) continue;
1679
+ const descendants = new Set(scheduled);
1680
+ descendants.add(child);
1681
+ this.removeAnchoredDescendants(draft, child, descendants);
1682
+ if (clipRole(draft, child) === "caption") this.removeCaptionClipGraph(draft, child);
1683
+ else this.removeClipGraph(draft, child);
1684
+ }
1685
+ }
1686
+ removeClipGraph(draft, clipEntityId) {
1687
+ const topology = requireClipTopology(draft, clipEntityId);
1688
+ assertOnlyStructuralIncidents(draft, topology.clip.entityId, new Set([
1689
+ "track-clip",
1690
+ "clip-marker",
1691
+ "clip-anchor"
1692
+ ]));
1693
+ assertOnlyStructuralIncidents(draft, topology.marker.entityId, new Set(["clip-marker", "marker-content"]));
1694
+ const markerIsExclusive = incidentRelations(draft, topology.marker.entityId).filter((relation) => relation.relationKind === "clip-marker").length === 1;
1695
+ const removed = new Set(incidentRelations(draft, topology.clip.entityId).map((relation) => relation.relationId));
1696
+ if (markerIsExclusive) for (const relation of incidentRelations(draft, topology.marker.entityId)) removed.add(relation.relationId);
1697
+ draft.relations = draft.relations.filter((relation) => !removed.has(relation.relationId));
1698
+ draft.entities = draft.entities.filter((entity) => entity.entityId !== topology.clip.entityId && (!markerIsExclusive || entity.entityId !== topology.marker.entityId));
1699
+ }
1700
+ transact(edit) {
1701
+ const draft = cloneRows(this.state);
1702
+ const result = edit(draft);
1703
+ validateFinalRows(draft);
1704
+ assertMediaAssetWritePolicy(this.state, draft);
1705
+ this.state = draft;
1706
+ return result;
1707
+ }
1708
+ mintEntityId(draft) {
1709
+ const entityId = createEntityId(this.idFactory("entity"));
1710
+ if (draft.entities.some((entity) => entity.entityId === entityId)) throw new Error(`Entity id "${entityId}" already exists`);
1711
+ return entityId;
1712
+ }
1713
+ createRelation(draft, relationKind, endpoint0EntityId, endpoint1EntityId, metadata = {}) {
1714
+ return {
1715
+ relationId: this.mintRelationId(draft),
1716
+ relationKind,
1717
+ endpoint0EntityId,
1718
+ endpoint1EntityId,
1719
+ metadata,
1720
+ trace: {}
1721
+ };
1722
+ }
1723
+ relinkRelation(draft, relation, endpoints) {
1724
+ const relationId = this.mintRelationId(draft);
1725
+ const index = draft.relations.findIndex((candidate) => candidate.relationId === relation.relationId);
1726
+ if (index < 0) throw new Error(`Relation id "${relation.relationId}" does not exist`);
1727
+ draft.relations[index] = {
1728
+ ...relation,
1729
+ ...endpoints,
1730
+ relationId
1731
+ };
1732
+ }
1733
+ mintRelationId(draft) {
1734
+ const relationId = createRelationId(this.idFactory("relation"));
1735
+ if (draft.relations.some((relation) => relation.relationId === relationId)) throw new Error(`Relation id "${relationId}" already exists`);
1736
+ return relationId;
1737
+ }
1738
+ };
1739
+ function validateFinalRows(rows) {
1740
+ decodeEntityRelationRows(rows, numericMarkerValidation);
1741
+ assertCanonicalEditorResources(rows);
1742
+ validateTimelineHierarchy(rows);
1743
+ }
1744
+ function validateTimelineHierarchy(rows) {
1745
+ for (const entity of rows.entities) {
1746
+ if (entity.entityKind === "track") requireTrackTimeline(rows, entity.entityId);
1747
+ if (entity.entityKind !== "clip") continue;
1748
+ const trackRelations = incidentRelations(rows, entity.entityId).filter((relation) => relation.relationKind === "track-clip");
1749
+ if (trackRelations.length !== 1) throw new Error(`Clip Entity "${entity.entityId}" must belong to exactly one Track`);
1750
+ requireEntityKind(rows, otherEndpoint(trackRelations[0], entity.entityId), "track");
1751
+ }
1752
+ }
1753
+ function requireTrackTimeline(rows, trackEntityId) {
1754
+ const timelineRelations = incidentRelations(rows, trackEntityId).filter((relation) => relation.relationKind === "timeline-track");
1755
+ if (timelineRelations.filter((relation) => {
1756
+ const otherId = otherEndpoint(relation, trackEntityId);
1757
+ return rows.entities.some((entity) => entity.entityId === otherId && entity.entityKind === "timeline");
1758
+ }).length !== 1 || timelineRelations.length !== 1) throw new Error(`Track Entity "${trackEntityId}" must belong to exactly one Timeline`);
1759
+ }
1760
+ function requireClipTopology(rows, clipEntityId) {
1761
+ const clip = requireEntityKind(rows, clipEntityId, "clip");
1762
+ const trackRelation = requireOneRelation(rows, clip.entityId, "track-clip");
1763
+ requireEntityKind(rows, otherEndpoint(trackRelation, clip.entityId), "track");
1764
+ const clipMarkerRelation = requireOneRelation(rows, clip.entityId, "clip-marker");
1765
+ const marker = requireEntityKind(rows, otherEndpoint(clipMarkerRelation, clip.entityId), "sequence-marker");
1766
+ const markerContentRelation = requireOneRelation(rows, marker.entityId, "marker-content");
1767
+ requireSequenceContent(rows, otherEndpoint(markerContentRelation, marker.entityId));
1768
+ return {
1769
+ clip,
1770
+ marker,
1771
+ trackRelation,
1772
+ clipMarkerRelation,
1773
+ markerContentRelation
1774
+ };
1775
+ }
1776
+ function requireOneRelation(rows, entityId, relationKind) {
1777
+ const matches = incidentRelations(rows, entityId).filter((relation) => relation.relationKind === relationKind);
1778
+ if (matches.length !== 1) throw new Error(`Entity "${entityId}" must have exactly one ${relationKind} Relation`);
1779
+ return matches[0];
1780
+ }
1781
+ function requireEntityKind(rows, entityIdValue, entityKind) {
1782
+ const entityId = createEntityId(entityIdValue);
1783
+ const entity = rows.entities.find((candidate) => candidate.entityId === entityId);
1784
+ if (entity == null) throw new Error(`Entity id "${entityId}" does not exist`);
1785
+ if (entity.entityKind !== entityKind) throw new Error(`Entity "${entityId}" must have kind "${entityKind}", got "${entity.entityKind}"`);
1786
+ return entity;
1787
+ }
1788
+ function requireSequenceContent(rows, entityIdValue) {
1789
+ 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");
1790
+ const entityId = createEntityId(entityIdValue);
1791
+ const row = rows.entities.find((candidate) => candidate.entityId === entityId);
1792
+ if (row == null) throw new Error(`Timeline content must reference an existing Sequence media Entity; "${entityId}" was not found`);
1793
+ if (!hasSequence({
1794
+ ...row.payload,
1795
+ entityId: row.entityId,
1796
+ entityKind: row.entityKind
1797
+ })) throw new Error(`Timeline content must reference a Sequence media Entity, but "${entityId}" has kind "${row.entityKind}"`);
1798
+ return row;
1799
+ }
1800
+ function assertOnlyStructuralIncidents(rows, entityId, allowedKinds) {
1801
+ const unsupported = incidentRelations(rows, entityId).filter((relation) => !allowedKinds.has(relation.relationKind));
1802
+ if (unsupported.length === 0) return;
1803
+ throw new Error(`Cannot delete Clip graph: Entity "${entityId}" has unsupported incident Relation id(s): ${unsupported.map((relation) => relation.relationId).sort().join(", ")}`);
1804
+ }
1805
+ function incidentRelations(rows, entityId) {
1806
+ return rows.relations.filter((relation) => relation.endpoint0EntityId === entityId || relation.endpoint1EntityId === entityId);
1807
+ }
1808
+ function hasOutgoingClipAnchor(rows, clipEntityId) {
1809
+ return rows.relations.some((relation) => relation.relationKind === "clip-anchor" && relation.endpoint0EntityId === clipEntityId);
1810
+ }
1811
+ function outgoingAnchorChildren(rows, hostIds) {
1812
+ return rows.relations.filter((relation) => relation.relationKind === "clip-anchor" && hostIds.has(relation.endpoint1EntityId)).map((relation) => String(relation.endpoint0EntityId));
1813
+ }
1814
+ function applyPlacementPayload(clipPayload, placement) {
1815
+ if (placement.kind === "sequential") {
1816
+ clipPayload.order = finiteNumber(placement.order, "Clip order");
1817
+ return {};
1818
+ }
1819
+ if (placement.kind === "absolute") return { targetRange: cloneJsonValue(placement.targetRange, "targetRange") };
1820
+ return { anchorOffset: finiteNonNegative(placement.anchorOffset, "anchorOffset") };
1821
+ }
1822
+ function requireAvailableEntityId(rows, value) {
1823
+ const entityId = createEntityId(value);
1824
+ if (rows.entities.some((entity) => entity.entityId === entityId)) throw new Error(`Entity id "${entityId}" already exists`);
1825
+ return entityId;
1826
+ }
1827
+ function setClipOrder(rows, clipEntityId, order) {
1828
+ const clip = requireEntityKind(rows, clipEntityId, "clip");
1829
+ replaceEntity(rows, clip.entityId, {
1830
+ ...clip,
1831
+ payload: {
1832
+ ...clip.payload,
1833
+ order
1834
+ }
1835
+ });
1836
+ }
1837
+ function normalizeSequentialOrders(rows) {
1838
+ 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));
202
1839
  }
203
- function parseSseFrame(frame) {
204
- let event = null;
205
- const data = [];
206
- for (const line of frame.split(/\r?\n/)) if (line.startsWith("event:")) event = line.slice(6).trim();
207
- else if (line.startsWith("data:")) data.push(line.slice(5).trimStart());
1840
+ function findRoleTrack(rows, timelineEntityId, role) {
1841
+ const timeline = requireEntityKind(rows, timelineEntityId, "timeline");
1842
+ 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);
1843
+ if (tracks.length > 1) throw new Error(`Timeline "${timelineEntityId}" has multiple ${role} Tracks`);
1844
+ return tracks[0];
1845
+ }
1846
+ function clipsOnTrack(rows, trackEntityId) {
1847
+ return incidentRelations(rows, trackEntityId).filter((relation) => relation.relationKind === "track-clip").map((relation) => requireEntityKind(rows, otherEndpoint(relation, trackEntityId), "clip"));
1848
+ }
1849
+ function clipRole(rows, clipEntityId) {
1850
+ const topology = requireClipTopology(rows, clipEntityId);
1851
+ return requireEntityKind(rows, otherEndpoint(topology.trackRelation, topology.clip.entityId), "track").payload.role;
1852
+ }
1853
+ function directAnchorChildren(rows, hostClipEntityId) {
1854
+ return rows.relations.filter((relation) => relation.relationKind === "clip-anchor" && relation.endpoint1EntityId === hostClipEntityId).map((relation) => String(relation.endpoint0EntityId));
1855
+ }
1856
+ function requireSupportedRole(rows, topology) {
1857
+ const role = requireEntityKind(rows, otherEndpoint(topology.trackRelation, topology.clip.entityId), "track").payload.role;
1858
+ if (role !== "video_clip" && role !== "speech" && role !== "caption" && role !== "bgm") throw new Error(`Clip "${topology.clip.entityId}" is not on a supported timeline Track`);
1859
+ return role;
1860
+ }
1861
+ function requireClipOnRole(rows, clipEntityId, role) {
1862
+ const topology = requireClipTopology(rows, clipEntityId);
1863
+ if (requireEntityKind(rows, otherEndpoint(topology.trackRelation, topology.clip.entityId), "track").payload.role !== role) throw new Error(`Clip "${clipEntityId}" must belong to the ${role} Track`);
1864
+ return topology;
1865
+ }
1866
+ function finiteNumber(value, label) {
1867
+ if (!Number.isFinite(value)) throw new Error(`${label} must be finite`);
1868
+ return value;
1869
+ }
1870
+ function finitePositive(value, label) {
1871
+ const result = finiteNumber(value, label);
1872
+ if (result <= 0) throw new Error(`${label} must be positive`);
1873
+ return result;
1874
+ }
1875
+ function requireVolume(value) {
1876
+ const volume = finiteNumber(value, "Clip volume");
1877
+ if (volume < -60 || volume > 20) throw new Error("Clip volume must be between -60 and 20 dB");
1878
+ return volume;
1879
+ }
1880
+ function requirePositiveRange(value, label) {
1881
+ if (!isJsonObject(value)) throw new Error(`${label} must be an object`);
1882
+ const start = finiteNonNegative(value.start, `${label}.start`);
1883
+ const end = finitePositive(value.end, `${label}.end`);
1884
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || end <= start) throw new Error(`${label} must be a positive whole-millisecond range`);
208
1885
  return {
209
- event,
210
- data
1886
+ start,
1887
+ end
211
1888
  };
212
1889
  }
213
- function findSseFrameBoundary(buffer) {
214
- const lf = buffer.indexOf("\n\n");
215
- const crlf = buffer.indexOf("\r\n\r\n");
216
- if (lf < 0) return crlf;
217
- if (crlf < 0) return lf;
218
- return Math.min(lf, crlf);
1890
+ function markerDuration(payload, sourceRange) {
1891
+ const duration = payload.duration;
1892
+ if (!isJsonObject(duration)) throw new Error("Sequence Marker duration must be an object");
1893
+ if (duration.mode === "from-source") return sourceRange.end - sourceRange.start;
1894
+ if (duration.mode !== "fixed") throw new Error("Sequence Marker duration mode is unsupported");
1895
+ return finitePositive(duration.value, "Sequence Marker fixed duration");
219
1896
  }
220
- //#endregion
221
- //#region src/editor/id-gen.ts
222
- /**
223
- * Part-id generation, aligned with the online ecosystem.
224
- *
225
- * The authoritative online producers — agent-harness (`@harness/shared`
226
- * `genObjId`) and director.v2 (`common/obj_id.py` `gen_obj_id`) — both mint part
227
- * ids as `` `${prefix}_${ulid()}` ``, and real captured drafts use exactly that
228
- * shape (`clip_…` / `spe_…` / `cap_…` / `bgm_…`, each a 26-char ULID). The engine
229
- * previously emitted `vc_<base36 timestamp><6 random>`, a different prefix AND a
230
- * different encoding — the sole cross-repo id divergence. This module removes it
231
- * by emitting the same `<prefix>_<ULID>` bytes.
232
- *
233
- * The ULID is generated inline (Crockford Base32, 48-bit time + 80-bit random)
234
- * rather than pulling the `ulid` npm package: the randomness class matches the
235
- * old generator (both `Math.random`-based) and it keeps `@mengine/medeo-client`
236
- * dependency-free for a purely mechanical id string. Part ids only need to be
237
- * unique and lexicographically time-sortable, which this satisfies.
238
- */
239
- /** Crockford Base32 alphabet (no I, L, O, U), per the ULID spec. */
240
- const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
241
- const TIME_LEN = 10;
242
- const RANDOM_LEN = 16;
243
- function encodeTime(now) {
244
- let out = "";
245
- let ms = now;
246
- for (let i = TIME_LEN - 1; i >= 0; i--) {
247
- const mod = ms % 32;
248
- out = CROCKFORD[mod] + out;
249
- ms = (ms - mod) / 32;
250
- }
251
- return out;
1897
+ function linearRate(value) {
1898
+ if (value === void 0) return 1;
1899
+ if (!isJsonObject(value) || value.kind !== "linear") throw new Error("Only linear Clip time remapping is supported");
1900
+ return finitePositive(value.rate, "linear speed rate");
252
1901
  }
253
- function encodeRandom() {
254
- let out = "";
255
- for (let i = 0; i < RANDOM_LEN; i++) out += CROCKFORD[Math.floor(Math.random() * 32)];
256
- return out;
1902
+ function resizeAbsoluteTarget(payload, duration) {
1903
+ if (payload.targetRange === void 0) return;
1904
+ const target = requirePositiveRange(payload.targetRange, "targetRange");
1905
+ payload.targetRange = {
1906
+ start: target.start,
1907
+ end: target.start + duration
1908
+ };
257
1909
  }
258
- /** A 26-char Crockford Base32 ULID (10-char time + 16-char random). */
259
- function ulid() {
260
- return encodeTime(Date.now()) + encodeRandom();
1910
+ function replaceRows(rows, replacement) {
1911
+ rows.entities = structuredClone([...replacement.entities]);
1912
+ rows.relations = structuredClone([...replacement.relations]);
261
1913
  }
262
- function generatePartId(prefix) {
263
- return `${prefix}_${ulid()}`;
1914
+ function finiteNonNegative(value, label) {
1915
+ const result = finiteNumber(value, label);
1916
+ if (result < 0) throw new Error(`${label} must be non-negative`);
1917
+ return result;
264
1918
  }
1919
+ function nextSequentialOrder(rows, trackEntityId) {
1920
+ 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));
1921
+ return orders.length === 0 ? 0 : Math.max(...orders) + 1;
1922
+ }
1923
+ function otherEndpoint(relation, entityId) {
1924
+ if (relation.endpoint0EntityId === entityId) return relation.endpoint1EntityId;
1925
+ if (relation.endpoint1EntityId === entityId) return relation.endpoint0EntityId;
1926
+ throw new Error(`Relation "${relation.relationId}" is not incident to Entity "${entityId}"`);
1927
+ }
1928
+ function replaceEntity(rows, entityId, replacement) {
1929
+ const index = rows.entities.findIndex((entity) => entity.entityId === entityId);
1930
+ if (index < 0) throw new Error(`Entity id "${entityId}" does not exist`);
1931
+ rows.entities[index] = replacement;
1932
+ }
1933
+ function markerPayload(value) {
1934
+ return cloneJsonObject(value, "Sequence Marker payload");
1935
+ }
1936
+ function cloneJsonObject(value, label) {
1937
+ const cloned = structuredClone(value);
1938
+ if (!isJsonObject(cloned)) throw new Error(`${label} must contain only JSON values`);
1939
+ return cloned;
1940
+ }
1941
+ function cloneJsonValue(value, label) {
1942
+ return cloneJsonObject({ value }, label).value;
1943
+ }
1944
+ function cloneRows(rows) {
1945
+ return {
1946
+ entities: rows.entities.map((entity) => structuredClone(entity)),
1947
+ relations: rows.relations.map((relation) => structuredClone(relation))
1948
+ };
1949
+ }
1950
+ const numericMarkerValidation = { compareMarkerPoints: (_marker, _range, left, right) => {
1951
+ if (typeof left !== "number" || !Number.isFinite(left) || typeof right !== "number" || !Number.isFinite(right)) throw new Error("Sequence Marker points must use finite numeric coordinates");
1952
+ return left - right;
1953
+ } };
265
1954
  //#endregion
266
- //#region src/editor/schemas/shared.ts
267
- const clipIdSchema = z.string().min(1).describe("The clip part ID on the timeline");
268
- 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)");
269
- const mediaIdSchema = z.string().min(1).describe("The media asset ID");
270
- const speechIdSchema = z.string().min(1).describe("The speech part ID on the timeline");
271
- const timelineMsSchema = z.number().int().min(0).describe("Time position in milliseconds on the timeline (>= 0)");
272
- const positiveMsSchema = z.number().int().positive().describe("Duration in milliseconds (> 0)");
273
- const volumeSchema = z.number().min(-60).max(20).describe("Volume in decibels (-60.0 to 20.0; 0.0 = original, -60 = mute, +20 = max)");
274
- 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)");
275
- const tangentHandleSchema = z.object({
276
- x: z.number().finite(),
277
- y: z.number().finite()
278
- }).describe("Bezier tangent handle (x, y)");
279
- const speedKeyframeSchema = z.object({
280
- position: z.number().min(0).max(1),
281
- rate: z.number().min(0),
282
- in_tangent: tangentHandleSchema.optional(),
283
- out_tangent: tangentHandleSchema.optional()
284
- }).describe("A speed keyframe: normalized position (0..1), rate, optional tangents");
285
- /**
286
- * A clip's playback-speed fact, the only thing `SetVideoClipSpeedShift` writes.
287
- * Mirrors the IDL `SpeedShift`: `category` is `linear` | `curve`, and `config`
288
- * is a discriminated union — `{ linear: { speed } }` for a constant multiplier
289
- * (the multiplier projection reads at `config.linear.speed`) or `{ curve: {
290
- * keyframes } }` for a Bezier-controlled variable speed (RFC 02 / `reference/16`
291
- * §0). Exactly one of `linear` / `curve` is present.
292
- */
293
- const speedShiftSchema = z.object({
294
- category: z.enum(["linear", "curve"]),
295
- mode: z.string(),
296
- config: z.union([z.object({ linear: z.object({ speed: z.number().finite().positive() }) }), z.object({ curve: z.object({ keyframes: z.array(speedKeyframeSchema).min(2) }) })])
297
- }).describe("Speed shift: linear multiplier or Bezier curve, mirroring the IDL shape");
298
- const voiceSchema = z.object({
299
- id: z.string().min(1),
300
- name: z.string()
301
- }).describe("TTS voice summary attached to a speech");
302
- //#endregion
303
- //#region src/editor/schemas/speech-assets.ts
304
- /**
305
- * The materialized TTS result shared by `AddSpeeches` / `ChangeSpeechScript` /
306
- * `ChangeSpeechVoice` (see `results/phase-4-side-effect-payload-contract.md`
307
- * §1/§2). The side effect (TTS/ASR + billing) runs upstream; the op receives the
308
- * stable speech + caption parts and writes them as authoritative facts. No
309
- * cascade runs on write — the projection derives absolute positions on read.
310
- *
311
- * Each speech carries the anchoring fact directly (RFC 02 §4): the host video
312
- * clip `anchor_part_id` and the `offset_ms` within it. The upstream caller
313
- * already knows which clip a speech attaches to, so the op writes
314
- * `{ mode:'anchored', anchorPartId, offsetMs }` verbatim — no write-time
315
- * host-picking. Captions anchor to their speech via the caption part's
316
- * `start_ms` (offset within the speech).
317
- */
318
- const speechAssetSchema = z.object({
319
- speech_id: speechIdSchema.describe("The speech part ID (= side-effect speech_parts[].id)"),
320
- anchor_part_id: clipIdSchema.describe("Host video clip part ID the speech anchors to (RFC 02 §4)"),
321
- offset_ms: timelineMsSchema.describe("Offset within the host clip (speech.abs = host.abs + offset_ms)"),
322
- audio_storage_key: z.string().min(1),
323
- duration_ms: positiveMsSchema,
324
- audio_script: z.string(),
325
- volume: volumeSchema,
326
- voice: voiceSchema,
327
- origin_speech_id: z.string().min(1),
328
- caption_ids: z.array(z.string().min(1)).describe("Caption part IDs owned by this speech")
329
- });
330
- const captionAssetSchema = z.object({
331
- caption_id: z.string().min(1).describe("The caption part ID (= side-effect created_caption_parts[].id)"),
332
- speech_part_id: speechIdSchema.describe("The owning speech part ID"),
333
- text: z.string(),
334
- start_ms: timelineMsSchema.describe("Offset within the host speech (caption.abs = speech.abs + start_ms)"),
335
- duration_ms: positiveMsSchema
336
- });
337
- /** A materialized speech-subtree write (speeches + their captions). */
338
- const speechAssetsSchema = z.object({
339
- speeches: z.array(speechAssetSchema).min(1).describe("Materialized speech parts to write"),
340
- captions: z.array(captionAssetSchema).describe("Materialized caption parts owned by the speeches")
341
- });
342
- //#endregion
343
- //#region src/editor/schemas/add-speeches.ts
344
- /**
345
- * Add speeches (and their captions). TTS runs upstream; the stable speech /
346
- * caption parts arrive materialized (see `speech-assets.ts`). The op writes the
347
- * parts and each speech's `{ mode:'anchored', anchorPartId, offsetMs }` fact
348
- * verbatim — no write-time host-picking, no cascade (RFC 02 §4). The projection
349
- * derives absolute positions on read.
350
- */
351
- const addSpeechesInputSchema = speechAssetsSchema.describe("Materialized speeches + captions to add");
352
- //#endregion
353
- //#region src/editor/schemas/add-video-clips.ts
354
- /**
355
- * Add video clips to a track. Each clip's duration facts are separated so a
356
- * single number is never overloaded (RFC 02 / `reference/16` §0b):
357
- *
358
- * - `media_duration_ms` is the source media's intrinsic full length (a resource
359
- * fact, written to the part);
360
- * - `play_in` / `play_out` are the optional trim window into that media; when
361
- * omitted the whole media is used (`play_in=0`, `play_out=media_duration_ms`).
362
- *
363
- * The clip's effective timeline duration is derived by the projection from the
364
- * trim window and `speed_shift` — it is never an input here.
365
- */
366
- const addVideoClipsInputSchema = z.object({
367
- clips: z.array(z.object({
368
- media_id: mediaIdSchema.describe("The media asset ID for the video clip"),
369
- start_ms: timelineMsSchema.optional().describe("Absolute start time in milliseconds on the timeline"),
370
- media_duration_ms: positiveMsSchema.describe("The source media's intrinsic full length in ms"),
371
- play_in: timelineMsSchema.optional().describe("Trim window start in the media (default 0)"),
372
- play_out: positiveMsSchema.optional().describe("Trim window end in the media (default media_duration_ms)"),
373
- track_id: z.string().min(1).optional().describe("Target track ID (optional, defaults to main track)")
374
- })).min(1).describe("List of video clips to create"),
375
- before_clip_id: z.string().min(1).optional().describe("Insert new clips before this clip ID"),
376
- after_clip_id: z.string().min(1).optional().describe("Insert new clips after this clip ID")
377
- }).superRefine((data, ctx) => {
378
- if (data.before_clip_id != null && data.after_clip_id != null) {
379
- ctx.addIssue({
380
- code: z.ZodIssueCode.custom,
381
- message: "Cannot provide both before_clip_id and after_clip_id"
382
- });
383
- return;
384
- }
385
- const hasRelative = data.before_clip_id != null || data.after_clip_id != null;
386
- for (let i = 0; i < data.clips.length; i++) {
387
- const clip = data.clips[i];
388
- if (hasRelative && clip.start_ms != null) ctx.addIssue({
389
- code: z.ZodIssueCode.custom,
390
- message: `clips[${i}].start_ms must not be provided when using before_clip_id or after_clip_id`,
391
- path: [
392
- "clips",
393
- i,
394
- "start_ms"
395
- ]
396
- });
397
- if (!hasRelative && clip.start_ms == null) ctx.addIssue({
398
- code: z.ZodIssueCode.custom,
399
- message: `clips[${i}].start_ms is required when not using relative positioning`,
400
- path: [
401
- "clips",
402
- i,
403
- "start_ms"
404
- ]
405
- });
406
- const playIn = clip.play_in ?? 0;
407
- const playOut = clip.play_out ?? clip.media_duration_ms;
408
- if (playOut > clip.media_duration_ms) ctx.addIssue({
409
- code: z.ZodIssueCode.custom,
410
- message: `clips[${i}].play_out ${playOut}ms exceeds media_duration_ms ${clip.media_duration_ms}ms`,
411
- path: [
412
- "clips",
413
- i,
414
- "play_out"
415
- ]
1955
+ //#region src/entity-editor/legacy-entity-migration.ts
1956
+ /** One-time import only. Ordinary editor operations must never reverse-diff a legacy document. */
1957
+ function migrateLegacyTimelineToEntities(legacy, assetFacts, initial = {
1958
+ entities: [],
1959
+ relations: []
1960
+ }, idFactory = (prefix) => `${prefix}_${globalThis.crypto.randomUUID()}`) {
1961
+ assertSupportedLegacy(legacy);
1962
+ if (initial.entities.some((row) => row.entityKind === "timeline")) fail("Timeline already exists; migration is not an editing operation");
1963
+ if (legacy.meta.schema_version === "video-document/entity-projection-v1") fail("An entity projection cannot be migrated as legacy state");
1964
+ const normalizedMainRanges = overlapNormalizedMainRanges(legacy);
1965
+ let entities = structuredClone([...initial.entities]);
1966
+ let relations = structuredClone([...initial.relations]);
1967
+ const addEntity = (kind, payload, existingId) => {
1968
+ const entityId = createEntityId(existingId ?? idFactory("entity"));
1969
+ if (entities.some((row) => row.entityId === entityId)) fail(`Migration entity identity collision: ${entityId}`);
1970
+ entities.push({
1971
+ entityId,
1972
+ entityKind: kind,
1973
+ payload
416
1974
  });
417
- if (playIn >= playOut) ctx.addIssue({
418
- code: z.ZodIssueCode.custom,
419
- message: `clips[${i}].play_in ${playIn}ms must be less than play_out ${playOut}ms`,
420
- path: [
421
- "clips",
422
- i,
423
- "play_in"
424
- ]
1975
+ return entityId;
1976
+ };
1977
+ const link = (kind, from, to, metadata = {}) => {
1978
+ const relationId = createRelationId(idFactory("relation"));
1979
+ if (relations.some((row) => row.relationId === relationId)) fail(`Migration relation identity collision: ${relationId}`);
1980
+ relations.push({
1981
+ relationId,
1982
+ relationKind: kind,
1983
+ endpoint0EntityId: createEntityId(from),
1984
+ endpoint1EntityId: createEntityId(to),
1985
+ metadata,
1986
+ trace: {}
425
1987
  });
1988
+ };
1989
+ const facts = /* @__PURE__ */ new Map();
1990
+ for (const fact of assetFacts) {
1991
+ if (facts.has(fact.assetId)) fail(`Duplicate asset facts for ${fact.assetId}`);
1992
+ facts.set(fact.assetId, fact);
1993
+ }
1994
+ const contentByPartId = /* @__PURE__ */ new Map();
1995
+ const scriptBySpeechClipId = /* @__PURE__ */ new Map();
1996
+ for (const track of legacy.tracks ?? []) for (const item of track.items ?? []) {
1997
+ const part = requirePart(legacy, item.part_id);
1998
+ if (part.video_clip !== void 0) {
1999
+ const assetId = part.video_clip.origin_media_id;
2000
+ const fact = facts.get(assetId);
2001
+ if (fact === void 0) fail(`Missing factual media metadata for ${assetId}`);
2002
+ if (fact.kind !== "image" && fact.kind !== "video") fail(`Legacy video Clip ${item.part_id} requires an image or video fact`);
2003
+ const imported = importMediaAsset({
2004
+ entities,
2005
+ relations
2006
+ }, fact, idFactory);
2007
+ entities = [...imported.rows.entities];
2008
+ relations = [...imported.rows.relations];
2009
+ contentByPartId.set(item.part_id, imported.contentEntityId);
2010
+ } else if (part.speech !== void 0) {
2011
+ const speech = part.speech;
2012
+ const imported = importMediaAsset({
2013
+ entities,
2014
+ relations
2015
+ }, {
2016
+ assetId: speech.origin_speech_id,
2017
+ kind: "voice",
2018
+ durationMs: speech.media_duration_ms,
2019
+ storageKey: speech.audio_storage_key,
2020
+ voice: {
2021
+ system: "voice-library",
2022
+ key: speech.voice.id,
2023
+ ...speech.voice.name === void 0 ? {} : { name: speech.voice.name }
2024
+ }
2025
+ }, idFactory);
2026
+ entities = [...imported.rows.entities];
2027
+ relations = [...imported.rows.relations];
2028
+ contentByPartId.set(item.part_id, imported.contentEntityId);
2029
+ scriptBySpeechClipId.set(item.part_id, ensureAudioScript(imported.contentEntityId, speech.audio_script, entities, relations, addEntity, link));
2030
+ } else if (part.bgm !== void 0) {
2031
+ const bgm = part.bgm;
2032
+ const fact = facts.get(bgm.origin_media_id);
2033
+ if (fact === void 0) fail(`Missing factual media metadata for ${bgm.origin_media_id}`);
2034
+ if (fact.kind !== "audio") fail(`Legacy BGM ${item.part_id} requires an audio fact`);
2035
+ if (fact.storageKey !== bgm.audio_storage_key) fail(`Factual storage key conflicts with legacy BGM ${item.part_id}`);
2036
+ const imported = importMediaAsset({
2037
+ entities,
2038
+ relations
2039
+ }, fact, idFactory);
2040
+ entities = [...imported.rows.entities];
2041
+ relations = [...imported.rows.relations];
2042
+ contentByPartId.set(item.part_id, imported.contentEntityId);
2043
+ }
426
2044
  }
427
- });
428
- //#endregion
429
- //#region src/editor/schemas/adjust-bgm-volume.ts
430
- const adjustBgmVolumeInputSchema = z.object({ bgm: z.array(z.object({
431
- bgm_id: clipIdSchema.describe("The bgm 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 bgm parts with their new volume settings") });
434
- //#endregion
435
- //#region src/editor/schemas/adjust-speech-volume.ts
436
- const adjustSpeechVolumeInputSchema = z.object({ speeches: z.array(z.object({
437
- speech_id: speechIdSchema.describe("The speech part ID to adjust volume for"),
438
- volume: volumeSchema.describe("Volume in decibels (-60.0 to 20.0; 0.0 = original)")
439
- })).min(1).describe("List of speeches with their new volume settings") });
440
- //#endregion
441
- //#region src/editor/schemas/adjust-video-clip-duration.ts
442
- /**
443
- * Re-trim existing video clips (the user-facing "adjust duration" gesture is a
444
- * trim of the source window). The new `play_in` / `play_out` are the facts; the
445
- * effective timeline duration is derived from them and the clip's `speed_shift`,
446
- * and the change reflows downstream clips, speeches, and the timeline inside the
447
- * op's transaction (no caller-materialized cascade).
448
- */
449
- const adjustVideoClipDurationInputSchema = z.object({ clips: z.array(z.object({
450
- clip_id: clipIdSchema.describe("The video clip part ID to re-trim"),
451
- play_in: timelineMsSchema.describe("New trim window start in the source media"),
452
- play_out: positiveMsSchema.describe("New trim window end in the source media")
453
- })).min(1).describe("Video clips with their new trim windows") });
454
- //#endregion
455
- //#region src/editor/schemas/adjust-video-clip-volume.ts
456
- const adjustVideoClipVolumeInputSchema = z.object({ clips: z.array(z.object({
457
- clip_id: clipIdSchema.describe("The video clip part ID to adjust volume for"),
458
- volume: volumeSchema.describe("Volume in decibels (-60.0 to 20.0; 0.0 = original)")
459
- })).min(1).describe("List of video clips with their new volume settings") });
460
- //#endregion
461
- //#region src/editor/schemas/change-speech.ts
462
- /**
463
- * Change a speech's script or voice. Both re-run TTS upstream and return the
464
- * regenerated speech / caption parts in the same materialized shape as
465
- * `AddSpeeches` (`speech-assets.ts`); the op upserts them by id (the speech part
466
- * id is preserved across a re-TTS), re-seats at `start_ms`, and reflows. Old
467
- * caption parts no longer owned by the speech are removed via `caption_ids`.
468
- */
469
- const changeSpeechScriptInputSchema = speechAssetsSchema.describe("Regenerated speeches + captions (new script)");
470
- const changeSpeechVoiceInputSchema = speechAssetsSchema.describe("Regenerated speeches + captions (new voice)");
471
- //#endregion
472
- //#region src/editor/schemas/delete-bgm.ts
473
- /**
474
- * Remove the document BGM. Pure document edit: clears the bgm lane and removes
475
- * the bgm part. Takes no input (a document holds at most one bgm); an empty
476
- * object keeps the op signature uniform with the rest.
477
- */
478
- const deleteBgmInputSchema = z.object({}).describe("Remove the document BGM (no parameters)");
479
- //#endregion
480
- //#region src/editor/schemas/delete-speeches.ts
481
- /**
482
- * Delete speeches with their captions. Pure document edit (no side effect): the
483
- * op removes each speech part, cascade-deletes the captions it owns (via
484
- * `caption_ids` / `speech_part_id`), drops their track items, and reflows.
485
- */
486
- const deleteSpeechesInputSchema = z.object({ speech_ids: speechIdsSchema.describe("Speech part IDs to delete (their captions cascade-delete)") });
487
- //#endregion
488
- //#region src/editor/schemas/delete-video-clips.ts
489
- /**
490
- * How a delete handles the anchored subtree (speeches anchored to a deleted clip,
491
- * and their captions) — a delete-op policy, not a data-model field (reference/17
492
- * §6). `cascade` (default) removes the subtree; `detach` keeps the direct
493
- * anchored children, re-pinning them to `absolute` so they stay on the timeline.
494
- */
495
- const anchoredDeletePolicySchema = z.enum(["cascade", "detach"]);
496
- const deleteVideoClipsInputSchema = z.object({
497
- clip_ids: clipIdsSchema.describe("List of video clip part IDs to delete from the main track"),
498
- on_anchored: anchoredDeletePolicySchema.optional().describe("How to treat anchored children (default cascade)")
499
- });
500
- //#endregion
501
- //#region src/editor/schemas/move-speeches.ts
502
- /**
503
- * Move speeches in time. Pure document edit: the op re-seats each speech at its
504
- * new absolute `start_ms`; the cascade reassigns it to the host video clip,
505
- * resolves overlaps, and reflows. Captions follow their speech.
506
- */
507
- const moveSpeechesInputSchema = z.object({ speeches: z.array(z.object({
508
- speech_id: speechIdSchema.describe("The speech part ID to move"),
509
- new_start_ms: timelineMsSchema.describe("New absolute start time on the timeline")
510
- })).min(1).describe("Speeches to move to new positions") });
511
- //#endregion
512
- //#region src/editor/schemas/move-video-clips-by-anchor.ts
513
- /**
514
- * Where the moved block lands on the main track.
515
- *
516
- * A discriminated union rather than two optional `before_clip_id` /
517
- * `after_clip_id` fields (the shape `addVideoClips` had to use, because there the
518
- * two modes share a whole clip description): here the alternatives carry nothing
519
- * in common, so making them mutually exclusive *by type* removes three runtime
520
- * `superRefine` checks that would otherwise have to be written and tested.
521
- *
522
- * `track_start` is an explicit member, not the absence of an anchor. The
523
- * agent-harness mutation this maps from treats "neither anchor given" as
524
- * "move to the front" (`applyBatchMoveVideoClips` falls back to `insertIndex = 0`),
525
- * which is a default buried in a tool description. Requiring the caller to name
526
- * that intent keeps a forgotten field from silently reordering the timeline.
527
- */
528
- const moveAnchorSchema = z.discriminatedUnion("position", [
529
- z.object({
530
- position: z.literal("before"),
531
- clip_id: clipIdSchema.describe("The moved block lands immediately before this clip")
532
- }),
533
- z.object({
534
- position: z.literal("after"),
535
- clip_id: clipIdSchema.describe("The moved block lands immediately after this clip")
536
- }),
537
- z.object({ position: z.literal("track_start") })
538
- ]).describe("Where the moved block lands: before/after a reference clip, or at the head of the track");
539
- /**
540
- * What happens to the speeches anchored to the clips being moved.
541
- *
542
- * - `follow` keeps each speech anchored where it is, so it travels with its clip
543
- * to the new position. In the anchored model this is the *no-op* branch: a
544
- * speech's authoritative fact is `{ anchorPartId, offsetMs }` and its absolute
545
- * time is derived on read from the host's position, so moving the host moves
546
- * the speech with no write to the speech at all.
547
- * - `keep_absolute` preserves each speech's current absolute landing instead, then
548
- * re-anchors it to whichever clip now covers that time (RFC 02 §9.1/§11.1). This
549
- * is the branch that costs an extra pass, and the one the FE timeline uses.
550
- *
551
- * **Required, with no default**, matching `deleteVideoClips` and
552
- * `replaceVideoClipSequence`. The two branches decide which picture the user's
553
- * narration ends up over, which is too consequential to infer from a missing
554
- * field — and neither branch is "safe enough" to be the implicit one.
555
- */
556
- const movedClipAnchoredPolicySchema = z.enum(["follow", "keep_absolute"]);
557
- /**
558
- * Reorder a set of main-track clips relative to a reference clip.
559
- *
560
- * Distinct from `moveVideoClips`, which positions clips by absolute time
561
- * (`new_start_ms`) and is what the FE timeline dispatches after a drag. Main-track
562
- * clips are `sequential`-positioned, so absolute time is not authoritative state
563
- * there (RFC 02 §4/§7): `moveVideoClips` has to *guess* an index back out of the
564
- * time it was handed, whereas an anchor already is the ordinal fact being changed.
565
- * Keeping them separate also isolates blast radius — this method can diverge on
566
- * speech policy without touching the FE path.
567
- *
568
- * `clip_ids` need not be contiguous. They move as one block, keeping their
569
- * relative order, which is the agent-harness `batch_move_video_clips` contract.
570
- */
571
- const moveVideoClipsByAnchorInputSchema = z.object({
572
- clip_ids: clipIdsSchema.describe("Clips to move as one block, keeping their relative order. Need not be contiguous on the track."),
573
- anchor: moveAnchorSchema,
574
- on_anchored: movedClipAnchoredPolicySchema.describe("What happens to speeches anchored to the moved clips (required — see the policy doc)")
575
- });
576
- //#endregion
577
- //#region src/editor/schemas/move-video-clips.ts
578
- const moveVideoClipsInputSchema = z.object({ clips: z.array(z.object({
579
- clip_id: clipIdSchema.describe("The video clip part ID to move"),
580
- new_start_ms: timelineMsSchema.describe("New absolute start time in milliseconds on the timeline"),
581
- new_track_id: z.string().min(1).optional().describe("Target track ID to move the clip to (optional)")
582
- })).min(1).describe("List of video clips to move to new positions") });
583
- //#endregion
584
- //#region src/editor/schemas/replace-video-clip-content.ts
585
- /**
586
- * Replace the media backing existing video clips. The media import runs upstream
587
- * (Director); its stable result — the new media id, intrinsic length, and the
588
- * reset trim window — arrives materialized (see
589
- * `results/phase-4-side-effect-payload-contract.md` §4). Director resets
590
- * `play_in=0` / `play_out=media_duration_ms` and clears `speed_shift` on
591
- * replacement. The clip `part_id`s (hence their track items) are unchanged; the
592
- * editor reflows the main track from the new effective durations.
593
- */
594
- const replaceVideoClipContentInputSchema = z.object({ clips: z.array(z.object({
595
- clip_id: clipIdSchema.describe("Existing video clip part ID to re-point"),
596
- origin_media_id: mediaIdSchema.describe("The new media asset ID"),
597
- media_duration_ms: positiveMsSchema.describe("The new media's intrinsic full length"),
598
- play_in: timelineMsSchema.describe("Trim window start in the new media (usually 0)"),
599
- play_out: positiveMsSchema.describe("Trim window end in the new media (usually = media_duration_ms)"),
600
- volume: volumeSchema
601
- })).min(1).describe("Video clips whose media is being replaced") });
602
- //#endregion
603
- //#region src/editor/schemas/replace-video-clip-sequence.ts
604
- /**
605
- * What happens to the speeches anchored to the clips being replaced.
606
- *
607
- * - `remap` re-anchors each surviving speech to the new clip in the SAME POSITION
608
- * of the sequence, keeping its offset — old[i]'s children become new[i]'s
609
- * children. An old clip with no counterpart (fewer new clips than old) has its
610
- * subtree deleted, because there is nothing left to anchor to.
611
- * - `cascade` deletes every anchored speech (and its captions) outright, like
612
- * `deleteVideoClips`.
613
- *
614
- * **Required, with no default.** The two branches differ in whether the user's
615
- * narration survives, and the agent tool that drives this op makes its
616
- * `preserve_speeches` flag required for that reason. A default here would let a
617
- * caller that forgot the field silently delete speech.
618
- */
619
- const anchoredReplacePolicySchema = z.enum(["remap", "cascade"]);
2045
+ const timeline = addEntity("timeline", legacy.timeline?.unit_time_ms === void 0 ? {} : { unit_time_ms: legacy.timeline.unit_time_ms });
2046
+ const trackIds = /* @__PURE__ */ new Map();
2047
+ for (const [order, oldTrack] of (legacy.tracks ?? []).entries()) {
2048
+ const track = addEntity("track", {
2049
+ role: oldTrack.parts_kind,
2050
+ order,
2051
+ ...oldTrack.is_hidden === void 0 ? {} : { hidden: oldTrack.is_hidden }
2052
+ }, oldTrack.id);
2053
+ trackIds.set(oldTrack, track);
2054
+ link("timeline-track", timeline, track);
2055
+ }
2056
+ for (const oldTrack of legacy.tracks ?? []) {
2057
+ const track = trackIds.get(oldTrack);
2058
+ for (const [order, item] of (oldTrack.items ?? []).entries()) {
2059
+ const part = requirePart(legacy, item.part_id);
2060
+ const role = oldTrack.parts_kind;
2061
+ const volume = part.video_clip?.volume ?? part.speech?.volume ?? part.bgm?.volume;
2062
+ const clip = addEntity("clip", {
2063
+ ...volume === void 0 ? {} : { volume },
2064
+ ...item.time_position.mode === "sequential" && !(role === "video_clip" && normalizedMainRanges !== void 0) || role === "bgm" ? { order: role === "bgm" ? 0 : order } : {}
2065
+ }, item.part_id);
2066
+ let content = contentByPartId.get(item.part_id);
2067
+ let duration;
2068
+ let markerPayload;
2069
+ if (part.video_clip !== void 0) {
2070
+ const video = part.video_clip;
2071
+ duration = effectiveVideoClipDurationMs(video);
2072
+ const fact = facts.get(video.origin_media_id);
2073
+ const rate = speedOf(video.speed_shift);
2074
+ markerPayload = {
2075
+ sourceRange: {
2076
+ start: video.play_in,
2077
+ end: video.play_out
2078
+ },
2079
+ duration: {
2080
+ mode: "fixed",
2081
+ value: duration
2082
+ },
2083
+ ...(fact.kind === "image" || fact.kind === "video") && video.speed_shift !== void 0 ? { timeRemapping: {
2084
+ kind: "linear",
2085
+ mode: video.speed_shift?.mode ?? "constant",
2086
+ rate
2087
+ } } : {}
2088
+ };
2089
+ } else if (part.speech !== void 0) {
2090
+ duration = part.speech.media_duration_ms;
2091
+ markerPayload = {
2092
+ sourceRange: {
2093
+ start: 0,
2094
+ end: duration
2095
+ },
2096
+ duration: {
2097
+ mode: "fixed",
2098
+ value: duration
2099
+ }
2100
+ };
2101
+ } else if (part.caption !== void 0) {
2102
+ const caption = part.caption;
2103
+ duration = caption.initial_duration_ms;
2104
+ content = addEntity("caption", {
2105
+ extent: {
2106
+ kind: "bounded",
2107
+ start: 0,
2108
+ end: duration
2109
+ },
2110
+ sampling: "native",
2111
+ coordinateSpace: "milliseconds",
2112
+ text: caption.text,
2113
+ ...caption.style === void 0 ? {} : { style: toEntityCaptionStyle(caption.style) }
2114
+ });
2115
+ const asset = addEntity("asset", { inline: {
2116
+ mediaType: "text/plain",
2117
+ text: caption.text
2118
+ } });
2119
+ link("physical-asset", content, asset);
2120
+ const voice = contentByPartId.get(caption.speech_part_id);
2121
+ const script = scriptBySpeechClipId.get(caption.speech_part_id);
2122
+ link("caption-alignment", content, voice, { alignment: {
2123
+ start: caption.start_ms,
2124
+ end: caption.start_ms + duration
2125
+ } });
2126
+ link("caption-provenance", content, script, { segmentAlignment: [] });
2127
+ markerPayload = {
2128
+ sourceRange: {
2129
+ start: 0,
2130
+ end: duration
2131
+ },
2132
+ duration: {
2133
+ mode: "fixed",
2134
+ value: duration
2135
+ }
2136
+ };
2137
+ } else {
2138
+ const bgm = part.bgm;
2139
+ const fact = facts.get(bgm.origin_media_id);
2140
+ if (fact.kind !== "audio") fail(`Legacy BGM ${item.part_id} requires an audio fact`);
2141
+ duration = fact.durationMs;
2142
+ markerPayload = {
2143
+ sourceRange: {
2144
+ start: 0,
2145
+ end: duration
2146
+ },
2147
+ duration: { mode: "from-source" },
2148
+ durationPolicy: "timeline"
2149
+ };
2150
+ }
2151
+ if (content === void 0) fail(`Migration could not resolve content for ${item.part_id}`);
2152
+ const normalizedMainRange = role === "video_clip" ? normalizedMainRanges?.get(item.part_id) : void 0;
2153
+ if (normalizedMainRange !== void 0) markerPayload = {
2154
+ ...markerPayload,
2155
+ targetRange: normalizedMainRange
2156
+ };
2157
+ else if (item.time_position.mode === "absolute" && role !== "bgm") markerPayload = {
2158
+ ...markerPayload,
2159
+ targetRange: {
2160
+ start: item.time_position.offsetMs,
2161
+ end: item.time_position.offsetMs + duration
2162
+ }
2163
+ };
2164
+ else if (item.time_position.mode === "anchored") markerPayload = {
2165
+ ...markerPayload,
2166
+ anchorOffset: item.time_position.offsetMs
2167
+ };
2168
+ const marker = addEntity("sequence-marker", markerPayload);
2169
+ link("track-clip", track, clip);
2170
+ link("clip-marker", clip, marker);
2171
+ link("marker-content", marker, content);
2172
+ if (item.time_position.mode === "anchored") link("clip-anchor", clip, item.time_position.anchorPartId);
2173
+ }
2174
+ }
2175
+ const rows = {
2176
+ entities,
2177
+ relations
2178
+ };
2179
+ assertEntityProjectionPreservesLegacy(legacy, projectEntityTimeline(rows, legacy.meta), rows);
2180
+ return rows;
2181
+ }
2182
+ /** Server gate: a cutover may change representation, never the existing render facts. */
2183
+ function assertEntityProjectionPreservesLegacy(legacy, projection, rows) {
2184
+ assertSupportedLegacy(legacy);
2185
+ if (projection.meta.schema_version !== "video-document/entity-projection-v1") fail("Expected an entity projection for migration");
2186
+ const normalizedMainRanges = overlapNormalizedMainRanges(legacy);
2187
+ const compatibilityFacts = (document) => {
2188
+ const { version: _version, ...view } = fromVideoDocument(document);
2189
+ for (const part of Object.values(view.part_library ?? {})) {
2190
+ const speech = part.speech;
2191
+ if (speech?.phoneme_script === null) delete speech.phoneme_script;
2192
+ }
2193
+ const { schema_version: _schemaVersion, version: _metaVersion, ...meta } = document.meta;
2194
+ return {
2195
+ meta,
2196
+ view
2197
+ };
2198
+ };
2199
+ if (canonical(compatibilityFacts(legacy)) !== canonical(compatibilityFacts(projection))) fail("Entity migration must preserve all existing timeline facts; edit after cutover");
2200
+ const trackOrders = [];
2201
+ for (const oldTrack of legacy.tracks ?? []) {
2202
+ const candidates = rows.entities.filter((row) => row.entityKind === "track" && (oldTrack.id === void 0 ? row.payload.role === oldTrack.parts_kind : row.entityId === oldTrack.id));
2203
+ if (candidates.length !== 1) fail("Migration must preserve every Track identity");
2204
+ const track = candidates[0];
2205
+ if (track.payload.role !== oldTrack.parts_kind || (track.payload.hidden ?? false) !== (oldTrack.is_hidden ?? false)) fail("Migration must preserve Track role and visibility");
2206
+ if (typeof track.payload.order !== "number" || !Number.isFinite(track.payload.order)) fail("Migration must preserve Track order");
2207
+ trackOrders.push(track.payload.order);
2208
+ const sequentialOrders = [];
2209
+ for (const item of oldTrack.items ?? []) {
2210
+ const clip = rows.entities.find((row) => row.entityId === item.part_id && row.entityKind === "clip");
2211
+ 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"));
2212
+ const marker = rows.entities.find((row) => row.entityId === binding[0]?.endpoint1EntityId && row.entityKind === "sequence-marker");
2213
+ if (clip === void 0 || binding.length !== 1 || marker === void 0) fail("Migration must preserve Clip/Marker placement identity");
2214
+ const anchors = rows.relations.filter((row) => row.relationKind === "clip-anchor" && row.endpoint0EntityId === clip.entityId);
2215
+ const normalizedMainRange = oldTrack.parts_kind === "video_clip" ? normalizedMainRanges?.get(item.part_id) : void 0;
2216
+ if (normalizedMainRange !== void 0) {
2217
+ 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");
2218
+ } else if (oldTrack.parts_kind === "bgm") {
2219
+ 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");
2220
+ } else if (item.time_position.mode === "sequential") {
2221
+ 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");
2222
+ sequentialOrders.push(clip.payload.order);
2223
+ } else if (item.time_position.mode === "absolute") {
2224
+ const target = marker.payload.targetRange;
2225
+ 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");
2226
+ } 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");
2227
+ }
2228
+ if (sequentialOrders.some((order, index) => index > 0 && order <= sequentialOrders[index - 1])) fail("Migration must preserve sequential Clip order");
2229
+ }
2230
+ if (trackOrders.some((order, index) => index > 0 && order <= trackOrders[index - 1])) fail("Migration must preserve Track stacking order");
2231
+ }
2232
+ function assertSupportedLegacy(document) {
2233
+ assertValidVideoDocument(document);
2234
+ const tracks = document.tracks ?? [];
2235
+ assertKnownFields(document.timeline ?? {}, ["unit_time_ms"], "Timeline");
2236
+ 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");
2237
+ const seenRoles = /* @__PURE__ */ new Set();
2238
+ const placed = /* @__PURE__ */ new Map();
2239
+ for (const track of tracks) {
2240
+ const role = track.parts_kind;
2241
+ if (role === void 0 || ![
2242
+ "video_clip",
2243
+ "speech",
2244
+ "caption",
2245
+ "bgm"
2246
+ ].includes(role)) fail("Every legacy Track requires a supported role");
2247
+ if (seenRoles.has(role)) fail(`The compatibility editor supports only one ${role} Track`);
2248
+ seenRoles.add(role);
2249
+ if (track.id !== void 0 && (track.id.trim() === "" || track.id.trim() !== track.id)) fail("Migration requires trimmed Track identities");
2250
+ for (const item of track.items ?? []) {
2251
+ if (item.part_id.trim() === "" || item.part_id.trim() !== item.part_id) fail("Migration requires trimmed Clip identities");
2252
+ if (placed.has(item.part_id)) fail(`Legacy part ${item.part_id} is placed more than once`);
2253
+ placed.set(item.part_id, {
2254
+ track,
2255
+ item
2256
+ });
2257
+ assertKnownFields(item.time_position, item.time_position.mode === "sequential" ? ["mode"] : [
2258
+ "mode",
2259
+ "anchorPartId",
2260
+ "offsetMs"
2261
+ ], "placement");
2262
+ if (item.time_position.mode === "absolute") requireMilliseconds(item.time_position.offsetMs, "absolute offset");
2263
+ if (item.time_position.mode === "anchored") {
2264
+ if (item.time_position.anchorPartId.trim() === "" || item.time_position.anchorPartId.trim() !== item.time_position.anchorPartId) fail("Migration requires a trimmed anchor identity");
2265
+ requireMilliseconds(item.time_position.offsetMs, "anchor offset");
2266
+ }
2267
+ if (item.fallback_abs_ms !== void 0) requireMilliseconds(item.fallback_abs_ms, "anchor fallback");
2268
+ assertKnownFields(item, [
2269
+ "part_id",
2270
+ "time_position",
2271
+ "fallback_abs_ms"
2272
+ ], "TrackItem");
2273
+ }
2274
+ assertKnownFields(track, [
2275
+ "id",
2276
+ "parts_kind",
2277
+ "is_hidden",
2278
+ "items"
2279
+ ], "Track");
2280
+ }
2281
+ for (const [id, part] of Object.entries(document.part_library ?? {})) {
2282
+ const placement = placed.get(id);
2283
+ if (placement === void 0) fail(`Cannot discard unplaced legacy part ${id}`);
2284
+ assertPartSupported(id, part, placement.track.parts_kind);
2285
+ }
2286
+ for (const id of placed.keys()) if (document.part_library?.[id] === void 0) fail(`Placed Clip ${id} has no part payload`);
2287
+ assertLegacyRelations(document, placed);
2288
+ }
2289
+ function assertPartSupported(id, part, role) {
2290
+ assertKnownFields(part, [
2291
+ "video_clip",
2292
+ "speech",
2293
+ "caption",
2294
+ "bgm"
2295
+ ], "Part");
2296
+ const present = [
2297
+ "video_clip",
2298
+ "speech",
2299
+ "caption",
2300
+ "bgm"
2301
+ ].filter((kind) => part[kind] !== void 0);
2302
+ if (present.length !== 1 || present[0] !== role) fail(`Legacy part ${id} must match its ${role} Track`);
2303
+ if (part.video_clip !== void 0) {
2304
+ const clip = part.video_clip;
2305
+ 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");
2306
+ requireMilliseconds(clip.play_in, "Clip play_in");
2307
+ requireMilliseconds(clip.play_out, "Clip play_out");
2308
+ if (clip.play_out <= clip.play_in) fail("Migration requires a non-empty Clip trim window");
2309
+ requireFinite(clip.volume, "Clip volume");
2310
+ const speed = clip.speed_shift;
2311
+ 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");
2312
+ if (speed !== void 0) {
2313
+ const rate = speed.config?.linear?.speed;
2314
+ if (typeof rate !== "number" || !Number.isFinite(rate) || rate <= 0) fail("Migration requires a positive finite speed");
2315
+ assertKnownFields(speed, [
2316
+ "category",
2317
+ "mode",
2318
+ "config"
2319
+ ], "speed_shift");
2320
+ assertKnownFields(speed.config, ["linear"], "speed config");
2321
+ assertKnownFields(speed.config.linear, ["speed"], "linear speed");
2322
+ }
2323
+ assertKnownFields(clip, [
2324
+ "id",
2325
+ "kind",
2326
+ "origin_media_id",
2327
+ "play_in",
2328
+ "play_out",
2329
+ "volume",
2330
+ "speed_shift"
2331
+ ], "Clip");
2332
+ } else if (part.speech !== void 0) {
2333
+ const speech = part.speech;
2334
+ const phonemeScript = speech.phoneme_script;
2335
+ 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");
2336
+ requirePositiveMilliseconds(speech.media_duration_ms, "Speech duration");
2337
+ requireFinite(speech.volume, "Speech volume");
2338
+ if (!trimmed(speech.voice?.id)) fail("Migration requires an explicit voice-library identity");
2339
+ if (speech.voice?.name !== void 0 && typeof speech.voice.name !== "string") fail("Migration requires a string voice name when present");
2340
+ if (!Array.isArray(speech.caption_ids) || speech.caption_ids.some((captionId) => !trimmed(captionId))) fail("Migration requires explicit Speech caption identities");
2341
+ if (new Set(speech.caption_ids).size !== speech.caption_ids.length) fail("Migration requires unique Speech caption identities");
2342
+ if (phonemeScript !== void 0 && phonemeScript !== null) fail("Non-null phoneme_script requires a phonetic-script migration adapter");
2343
+ assertKnownFields(speech.voice, ["id", "name"], "voice");
2344
+ assertKnownFields(speech, [
2345
+ "id",
2346
+ "kind",
2347
+ "media_duration_ms",
2348
+ "audio_script",
2349
+ "volume",
2350
+ "audio_storage_key",
2351
+ "origin_speech_id",
2352
+ "voice",
2353
+ "caption_ids",
2354
+ "phoneme_script"
2355
+ ], "Speech");
2356
+ } else if (part.caption !== void 0) {
2357
+ const caption = part.caption;
2358
+ 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");
2359
+ requireMilliseconds(caption.start_ms, "Caption source offset");
2360
+ requirePositiveMilliseconds(caption.initial_duration_ms, "Caption duration");
2361
+ if (caption.style !== void 0) assertCaptionStyle(caption.style);
2362
+ assertKnownFields(caption, [
2363
+ "id",
2364
+ "kind",
2365
+ "initial_duration_ms",
2366
+ "speech_part_id",
2367
+ "text",
2368
+ "start_ms",
2369
+ "style"
2370
+ ], "Caption");
2371
+ } else if (part.bgm !== void 0) {
2372
+ const bgm = part.bgm;
2373
+ 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");
2374
+ requireFinite(bgm.volume, "BGM volume");
2375
+ assertKnownFields(bgm, [
2376
+ "id",
2377
+ "kind",
2378
+ "audio_storage_key",
2379
+ "volume",
2380
+ "origin_media_id"
2381
+ ], "BGM");
2382
+ }
2383
+ }
2384
+ function assertLegacyRelations(document, placed) {
2385
+ const captionIdsBySpeech = /* @__PURE__ */ new Map();
2386
+ for (const track of document.tracks ?? []) {
2387
+ if (track.parts_kind === "bgm" && (track.items?.length ?? 0) > 1) fail("The compatibility editor supports only one BGM Clip");
2388
+ for (const item of track.items ?? []) {
2389
+ const part = requirePart(document, item.part_id);
2390
+ const position = item.time_position;
2391
+ if (track.parts_kind === "video_clip" && position.mode === "anchored") fail("Anchored video Clips require an overlay adapter");
2392
+ if (track.parts_kind === "bgm") {
2393
+ if (position.mode !== "absolute" || position.offsetMs !== 0) fail("Legacy BGM must start at the Timeline origin");
2394
+ } else if (position.mode === "anchored") {
2395
+ const host = placed.get(position.anchorPartId);
2396
+ if (host === void 0) fail(`Legacy anchor ${position.anchorPartId} is not placed`);
2397
+ if (track.parts_kind === "speech" && host.track.parts_kind !== "video_clip") fail("Speech may only anchor to a video Clip");
2398
+ if (track.parts_kind === "caption") {
2399
+ if (host.track.parts_kind !== "speech") fail("Caption may only anchor to a Speech Clip");
2400
+ const caption = part.caption;
2401
+ if (position.anchorPartId !== caption.speech_part_id || position.offsetMs !== caption.start_ms) fail("Caption placement must agree with its Speech provenance and source offset");
2402
+ }
2403
+ } else if (track.parts_kind === "caption") fail("Caption placement requires an explicit Speech anchor");
2404
+ if (part.caption !== void 0) {
2405
+ const ids = captionIdsBySpeech.get(part.caption.speech_part_id) ?? [];
2406
+ ids.push(item.part_id);
2407
+ captionIdsBySpeech.set(part.caption.speech_part_id, ids);
2408
+ }
2409
+ }
2410
+ }
2411
+ for (const [id, placement] of placed) {
2412
+ const speech = requirePart(document, id).speech;
2413
+ if (speech === void 0) continue;
2414
+ const expected = captionIdsBySpeech.get(id) ?? [];
2415
+ if (canonical(speech.caption_ids) !== canonical(expected)) fail(`Speech ${id} caption_ids must agree with the Caption Track order`);
2416
+ if (placement.item.time_position.mode === "anchored") continue;
2417
+ if (placement.item.time_position.mode !== "absolute") fail("Speech placement must be anchored or absolute");
2418
+ }
2419
+ const intervals = (fromVideoDocument(document).main_track?.items ?? []).map((item) => {
2420
+ const clip = document.part_library?.[item.part_id]?.video_clip;
2421
+ if (clip === void 0) fail("Projection must preserve every video Clip");
2422
+ return {
2423
+ start: item.abs_time_position ?? 0,
2424
+ end: (item.abs_time_position ?? 0) + effectiveVideoClipDurationMs(clip)
2425
+ };
2426
+ }).sort((left, right) => left.start - right.start);
2427
+ if (intervals.some((interval, index) => index > 0 && interval.start < intervals[index - 1].end)) fail("Overlapping video Clips require an overlay adapter");
2428
+ }
620
2429
  /**
621
- * Replace a contiguous run of main-track clips with a new run.
622
- *
623
- * A composite of delete + insert that cannot be expressed as the two ops in
624
- * sequence, because the anchored speeches have to survive *across* the swap: with
625
- * `remap` they are re-anchored positionally, which needs both the old and the new
626
- * ids in the same transaction (ADR 0009 — the cascade stays in the editor, callers
627
- * never re-wire anchors themselves).
628
- *
629
- * Duration facts follow `addVideoClips`: `media_duration_ms` is the source's
630
- * intrinsic length and the trim window defaults to the whole media. The effective
631
- * timeline duration is derived by the projection, never an input.
632
- *
633
- * `media_id` is optional: omitting it creates a **deliberate empty placeholder
634
- * clip** (`origin_media_id: ''`) — structure with no picture. This is the only op
635
- * that can produce one, and it is authoritative state, unlike the gap fillers the
636
- * read-side solve mints (which never enter the document).
2430
+ * Legacy reads perform one speech-overlap pass after laying the visual lane out
2431
+ * sequentially. Entity reads deliberately do not run that hidden cascade. When
2432
+ * the pass moved any visual Clip, cutover therefore records the complete solved
2433
+ * visual lane as explicit target ranges. Mixing absolute and sequential Clips
2434
+ * would create two unrelated placement chains and could reorder the lane.
637
2435
  */
638
- const replaceVideoClipSequenceInputSchema = z.object({
639
- old_clip_ids: clipIdsSchema.describe("The clips being replaced: a contiguous main-track run, listed in timeline order"),
640
- new_clips: z.array(z.object({
641
- media_id: mediaIdSchema.optional().describe("The replacement media asset ID. Omit to create an empty placeholder clip."),
642
- media_duration_ms: positiveMsSchema.describe("The source media's intrinsic full length in ms"),
643
- play_in: timelineMsSchema.optional().describe("Trim window start in the media (default 0)"),
644
- play_out: positiveMsSchema.optional().describe("Trim window end in the media (default media_duration_ms)")
645
- })).min(1).describe("The replacement clips, in the order they take on the track"),
646
- on_anchored: anchoredReplacePolicySchema.describe("What happens to speeches anchored to the replaced clips (required — see the policy doc)")
647
- }).superRefine((data, ctx) => {
648
- for (let i = 0; i < data.new_clips.length; i++) {
649
- const clip = data.new_clips[i];
650
- const playIn = clip.play_in ?? 0;
651
- const playOut = clip.play_out ?? clip.media_duration_ms;
652
- if (playOut > clip.media_duration_ms) ctx.addIssue({
653
- code: z.ZodIssueCode.custom,
654
- message: `new_clips[${i}].play_out ${playOut}ms exceeds media_duration_ms ${clip.media_duration_ms}ms`,
655
- path: [
656
- "new_clips",
657
- i,
658
- "play_out"
659
- ]
660
- });
661
- if (playIn >= playOut) ctx.addIssue({
662
- code: z.ZodIssueCode.custom,
663
- message: `new_clips[${i}].play_in ${playIn}ms must be less than play_out ${playOut}ms`,
664
- path: [
665
- "new_clips",
666
- i,
667
- "play_in"
668
- ]
2436
+ function overlapNormalizedMainRanges(document) {
2437
+ const track = document.tracks?.find((candidate) => candidate.parts_kind === "video_clip");
2438
+ if (track === void 0 || (track.items?.length ?? 0) === 0) return void 0;
2439
+ const solved = fromVideoDocument(document).main_track?.items ?? [];
2440
+ const starts = new Map(solved.map((item) => [item.part_id, requireMilliseconds(item.abs_time_position, `Solved position for ${item.part_id ?? "unknown Clip"}`)]));
2441
+ let cursor = 0;
2442
+ let moved = false;
2443
+ const ranges = /* @__PURE__ */ new Map();
2444
+ for (const item of track.items ?? []) {
2445
+ const part = requirePart(document, item.part_id).video_clip;
2446
+ if (part === void 0) fail(`Projection must preserve video Clip ${item.part_id}`);
2447
+ const duration = effectiveVideoClipDurationMs(part);
2448
+ const start = starts.get(item.part_id);
2449
+ if (start === void 0) fail(`Projection must preserve video Clip ${item.part_id}`);
2450
+ if (start !== cursor) moved = true;
2451
+ const end = start + duration;
2452
+ requireMilliseconds(end, `Solved end for ${item.part_id}`);
2453
+ ranges.set(item.part_id, {
2454
+ start,
2455
+ end
669
2456
  });
2457
+ cursor += duration;
670
2458
  }
671
- });
672
- //#endregion
673
- //#region src/editor/schemas/set-bgm.ts
674
- /**
675
- * Set the document BGM. The media's stable result (storage key) arrives
676
- * materialized from upstream (see
677
- * `results/phase-4-side-effect-payload-contract.md` §3). The op upserts the bgm
678
- * part and seats it on the bgm lane; its effective length is always the whole
679
- * timeline, derived by the projection on read — so there is no `duration_ms`
680
- * input or fact (RFC 02 / `reference/16` §0b). A `bgm_id` lets the op replace an
681
- * existing bgm part by id.
682
- */
683
- const setBgmInputSchema = z.object({
684
- bgm_id: z.string().min(1).describe("The bgm part ID to write"),
685
- audio_storage_key: z.string().min(1),
686
- origin_media_id: mediaIdSchema,
687
- volume: volumeSchema
688
- });
689
- //#endregion
690
- //#region src/editor/schemas/set-caption-style.ts
691
- /**
692
- * Set the caption visual style. GLOBAL by design: the style applies to every
693
- * caption part in the document — it carries NO `caption_id`. This mirrors the FE,
694
- * whose caption-style store (`caption-style.ts:persistCaptionStylePatch`) iterates
695
- * ALL captions and writes the same normalized style to each; the product has a
696
- * single document-wide caption style, not per-caption styling.
697
- *
698
- * Every field is optional and maps to a `CaptionStyle` attribute (snake_case
699
- * IDL). A field present in the input is written to every caption; a field ABSENT
700
- * from the input is left untouched on each caption (the editor merges the patch
701
- * onto each caption's existing style — this is a value edit, not a full-style
702
- * replace, so a partial patch such as "recolor only" does not wipe font size).
703
- *
704
- * Pure document edit, no cascade — captions keep their positions; only the style
705
- * sub-map of each caption part changes.
706
- */
707
- const setCaptionStyleInputSchema = z.object({
708
- font_id: z.string().min(1).optional().describe("Font ID referencing a font from the font library"),
709
- font_size: z.number().positive().optional().describe("Font size in points"),
710
- font_color: z.string().min(1).optional().describe("Font color as hex string, e.g. \"#FFFFFF\""),
711
- font_weight: z.number().int().optional().describe("Numeric font weight, e.g. 400 or 700"),
712
- entrance_animation: z.string().optional().describe("Entrance animation preset ID, e.g. \"fade\" or \"none\""),
713
- entrance_animation_duration_ms: z.number().min(0).optional().describe("Entrance animation duration in ms"),
714
- stroke_color: z.string().min(1).optional().describe("Outline/stroke color as hex string, e.g. \"#000000\""),
715
- stroke_width: z.number().min(0).optional().describe("Outline/stroke width in pixels"),
716
- position_x: z.number().optional().describe("Caption center X as a fraction (0.0 to 1.0)"),
717
- position_y: z.number().optional().describe("Caption center Y as a fraction (0.0 to 1.0)")
718
- }).describe("Document-wide caption style patch (no caption_id; applies to every caption)");
719
- //#endregion
720
- //#region src/editor/schemas/set-caption-visibility.ts
721
- /**
722
- * Toggle caption visibility (the caption track's `is_hidden` flag). Pure
723
- * document edit, no cascade — captions keep their positions; only the lane's
724
- * hidden flag changes.
725
- */
726
- const setCaptionVisibilityInputSchema = z.object({ is_hidden: z.boolean().describe("Whether the caption track is hidden") });
727
- //#endregion
728
- //#region src/editor/schemas/set-video-clip-speed-shift.ts
729
- /**
730
- * Set the playback speed of existing video clips. Per the speed-shift decision
731
- * (`reference/16` §0): the op writes only the `speed_shift` fact — it does NOT
732
- * store an effective `duration_ms` (projection derives it from the trim window /
733
- * speed) and does NOT scale anchored speeches' relative offsets (offsets stay
734
- * put; the cascade reflows absolute positions). A `null` speed_shift clears the
735
- * speed back to original (1×).
736
- */
737
- const setVideoClipSpeedShiftInputSchema = z.object({ clips: z.array(z.object({
738
- clip_id: clipIdSchema.describe("The video clip part ID to set speed for"),
739
- speed_shift: speedShiftSchema.nullable().describe("The new speed setting, or null to reset to 1×")
740
- })).min(1).describe("Video clips with their new speed settings") });
741
- //#endregion
742
- //#region src/editor/schemas/index.ts
743
- var schemas_exports = /* @__PURE__ */ __exportAll({
744
- addSpeechesInputSchema: () => addSpeechesInputSchema,
745
- addVideoClipsInputSchema: () => addVideoClipsInputSchema,
746
- adjustBgmVolumeInputSchema: () => adjustBgmVolumeInputSchema,
747
- adjustSpeechVolumeInputSchema: () => adjustSpeechVolumeInputSchema,
748
- adjustVideoClipDurationInputSchema: () => adjustVideoClipDurationInputSchema,
749
- adjustVideoClipVolumeInputSchema: () => adjustVideoClipVolumeInputSchema,
750
- anchoredDeletePolicySchema: () => anchoredDeletePolicySchema,
751
- anchoredReplacePolicySchema: () => anchoredReplacePolicySchema,
752
- changeSpeechScriptInputSchema: () => changeSpeechScriptInputSchema,
753
- changeSpeechVoiceInputSchema: () => changeSpeechVoiceInputSchema,
754
- clipIdSchema: () => clipIdSchema,
755
- clipIdsSchema: () => clipIdsSchema,
756
- deleteBgmInputSchema: () => deleteBgmInputSchema,
757
- deleteSpeechesInputSchema: () => deleteSpeechesInputSchema,
758
- deleteVideoClipsInputSchema: () => deleteVideoClipsInputSchema,
759
- mediaIdSchema: () => mediaIdSchema,
760
- moveAnchorSchema: () => moveAnchorSchema,
761
- moveSpeechesInputSchema: () => moveSpeechesInputSchema,
762
- moveVideoClipsByAnchorInputSchema: () => moveVideoClipsByAnchorInputSchema,
763
- moveVideoClipsInputSchema: () => moveVideoClipsInputSchema,
764
- movedClipAnchoredPolicySchema: () => movedClipAnchoredPolicySchema,
765
- positiveMsSchema: () => positiveMsSchema,
766
- replaceVideoClipContentInputSchema: () => replaceVideoClipContentInputSchema,
767
- replaceVideoClipSequenceInputSchema: () => replaceVideoClipSequenceInputSchema,
768
- setBgmInputSchema: () => setBgmInputSchema,
769
- setCaptionStyleInputSchema: () => setCaptionStyleInputSchema,
770
- setCaptionVisibilityInputSchema: () => setCaptionVisibilityInputSchema,
771
- setVideoClipSpeedShiftInputSchema: () => setVideoClipSpeedShiftInputSchema,
772
- speechAssetsSchema: () => speechAssetsSchema,
773
- speechIdSchema: () => speechIdSchema,
774
- speechIdsSchema: () => speechIdsSchema,
775
- speedShiftSchema: () => speedShiftSchema,
776
- timelineMsSchema: () => timelineMsSchema,
777
- voiceSchema: () => voiceSchema,
778
- volumeSchema: () => volumeSchema
779
- });
2459
+ return moved ? ranges : void 0;
2460
+ }
2461
+ function requirePart(document, partId) {
2462
+ const part = document.part_library?.[partId];
2463
+ if (part === void 0) fail(`Placed Clip ${partId} has no part payload`);
2464
+ return part;
2465
+ }
2466
+ function ensureAudioScript(voiceEntityId, text, entities, relations, addEntity, link) {
2467
+ const renders = relations.filter((relation) => relation.relationKind === "audio-script-render" && relation.endpoint0EntityId === voiceEntityId);
2468
+ if (renders.length > 1) fail(`Voice ${voiceEntityId} has ambiguous AudioScript provenance`);
2469
+ if (renders.length === 1) {
2470
+ const script = entities.find((entity) => entity.entityId === renders[0].endpoint1EntityId && entity.entityKind === "audio-script");
2471
+ if (script === void 0 || scriptText(script) !== text) fail(`Voice ${voiceEntityId} conflicts with the legacy Speech script`);
2472
+ return script.entityId;
2473
+ }
2474
+ const script = addEntity("audio-script", { segments: [{
2475
+ segmentId: "segment-0",
2476
+ text
2477
+ }] });
2478
+ link("audio-script-render", voiceEntityId, script);
2479
+ return script;
2480
+ }
2481
+ function scriptText(script) {
2482
+ const segments = script.payload.segments;
2483
+ if (!Array.isArray(segments)) fail("AudioScript requires segments");
2484
+ return segments.map((segment) => {
2485
+ if (segment === null || typeof segment !== "object" || Array.isArray(segment) || typeof segment.text !== "string") fail("AudioScript segment requires text");
2486
+ return segment.text;
2487
+ }).join("");
2488
+ }
2489
+ function toEntityCaptionStyle(style) {
2490
+ return {
2491
+ ...style.font_id === void 0 ? {} : { font: {
2492
+ system: "font-library",
2493
+ key: style.font_id
2494
+ } },
2495
+ ...style.font_size === void 0 ? {} : { fontSize: style.font_size },
2496
+ ...style.font_color === void 0 ? {} : { fontColor: style.font_color },
2497
+ ...style.font_weight === void 0 ? {} : { fontWeight: style.font_weight },
2498
+ ...style.entrance_animation === void 0 ? {} : { entranceAnimation: style.entrance_animation },
2499
+ ...style.entrance_animation_duration_ms === void 0 ? {} : { entranceAnimationDurationMs: style.entrance_animation_duration_ms },
2500
+ ...style.stroke_color === void 0 ? {} : { strokeColor: style.stroke_color },
2501
+ ...style.stroke_width === void 0 ? {} : { strokeWidth: style.stroke_width },
2502
+ ...style.position_x === void 0 ? {} : { positionX: style.position_x },
2503
+ ...style.position_y === void 0 ? {} : { positionY: style.position_y }
2504
+ };
2505
+ }
2506
+ function assertCaptionStyle(style) {
2507
+ if (style.font_id !== void 0 && !trimmed(style.font_id)) fail("Caption font_id must be a trimmed identity");
2508
+ for (const value of [
2509
+ style.font_size,
2510
+ style.font_weight,
2511
+ style.entrance_animation_duration_ms,
2512
+ style.stroke_width,
2513
+ style.position_x,
2514
+ style.position_y
2515
+ ]) if (value !== void 0) requireFinite(value, "Caption style number");
2516
+ for (const value of [
2517
+ style.font_color,
2518
+ style.entrance_animation,
2519
+ style.stroke_color
2520
+ ]) if (value !== void 0 && typeof value !== "string") fail("Caption style text must be a string");
2521
+ assertKnownFields(style, [
2522
+ "font_id",
2523
+ "font_size",
2524
+ "font_color",
2525
+ "font_weight",
2526
+ "entrance_animation",
2527
+ "entrance_animation_duration_ms",
2528
+ "stroke_color",
2529
+ "stroke_width",
2530
+ "position_x",
2531
+ "position_y"
2532
+ ], "Caption style");
2533
+ }
2534
+ function isRangeStartingAt(value, expectedStart) {
2535
+ return value !== null && typeof value === "object" && !Array.isArray(value) && value.start === expectedStart;
2536
+ }
2537
+ function isExactRange(value, expected) {
2538
+ return value !== null && typeof value === "object" && !Array.isArray(value) && value.start === expected.start && value.end === expected.end;
2539
+ }
2540
+ function requireFinite(value, label) {
2541
+ if (typeof value !== "number" || !Number.isFinite(value)) fail(`${label} must be finite`);
2542
+ return value;
2543
+ }
2544
+ function requireMilliseconds(value, label) {
2545
+ const result = requireFinite(value, label);
2546
+ if (!Number.isSafeInteger(result) || result < 0) fail(`${label} must be non-negative whole milliseconds`);
2547
+ return result;
2548
+ }
2549
+ function requirePositiveMilliseconds(value, label) {
2550
+ const result = requireMilliseconds(value, label);
2551
+ if (result <= 0) fail(`${label} must be positive`);
2552
+ return result;
2553
+ }
2554
+ function trimmed(value) {
2555
+ return typeof value === "string" && value.trim() !== "" && value.trim() === value;
2556
+ }
2557
+ function assertKnownFields(value, fields, label) {
2558
+ if (Object.entries(value).some(([key, field]) => field !== void 0 && !fields.includes(key))) fail(`Unknown legacy ${label} fields require an explicit migration adapter`);
2559
+ }
2560
+ function canonical(value) {
2561
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
2562
+ 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(",")}}`;
2563
+ return JSON.stringify(value) ?? "undefined";
2564
+ }
2565
+ function fail(message) {
2566
+ throw new EntityTimelineProjectionError(message);
2567
+ }
780
2568
  //#endregion
781
2569
  //#region src/editor/snapshot-utils.ts
782
2570
  function isMap(value) {
@@ -1126,9 +2914,11 @@ function readPartLibrary(draft) {
1126
2914
  var SemanticEditor = class {
1127
2915
  doc;
1128
2916
  validator;
1129
- constructor(doc, validator = new SchemaValidator()) {
2917
+ idFactory;
2918
+ constructor(doc, validator = new SchemaValidator(), idFactory = generatePartId) {
1130
2919
  this.doc = doc;
1131
2920
  this.validator = validator;
2921
+ this.idFactory = idFactory;
1132
2922
  }
1133
2923
  async moveVideoClips(input, options) {
1134
2924
  this.validator.validateMoveVideoClips(input, this.doc);
@@ -1208,7 +2998,7 @@ var SemanticEditor = class {
1208
2998
  track.items ??= [];
1209
2999
  let at = insertIndex;
1210
3000
  for (const clip of input.clips) {
1211
- const partId = generatePartId("clip");
3001
+ const partId = this.idFactory("clip");
1212
3002
  setPart(draft, partId, { video_clip: {
1213
3003
  id: partId,
1214
3004
  kind: "video_clip",
@@ -1255,7 +3045,7 @@ var SemanticEditor = class {
1255
3045
  const newItems = [];
1256
3046
  const newClipIds = [];
1257
3047
  for (const clip of input.new_clips) {
1258
- const partId = generatePartId("clip");
3048
+ const partId = this.idFactory("clip");
1259
3049
  setPart(draft, partId, { video_clip: {
1260
3050
  id: partId,
1261
3051
  kind: "video_clip",
@@ -1875,6 +3665,111 @@ function deleteAnchoredSubtree(draft, clipId) {
1875
3665
  for (const speechId of anchored) deleteSpeechSubtree(draft, speechId);
1876
3666
  }
1877
3667
  //#endregion
3668
+ //#region src/editor/journal.ts
3669
+ /**
3670
+ * Wire a plain-memory adapter + editor that share a recording id factory, so
3671
+ * every mutating transact lands in `journal` with ordered `generated_ids`.
3672
+ */
3673
+ function createEditSandbox(document, options) {
3674
+ const adapter = createPlainMemoryAdapter(document, options);
3675
+ return {
3676
+ adapter,
3677
+ editor: new SemanticEditor(adapter, new SchemaValidator(), adapter.idFactory),
3678
+ journal: adapter.journal
3679
+ };
3680
+ }
3681
+ /**
3682
+ * Re-drive `doc` from a recorded journal, forcing each entry's `generated_ids`
3683
+ * through a queue-backed id factory. Never mints fresh ids: an empty queue on
3684
+ * demand throws `unrecorded id`; leftover ids after an entry throws
3685
+ * `unconsumed ids`. Legacy entries without `generated_ids` are treated as `[]`.
3686
+ */
3687
+ async function replayJournal(doc, journal) {
3688
+ const queue = [];
3689
+ const idFactory = (_prefix) => {
3690
+ const id = queue.shift();
3691
+ if (id == null) throw new Error("unrecorded id");
3692
+ return id;
3693
+ };
3694
+ const editor = new SemanticEditor(doc, new SchemaValidator(), idFactory);
3695
+ for (const entry of journal) {
3696
+ queue.push(...entry.generated_ids ?? []);
3697
+ await dispatchEntry(editor, entry);
3698
+ if (queue.length > 0) throw new Error("unconsumed ids");
3699
+ }
3700
+ }
3701
+ /** Dispatch one journal entry to the matching editor method; payload is passed through. */
3702
+ async function dispatchEntry(editor, entry) {
3703
+ const payload = entry.payload;
3704
+ const options = entry.intent != null ? { intent: entry.intent } : void 0;
3705
+ switch (entry.kind) {
3706
+ case "MoveVideoClips":
3707
+ await editor.moveVideoClips(payload, options);
3708
+ return;
3709
+ case "MoveVideoClipsByAnchor":
3710
+ await editor.moveVideoClipsByAnchor(payload, options);
3711
+ return;
3712
+ case "DeleteVideoClips":
3713
+ await editor.deleteVideoClips(payload, options);
3714
+ return;
3715
+ case "AddVideoClips":
3716
+ await editor.addVideoClips(payload, options);
3717
+ return;
3718
+ case "AdjustVideoClipVolume":
3719
+ await editor.adjustVideoClipVolume(payload, options);
3720
+ return;
3721
+ case "SetVideoClipSpeedShift":
3722
+ await editor.setVideoClipSpeedShift(payload, options);
3723
+ return;
3724
+ case "ReplaceVideoClipContent":
3725
+ await editor.replaceVideoClipContent(payload, options);
3726
+ return;
3727
+ case "ReplaceVideoClipSequence":
3728
+ await editor.replaceVideoClipSequence(payload, options);
3729
+ return;
3730
+ case "AdjustVideoClipDuration":
3731
+ await editor.adjustVideoClipDuration(payload, options);
3732
+ return;
3733
+ case "AddSpeeches":
3734
+ await editor.addSpeeches(payload, options);
3735
+ return;
3736
+ case "DeleteSpeeches":
3737
+ await editor.deleteSpeeches(payload, options);
3738
+ return;
3739
+ case "MoveSpeeches":
3740
+ await editor.moveSpeeches(payload, options);
3741
+ return;
3742
+ case "ChangeSpeechScript":
3743
+ await editor.changeSpeechScript(payload, options);
3744
+ return;
3745
+ case "ChangeSpeechVoice":
3746
+ await editor.changeSpeechVoice(payload, options);
3747
+ return;
3748
+ case "AdjustSpeechVolume":
3749
+ await editor.adjustSpeechVolume(payload, options);
3750
+ return;
3751
+ case "SetCaptionVisibility":
3752
+ await editor.setCaptionVisibility(payload, options);
3753
+ return;
3754
+ case "SetCaptionStyle":
3755
+ await editor.setCaptionStyle(payload, options);
3756
+ return;
3757
+ case "SetBgm":
3758
+ await editor.setBgm(payload, options);
3759
+ return;
3760
+ case "DeleteBgm":
3761
+ await editor.deleteBgm(payload, options);
3762
+ return;
3763
+ case "AdjustBgmVolume":
3764
+ await editor.adjustBgmVolume(payload, options);
3765
+ return;
3766
+ default: {
3767
+ const _exhaustive = entry.kind;
3768
+ throw new Error(`replayJournal: unsupported kind ${String(_exhaustive)}`);
3769
+ }
3770
+ }
3771
+ }
3772
+ //#endregion
1878
3773
  //#region src/editor/types.ts
1879
3774
  /** Runtime list of the frozen, implemented kinds (for guards / introspection). */
1880
3775
  const IMPLEMENTED_SEMANTIC_OP_KINDS = [
@@ -2069,6 +3964,18 @@ var ManualSyncDoc = class ManualSyncDoc {
2069
3964
  return fromVideoDocument(this.adapter.snapshot());
2070
3965
  }
2071
3966
  /**
3967
+ * Replay a deterministic sandbox journal into this document.
3968
+ *
3969
+ * The adapter stays private so callers cannot bypass the manual-sync
3970
+ * lifecycle; journal replay is the one host-side operation that needs the
3971
+ * adapter's transaction boundary and recorded id queue. Durability is still
3972
+ * explicit: call {@link push} after replay and report success only from its
3973
+ * verdict.
3974
+ */
3975
+ async replayJournal(journal) {
3976
+ await replayJournal(this.adapter, journal);
3977
+ }
3978
+ /**
2072
3979
  * Mark the document state the caller has just observed, for a later
2073
3980
  * {@link hasChangedSince}.
2074
3981
  *
@@ -2160,7 +4067,6 @@ var ManualSyncDoc = class ManualSyncDoc {
2160
4067
  if (serverVV != null) this.watermark = serverVV;
2161
4068
  return {
2162
4069
  kind: response.kind,
2163
- mengineUpdateSeq: response.version?.update_seq ?? response.update_seq ?? void 0,
2164
4070
  updateSeq: response.update_seq ?? void 0,
2165
4071
  collaborated: serverVV != null && !covers(localVersion, serverVV)
2166
4072
  };
@@ -2279,7 +4185,6 @@ var SseConnection = class {
2279
4185
  for (const update of event.updates) this.onUpdate(update);
2280
4186
  }
2281
4187
  });
2282
- if (!signal.aborted) this.setStatus("connecting", /* @__PURE__ */ new Error("SSE stream closed"));
2283
4188
  } catch (error) {
2284
4189
  if (signal.aborted) break;
2285
4190
  this.setStatus("connecting", error instanceof Error ? error : new Error(String(error)));
@@ -2332,7 +4237,6 @@ var MedeoHttpDocStorage = class {
2332
4237
  async getDoc(docId) {
2333
4238
  this.assertDocId(docId);
2334
4239
  const snapshot = await this.client.fetchSnapshot();
2335
- this.reportServerVersion(snapshot.version?.server_vv);
2336
4240
  const now = /* @__PURE__ */ new Date();
2337
4241
  return {
2338
4242
  docId,
@@ -2344,7 +4248,6 @@ var MedeoHttpDocStorage = class {
2344
4248
  async getDocDiff(docId, knownVersion) {
2345
4249
  this.assertDocId(docId);
2346
4250
  const response = await this.client.sync(knownVersion);
2347
- this.reportServerVersion(response.server_vv);
2348
4251
  return {
2349
4252
  docId,
2350
4253
  missing: base64ToBytes(response.update),
@@ -2375,7 +4278,7 @@ var MedeoHttpDocStorage = class {
2375
4278
  if (update.data.byteLength === 0) return {};
2376
4279
  try {
2377
4280
  const response = await this.client.pushUpdate(update.data);
2378
- const serverVV = this.reportServerVersion(response.version?.server_vv);
4281
+ const serverVV = decodeServerVV(response.version?.server_vv);
2379
4282
  this.events.emit("pushOutcome", {
2380
4283
  kind: response.kind,
2381
4284
  updateSeq: response.update_seq ?? void 0,
@@ -2403,15 +4306,6 @@ var MedeoHttpDocStorage = class {
2403
4306
  subscribePushOutcome(callback) {
2404
4307
  return this.events.on("pushOutcome", callback);
2405
4308
  }
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
4309
  async deleteDoc(_docId) {
2416
4310
  throw new Error("MedeoHttpDocStorage does not support deleteDoc");
2417
4311
  }
@@ -2593,14 +4487,8 @@ var MengineDocSession = class {
2593
4487
  adapterValue = null;
2594
4488
  editorValue = null;
2595
4489
  started = false;
2596
- destroyed = false;
2597
- lifetime = null;
2598
- hasConnected = false;
2599
- initialVersionValue = null;
2600
- localVersionValue = null;
2601
- pushErrorValue = null;
2602
4490
  /**
2603
- * Latest server oplog version seen on an authoritative HTTP response. Lets `waitForServerAck`
4491
+ * Latest server oplog version seen on a push outcome. Lets `waitForServerAck`
2604
4492
  * return without waiting when the server is already known to cover the local
2605
4493
  * doc (e.g. nothing was edited since the last confirmed push).
2606
4494
  */
@@ -2612,7 +4500,8 @@ var MengineDocSession = class {
2612
4500
  this.server = new MedeoHttpDocStorage({
2613
4501
  docId: options.docId,
2614
4502
  client: options.client,
2615
- sseReconnectDelayMs: options.sseReconnectDelayMs
4503
+ sseReconnectDelayMs: options.sseReconnectDelayMs,
4504
+ readonlyMode: options.readonlyMode
2616
4505
  });
2617
4506
  this.synchronizer = new ClientServerSynchronizer(this.local, this.server);
2618
4507
  this.manager = new DocManager(this.local, this.synchronizer);
@@ -2628,14 +4517,14 @@ var MengineDocSession = class {
2628
4517
  return this.server.subscribePushOutcome(callback);
2629
4518
  }
2630
4519
  /**
2631
- * Resolve once the server has durably accepted the local commits as of
4520
+ * Resolve once the server has durably accepted the local document state as of
2632
4521
  * *now* — the capability an Agent tool needs to answer "did my edit land?"
2633
4522
  * before reporting success.
2634
4523
  *
2635
4524
  * Call it right after the editor ops whose durability matters. It snapshots the
2636
- * latest local commit's version (or the loaded baseline before any edit) and
2637
- * resolves when an authoritative server version covers it. Remote-only
2638
- * imports do not extend this target, matching the displayed confirmation state.
4525
+ * local doc's current version and resolves on the first push outcome whose
4526
+ * `serverVV` covers that version, i.e. the server log is at least as advanced as
4527
+ * the local doc was when this was called.
2639
4528
  *
2640
4529
  * Version coverage, not byte identity, is the acceptance test — for two reasons:
2641
4530
  * the ops may reach the server inside a merged blob rather than as the exact
@@ -2650,39 +4539,31 @@ var MengineDocSession = class {
2650
4539
  * @throws {MengineAckFailedError} on timeout, rejection, or transport failure.
2651
4540
  */
2652
4541
  async waitForServerAck(options = {}) {
2653
- if (this.adapterValue == null || this.lifetime == null) throw new Error("mengine doc session is not started");
4542
+ if (this.adapterValue == null) throw new Error("mengine doc session is not started");
2654
4543
  const timeoutMs = options.timeoutMs ?? 15e3;
2655
- const target = this.confirmationTarget() ?? this.manager.connectDoc(this.docId).version();
2656
- const signal = this.lifetime.signal;
4544
+ const target = this.manager.connectDoc(this.docId).version();
2657
4545
  if (this.serverVVValue != null && serverCovers(this.serverVVValue, target)) return;
2658
4546
  await new Promise((resolve, reject) => {
2659
- const cleanup = [];
4547
+ let off = () => {};
2660
4548
  let done = false;
2661
4549
  const settle = (error) => {
2662
4550
  if (done) return;
2663
4551
  done = true;
2664
4552
  clearTimeout(timer);
2665
- cleanup.forEach((off) => off());
4553
+ off();
2666
4554
  if (error == null) resolve();
2667
4555
  else reject(error);
2668
4556
  };
2669
4557
  const timer = setTimeout(() => {
2670
4558
  settle(new MengineAckFailedError("timeout", void 0, void 0, `mengine did not acknowledge the update within ${timeoutMs}ms`));
2671
4559
  }, timeoutMs);
2672
- const onAbort = () => settle(new MengineAckFailedError("failed", void 0, void 0, "mengine doc session destroyed"));
2673
- signal.addEventListener("abort", onAbort, { once: true });
2674
- cleanup.push(() => signal.removeEventListener("abort", onAbort));
2675
- cleanup.push(this.events.on("syncState", () => {
2676
- if (this.serverVVValue != null && serverCovers(this.serverVVValue, target)) settle(void 0);
2677
- }));
2678
- cleanup.push(this.server.subscribePushOutcome((outcome) => {
4560
+ off = this.server.subscribePushOutcome((outcome) => {
2679
4561
  if (outcome.kind === "rejected" || outcome.kind === "failed") {
2680
4562
  settle(new MengineAckFailedError(outcome.kind, outcome.code, outcome.error, outcome.error?.message ?? `mengine push ${outcome.kind}`));
2681
4563
  return;
2682
4564
  }
2683
- }));
2684
- if (signal.aborted) onAbort();
2685
- else this.synchronizer.requestSync(this.docId);
4565
+ if (outcome.serverVV != null && serverCovers(outcome.serverVV, target)) settle(void 0);
4566
+ });
2686
4567
  });
2687
4568
  }
2688
4569
  /**
@@ -2695,6 +4576,24 @@ var MengineDocSession = class {
2695
4576
  if (this.editorValue == null) throw new Error("mengine doc session is not started");
2696
4577
  return this.editorValue;
2697
4578
  }
4579
+ /**
4580
+ * Opaque version token of the local oplog (base64 `VersionVector.encode`).
4581
+ * Equality-comparable only: equal means no observed change (local or
4582
+ * remote-arrived) since the token was taken. Throws when not started.
4583
+ */
4584
+ version() {
4585
+ if (this.adapterValue == null) throw new Error("mengine doc session is not started");
4586
+ return bytesToBase64(this.adapterValue.doc.oplogVersion().encode());
4587
+ }
4588
+ /**
4589
+ * The live document adapter, exposed for journal replay (commit channel).
4590
+ * Replaying through it still goes SemanticEditor → Loro → mengine-server —
4591
+ * no write bypass. Typed by the narrow interface on purpose.
4592
+ */
4593
+ get documentAdapter() {
4594
+ if (this.adapterValue == null) throw new Error("mengine doc session is not started");
4595
+ return this.adapterValue;
4596
+ }
2698
4597
  /** Current document snapshot (read model). */
2699
4598
  snapshot() {
2700
4599
  if (this.adapterValue == null) throw new Error("mengine doc session is not started");
@@ -2708,23 +4607,8 @@ var MengineDocSession = class {
2708
4607
  * surfaces through `subscribe`.
2709
4608
  */
2710
4609
  async start() {
2711
- if (this.destroyed) throw new Error("mengine doc session destroyed");
2712
4610
  if (this.started) return this.snapshot();
2713
4611
  this.started = true;
2714
- this.lifetime = new AbortController();
2715
- this.disposables.add(this.server.subscribeServerVersion((version) => {
2716
- this.serverVVValue = version;
2717
- if (this.getSyncState().confirmation === "confirmed") this.pushErrorValue = null;
2718
- this.emitSyncState();
2719
- }));
2720
- this.disposables.add(this.server.subscribePushOutcome((outcome) => {
2721
- this.pushErrorValue = outcome.kind === "failed" || outcome.kind === "rejected" ? outcome.error ?? /* @__PURE__ */ new Error(`mengine push ${outcome.kind}`) : null;
2722
- this.emitSyncState();
2723
- }));
2724
- this.disposables.add(this.server.connection.onStatusChanged((status) => {
2725
- if (status === "connected") this.hasConnected = true;
2726
- this.emitSyncState();
2727
- }));
2728
4612
  this.local.connection.connect();
2729
4613
  this.server.connection.connect();
2730
4614
  this.disposables.add(() => this.local.connection.disconnect());
@@ -2740,46 +4624,19 @@ var MengineDocSession = class {
2740
4624
  this.disposables.add(() => this.manager.disconnectDoc(this.docId));
2741
4625
  const unsubscribe = doc.subscribe((event) => {
2742
4626
  if (this.adapterValue == null) return;
2743
- if (this.initialVersionValue == null && this.hasContent()) this.initialVersionValue = doc.version();
2744
- if (event.by === "local") this.localVersionValue = doc.version();
2745
- this.emitSyncState();
2746
4627
  this.events.emit("update", {
2747
4628
  source: event.by === "local" ? "local" : "remote",
2748
4629
  snapshot: this.adapterValue.snapshot()
2749
4630
  });
2750
4631
  });
2751
4632
  this.disposables.add(unsubscribe);
2752
- this.disposables.add(this.manager.onDocStateChange(this.docId, (state) => {
2753
- this.events.emit("state", state);
2754
- this.emitSyncState();
4633
+ this.disposables.add(this.manager.onDocStateChange(this.docId, (state) => this.events.emit("state", state)));
4634
+ this.disposables.add(this.server.subscribePushOutcome((outcome) => {
4635
+ if (outcome.serverVV != null) this.serverVVValue = outcome.serverVV;
2755
4636
  }));
2756
4637
  await this.waitForContent();
2757
- this.initialVersionValue ??= doc.version();
2758
- this.emitSyncState();
2759
4638
  return this.snapshot();
2760
4639
  }
2761
- getSyncState() {
2762
- const state = this.getState();
2763
- const target = this.confirmationTarget();
2764
- const confirmation = this.serverVVValue == null || target == null ? this.localVersionValue == null ? "unknown" : "pending" : serverCovers(this.serverVVValue, target) ? "confirmed" : "pending";
2765
- const connection = !this.started ? "disconnected" : this.server.connection.status === "connected" ? "connected" : this.hasConnected || this.server.connection.error != null ? "disconnected" : "connecting";
2766
- return {
2767
- confirmation,
2768
- phase: connection === "disconnected" ? "offline" : this.pushErrorValue != null || state.error != null ? "failed" : connection === "connecting" ? "connecting" : state.syncing ? "syncing" : "idle"
2769
- };
2770
- }
2771
- confirmationTarget() {
2772
- return this.localVersionValue ?? this.initialVersionValue;
2773
- }
2774
- /** Immediately supplies current state; unsubscribe when the host changes docs. */
2775
- subscribeSyncState(cb) {
2776
- const off = this.events.on("syncState", cb);
2777
- cb(this.getSyncState());
2778
- return off;
2779
- }
2780
- emitSyncState() {
2781
- this.events.emit("syncState", this.getSyncState());
2782
- }
2783
4640
  subscribe(cb) {
2784
4641
  return this.events.on("update", cb);
2785
4642
  }
@@ -2790,12 +4647,7 @@ var MengineDocSession = class {
2790
4647
  return this.manager.getDocState(this.docId);
2791
4648
  }
2792
4649
  destroy() {
2793
- if (this.destroyed) return;
2794
- this.destroyed = true;
2795
- this.started = false;
2796
- this.lifetime?.abort();
2797
4650
  this.disposables.dispose();
2798
- this.emitSyncState();
2799
4651
  this.events.clearAll();
2800
4652
  this.adapterValue = null;
2801
4653
  this.editorValue = null;
@@ -2812,21 +4664,13 @@ var MengineDocSession = class {
2812
4664
  */
2813
4665
  async waitForContent() {
2814
4666
  if (this.hasContent()) return;
2815
- const signal = this.lifetime.signal;
2816
- await new Promise((resolve, reject) => {
2817
- const onAbort = () => {
2818
- off();
2819
- reject(/* @__PURE__ */ new Error("mengine doc session destroyed"));
2820
- };
4667
+ await new Promise((resolve) => {
2821
4668
  const off = this.events.on("update", () => {
2822
4669
  if (this.hasContent()) {
2823
4670
  off();
2824
- signal.removeEventListener("abort", onAbort);
2825
4671
  resolve();
2826
4672
  }
2827
4673
  });
2828
- signal.addEventListener("abort", onAbort, { once: true });
2829
- if (signal.aborted) onAbort();
2830
4674
  });
2831
4675
  }
2832
4676
  hasContent() {
@@ -2860,4 +4704,4 @@ function serverCovers(serverVV, target) {
2860
4704
  return covers(server, target);
2861
4705
  }
2862
4706
  //#endregion
2863
- 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, VIDEO_DOCUMENT_SCHEMA_VERSION, 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 };
4707
+ export { DEFAULT_UNIT_TIME_MS, ENTITY_TIMELINE_PROJECTION_SCHEMA_VERSION, EntityGraphHttpClient, EntityTimelineEditor, EntityTimelineProjectionError, IMPLEMENTED_SEMANTIC_OP_KINDS, LANE_KINDS_IN_STACK_ORDER, ManualSyncDoc, MedeoHttpDocStorage, MemoryDocStorage, MengineAckFailedError, MengineDocSession, MengineHttpClient, MengineHttpRequestError, MenginePushRejectedError, MirrorVideoDocumentAdapter, PlainMemoryAdapter, SchemaValidator, SemanticEditor, TIMELINE_SKELETON_DURATION_MS, VIDEO_DOCUMENT_SCHEMA_VERSION, ValidationError, VideoDocumentValidationError, applyEntityTimelineProjection, arrangeMainTrackSeamlessly, assertCanonicalEditorResources, assertEntityProjectionPreservesLegacy, assertMediaAssetWritePolicy, assertValidVideoDocument, base64ToBytes, buildInitialVideoDocument, buildSpeechHostMap, bytesToBase64, cascadeAfterVideoClipChanges, createEditSandbox, createMirrorVideoDocument, createMirrorVideoDocumentAdapter, createPlainMemoryAdapter, decodeDocVersionMark, derivePositionFromAbs, effectiveVideoClipDurationMs, encodeDocVersionMark, ensureEditorFoundation, ensureLaneTrack, fillMainTrackTimeGaps, findLaneTrack, fromVideoDocument, generatePartId, getAt, hostForAbsMs, importMediaAsset, isEmptyVideoClip, isImplementedSemanticOpKind, isMap, laneTrackId, mainTrackRanges, migrateLegacyTimelineToEntities, partDurationMs, partUnionSchema, projectEntityTimeline, readMainTrackItems, readMengineEventStream, readPart, readPartDurationMs, readVideoDocumentFromDraft, reassignSpeechesToVideoClipsByTime, recalculateTimelineDuration, relativePositionForAbs, replayJournal, resolveAllSpeechOverlaps, resolveEntityTimelineLayout, resolveSpeechOverlapByShiftingVideos, safeDurationMs, schemas_exports as schemas, snapshotToPlain, solveVideoDocument, speedOf, syncAggregatedClipsTimePosition, toVideoDocument, validateVideoDocument, videoDocumentMirrorSchema, videoDocumentSchema, writeVideoDocumentToDraft };