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

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