@mengine/medeo-tool 1.4.1-alpha.5 → 2.0.1-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entity-sandbox-BTR2cRl1.mjs","names":["isRecord"],"sources":["../../medeo-dsl/src/entities.ts","../../medeo-dsl/src/ids.ts","../../medeo-dsl/src/json-values.ts","../../medeo-dsl/src/composition.ts","../../medeo-dsl/src/rows.ts","../../medeo-dsl/src/invariants.ts","../../medeo-dsl/src/relation-specs.ts","../../medeo-dsl/src/relations.ts","../../medeo-dsl/src/relation-index.ts","../../medeo-dsl/src/entity-relation-rows.ts","../src/sandbox/business-facades.ts","../src/entity/entity-sandbox.ts"],"sourcesContent":["import type { EntityId } from './ids.ts';\nimport type { JsonObject } from './json-values.ts';\n\nexport type KnownEntityKind =\n | 'axvideo'\n | 'timeline'\n | 'track'\n | 'clip'\n | 'asset'\n | 'video'\n | 'audio'\n | 'voice'\n | 'image'\n | 'sequence-marker'\n | 'viewport'\n | 'audio-script'\n | 'phonetic-script'\n | 'caption';\n\nexport type KnownSequenceEntityKind = 'video' | 'audio' | 'image' | 'caption' | 'axvideo';\ndeclare const extensionEntityKindBrand: unique symbol;\nexport type ExtensionEntityKind = string & { readonly [extensionEntityKindBrand]: 'ExtensionEntityKind' };\n\n/** Extensions require explicit branding so removed or reserved domain kinds cannot reappear accidentally. */\nexport type EntityKind = KnownEntityKind | ExtensionEntityKind;\n\n/**\n * One property an entity shares with other kinds.\n *\n * A Kind is never one-per-entity: naming the object is already `entityKind`'s\n * job, so a declaration that only ever described a single kind would carry no\n * information. Every entry here is held by more than one entity kind, or is\n * open to being.\n */\nexport type Kind = 'Container' | 'Sequence' | 'Visual' | 'Audible' | 'SegmentText' | 'IPBound' | 'FromAsset';\n\n/**\n * What every known entity kind declares.\n *\n * `kinds` is a multi-declaration: every entry holds at the same time, and each\n * is a property shared with other entity kinds — what the object *is* comes\n * from `entityKind` and is never repeated here. The order carries no priority,\n * endpoint role, or edit sequence — an operation asks whether the entity\n * declares the kind it needs, never what its \"main type\" is. An entity kind\n * that shares nothing declares nothing.\n *\n * `Caption` declares `Sequence` on purpose: it owns the display timing of the\n * one AudioScript segment it shows, which is what admits it into a Clip.\n * `Voice` declares no `Sequence` — it is a timbre identity, not playable\n * content; a rendered voiceover is an `audio` entity.\n *\n * No declaration says anything about resources: whether an entity has one, and\n * which, is the `from-asset` Relation's answer alone.\n */\nexport const ENTITY_KINDS: Readonly<Record<KnownEntityKind, readonly Kind[]>> = Object.freeze({\n axvideo: Object.freeze(['Container', 'Sequence', 'Visual', 'Audible'] as const),\n timeline: Object.freeze(['Container'] as const),\n track: Object.freeze(['Container'] as const),\n clip: Object.freeze(['Container'] as const),\n asset: Object.freeze([] as const),\n video: Object.freeze(['Sequence', 'Visual', 'Audible', 'FromAsset'] as const),\n audio: Object.freeze(['Sequence', 'Audible', 'FromAsset'] as const),\n image: Object.freeze(['Sequence', 'Visual', 'FromAsset'] as const),\n voice: Object.freeze(['Container', 'IPBound'] as const),\n 'sequence-marker': Object.freeze([] as const),\n viewport: Object.freeze([] as const),\n 'audio-script': Object.freeze(['SegmentText', 'FromAsset'] as const),\n 'phonetic-script': Object.freeze(['SegmentText'] as const),\n caption: Object.freeze(['SegmentText', 'Sequence', 'FromAsset'] as const),\n});\n\n/** What a known kind declares; extension kinds declare nothing through this table. */\nexport function kindsOf(entityKind: string): readonly Kind[] {\n return isKnownEntityKind(entityKind) ? ENTITY_KINDS[entityKind] : [];\n}\n\nexport function declaresKind(entityKind: string, kind: Kind): boolean {\n return kindsOf(entityKind).includes(kind);\n}\n\nexport type EntityLifecycle = Readonly<Record<string, unknown>>;\n\n/** One independently identified Medeo domain object. Peer associations belong in Relation rows. */\nexport interface MedeoEntity<K extends EntityKind = EntityKind> {\n readonly entityId: EntityId;\n readonly entityKind: K;\n /** Direct variant composition; ordinary associations remain Relation rows. */\n readonly baseEntityIds?: readonly EntityId[];\n readonly lifecycle?: EntityLifecycle;\n}\n\n/**\n * How long an entity's own content runs.\n *\n * A Sequence carries no position: where the content is taken from and where it\n * lands both belong to its Sequence Marker, so the content itself only states\n * its own length. That leaves one degree of freedom and one field, which is why\n * a position can no longer be written here by mistake.\n *\n * `null` means the content has no intrinsic length — a still image runs for as\n * long as its use asks. It is stored as `null` because JSON has no `Infinity`;\n * `resolveDurationMs` hands readers `Infinity` so arithmetic needs no branch.\n *\n * A derived length (an AXVideo's, which its Timeline decides) is not stored at\n * all: a cached copy would drift from the structure that defines it.\n */\nexport interface SequenceFields {\n /** Whole milliseconds, or `null` when the content has no intrinsic length. */\n readonly durationMs: number | null;\n}\n\n/** Read an entity's own length for arithmetic; unbounded content reads as `Infinity`. */\nexport function resolveDurationMs(entity: SequenceFields): number {\n return entity.durationMs ?? Number.POSITIVE_INFINITY;\n}\n\nexport interface SequenceRange<Point = unknown> {\n readonly start: Point;\n readonly end: Point;\n}\n\nexport type SequenceDuration<Span = unknown> =\n | { readonly mode: 'from-source' }\n | { readonly mode: 'fixed'; readonly value: Span };\n\nexport interface ScriptTextSegment {\n readonly segmentId: string;\n readonly text: string;\n readonly language?: string;\n}\n\n/**\n * One directly assigned time value for an AudioScript segment, stored on an\n * annotation Sequence Marker (`audio-script-marker` Relation). `segmentId`\n * quotes the script's own stable segment identity — a local id, never a peer\n * Entity reference. Marker values are assigned by the generation process; they\n * do not reference an upstream Sequence or another Marker.\n */\nexport interface ScriptSegmentRange {\n readonly segmentId: string;\n readonly startMs: number;\n readonly endMs: number;\n}\n\nexport interface ScriptTextFields<Segment extends ScriptTextSegment = ScriptTextSegment> {\n readonly segments: readonly Segment[];\n}\n\n/** Where the bytes live. Only an Asset entity states this. */\nexport interface AssetLocator {\n readonly system: 'memota' | 'memota-speech';\n readonly key: string;\n}\n\nexport interface VoiceDescriptor {\n readonly system: 'voice-library';\n readonly key: string;\n readonly name?: string;\n}\n\nexport interface CaptionFontDescriptor {\n readonly system: 'font-library';\n readonly key: string;\n}\n\nexport interface CaptionStyleFields {\n readonly font?: CaptionFontDescriptor;\n readonly fontSize?: number;\n readonly fontColor?: string;\n readonly fontWeight?: number;\n readonly entranceAnimation?: string;\n readonly entranceAnimationDurationMs?: number;\n readonly strokeColor?: string;\n readonly strokeWidth?: number;\n readonly positionX?: number;\n readonly positionY?: number;\n}\n\nexport type EmptyFields = Readonly<Record<never, never>>;\n\nexport type Timeline = MedeoEntity<'timeline'>;\n\nexport type Track = MedeoEntity<'track'> & {\n readonly hidden?: boolean;\n /** The vocabulary remains deliberately open in Review v8. */\n readonly role?: string;\n /** Stable stacking order among sibling Tracks. */\n readonly order?: number;\n};\n\nexport type Clip = MedeoEntity<'clip'> & {\n /** Stable flow order for a sequential Clip. */\n readonly order?: number;\n /** Playback gain in decibels. */\n readonly volume?: number;\n};\n/**\n * One immutable stored resource. It is the only entity that states where bytes\n * live; every entity made from it reaches it through a `from-asset` Relation,\n * so one resource can back several entities without being copied into each.\n */\nexport type Asset = MedeoEntity<'asset'> & AssetLocator & { readonly storageKey?: string };\n\nexport type MediaAssetVariantKind = 'video' | 'image' | 'audio';\n\nexport type Viewport = MedeoEntity<'viewport'>;\n\nexport type Video = MedeoEntity<'video'> & { readonly durationMs: number };\n\nexport type Audio = MedeoEntity<'audio'> & { readonly durationMs: number };\n\n/**\n * A timbre identity selected for synthesis. Voice is never playable content:\n * a rendered voiceover is an `audio` entity bound back to its Voice by a\n * `voice-timbre` Relation.\n */\nexport type Voice = MedeoEntity<'voice'> & {\n readonly voice: VoiceDescriptor;\n};\n\n/** A still frame has no intrinsic length; each use decides how long it runs. */\nexport type Image = MedeoEntity<'image'> & { readonly durationMs: null };\n\n/** One entity that is both the Asset and its media variant (shared identity). */\nexport type MediaAssetVariant = Video | Image | Audio;\n\n/**\n * Half-open `[start, end)` position window inside one Segment's text, counted\n * in Unicode code points (not UTF-16 code units), so a boundary never splits a\n * surrogate pair. Positions are non-negative safe integers with `start < end`;\n * `end` must not exceed the Segment's code-point length.\n */\nexport interface CaptionTextRange extends JsonObject {\n readonly start: number;\n readonly end: number;\n}\n\n/**\n * The Caption's single text selection. `segmentId` quotes the\n * composed AudioScript's own stable segment identity — a local id quoted by the\n * variant, never a peer Entity reference. Text itself is never copied here;\n * complete Caption content is assembled through its direct baseEntityIds.\n * The optional `textRange` narrows one Segment to an intra-Segment sub-span\n * (intra-segment re-segmentation); without it the whole Segment text is selected.\n */\nexport type CaptionSegmentSelection = JsonObject & {\n readonly segmentId: string;\n readonly textRange?: CaptionTextRange;\n};\n\n/** A selected view of one complete AudioScript; multiple captions may share that text owner. */\nexport type Caption = MedeoEntity<'caption'> &\n SequenceFields & {\n readonly durationMs: number;\n readonly baseEntityIds: readonly EntityId[];\n /** Exactly one segment, optionally narrowed to one contiguous code-point range. */\n readonly selection: CaptionSegmentSelection;\n /** Intrinsic caption timing, independent of a placed Clip display Marker. */\n readonly segmentRanges?: readonly ScriptSegmentRange[];\n readonly style?: CaptionStyleFields;\n };\n\n/**\n * The composed unit. Its length is whatever its Timeline adds up to, so it is\n * derived on read and never stored — a stored copy would drift from the\n * structure that defines it.\n */\nexport type AXVideo = MedeoEntity<'axvideo'>;\n\nexport type AudioScript<Segment extends ScriptTextSegment = ScriptTextSegment> = MedeoEntity<'audio-script'> &\n ScriptTextFields<Segment> & {\n /** Program-owned fingerprint of the last synchronized resource content. */\n readonly assetContentHash?: string;\n };\n\n/**\n * Pronunciation variant of an AudioScript. Its own row stores phoneme and\n * prosody expression only; the base text stays owned by the composed\n * AudioScript and is assembled through direct baseEntityIds.\n * Per-segment phonetic granularity remains an open wire question.\n */\nexport type PhoneticScript = MedeoEntity<'phonetic-script'> & {\n readonly baseEntityIds: readonly EntityId[];\n /** Whole-script phoneme control expression in the target TTS vocabulary. */\n readonly phonemeScript?: string;\n /** Prosody expression; structure stays open until the TTS contract freezes. */\n readonly prosody?: JsonObject;\n};\n\nexport type SequenceMarker<\n SourcePoint = unknown,\n TargetPoint = SourcePoint,\n Span = unknown,\n Remapping = unknown,\n> = MedeoEntity<'sequence-marker'> & {\n readonly sourceRange: SequenceRange<SourcePoint>;\n readonly targetRange?: SequenceRange<TargetPoint>;\n readonly duration: SequenceDuration<Span>;\n readonly timeRemapping?: Remapping;\n /** Offset from the host Clip selected by an ordered clip-anchor Relation. */\n readonly anchorOffset?: Span;\n /** Dynamic playback behavior. The source duration remains authoritative. */\n readonly durationPolicy?: 'timeline';\n /**\n * Directly assigned per-Segment time values for an AudioScript annotation\n * Marker (`audio-script-marker` Relation). Present only in that scenario;\n * annotation Markers cannot enter Clip/AXVideo use chains, and annotating a\n * script never grants it Sequence or Clip admission.\n */\n readonly segmentRanges?: readonly ScriptSegmentRange[];\n};\n\n/**\n * Capability constraint, intentionally open to future entity kinds.\n *\n * The length is optional because an AXVideo declares `Sequence` while deriving\n * its length from its Timeline instead of storing one.\n */\nexport type SequenceEntity<\n K extends KnownSequenceEntityKind | ExtensionEntityKind = KnownSequenceEntityKind | ExtensionEntityKind,\n> = MedeoEntity<K> & Partial<SequenceFields>;\n\nexport function createExtensionEntityKind(value: string): ExtensionEntityKind {\n if (value.length === 0 || value.trim() !== value) {\n throw new Error('ExtensionEntityKind must be a non-empty trimmed string');\n }\n if (isKnownEntityKind(value) || isReservedEntityKind(value)) {\n throw new Error(`Entity kind \"${value}\" is known or reserved and cannot be registered as an extension`);\n }\n return value as ExtensionEntityKind;\n}\n\n/**\n * Sequence admission is a declaration, not a shape: a known kind is admitted\n * because its `kinds` say so, and a malformed payload is a separate, louder\n * failure than a silently non-Sequence entity. Extension kinds declare nothing\n * through the table and stay structurally detected.\n */\nexport function hasSequence(entity: MedeoEntity): entity is SequenceEntity {\n if (isReservedEntityKind(entity.entityKind)) return false;\n if (isKnownEntityKind(entity.entityKind)) return declaresKind(entity.entityKind, 'Sequence');\n return isSequenceFields(entity);\n}\n\nexport function isSequenceFields(value: unknown): value is SequenceFields {\n if (!isRecord(value)) return false;\n const duration = value.durationMs;\n return duration === null || (typeof duration === 'number' && Number.isSafeInteger(duration) && duration > 0);\n}\n\nexport function isKnownSequenceKind(kind: string): kind is KnownSequenceEntityKind {\n return isMediaAssetVariantKind(kind) || kind === 'caption' || kind === 'axvideo';\n}\n\nexport function isMediaAssetVariantKind(kind: string): kind is MediaAssetVariantKind {\n return kind === 'video' || kind === 'image' || kind === 'audio';\n}\n\nexport function isMediaAssetVariant(entity: MedeoEntity): entity is MediaAssetVariant {\n return isMediaAssetVariantKind(entity.entityKind);\n}\n\nexport function isKnownEntityKind(kind: string): kind is KnownEntityKind {\n return Object.hasOwn(ENTITY_KINDS, kind);\n}\n\nexport function isReservedEntityKind(kind: string): boolean {\n const normalized = kind.toLowerCase().replaceAll('-', '').replaceAll('_', '');\n return normalized === 'speech' || normalized === 'videodocument';\n}\n\nexport function isKnownNonSequenceKind(kind: string): boolean {\n return isKnownEntityKind(kind) && !declaresKind(kind, 'Sequence');\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value != null && !Array.isArray(value);\n}\n","declare const entityIdBrand: unique symbol;\ndeclare const relationIdBrand: unique symbol;\n\nexport type EntityId = string & { readonly [entityIdBrand]: 'EntityId' };\nexport type RelationId = string & { readonly [relationIdBrand]: 'RelationId' };\n\nexport function createEntityId(value: string): EntityId {\n return createId(value, 'EntityId') as EntityId;\n}\n\nexport function createRelationId(value: string): RelationId {\n return createId(value, 'RelationId') as RelationId;\n}\n\nfunction createId(value: string, label: string): string {\n if (value.length === 0 || value.trim() !== value) throw new Error(`${label} must be a non-empty trimmed string`);\n return value;\n}\n","export type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[];\nexport type JsonObject = { readonly [key: string]: JsonValue };\n\nconst nativeObjectConstructorSource = Function.prototype.toString.call(Object);\n\nexport function isJsonObject(value: unknown): value is JsonObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value) && isJsonValue(value, new Set());\n}\n\nfunction isJsonValue(value: unknown, ancestors: Set<object>): value is JsonValue {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return true;\n if (typeof value === 'number') return Number.isFinite(value);\n if (typeof value !== 'object') return false;\n\n if (!Array.isArray(value) && !isPlainObject(value)) return false;\n if (ancestors.has(value)) return false;\n\n ancestors.add(value);\n const valid = Array.isArray(value)\n ? value.every((item) => isJsonValue(item, ancestors))\n : Object.values(value).every((item) => isJsonValue(item, ancestors));\n ancestors.delete(value);\n return valid;\n}\n\n/** Recognize an ordinary object from any VM realm without admitting class instances. */\nfunction isPlainObject(value: object): boolean {\n try {\n const prototype = Object.getPrototypeOf(value);\n if (prototype === null) return true;\n if (Object.getPrototypeOf(prototype) !== null) return false;\n const constructor = Object.getOwnPropertyDescriptor(prototype, 'constructor')?.value;\n return (\n typeof constructor === 'function' &&\n constructor.prototype === prototype &&\n Function.prototype.toString.call(constructor) === nativeObjectConstructorSource\n );\n } catch {\n return false;\n }\n}\n","import type { CaptionSegmentSelection, ScriptTextSegment } from './entities.ts';\nimport { createEntityId, type EntityId } from './ids.ts';\nimport { isJsonObject, type JsonObject } from './json-values.ts';\nimport type { EntityRelationRows, EntityRow } from './rows.ts';\n\nexport type ScriptCompositionIssueCode =\n | 'field_conflict'\n | 'composition_cycle'\n | 'invalid_bases'\n | 'composition_missing'\n | 'composition_ambiguous'\n | 'composition_dangling'\n | 'unknown_segment'\n | 'empty_selection'\n | 'invalid_script'\n | 'invalid_selection';\n\n/** Assembly fails explicitly when declared bases cannot provide valid, unambiguous content. */\nexport class ScriptCompositionError extends Error {\n constructor(\n readonly code: ScriptCompositionIssueCode,\n readonly entityId: EntityId,\n message: string,\n ) {\n super(message);\n this.name = 'ScriptCompositionError';\n }\n}\n\nexport interface AssembledCaptionContent {\n readonly caption: EntityRow<'caption'>;\n readonly audioScript: EntityRow<'audio-script'>;\n /** Selected AudioScript segments in Caption selection order. */\n readonly segments: readonly ScriptTextSegment[];\n /**\n * Where the selected segment sits in the AudioScript's ordered segments.\n *\n * A Caption locates its text as AudioScript plus index. The selection is\n * stored as the segment's own stable id rather than this ordinal, so a\n * concurrent insert or re-segmentation cannot silently slide a Caption onto\n * different text; the ordinal is derived here for readers that want the\n * position.\n */\n readonly segmentIndex: number;\n /** Complete display text: the selected segments' text joined in order. */\n readonly text: string;\n}\n\nexport interface AssembledPhoneticScriptContent {\n readonly phoneticScript: EntityRow<'phonetic-script'>;\n readonly audioScript: EntityRow<'audio-script'>;\n /** All AudioScript segments in script order; the pronunciation variant never reorders text. */\n readonly segments: readonly ScriptTextSegment[];\n /** Complete base text owned by the AudioScript. */\n readonly text: string;\n}\n\n/** Direct base IDs are structural fields, never ordinary Relation endpoints. */\nexport function variantBaseEntityIds(entity: EntityRow): readonly EntityId[] {\n if (!Object.hasOwn(entity.payload, 'baseEntityIds')) return [];\n const ids = entity.payload.baseEntityIds;\n if (\n !Array.isArray(ids) ||\n ids.length === 0 ||\n !ids.every((id) => typeof id === 'string' && id.trim() === id && id.length > 0) ||\n new Set(ids).size !== ids.length\n )\n throw new ScriptCompositionError(\n 'invalid_bases',\n entity.entityId,\n `Entity \"${entity.entityId}\" requires non-empty, unique baseEntityIds`,\n );\n return (ids as string[]).map(createEntityId);\n}\n\n/** Validate all base providers before applying explicit own fields; ordering cannot resolve ambiguity. */\nexport function assembleEntityContent(rows: EntityRelationRows, entityId: EntityId): EntityRow {\n const byId = new Map<EntityId, EntityRow>();\n for (const row of rows.entities) {\n if (byId.has(row.entityId))\n throw new ScriptCompositionError('composition_ambiguous', row.entityId, `duplicate entity id \"${row.entityId}\"`);\n byId.set(row.entityId, row);\n }\n const active = new Set<EntityId>();\n const cache = new Map<EntityId, EntityRow>();\n const visit = (id: EntityId): EntityRow => {\n const cached = cache.get(id);\n if (cached !== undefined) return cached;\n if (active.has(id)) throw new ScriptCompositionError('composition_cycle', id, `Cyclic baseEntityIds at \"${id}\"`);\n const row = byId.get(id);\n if (row === undefined)\n throw new ScriptCompositionError('composition_dangling', id, `Missing base entity \"${id}\" in this document`);\n if (\n !isJsonObject(row.payload) ||\n Object.hasOwn(row.payload, 'entityId') ||\n Object.hasOwn(row.payload, 'entityKind')\n )\n throw new ScriptCompositionError(\n 'invalid_bases',\n id,\n `Entity \"${id}\" requires JSON own fields without reserved identity fields`,\n );\n active.add(id);\n const inherited: JsonObject = {};\n const providers = new Map<string, EntityId>();\n for (const baseId of variantBaseEntityIds(row)) {\n const base = visit(baseId);\n for (const [field, value] of Object.entries(base.payload)) {\n if (field === 'baseEntityIds') continue;\n const previous = providers.get(field);\n if (previous !== undefined)\n throw new ScriptCompositionError(\n 'field_conflict',\n id,\n `Entity \"${id}\" field \"${field}\" conflicts between bases \"${previous}\" and \"${baseId}\"; own fields cannot resolve base ambiguity`,\n );\n providers.set(field, baseId);\n Object.defineProperty(inherited, field, { value, enumerable: true, configurable: true, writable: true });\n }\n }\n const assembled: EntityRow = {\n ...row,\n payload: JSON.parse(JSON.stringify({ ...inherited, ...row.payload })) as JsonObject,\n };\n active.delete(id);\n cache.set(id, assembled);\n return assembled;\n };\n return visit(entityId);\n}\n\n/** Resolve a field's declaring entity after validating the entire composition. */\nexport function resolveEntityFieldOwner(rows: EntityRelationRows, entityId: EntityId, field: string): EntityId {\n assembleEntityContent(rows, entityId);\n const byId = new Map(rows.entities.map((row) => [row.entityId, row]));\n const find = (id: EntityId): EntityId | undefined => {\n const row = byId.get(id)!;\n if (Object.hasOwn(row.payload, field)) return id;\n if (field === 'baseEntityIds') return undefined;\n for (const baseId of variantBaseEntityIds(row)) {\n const owner = find(baseId);\n if (owner !== undefined) return owner;\n }\n return undefined;\n };\n return find(entityId) ?? entityId;\n}\n\n/** Patch assembled fields without copying inherited fields into the variant's stored payload. */\nexport function updateEntityFields(\n rows: EntityRelationRows,\n entityId: EntityId,\n fields: JsonObject,\n): readonly EntityRow[] {\n assembleEntityContent(rows, entityId);\n if (!isJsonObject(fields) || Object.hasOwn(fields, 'entityId') || Object.hasOwn(fields, 'entityKind'))\n throw new ScriptCompositionError(\n 'invalid_bases',\n entityId,\n 'Field updates require JSON without reserved identity fields',\n );\n const updates = new Map<EntityId, EntityRow>();\n for (const [field, value] of Object.entries(fields)) {\n const ownerId = resolveEntityFieldOwner(rows, entityId, field);\n const owner = updates.get(ownerId) ?? rows.entities.find((row) => row.entityId === ownerId)!;\n updates.set(ownerId, { ...owner, payload: { ...owner.payload, [field]: value } });\n }\n return [...updates.values()].map((row) => JSON.parse(JSON.stringify(row)) as EntityRow);\n}\n\n/** Find the actual AudioScript text owner through direct variant bases. */\nexport function findComposedAudioScript(\n rows: EntityRelationRows,\n variantEntityId: EntityId,\n variantKind: 'caption' | 'phonetic-script',\n): EntityRow<'audio-script'> {\n const variant = requireEntityKind(rows, variantEntityId, variantKind);\n assembleEntityContent(rows, variantEntityId);\n const sources = new Map<EntityId, EntityRow<'audio-script'>>();\n const seen = new Set<EntityId>();\n const visit = (row: EntityRow): void => {\n for (const id of variantBaseEntityIds(row)) {\n if (seen.has(id)) continue;\n seen.add(id);\n const base = rows.entities.find((candidate) => candidate.entityId === id)!;\n if (base.entityKind === 'audio-script')\n sources.set(id, assembleEntityContent(rows, id) as EntityRow<'audio-script'>);\n else visit(base);\n }\n };\n visit(variant);\n if (sources.size !== 1)\n throw new ScriptCompositionError(\n sources.size === 0 ? 'composition_missing' : 'composition_ambiguous',\n variantEntityId,\n `${variantKind} \"${variantEntityId}\" baseEntityIds must resolve one AudioScript text owner, got ${sources.size}`,\n );\n return [...sources.values()][0]!;\n}\n\n/** Join the whole AudioScript text in segment order. */\nexport function assembleScriptText(script: EntityRow<'audio-script'>): string {\n return scriptSegments(script)\n .map((segment) => segment.text)\n .join('');\n}\n\nfunction scriptSegments(script: EntityRow<'audio-script'>): readonly ScriptTextSegment[] {\n const segments = script.payload.segments;\n if (!Array.isArray(segments)) {\n throw new ScriptCompositionError(\n 'composition_dangling',\n script.entityId,\n `AudioScript \"${script.entityId}\" requires segments`,\n );\n }\n if (!segments.every(isScriptSegment) || new Set(segments.map((s) => s.segmentId)).size !== segments.length) {\n throw new ScriptCompositionError(\n 'invalid_script',\n script.entityId,\n 'AudioScript requires valid segments with unique local segmentId and text',\n );\n }\n return segments;\n}\n\nfunction isScriptSegment(value: unknown): value is ScriptTextSegment {\n if (typeof value !== 'object' || value == null || Array.isArray(value)) return false;\n const segment = value as Record<string, unknown>;\n return (\n typeof segment.segmentId === 'string' &&\n segment.segmentId.trim() !== '' &&\n typeof segment.text === 'string' &&\n (segment.language === undefined || typeof segment.language === 'string')\n );\n}\n\n/** Assemble selected text after base-field validation and explicit variant overrides. */\nexport function assembleCaptionContent(rows: EntityRelationRows, captionEntityId: EntityId): AssembledCaptionContent {\n requireEntityKind(rows, captionEntityId, 'caption');\n const caption = assembleEntityContent(rows, captionEntityId) as EntityRow<'caption'>;\n const script = findComposedAudioScript(rows, captionEntityId, 'caption');\n const selection = captionSelection(caption);\n const composed = { ...script, payload: caption.payload };\n const segment = selectAudioScriptSegment(composed, selection);\n return {\n caption,\n audioScript: script,\n segments: [segment],\n segmentIndex: scriptSegments(composed).findIndex((entry) => entry.segmentId === selection.segmentId),\n text: segment.text,\n };\n}\n\n/**\n * Assemble the complete Phonetic Script content for TTS: the composed\n * AudioScript's base text plus the variant's own phoneme and prosody fields.\n */\nexport function assemblePhoneticScriptContent(\n rows: EntityRelationRows,\n phoneticScriptEntityId: EntityId,\n): AssembledPhoneticScriptContent {\n requireEntityKind(rows, phoneticScriptEntityId, 'phonetic-script');\n const phoneticScript = assembleEntityContent(rows, phoneticScriptEntityId) as EntityRow<'phonetic-script'>;\n const audioScript = findComposedAudioScript(rows, phoneticScriptEntityId, 'phonetic-script');\n const segments = scriptSegments({ ...audioScript, payload: phoneticScript.payload });\n return {\n phoneticScript,\n audioScript,\n segments,\n text: segments.map((segment) => segment.text).join(''),\n };\n}\n\nfunction captionSelection(caption: EntityRow<'caption'>): CaptionSegmentSelection {\n if (Object.hasOwn(caption.payload, 'selections') || !isSegmentSelection(caption.payload.selection))\n throw new ScriptCompositionError(\n 'invalid_selection',\n caption.entityId,\n 'Caption requires one selection object with segmentId and optional textRange; selections arrays are forbidden',\n );\n return caption.payload.selection;\n}\n\nfunction isSegmentSelection(value: unknown): value is CaptionSegmentSelection {\n return (\n typeof value === 'object' &&\n value != null &&\n !Array.isArray(value) &&\n typeof (value as CaptionSegmentSelection).segmentId === 'string' &&\n (value as CaptionSegmentSelection).segmentId.trim() !== '' &&\n Object.keys(value).every((key) => key === 'segmentId' || key === 'textRange')\n );\n}\n\n/** Select source text without creating another authoritative text field. */\nexport function selectAudioScriptSegment(\n script: EntityRow<'audio-script'>,\n selection: CaptionSegmentSelection,\n): ScriptTextSegment {\n if (!isSegmentSelection(selection))\n throw new ScriptCompositionError(\n 'invalid_selection',\n script.entityId,\n 'Caption requires one selection object with segmentId and optional textRange',\n );\n const bySegmentId = new Map(scriptSegments(script).map((segment) => [segment.segmentId, segment]));\n const selected = (() => {\n const segment = bySegmentId.get(selection.segmentId);\n if (segment === undefined) {\n throw new ScriptCompositionError(\n 'unknown_segment',\n script.entityId,\n `Caption selection \"${selection.segmentId}\" does not name a segment of AudioScript \"${script.entityId}\"`,\n );\n }\n if (selection.textRange === undefined) return segment;\n const range = selection.textRange;\n const points = Array.from(segment.text);\n if (\n typeof range !== 'object' ||\n range === null ||\n !Number.isSafeInteger(range.start) ||\n !Number.isSafeInteger(range.end) ||\n range.start < 0 ||\n range.end <= range.start ||\n range.end > points.length ||\n Object.keys(range).some((key) => key !== 'start' && key !== 'end')\n ) {\n throw new ScriptCompositionError(\n 'invalid_selection',\n script.entityId,\n 'Caption textRange must be a non-empty half-open Unicode code-point range within its source segment',\n );\n }\n return { ...segment, text: points.slice(range.start, range.end).join('') };\n })();\n if (!selected.text.trim())\n throw new ScriptCompositionError(\n 'empty_selection',\n script.entityId,\n 'Caption selection must contain visible source text',\n );\n return selected;\n}\n\nfunction requireEntityKind<K extends EntityRow['entityKind']>(\n rows: EntityRelationRows,\n entityIdValue: string,\n entityKind: K,\n): EntityRow<K> {\n const entity = rows.entities.find((candidate) => candidate.entityId === entityIdValue);\n if (entity === undefined) {\n throw new ScriptCompositionError(\n 'composition_dangling',\n entityIdValue as EntityId,\n `Entity \"${entityIdValue}\" does not exist`,\n );\n }\n if (entity.entityKind !== entityKind) {\n throw new ScriptCompositionError(\n 'composition_dangling',\n entityIdValue as EntityId,\n `Entity \"${entityIdValue}\" must have kind \"${entityKind}\", got \"${entity.entityKind}\"`,\n );\n }\n return entity as EntityRow<K>;\n}\n","import type { EntityKind, MedeoEntity } from './entities.ts';\nimport type { EntityId } from './ids.ts';\nimport { isJsonObject, type JsonObject } from './json-values.ts';\nimport type { RelationRow } from './relations.ts';\n\n/** One persisted first-class entity. Its owned fields live directly in payload. */\nexport interface EntityRow<K extends EntityKind = EntityKind> {\n readonly entityId: EntityId;\n readonly entityKind: K;\n readonly payload: JsonObject;\n}\n\n/** Complete persistence value for an entity set and its authoritative relations. */\nexport interface EntityRelationRows {\n readonly entities: readonly EntityRow[];\n readonly relations: readonly RelationRow[];\n}\n\nexport function entityToRow<K extends EntityKind>(entity: MedeoEntity<K>): EntityRow<K> {\n const { entityId, entityKind, ...payload } = entity;\n if (!isJsonObject(payload)) {\n throw new Error(`Entity \"${entityId}\" payload must contain only JSON values`);\n }\n return { entityId, entityKind, payload };\n}\n","import { assembleEntityContent, assembleCaptionContent, assemblePhoneticScriptContent } from './composition.ts';\nimport {\n hasSequence,\n isReservedEntityKind,\n type AXVideo,\n type AudioScript,\n type Caption,\n type Clip,\n type MedeoEntity,\n type PhoneticScript,\n type SequenceMarker,\n} from './entities.ts';\nimport type { EntityId } from './ids.ts';\nimport type { BiRelationIndex } from './relation-index.ts';\nimport type { EntityRef, RelationAny } from './relations.ts';\nimport { entityToRow } from './rows.ts';\n\nexport type EntityRelationIssueCode =\n | 'invalid_variant_composition'\n | 'invalid_sequence_composition'\n | 'marker_container_xor'\n | 'marker_content_xor'\n | 'marker_pair_mismatch'\n | 'marker_source_range_empty'\n | 'marker_target_range_empty'\n | 'marker_source_out_of_bounds'\n | 'clip_marker_cardinality'\n | 'clip_content_cardinality'\n | 'clip_content_not_sequence'\n | 'axvideo_marker_cardinality'\n | 'caption_composition_required'\n | 'phonetic_script_composition_required'\n | 'caption_selection_invalid'\n | 'asset_source_cardinality'\n | 'clip_anchor_cardinality'\n | 'clip_anchor_cycle'\n | 'clip_placement_invalid'\n | 'timeline_duration_policy_invalid'\n | 'forbidden_entity_kind'\n | 'invalid_entity_payload'\n | 'peer_entity_id_field'\n | 'duplicate_entity_id';\n\nexport interface EntityRelationIssue {\n readonly code: EntityRelationIssueCode;\n readonly entityId: EntityId;\n readonly message: string;\n}\n\nexport interface MarkerRangeComparators<SourcePoint = unknown, TargetPoint = unknown> {\n readonly source: (left: SourcePoint, right: SourcePoint) => number;\n readonly target: (left: TargetPoint, right: TargetPoint) => number;\n}\n\nexport interface EntityRelationValidationOptions {\n readonly compareMarkerPoints: (\n marker: EntityRef<SequenceMarker>,\n range: 'source' | 'target',\n left: unknown,\n right: unknown,\n ) => number;\n}\n\n/** An entity is made from at most one Asset; two would leave its bytes ambiguous. */\nfunction validateAssetSource(entity: EntityRef, index: BiRelationIndex): EntityRelationIssue[] {\n // One Asset is shared by every entity made from it, so the cardinality rule\n // applies to the side that is made from bytes, never to the bytes themselves.\n if (entity.current().entityKind === 'asset') return [];\n const links = [...index.relationsOf(entity)].filter((relation) => relation.kind === 'from-asset');\n if (links.length <= 1) return [];\n return [\n {\n code: 'asset_source_cardinality' as const,\n entityId: entity.entityId,\n message: `Entity \"${entity.entityId}\" is made from more than one Asset`,\n },\n ];\n}\n\n/** Validates one complete set of entities and its authoritative Relation rows. */\nexport function validateEntityRelationSet(\n entityRefs: readonly EntityRef[],\n index: BiRelationIndex,\n options: EntityRelationValidationOptions,\n): EntityRelationIssue[] {\n const { entities, issues } = collectRelatedEntities(entityRefs, index);\n const entityIds = new Set(entities.map((entity) => entity.entityId));\n const rows = { entities: entities.map((entity) => entityToRow(entity.current())), relations: [] };\n for (const entity of entities) {\n try {\n assembleEntityContent(rows, entity.entityId);\n } catch (error) {\n issues.push({\n code: 'invalid_variant_composition',\n entityId: entity.entityId,\n message: error instanceof Error ? error.message : 'Invalid variant composition',\n });\n }\n }\n for (const entity of entities) {\n const current = entity.current();\n const entityIssues = validateEntity(entity, entityIds);\n issues.push(...entityIssues);\n issues.push(...validateAssetSource(entity, index));\n if (entityIssues.some((issue) => issue.code === 'invalid_entity_payload')) continue;\n if (current.entityKind === 'sequence-marker') {\n const marker = entity as EntityRef<SequenceMarker>;\n issues.push(...validateMarkerUse(entity as EntityRef<SequenceMarker>, index));\n issues.push(\n ...validateMarkerRanges(marker, {\n source: (left, right) => options.compareMarkerPoints(marker, 'source', left, right),\n target: (left, right) => options.compareMarkerPoints(marker, 'target', left, right),\n }),\n );\n issues.push(\n ...validateMarkerSourceBounds(marker, index, (left, right) =>\n options.compareMarkerPoints(marker, 'source', left, right),\n ),\n );\n }\n if (current.entityKind === 'clip') {\n issues.push(...validateClipAdmission(entity as EntityRef<Clip>, index));\n issues.push(...validateClipPlacement(entity as EntityRef<Clip>, index));\n }\n if (current.entityKind === 'axvideo') issues.push(...validateAXVideoAdmission(entity as EntityRef<AXVideo>, index));\n if (current.entityKind === 'caption')\n issues.push(...validateCaptionComposition(entity as EntityRef<Caption>, index, entities));\n if (current.entityKind === 'phonetic-script')\n issues.push(...validatePhoneticComposition(entity as EntityRef<PhoneticScript>, index, entities));\n issues.push(...validateSequenceComposition(entity));\n }\n issues.push(...validateClipAnchorCycles(entities, index));\n return issues;\n}\n\nexport function validateMarkerUse(marker: EntityRef<SequenceMarker>, index: BiRelationIndex): EntityRelationIssue[] {\n const relations = [...index.relationsOf(marker)];\n const clipEdges = ofKind(relations, 'clip-marker');\n const axVideoEdges = ofKind(relations, 'axvideo-marker');\n const contentEdges = ofKind(relations, 'marker-content');\n const timelineEdges = ofKind(relations, 'marker-timeline');\n const scriptEdges = ofKind(relations, 'audio-script-marker');\n const issues: EntityRelationIssue[] = [];\n\n if (scriptEdges.length > 0) {\n // AudioScript annotation Markers are a separate scenario: they carry only\n // their directly assigned segmentRanges and never join a container use chain.\n if (clipEdges.length + axVideoEdges.length + contentEdges.length + timelineEdges.length > 0) {\n issues.push({\n code: 'marker_container_xor',\n entityId: marker.entityId,\n message: 'An AudioScript annotation Marker must not carry Clip, AXVideo, content, or Timeline relations',\n });\n }\n const ranges = marker.current().segmentRanges;\n if (!ranges?.length) {\n issues.push({\n code: 'invalid_entity_payload',\n entityId: marker.entityId,\n message: 'An AudioScript annotation Marker requires segmentRanges',\n });\n }\n for (const relation of scriptEdges) {\n const script = relation.other(marker)?.deref()?.current();\n if (script?.entityKind !== 'audio-script') continue;\n const segments = (script as AudioScript).segments;\n if (!Array.isArray(segments)) continue;\n const segmentIds = new Set(segments.map((segment) => segment.segmentId));\n if (ranges?.some((range) => !segmentIds.has(range.segmentId))) {\n issues.push({\n code: 'invalid_entity_payload',\n entityId: marker.entityId,\n message: 'Annotation segmentRanges must name segments of the related AudioScript',\n });\n }\n }\n return issues;\n }\n if (marker.current().segmentRanges !== undefined) {\n issues.push({\n code: 'invalid_entity_payload',\n entityId: marker.entityId,\n message: 'segmentRanges belongs to an AudioScript annotation Marker, not a display Marker',\n });\n }\n\n if (clipEdges.length + axVideoEdges.length !== 1) {\n issues.push({\n code: 'marker_container_xor',\n entityId: marker.entityId,\n message: 'Sequence Marker must have exactly one Clip XOR AXVideo container relation',\n });\n }\n if (contentEdges.length + timelineEdges.length !== 1) {\n issues.push({\n code: 'marker_content_xor',\n entityId: marker.entityId,\n message: 'Sequence Marker must have exactly one Sequence content XOR Timeline relation',\n });\n }\n if (\n (clipEdges.length === 1 && timelineEdges.length === 1) ||\n (axVideoEdges.length === 1 && contentEdges.length === 1)\n ) {\n issues.push({\n code: 'marker_pair_mismatch',\n entityId: marker.entityId,\n message: 'Only Clip+Content or AXVideo+Timeline Marker relation pairs are valid',\n });\n }\n return issues;\n}\n\nexport function validateClipAdmission(clip: EntityRef<Clip>, index: BiRelationIndex): EntityRelationIssue[] {\n const markerEdges = ofKind([...index.relationsOf(clip)], 'clip-marker');\n if (markerEdges.length !== 1) {\n return [\n {\n code: 'clip_marker_cardinality',\n entityId: clip.entityId,\n message: 'Clip must have exactly one authoritative Clip-Marker Relation',\n },\n ];\n }\n\n const marker = markerEdges[0]?.other(clip)?.deref();\n if (marker == null) {\n return [\n {\n code: 'clip_content_cardinality',\n entityId: clip.entityId,\n message: 'Clip must resolve one live Sequence Marker and one content Relation',\n },\n ];\n }\n const contentEdges = ofKind([...index.relationsOf(marker)], 'marker-content');\n if (contentEdges.length !== 1) {\n return [\n {\n code: 'clip_content_cardinality',\n entityId: clip.entityId,\n message: 'Clip Marker must resolve exactly one content Relation',\n },\n ];\n }\n const content = contentEdges[0]?.other(marker)?.deref()?.current();\n if (content == null) {\n return [\n {\n code: 'clip_content_cardinality',\n entityId: clip.entityId,\n message: 'Clip Marker content Relation must resolve one live entity',\n },\n ];\n }\n if (!hasSequence(content)) {\n return [\n {\n code: 'clip_content_not_sequence',\n entityId: clip.entityId,\n message: `Clip Marker resolves to non-Sequence entity \"${content.entityId}\"`,\n },\n ];\n }\n return [];\n}\n\nexport function validateAXVideoAdmission(axVideo: EntityRef<AXVideo>, index: BiRelationIndex): EntityRelationIssue[] {\n const markerEdges = ofKind([...index.relationsOf(axVideo)], 'axvideo-marker');\n if (markerEdges.length === 1 && markerEdges[0]?.other(axVideo)?.deref() != null) return [];\n return [\n {\n code: 'axvideo_marker_cardinality',\n entityId: axVideo.entityId,\n message: 'AXVideo must have exactly one live AXVideo-Marker Relation',\n },\n ];\n}\n\n/** Validate a Caption against the complete entity set, including its directly held bases. */\nexport function validateCaptionComposition(\n caption: EntityRef<Caption>,\n index: BiRelationIndex,\n entities: readonly EntityRef[] = [],\n): EntityRelationIssue[] {\n return validateVariantComposition(caption, index, entities, 'caption');\n}\n\nexport function validatePhoneticComposition(\n phonetic: EntityRef<PhoneticScript>,\n index: BiRelationIndex,\n entities: readonly EntityRef[] = [],\n): EntityRelationIssue[] {\n return validateVariantComposition(phonetic, index, entities, 'phonetic-script');\n}\n\nfunction validateVariantComposition(\n variant: EntityRef,\n index: BiRelationIndex,\n entities: readonly EntityRef[],\n kind: 'caption' | 'phonetic-script',\n): EntityRelationIssue[] {\n const issues: EntityRelationIssue[] = [];\n const refs = collectRelatedEntities([...entities, variant], index).entities;\n const rows = { entities: refs.map((ref) => entityToRow(ref.current())), relations: [] };\n try {\n if (kind === 'caption') assembleCaptionContent(rows, variant.entityId);\n else assemblePhoneticScriptContent(rows, variant.entityId);\n } catch (error) {\n issues.push({\n code: kind === 'caption' ? 'caption_composition_required' : 'phonetic_script_composition_required',\n entityId: variant.entityId,\n message: error instanceof Error ? error.message : 'Invalid variant composition',\n });\n }\n return issues;\n}\n\nexport function validateClipPlacement(clip: EntityRef<Clip>, index: BiRelationIndex): EntityRelationIssue[] {\n const markerEdge = ofKind([...index.relationsOf(clip)], 'clip-marker')[0];\n const marker = markerEdge?.other(clip)?.deref();\n if (marker?.current().entityKind !== 'sequence-marker') return [];\n const markerValue = marker.current() as SequenceMarker;\n const anchors = ofKind([...index.relationsOf(clip)], 'clip-anchor').filter(\n (relation) => relation.endpoints[0].deref() === clip,\n );\n const hasOrder = clip.current().order !== undefined;\n const hasTarget = markerValue.targetRange !== undefined;\n const hasAnchorOffset = markerValue.anchorOffset !== undefined;\n const issues: EntityRelationIssue[] = [];\n if (anchors.length > 1) {\n issues.push({\n code: 'clip_anchor_cardinality',\n entityId: clip.entityId,\n message: 'A Clip may follow at most one host Clip',\n });\n }\n const hasAnchor = anchors.length === 1;\n if (\n (hasAnchor && (!hasAnchorOffset || hasOrder || hasTarget)) ||\n (!hasAnchor && (hasAnchorOffset || Number(hasOrder) + Number(hasTarget) !== 1))\n ) {\n issues.push({\n code: 'clip_placement_invalid',\n entityId: clip.entityId,\n message:\n 'Clip placement must be exactly one of Clip.order, Marker.targetRange, or clip-anchor with Marker.anchorOffset',\n });\n }\n if (markerValue.durationPolicy === 'timeline') {\n const content = ofKind([...index.relationsOf(marker)], 'marker-content')[0]\n ?.other(marker)\n ?.deref()\n ?.current();\n const track = ofKind([...index.relationsOf(clip)], 'track-clip')[0]\n ?.other(clip)\n ?.deref()\n ?.current();\n const trackRole =\n track?.entityKind === 'track' ? (track as unknown as Readonly<Record<string, unknown>>).role : undefined;\n if (content?.entityKind !== 'audio' || trackRole !== 'bgm' || (!hasOrder && !hasTarget)) {\n issues.push({\n code: 'timeline_duration_policy_invalid',\n entityId: marker.entityId,\n message:\n 'Marker durationPolicy \"timeline\" is only valid for ordered or absolutely placed Audio Clips on the bgm Track',\n });\n }\n }\n return issues;\n}\n\nfunction validateClipAnchorCycles(entities: readonly EntityRef[], index: BiRelationIndex): EntityRelationIssue[] {\n const hostByChild = new Map<EntityId, EntityId>();\n for (const entity of entities) {\n if (entity.current().entityKind !== 'clip') continue;\n for (const relation of ofKind([...index.relationsOf(entity)], 'clip-anchor')) {\n if (relation.endpoints[0].deref() !== entity) continue;\n const host = relation.endpoints[1].deref();\n if (host != null) hostByChild.set(entity.entityId, host.entityId);\n }\n }\n const issues: EntityRelationIssue[] = [];\n for (const child of hostByChild.keys()) {\n const seen = new Set<EntityId>();\n let current: EntityId | undefined = child;\n while (current !== undefined && !seen.has(current)) {\n seen.add(current);\n current = hostByChild.get(current);\n }\n if (current === undefined) continue;\n issues.push({\n code: 'clip_anchor_cycle',\n entityId: child,\n message: 'clip-anchor Relations must form an acyclic dependency graph',\n });\n }\n return issues;\n}\n\nexport function validateMarkerRanges<SourcePoint, TargetPoint>(\n marker: EntityRef<SequenceMarker<SourcePoint, TargetPoint>>,\n compare: MarkerRangeComparators<SourcePoint, TargetPoint>,\n): EntityRelationIssue[] {\n const current = marker.current();\n const issues: EntityRelationIssue[] = [];\n if (!(compare.source(current.sourceRange.start, current.sourceRange.end) < 0)) {\n issues.push({\n code: 'marker_source_range_empty',\n entityId: marker.entityId,\n message: 'Sequence Marker sourceRange must be a non-empty half-open interval',\n });\n }\n if (current.targetRange != null && !(compare.target(current.targetRange.start, current.targetRange.end) < 0)) {\n issues.push({\n code: 'marker_target_range_empty',\n entityId: marker.entityId,\n message: 'Sequence Marker targetRange must be a non-empty half-open interval',\n });\n }\n return issues;\n}\n\nexport function validateMarkerSourceBounds(\n marker: EntityRef<SequenceMarker>,\n index: BiRelationIndex,\n compare: (left: unknown, right: unknown) => number,\n): EntityRelationIssue[] {\n const contentEdges = ofKind([...index.relationsOf(marker)], 'marker-content');\n if (contentEdges.length !== 1) return [];\n const content = contentEdges[0]?.other(marker)?.deref()?.current();\n if (content == null || !hasSequence(content)) return [];\n\n // Content states only its own length, so the window it can be taken from\n // always starts at 0. Content without a stored length (a still frame, or an\n // AXVideo whose Timeline decides it) has no upper bound to check.\n const sourceRange = marker.current().sourceRange;\n const startVsOrigin = compare(sourceRange.start, 0);\n const endVsDuration = content.durationMs == null ? undefined : compare(sourceRange.end, content.durationMs);\n if (\n !Number.isNaN(startVsOrigin) &&\n startVsOrigin >= 0 &&\n (endVsDuration == null || (!Number.isNaN(endVsDuration) && endVsDuration <= 0))\n ) {\n return [];\n }\n return [\n {\n code: 'marker_source_out_of_bounds',\n entityId: marker.entityId,\n message: `Sequence Marker sourceRange must stay within content \"${content.entityId}\" duration`,\n },\n ];\n}\n\nexport function validateSequenceComposition(entity: EntityRef): EntityRelationIssue[] {\n const current = entity.current();\n const expected = expectedDurationShape(current.entityKind);\n if (expected === undefined) return [];\n const duration = (current as unknown as Readonly<Record<string, unknown>>).durationMs;\n const actual = duration === null ? 'none' : isPositiveInteger(duration) ? 'own' : 'invalid';\n if (actual === expected) return [];\n return [\n {\n code: 'invalid_sequence_composition',\n entityId: current.entityId,\n message:\n expected === 'own'\n ? `${current.entityKind} must state its own durationMs in whole milliseconds`\n : `${current.entityKind} has no intrinsic length; durationMs must be null`,\n },\n ];\n}\n\nexport function validateEntity(entity: EntityRef, entityIds: ReadonlySet<EntityId> = new Set()): EntityRelationIssue[] {\n const current = entity.current();\n const issues: EntityRelationIssue[] = [];\n if (isReservedEntityKind(current.entityKind)) {\n issues.push({\n code: 'forbidden_entity_kind',\n entityId: current.entityId,\n message: `Entity kind \"${current.entityKind}\" is explicitly outside the Medeo DSL`,\n });\n }\n\n for (const problem of validateKnownEntityPayload(current)) {\n issues.push({\n code: 'invalid_entity_payload',\n entityId: current.entityId,\n message: `Entity \"${current.entityKind}\" ${problem}`,\n });\n }\n\n const peerIdPaths = [\n ...collectPeerEntityIdPaths(current, current.entityKind),\n ...collectPeerEntityValuePaths(current, current.entityKind, current.entityId, entityIds),\n ];\n const uniquePeerIdPaths = [...new Set(peerIdPaths)].sort();\n if (uniquePeerIdPaths.length > 0) {\n issues.push({\n code: 'peer_entity_id_field',\n entityId: current.entityId,\n message: `Entity embeds forbidden peer-ID field/value path(s): ${uniquePeerIdPaths.join(', ')}`,\n });\n }\n\n return issues;\n}\n\nfunction validateKnownEntityPayload(entity: MedeoEntity): readonly string[] {\n const value = entity as unknown as Readonly<Record<string, unknown>>;\n const problems: string[] = [];\n\n if (value.lifecycle !== undefined && !isRecord(value.lifecycle)) {\n problems.push('lifecycle must be an object when present');\n }\n\n if (entity.entityKind === 'audio-script' || entity.entityKind === 'phonetic-script') {\n for (const key of [\n 'durationMs',\n 'extent',\n 'sampling',\n 'coordinateSpace',\n 'sourceRange',\n 'targetRange',\n 'duration',\n 'startMs',\n 'endMs',\n ]) {\n if (Object.hasOwn(value, key))\n problems.push(`${key} is not intrinsic script data; assign an annotation Marker instead`);\n }\n }\n\n switch (entity.entityKind) {\n case 'track':\n validateOptionalField(value, 'hidden', 'boolean', problems);\n validateOptionalField(value, 'role', 'string', problems);\n validateOptionalFiniteNumber(value, 'order', problems);\n break;\n case 'video':\n case 'audio':\n validateDurationPayload(value, 'own', problems);\n break;\n case 'caption':\n validateDurationPayload(value, 'own', problems);\n validateCaptionPayload(value, problems);\n break;\n case 'voice':\n validateVoicePayload(value, problems);\n break;\n case 'image':\n validateDurationPayload(value, 'none', problems);\n break;\n case 'axvideo':\n // Length comes from its Timeline; an AXVideo stores none.\n for (const retired of ['extent', 'sampling', 'coordinateSpace', 'durationMs'])\n if (Object.hasOwn(value, retired)) problems.push(`${retired} is derived from the Timeline, not stored`);\n break;\n case 'sequence-marker':\n validateMarkerPayload(value, problems);\n break;\n case 'audio-script':\n validateScriptPayload(value, problems);\n break;\n case 'phonetic-script':\n validatePhoneticScriptPayload(value, problems);\n break;\n case 'timeline':\n case 'viewport':\n break;\n case 'clip':\n validateOptionalFiniteNumber(value, 'order', problems);\n validateOptionalFiniteNumber(value, 'volume', problems);\n if (typeof value.volume === 'number' && (value.volume < -60 || value.volume > 20)) {\n problems.push('volume must be decibels between -60 and 20');\n }\n break;\n case 'asset':\n validateAssetPayload(value, problems);\n break;\n default:\n break;\n }\n\n return problems;\n}\n\n/**\n * Content states its own length and nothing else. The retired `extent` carried\n * a start as well, which had no meaning of its own and drifted into holding a\n * position; rejecting it keeps that mistake unwritable.\n */\nfunction validateDurationPayload(\n value: Readonly<Record<string, unknown>>,\n expected: 'own' | 'none',\n problems: string[],\n): void {\n for (const retired of ['extent', 'sampling', 'coordinateSpace']) {\n if (Object.hasOwn(value, retired)) problems.push(`${retired} is retired; state durationMs instead`);\n }\n if (!Object.hasOwn(value, 'durationMs')) {\n problems.push('durationMs is required');\n return;\n }\n const duration = value.durationMs;\n if (expected === 'none') {\n if (duration !== null) problems.push('durationMs must be null; this content has no intrinsic length');\n return;\n }\n if (!isPositiveInteger(duration)) problems.push('durationMs must be positive whole milliseconds');\n}\n\nfunction validateMarkerPayload(value: Readonly<Record<string, unknown>>, problems: string[]): void {\n validateRange(value.sourceRange, 'sourceRange', true, problems);\n if (Object.hasOwn(value, 'targetRange') && value.targetRange !== undefined) {\n validateRange(value.targetRange, 'targetRange', true, problems);\n }\n\n const duration = value.duration;\n if (!isRecord(duration)) {\n problems.push('duration must be an object');\n } else if (duration.mode === 'fixed') {\n if (!Object.hasOwn(duration, 'value') || duration.value === undefined) {\n problems.push('duration.value is required when duration.mode is \"fixed\"');\n }\n } else if (duration.mode !== 'from-source') {\n problems.push('duration.mode must be \"from-source\" or \"fixed\"');\n }\n if (value.anchorOffset === undefined && Object.hasOwn(value, 'anchorOffset')) {\n problems.push('anchorOffset cannot be undefined when present');\n }\n if (value.durationPolicy !== undefined && value.durationPolicy !== 'timeline') {\n problems.push('durationPolicy must be \"timeline\" when present');\n }\n if (value.segmentRanges !== undefined) validateSegmentRanges(value.segmentRanges, problems);\n}\n\n/** Annotation Marker time values are directly assigned facts; no cross-references are allowed. */\nfunction validateSegmentRanges(value: unknown, problems: string[]): void {\n if (!Array.isArray(value)) {\n problems.push('segmentRanges must be an array when present');\n return;\n }\n const seen = new Set<string>();\n for (const [index, entry] of value.entries()) {\n if (!isRecord(entry)) {\n problems.push(`segmentRanges[${index}] must be an object`);\n continue;\n }\n if (typeof entry.segmentId !== 'string') problems.push(`segmentRanges[${index}].segmentId must be a string`);\n else if (seen.has(entry.segmentId))\n problems.push(`segmentRanges[${index}].segmentId must be unique within the Marker`);\n else seen.add(entry.segmentId);\n for (const key of ['startMs', 'endMs'] as const) {\n const point = entry[key];\n if (typeof point !== 'number' || !Number.isFinite(point)) {\n problems.push(`segmentRanges[${index}].${key} must be a finite number`);\n }\n }\n if (\n typeof entry.startMs === 'number' &&\n Number.isFinite(entry.startMs) &&\n typeof entry.endMs === 'number' &&\n Number.isFinite(entry.endMs) &&\n entry.startMs > entry.endMs\n ) {\n problems.push(`segmentRanges[${index}].startMs must not exceed segmentRanges[${index}].endMs`);\n }\n }\n}\n\n/** The Asset entity is the locator; it states where the bytes live and nothing else. */\nfunction validateAssetPayload(value: Readonly<Record<string, unknown>>, problems: string[]): void {\n if (value.system !== 'memota' && value.system !== 'memota-speech') {\n problems.push('system must be \"memota\" or \"memota-speech\"');\n }\n if (typeof value.key !== 'string' || value.key.trim() === '') {\n problems.push('key must be a non-empty string');\n }\n if (value.inline !== undefined) {\n problems.push('inline is not a physical location; text is domain content owned by its AudioScript');\n }\n validateStorageKey(value, problems);\n}\n\nfunction validateStorageKey(value: Readonly<Record<string, unknown>>, problems: string[]): void {\n if (value.storageKey !== undefined && (typeof value.storageKey !== 'string' || value.storageKey.trim() === '')) {\n problems.push('storageKey must be a non-empty string when present');\n }\n}\n\n/**\n * Voice is a timbre identity, not playable content: it owns the voice-library\n * descriptor and nothing that would make it look like media or a Sequence. The\n * rendered voiceover is an `audio` entity bound by a `voice-timbre` Relation.\n */\nfunction validateVoicePayload(value: Readonly<Record<string, unknown>>, problems: string[]): void {\n for (const key of ['durationMs', 'extent', 'sampling', 'coordinateSpace', 'system', 'key', 'storageKey']) {\n if (Object.hasOwn(value, key)) problems.push(`${key} belongs to the rendered Audio, not to the Voice identity`);\n }\n const voice = value.voice;\n if (voice === undefined) {\n problems.push('voice is required; a Voice entity is its voice-library identity');\n return;\n }\n if (!isRecord(voice)) {\n problems.push('voice must be an object');\n return;\n }\n if (voice.system !== 'voice-library') problems.push('voice.system must be \"voice-library\"');\n if (typeof voice.key !== 'string' || voice.key.trim() === '') problems.push('voice.key must be a non-empty string');\n if (voice.name !== undefined && typeof voice.name !== 'string')\n problems.push('voice.name must be a string when present');\n}\n\nfunction validateCaptionPayload(value: Readonly<Record<string, unknown>>, problems: string[]): void {\n if (value.segmentRanges !== undefined) validateSegmentRanges(value.segmentRanges, problems);\n if (Object.hasOwn(value, 'selections'))\n problems.push('selections is forbidden; Caption requires one selection object');\n const selection = value.selection;\n if (!isRecord(selection)) {\n problems.push('selection must be one AudioScript segment selection object, not an array');\n } else {\n if (typeof selection.segmentId !== 'string' || !selection.segmentId.trim())\n problems.push('selection.segmentId must be a non-empty string');\n if (Object.keys(selection).some((key) => key !== 'segmentId' && key !== 'textRange'))\n problems.push('selection may only contain segmentId and textRange');\n const range = selection.textRange;\n if (\n range !== undefined &&\n (!isRecord(range) ||\n !Number.isSafeInteger(range.start) ||\n !Number.isSafeInteger(range.end) ||\n (range.start as number) < 0 ||\n (range.end as number) <= (range.start as number) ||\n Object.keys(range).some((key) => key !== 'start' && key !== 'end'))\n )\n problems.push('selection.textRange must be a non-empty half-open code-point range');\n if (\n Array.isArray(value.segmentRanges) &&\n (value.segmentRanges.length !== 1 ||\n !isRecord(value.segmentRanges[0]) ||\n value.segmentRanges[0].segmentId !== selection.segmentId)\n )\n problems.push('Caption segmentRanges must contain only the selected segment timing');\n }\n const style = value.style;\n if (style === undefined) return;\n if (!isRecord(style)) {\n problems.push('style must be an object when present');\n return;\n }\n const font = style.font;\n if (font !== undefined) {\n if (!isRecord(font)) {\n problems.push('style.font must be an object when present');\n } else {\n if (font.system !== 'font-library') problems.push('style.font.system must be \"font-library\"');\n if (typeof font.key !== 'string' || font.key.trim() === '') {\n problems.push('style.font.key must be a non-empty string');\n }\n }\n }\n for (const key of [\n 'fontSize',\n 'fontWeight',\n 'entranceAnimationDurationMs',\n 'strokeWidth',\n 'positionX',\n 'positionY',\n ]) {\n validateOptionalFiniteNumber(style, key, problems, `style.${key}`);\n }\n for (const key of ['fontColor', 'entranceAnimation', 'strokeColor']) {\n if (style[key] !== undefined && typeof style[key] !== 'string') problems.push(`style.${key} must be a string`);\n }\n}\n\nfunction validateRange(value: unknown, path: string, required: boolean, problems: string[]): void {\n if (!isRecord(value)) {\n if (required) problems.push(`${path} must be an object`);\n return;\n }\n if (!Object.hasOwn(value, 'start') || value.start === undefined) problems.push(`${path}.start is required`);\n if (!Object.hasOwn(value, 'end') || value.end === undefined) problems.push(`${path}.end is required`);\n}\n\n/** Phonetic variants store pronunciation fields only; base text stays in the AudioScript. */\nfunction validatePhoneticScriptPayload(value: Readonly<Record<string, unknown>>, problems: string[]): void {\n if (value.segments !== undefined) validateScriptPayload(value, problems);\n if (\n value.phonemeScript !== undefined &&\n (typeof value.phonemeScript !== 'string' || value.phonemeScript.trim() === '')\n ) {\n problems.push('phonemeScript must be a non-empty string when present');\n }\n if (value.prosody !== undefined && !isRecord(value.prosody)) {\n problems.push('prosody must be an object when present');\n }\n}\n\nfunction validateScriptPayload(value: Readonly<Record<string, unknown>>, problems: string[]): void {\n if (!Array.isArray(value.segments)) {\n problems.push('segments must be an array');\n return;\n }\n for (const [index, segment] of value.segments.entries()) {\n if (!isRecord(segment)) {\n problems.push(`segments[${index}] must be an object`);\n continue;\n }\n for (const key of ['startMs', 'endMs', 'start_ms', 'end_ms', 'sourceRange', 'targetRange', 'duration']) {\n if (Object.hasOwn(segment, key))\n problems.push(`segments[${index}].${key} is timing; attach an AudioScript annotation Marker instead`);\n }\n if (typeof segment.segmentId !== 'string') problems.push(`segments[${index}].segmentId must be a string`);\n if (typeof segment.text !== 'string') problems.push(`segments[${index}].text must be a string`);\n if (segment.language !== undefined && typeof segment.language !== 'string') {\n problems.push(`segments[${index}].language must be a string when present`);\n }\n }\n}\n\nfunction validateOptionalField(\n value: Readonly<Record<string, unknown>>,\n key: string,\n expectedType: 'boolean' | 'string',\n problems: string[],\n): void {\n if (value[key] !== undefined && typeof value[key] !== expectedType) {\n problems.push(`${key} must be a ${expectedType} when present`);\n }\n}\n\nfunction validateOptionalFiniteNumber(\n value: Readonly<Record<string, unknown>>,\n key: string,\n problems: string[],\n label: string = key,\n): void {\n if (value[key] !== undefined && (typeof value[key] !== 'number' || !Number.isFinite(value[key]))) {\n problems.push(`${label} must be a finite number when present`);\n }\n}\n\nfunction collectPeerEntityIdPaths(value: unknown, entityKind: string): readonly string[] {\n const paths: string[] = [];\n visitPeerEntityIdPaths(value, entityKind, '', new Set(), paths);\n return paths;\n}\n\nfunction visitPeerEntityIdPaths(\n value: unknown,\n entityKind: string,\n parentPath: string,\n ancestors: Set<object>,\n paths: string[],\n): void {\n if (typeof value !== 'object' || value == null) return;\n if (ancestors.has(value)) return;\n\n ancestors.add(value);\n if (Array.isArray(value)) {\n for (const [index, item] of value.entries()) {\n visitPeerEntityIdPaths(item, entityKind, `${parentPath}[${index}]`, ancestors, paths);\n }\n } else {\n for (const [key, child] of Object.entries(value)) {\n const path = parentPath.length === 0 ? key : `${parentPath}.${key}`;\n if (parentPath.length === 0 && key === 'baseEntityIds') continue;\n const isOwnEntityId = parentPath.length === 0 && key === 'entityId';\n if (!isOwnEntityId && !isOwnedLocalIdPath(entityKind, path) && isEntityIdFieldName(key)) paths.push(path);\n visitPeerEntityIdPaths(child, entityKind, path, ancestors, paths);\n }\n }\n ancestors.delete(value);\n}\n\nfunction collectPeerEntityValuePaths(\n value: unknown,\n entityKind: string,\n ownEntityId: EntityId,\n entityIds: ReadonlySet<EntityId>,\n): readonly string[] {\n const paths: string[] = [];\n visitPeerEntityValues(value, entityKind, ownEntityId, entityIds, '', new Set(), paths);\n return paths;\n}\n\nfunction visitPeerEntityValues(\n value: unknown,\n entityKind: string,\n ownEntityId: EntityId,\n entityIds: ReadonlySet<EntityId>,\n path: string,\n ancestors: Set<object>,\n paths: string[],\n): void {\n if (typeof value === 'string') {\n if (value !== ownEntityId && entityIds.has(value as EntityId) && !isOwnedLocalEntityValuePath(entityKind, path))\n paths.push(path);\n return;\n }\n if (typeof value !== 'object' || value == null || ancestors.has(value)) return;\n\n ancestors.add(value);\n if (Array.isArray(value)) {\n for (const [index, item] of value.entries()) {\n visitPeerEntityValues(item, entityKind, ownEntityId, entityIds, `${path}[${index}]`, ancestors, paths);\n }\n } else {\n for (const [key, child] of Object.entries(value)) {\n if (path.length === 0 && (key === 'entityId' || key === 'entityKind' || key === 'baseEntityIds')) continue;\n visitPeerEntityValues(\n child,\n entityKind,\n ownEntityId,\n entityIds,\n path.length === 0 ? key : `${path}.${key}`,\n ancestors,\n paths,\n );\n }\n }\n ancestors.delete(value);\n}\n\nfunction isOwnedLocalEntityValuePath(entityKind: string, path: string): boolean {\n if (entityKind === 'track' && path === 'role') return true;\n if (['video', 'audio', 'image', 'caption', 'axvideo'].includes(entityKind) && /^durationMs$/.test(path)) return true;\n if (entityKind === 'sequence-marker' && /^(?:durationPolicy|duration\\.mode|timeRemapping\\.(?:kind|mode))$/.test(path))\n return true;\n if ((entityKind === 'sequence-marker' || entityKind === 'caption') && /^segmentRanges\\[\\d+\\]\\.segmentId$/.test(path))\n return true;\n if (entityKind === 'asset' && /^(?:system|key|storageKey)$/.test(path)) return true;\n if (entityKind === 'voice' && /^voice\\.(?:system|key|name)$/.test(path)) return true;\n // Caption selection segment ids quote the composed script's own segment identity.\n if (entityKind === 'caption' && (path.startsWith('style.') || path === 'selection.segmentId')) return true;\n if (\n ['audio-script', 'caption', 'phonetic-script'].includes(entityKind) &&\n /^segments\\[\\d+\\]\\.(?:segmentId|text|language)$/.test(path)\n )\n return true;\n return false;\n}\n\nfunction isOwnedLocalIdPath(entityKind: string, path: string): boolean {\n if (path === 'lifecycle.actorId') return true;\n if (['audio-script', 'caption', 'phonetic-script'].includes(entityKind) && /^segments\\[\\d+\\]\\.segmentId$/.test(path))\n return true;\n // Caption selection quote the composed script's own segment identity.\n if (entityKind === 'caption' && path === 'selection.segmentId') return true;\n // Annotation Marker segment ids quote the annotated script's own segment identity.\n if ((entityKind === 'sequence-marker' || entityKind === 'caption') && /^segmentRanges\\[\\d+\\]\\.segmentId$/.test(path))\n return true;\n if (entityKind === 'asset' && /^(?:tracks\\[\\d+\\]\\.trackId|renditions\\[\\d+\\]\\.renditionId)$/.test(path)) {\n return true;\n }\n return false;\n}\n\nfunction isEntityIdFieldName(key: string): boolean {\n return key.endsWith('Id') || key.endsWith('Ids') || key.endsWith('ID') || key.endsWith('IDs') || /_ids?$/i.test(key);\n}\n\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === 'object' && value != null && !Array.isArray(value);\n}\n\nfunction collectRelatedEntities(\n entityRefs: readonly EntityRef[],\n index: BiRelationIndex,\n): { readonly entities: readonly EntityRef[]; readonly issues: EntityRelationIssue[] } {\n const byId = new Map<EntityId, EntityRef>();\n const queue = [...entityRefs];\n const issues: EntityRelationIssue[] = [];\n while (queue.length > 0) {\n const entity = queue.shift();\n if (entity == null) continue;\n const existing = byId.get(entity.entityId);\n if (existing != null) {\n if (existing !== entity) {\n issues.push({\n code: 'duplicate_entity_id',\n entityId: entity.entityId,\n message: `Entity id \"${entity.entityId}\" has more than one live EntityRef`,\n });\n }\n continue;\n }\n byId.set(entity.entityId, entity);\n for (const relation of index.relationsOf(entity)) {\n for (const endpoint of relation.endpoints) {\n const ref = endpoint.deref();\n if (ref != null && !byId.has(ref.entityId)) queue.push(ref);\n }\n }\n }\n return { entities: [...byId.values()], issues };\n}\n\n/**\n * What a kind must state about its own length. An AXVideo is absent here on\n * purpose: its Timeline decides its length, so it stores none.\n */\nfunction expectedDurationShape(kind: string): 'own' | 'none' | undefined {\n if (kind === 'video' || kind === 'audio' || kind === 'caption') return 'own';\n if (kind === 'image') return 'none';\n return undefined;\n}\n\nfunction isPositiveInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;\n}\n\nfunction ofKind(relations: readonly RelationAny[], kind: string): RelationAny[] {\n return relations.filter((relation) => relation.kind === kind);\n}\n","import type {\n Asset,\n Audio,\n AudioScript,\n AXVideo,\n Caption,\n Clip,\n EntityKind,\n Image,\n MedeoEntity,\n PhoneticScript,\n SequenceEntity,\n SequenceMarker,\n Timeline,\n Track,\n Video,\n Voice,\n} from './entities.ts';\nimport { declaresKind, hasSequence } from './entities.ts';\nimport { isJsonObject, type JsonObject, type JsonValue } from './json-values.ts';\nimport type { EmptyMetadata, EntityRef, RelationEndpoints, RelationKindSpec } from './relations.ts';\n\nexport type AssetBinding = JsonObject;\nexport type GeneratedMedia = Video | Image | Audio;\nexport type GeneratedMetadata = EmptyMetadata;\n/** Media an AudioScript was transcribed from; script-sourced scripts have no edge. */\nexport type AudioScriptSourceMedia = Audio | Video;\n\nexport interface SegmentAlignmentMetadata extends JsonObject {\n readonly segmentAlignment: JsonValue;\n}\n\nexport interface CaptionAlignmentMetadata extends JsonObject {\n readonly alignment: JsonValue;\n}\n\nexport const timelineTrackRelationSpec = emptySpec<'timeline-track', Timeline, Track>(\n 'timeline-track',\n 'timeline',\n 'track',\n);\nexport const trackClipRelationSpec = emptySpec<'track-clip', Track, Clip>('track-clip', 'track', 'clip');\nexport const clipMarkerRelationSpec = emptySpec<'clip-marker', Clip, SequenceMarker>(\n 'clip-marker',\n 'clip',\n 'sequence-marker',\n);\nexport const axVideoMarkerRelationSpec = emptySpec<'axvideo-marker', AXVideo, SequenceMarker>(\n 'axvideo-marker',\n 'axvideo',\n 'sequence-marker',\n);\nexport const markerTimelineRelationSpec = emptySpec<'marker-timeline', SequenceMarker, Timeline>(\n 'marker-timeline',\n 'sequence-marker',\n 'timeline',\n);\n\nexport const markerContentRelationSpec: RelationKindSpec<\n 'marker-content',\n SequenceMarker,\n SequenceEntity,\n EmptyMetadata\n> = Object.freeze({\n kind: 'marker-content',\n validateEndpoints: (\n endpoints: RelationEndpoints<EntityRef, EntityRef>,\n ): endpoints is RelationEndpoints<EntityRef<SequenceMarker>, EntityRef<SequenceEntity>> =>\n hasMarkerAndSequence(endpoints),\n validateMetadata: isEmptyMetadata,\n});\n\n/**\n * `from-asset(entity, asset)` — the entity was made from that stored resource.\n *\n * Eligibility is declared: the non-Asset endpoint must carry the `FromAsset`\n * kind, which says an entity of that kind can be made from stored bytes and\n * asks nothing of its payload. The bytes stay named in exactly one place, so\n * no entity copies the locator into its own row and one Asset can back several\n * entities.\n */\nexport const fromAssetRelationSpec: RelationKindSpec<'from-asset', MedeoEntity, Asset, AssetBinding> = Object.freeze({\n kind: 'from-asset',\n validateEndpoints: (\n endpoints: RelationEndpoints<EntityRef, EntityRef>,\n ): endpoints is RelationEndpoints<EntityRef<MedeoEntity>, EntityRef<Asset>> => hasExactlyOneAsset(endpoints),\n validateMetadata: isAssetBinding,\n});\n\n/** `generated(output, input)` means endpoint 0 was generated from endpoint 1. */\nexport const generatedRelationSpec: RelationKindSpec<'generated', GeneratedMedia, GeneratedMedia, GeneratedMetadata> =\n Object.freeze({\n kind: 'generated',\n validateEndpoints: (\n endpoints: RelationEndpoints<EntityRef, EntityRef>,\n ): endpoints is RelationEndpoints<EntityRef<GeneratedMedia>, EntityRef<GeneratedMedia>> =>\n endpoints.every((endpoint) => isGeneratedMedia(endpoint.current())),\n validateMetadata: isEmptyMetadata,\n });\n\nexport const captionAlignmentRelationSpec: RelationKindSpec<\n 'caption-alignment',\n Caption,\n Audio,\n CaptionAlignmentMetadata\n> = Object.freeze({\n kind: 'caption-alignment',\n validateEndpoints: (\n endpoints: RelationEndpoints<EntityRef, EntityRef>,\n ): endpoints is RelationEndpoints<EntityRef<Caption>, EntityRef<Audio>> =>\n hasKinds(endpoints, new Set(['caption']), new Set(['audio'])),\n validateMetadata: isCaptionAlignmentMetadata,\n});\n\n/** `clip-anchor(child, host)` means endpoint 0 follows endpoint 1. */\nexport const clipAnchorRelationSpec: RelationKindSpec<'clip-anchor', Clip, Clip, EmptyMetadata> = Object.freeze({\n kind: 'clip-anchor',\n validateEndpoints: (\n endpoints: RelationEndpoints<EntityRef, EntityRef>,\n ): endpoints is RelationEndpoints<EntityRef<Clip>, EntityRef<Clip>> =>\n endpoints[0].current().entityKind === 'clip' && endpoints[1].current().entityKind === 'clip',\n validateMetadata: isEmptyMetadata,\n});\n\n/**\n * The rendered voiceover Audio and the PhoneticScript it was synthesized from;\n * kinds determine roles regardless of endpoint positions.\n */\nexport const phoneticScriptRenderRelationSpec: RelationKindSpec<\n 'phonetic-script-render',\n Audio,\n PhoneticScript,\n EmptyMetadata\n> = Object.freeze({\n kind: 'phonetic-script-render',\n validateEndpoints: (\n endpoints: RelationEndpoints<EntityRef, EntityRef>,\n ): endpoints is RelationEndpoints<EntityRef<Audio>, EntityRef<PhoneticScript>> =>\n hasKinds(endpoints, new Set(['audio']), new Set(['phonetic-script'])),\n validateMetadata: isEmptyMetadata,\n});\n\n/**\n * The timbre identity a rendered voiceover Audio was synthesized with. Voice\n * stays an identity: it never carries the audio itself, so the link between the\n * two is a Relation rather than one shared entity.\n */\nexport const voiceTimbreRelationSpec: RelationKindSpec<'voice-timbre', Audio, Voice, EmptyMetadata> = Object.freeze({\n kind: 'voice-timbre',\n validateEndpoints: (\n endpoints: RelationEndpoints<EntityRef, EntityRef>,\n ): endpoints is RelationEndpoints<EntityRef<Audio>, EntityRef<Voice>> =>\n hasKinds(endpoints, new Set(['audio']), new Set(['voice'])),\n validateMetadata: isEmptyMetadata,\n});\n\n/** AudioScript was transcribed from Audio, Video, or recorded Voice; kinds determine roles. */\nexport const audioScriptSourceRelationSpec: RelationKindSpec<\n 'audio-script-source',\n AudioScript,\n AudioScriptSourceMedia,\n EmptyMetadata\n> = Object.freeze({\n kind: 'audio-script-source',\n validateEndpoints: (\n endpoints: RelationEndpoints<EntityRef, EntityRef>,\n ): endpoints is RelationEndpoints<EntityRef<AudioScript>, EntityRef<AudioScriptSourceMedia>> =>\n hasKinds(endpoints, new Set(['audio-script']), new Set(['audio', 'video'])),\n validateMetadata: isEmptyMetadata,\n});\n\n/**\n * `audio-script-marker(script, marker)` attaches an annotation Sequence Marker\n * whose `segmentRanges` hold directly assigned per-Segment time values. The\n * script keeps no Sequence and no Clip admission; annotation Markers cannot\n * enter Clip/AXVideo use chains (enforced by the marker-use invariant).\n */\nexport const audioScriptMarkerRelationSpec: RelationKindSpec<\n 'audio-script-marker',\n AudioScript,\n SequenceMarker,\n EmptyMetadata\n> = Object.freeze({\n kind: 'audio-script-marker',\n validateEndpoints: (\n endpoints: RelationEndpoints<EntityRef, EntityRef>,\n ): endpoints is RelationEndpoints<EntityRef<AudioScript>, EntityRef<SequenceMarker>> =>\n hasKinds(endpoints, new Set(['audio-script']), new Set(['sequence-marker'])),\n validateMetadata: isEmptyMetadata,\n});\n\n/** Built-in kinds are reserved; callers may add specs only under new names. */\nexport const builtInRelationSpecs = Object.freeze([\n timelineTrackRelationSpec,\n trackClipRelationSpec,\n clipMarkerRelationSpec,\n markerContentRelationSpec,\n axVideoMarkerRelationSpec,\n markerTimelineRelationSpec,\n fromAssetRelationSpec,\n generatedRelationSpec,\n captionAlignmentRelationSpec,\n clipAnchorRelationSpec,\n phoneticScriptRenderRelationSpec,\n voiceTimbreRelationSpec,\n audioScriptSourceRelationSpec,\n audioScriptMarkerRelationSpec,\n]);\n\nfunction emptySpec<K extends string, A extends MedeoEntity<EntityKind>, B extends MedeoEntity<EntityKind>>(\n kind: K,\n a: A['entityKind'],\n b: B['entityKind'],\n): RelationKindSpec<K, A, B, EmptyMetadata> {\n return metadataSpec(kind, a, b, isEmptyMetadata);\n}\n\nfunction metadataSpec<\n K extends string,\n A extends MedeoEntity<EntityKind>,\n B extends MedeoEntity<EntityKind>,\n Metadata extends JsonObject,\n>(\n kind: K,\n a: A['entityKind'],\n b: B['entityKind'],\n validateMetadata: (value: unknown) => value is Metadata,\n): RelationKindSpec<K, A, B, Metadata> {\n return Object.freeze({\n kind,\n validateEndpoints: (\n endpoints: RelationEndpoints<EntityRef, EntityRef>,\n ): endpoints is RelationEndpoints<EntityRef<A>, EntityRef<B>> => hasKinds(endpoints, new Set([a]), new Set([b])),\n validateMetadata,\n });\n}\n\nfunction hasKinds(\n endpoints: RelationEndpoints<EntityRef, EntityRef>,\n aKinds: ReadonlySet<string>,\n bKinds: ReadonlySet<string>,\n): boolean {\n const first = endpoints[0].current().entityKind;\n const second = endpoints[1].current().entityKind;\n return (aKinds.has(first) && bKinds.has(second)) || (aKinds.has(second) && bKinds.has(first));\n}\n\nfunction hasMarkerAndSequence(endpoints: RelationEndpoints<EntityRef, EntityRef>): boolean {\n const first = endpoints[0].current();\n const second = endpoints[1].current();\n return (\n (first.entityKind === 'sequence-marker' && hasSequence(second)) ||\n (second.entityKind === 'sequence-marker' && hasSequence(first))\n );\n}\n\n/** Exactly one end is the Asset, so the other end is unambiguously the maker. */\nfunction hasExactlyOneAsset(endpoints: RelationEndpoints<EntityRef, EntityRef>): boolean {\n const kinds = endpoints.map((endpoint) => endpoint.current().entityKind);\n const assets = kinds.map((kind) => kind === 'asset');\n if (assets[0] === assets[1]) return false;\n const made = assets[0] ? kinds[1]! : kinds[0]!;\n return declaresKind(made, 'FromAsset');\n}\n\nfunction isGeneratedMedia(entity: MedeoEntity): entity is GeneratedMedia {\n return entity.entityKind === 'video' || entity.entityKind === 'image' || entity.entityKind === 'audio';\n}\n\nfunction isEmptyMetadata(value: unknown): value is EmptyMetadata {\n return isJsonObject(value) && Object.keys(value).length === 0;\n}\n\nfunction isAssetBinding(value: unknown): value is AssetBinding {\n if (!isJsonObject(value)) return false;\n const orderingKey = /(order|ordinal|position|rank|index|z[_-]?index)/i;\n return Object.keys(value).every((key) => !orderingKey.test(key));\n}\n\nfunction isCaptionAlignmentMetadata(value: unknown): value is CaptionAlignmentMetadata {\n return isJsonObject(value) && Object.hasOwn(value, 'alignment');\n}\n","import type { EntityKind, MedeoEntity } from './entities.ts';\nimport type { EntityId, RelationId } from './ids.ts';\nimport type { JsonObject } from './json-values.ts';\n\nexport type KnownRelationKind =\n | 'timeline-track'\n | 'track-clip'\n | 'clip-marker'\n | 'marker-content'\n | 'axvideo-marker'\n | 'marker-timeline'\n | 'from-asset'\n | 'generated'\n | 'caption-alignment'\n | 'clip-anchor'\n | 'phonetic-script-render'\n | 'audio-script-source'\n | 'audio-script-marker';\n\nexport type RelationKind = KnownRelationKind | (string & {});\nexport type RelationTrace = JsonObject;\nexport type EmptyMetadata = Readonly<Record<string, never>>;\n\n/** Two persisted endpoint positions. Their meaning belongs to the Relation kind. */\nexport type RelationEndpoints<A, B> = readonly [A, B] | readonly [B, A];\n\n/**\n * Authoritative persisted relation value.\n *\n * A kind may assign semantic roles to endpoint 0 and endpoint 1. Callers and\n * storage adapters must preserve the submitted positions; kinds whose\n * semantics are unordered simply do not interpret those positions.\n */\nexport interface RelationRow<K extends RelationKind = RelationKind, Metadata extends JsonObject = JsonObject> {\n readonly relationId: RelationId;\n readonly endpoint0EntityId: EntityId;\n readonly endpoint1EntityId: EntityId;\n readonly relationKind: K;\n readonly metadata: Metadata;\n readonly trace: RelationTrace;\n}\n\nexport interface EntityRef<T extends MedeoEntity<EntityKind> = MedeoEntity<EntityKind>> {\n readonly entityId: EntityId;\n current(): T;\n}\n\nexport interface Relation<\n K extends RelationKind = RelationKind,\n A extends MedeoEntity<EntityKind> = MedeoEntity<EntityKind>,\n B extends MedeoEntity<EntityKind> = MedeoEntity<EntityKind>,\n Metadata extends JsonObject = JsonObject,\n> {\n readonly relationId: RelationId;\n readonly kind: K;\n readonly endpoints: RelationEndpoints<WeakRef<EntityRef<A>>, WeakRef<EntityRef<B>>>;\n readonly metadata: Metadata;\n readonly trace: RelationTrace;\n other(entity: EntityRef<A | B>): WeakRef<EntityRef<A | B>> | undefined;\n toRow(): RelationRow<K, Metadata> | undefined;\n}\n\nexport type RelationAny = Relation<RelationKind, MedeoEntity<EntityKind>, MedeoEntity<EntityKind>, JsonObject>;\n\n/** Type-erased validation contract used when decoding persisted relation rows. */\nexport interface RuntimeRelationKindSpec {\n readonly kind: RelationKind;\n validateEndpoints(endpoints: RelationEndpoints<EntityRef, EntityRef>): boolean;\n validateMetadata(value: unknown): value is JsonObject;\n}\n\nexport interface RelationKindSpec<\n K extends RelationKind,\n A extends MedeoEntity<EntityKind>,\n B extends MedeoEntity<EntityKind>,\n Metadata extends JsonObject,\n> extends RuntimeRelationKindSpec {\n readonly kind: K;\n validateEndpoints(\n endpoints: RelationEndpoints<EntityRef, EntityRef>,\n ): endpoints is RelationEndpoints<EntityRef<A>, EntityRef<B>>;\n validateMetadata(value: unknown): value is Metadata;\n}\n\nexport function createEntityRef<T extends MedeoEntity<EntityKind>>(entity: T): EntityRef<T> {\n return { entityId: entity.entityId, current: () => entity };\n}\n","import {\n hasSequence,\n type Asset,\n type Audio,\n type AudioScript,\n type Clip,\n type EntityKind,\n type MedeoEntity,\n type PhoneticScript,\n type Video,\n} from './entities.ts';\nimport type { RelationId } from './ids.ts';\nimport type { JsonObject } from './json-values.ts';\nimport {\n audioScriptSourceRelationSpec,\n builtInRelationSpecs,\n clipAnchorRelationSpec,\n generatedRelationSpec,\n type GeneratedMedia,\n type GeneratedMetadata,\n phoneticScriptRenderRelationSpec,\n} from './relation-specs.ts';\nimport {\n type EntityRef,\n type EmptyMetadata,\n type Relation,\n type RelationAny,\n type RelationEndpoints,\n type RelationKind,\n type RelationKindSpec,\n type RelationRow,\n type RelationTrace,\n type RuntimeRelationKindSpec,\n} from './relations.ts';\n\nclass RelationEdge<\n K extends RelationKind,\n A extends MedeoEntity<EntityKind>,\n B extends MedeoEntity<EntityKind>,\n Metadata extends JsonObject,\n> implements Relation<K, A, B, Metadata> {\n readonly endpoints: RelationEndpoints<WeakRef<EntityRef<A>>, WeakRef<EntityRef<B>>>;\n\n constructor(\n readonly relationId: RelationId,\n readonly kind: K,\n endpoints: RelationEndpoints<EntityRef<A>, EntityRef<B>>,\n readonly metadata: Metadata,\n readonly trace: RelationTrace,\n ) {\n this.endpoints = [\n new WeakRef(endpoints[0] as EntityRef<A | B>),\n new WeakRef(endpoints[1] as EntityRef<A | B>),\n ] as unknown as RelationEndpoints<WeakRef<EntityRef<A>>, WeakRef<EntityRef<B>>>;\n }\n\n other(entity: EntityRef<A | B>): WeakRef<EntityRef<A | B>> | undefined {\n const first = this.endpoints[0].deref();\n const second = this.endpoints[1].deref();\n if (first === entity) return this.endpoints[1] as WeakRef<EntityRef<A | B>>;\n if (second === entity) return this.endpoints[0] as WeakRef<EntityRef<A | B>>;\n return undefined;\n }\n\n toRow(): RelationRow<K, Metadata> | undefined {\n const first = this.endpoints[0].deref();\n const second = this.endpoints[1].deref();\n if (first == null || second == null) return undefined;\n return {\n relationId: this.relationId,\n endpoint0EntityId: first.entityId,\n endpoint1EntityId: second.entityId,\n relationKind: this.kind,\n metadata: this.metadata,\n trace: this.trace,\n };\n }\n\n isStale(): boolean {\n return this.endpoints[0].deref() == null || this.endpoints[1].deref() == null;\n }\n}\n\nexport interface LinkRelationInput<\n K extends RelationKind,\n A extends MedeoEntity<EntityKind>,\n B extends MedeoEntity<EntityKind>,\n Metadata extends JsonObject,\n> {\n readonly relationId: RelationId;\n readonly spec: RelationKindSpec<K, A, B, Metadata>;\n readonly endpoints: RelationEndpoints<EntityRef<A>, EntityRef<B>>;\n readonly metadata: Metadata;\n readonly trace?: RelationTrace;\n}\n\nexport interface LinkRuntimeRelationInput {\n readonly relationId: RelationId;\n readonly spec: RuntimeRelationKindSpec;\n readonly endpoints: RelationEndpoints<EntityRef, EntityRef>;\n readonly metadata: unknown;\n readonly trace?: RelationTrace;\n}\n\nexport interface LinkGeneratedRelationInput {\n readonly relationId: RelationId;\n readonly output: EntityRef<GeneratedMedia>;\n readonly input: EntityRef<GeneratedMedia>;\n readonly trace?: RelationTrace;\n}\n\nexport interface LinkClipAnchorRelationInput {\n readonly relationId: RelationId;\n readonly child: EntityRef<Clip>;\n readonly host: EntityRef<Clip>;\n readonly trace?: RelationTrace;\n}\n\nexport interface LinkPhoneticScriptRenderRelationInput {\n readonly relationId: RelationId;\n /** The rendered voiceover Audio; Voice stays the timbre identity, not the output. */\n readonly output: EntityRef<Audio>;\n readonly phoneticScript: EntityRef<PhoneticScript>;\n readonly trace?: RelationTrace;\n}\n\nexport interface LinkAudioScriptSourceRelationInput {\n readonly relationId: RelationId;\n readonly script: EntityRef<AudioScript>;\n readonly source: EntityRef<Audio | Video>;\n readonly trace?: RelationTrace;\n}\n\n/**\n * The Asset an entity was made from, or undefined when it has none.\n *\n * Callers ask through this rather than reading a locator off the entity: the\n * bytes are named on the Asset alone, so every consumer takes the same single\n * hop instead of open-coding the traversal.\n */\nexport function assetOf(entity: EntityRef, index: BiRelationIndex): Asset | undefined {\n const found = [...index.relationsOf(entity)]\n .filter((relation) => relation.kind === 'from-asset')\n .map((relation) => relation.other(entity)?.deref()?.current())\n .filter((other): other is Asset => other?.entityKind === 'asset');\n if (found.length > 1) throw new Error(`Entity \"${entity.entityId}\" resolves more than one Asset`);\n return found[0];\n}\n\n/** Endpoint-agnostic secondary index. Relation rows remain the persistence authority. */\nexport class BiRelationIndex {\n private readonly byEntity = new WeakMap<EntityRef, Set<RelationAny>>();\n private readonly canonicalRefs = new Map<string, WeakRef<EntityRef>>();\n private readonly byRelationId = new Map<RelationId, WeakRef<RelationAny>>();\n\n link<\n K extends RelationKind,\n A extends MedeoEntity<EntityKind>,\n B extends MedeoEntity<EntityKind>,\n Metadata extends JsonObject,\n >(input: LinkRelationInput<K, A, B, Metadata>): Relation<K, A, B, Metadata> {\n if (input.spec.kind === 'generated')\n throw new Error('Author generated Relations with linkGenerated({ output, input })');\n if (\n input.spec.kind === 'clip-anchor' ||\n input.spec.kind === 'phonetic-script-render' ||\n input.spec.kind === 'audio-script-source'\n )\n throw new Error(`Author ordered ${input.spec.kind} Relations with the dedicated role-named method`);\n return this.linkValidated(input) as Relation<K, A, B, Metadata>;\n }\n\n /** Author `generated(output, input)` without exposing positional arguments. */\n linkGenerated(\n input: LinkGeneratedRelationInput,\n ): Relation<'generated', GeneratedMedia, GeneratedMedia, GeneratedMetadata> {\n return this.linkValidated({\n relationId: input.relationId,\n spec: generatedRelationSpec,\n endpoints: [input.output, input.input],\n metadata: {},\n trace: input.trace,\n }) as Relation<'generated', GeneratedMedia, GeneratedMedia, GeneratedMetadata>;\n }\n\n /** Author `clip-anchor(child, host)` without exposing positional arguments. */\n linkClipAnchor(input: LinkClipAnchorRelationInput): Relation<'clip-anchor', Clip, Clip, EmptyMetadata> {\n return this.linkValidated({\n relationId: input.relationId,\n spec: clipAnchorRelationSpec,\n endpoints: [input.child, input.host],\n metadata: {},\n trace: input.trace,\n }) as Relation<'clip-anchor', Clip, Clip, EmptyMetadata>;\n }\n\n /** Author `phonetic-script-render(output, phoneticScript)` without exposing positional arguments. */\n linkPhoneticScriptRender(\n input: LinkPhoneticScriptRenderRelationInput,\n ): Relation<'phonetic-script-render', Audio, PhoneticScript, EmptyMetadata> {\n return this.linkValidated({\n relationId: input.relationId,\n spec: phoneticScriptRenderRelationSpec,\n endpoints: [input.output, input.phoneticScript],\n metadata: {},\n trace: input.trace,\n }) as Relation<'phonetic-script-render', Audio, PhoneticScript, EmptyMetadata>;\n }\n\n /** Author `audio-script-source(script, source)` without exposing positional arguments. */\n linkAudioScriptSource(\n input: LinkAudioScriptSourceRelationInput,\n ): Relation<'audio-script-source', AudioScript, Audio | Video, EmptyMetadata> {\n return this.linkValidated({\n relationId: input.relationId,\n spec: audioScriptSourceRelationSpec,\n endpoints: [input.script, input.source],\n metadata: {},\n trace: input.trace,\n }) as Relation<'audio-script-source', AudioScript, Audio | Video, EmptyMetadata>;\n }\n\n /**\n * Rehydrate a persisted row after resolving its spec and endpoint refs.\n *\n * This is a storage-boundary escape hatch, not an authoring API: persisted\n * positions already are the semantic assertion made by their relation kind.\n */\n linkRuntime(input: LinkRuntimeRelationInput): RelationAny {\n return this.linkValidated(input);\n }\n\n private linkValidated(input: LinkRuntimeRelationInput): RelationAny {\n const [first, second] = input.endpoints;\n if (first.entityId === second.entityId) throw new Error('A Relation cannot connect an entity to itself');\n this.assertRelationIdAvailable(input.relationId);\n const builtInSpec = builtInSpecByKind.get(input.spec.kind);\n if (builtInSpec != null && builtInSpec !== input.spec) {\n throw new Error(`Relation kind \"${input.spec.kind}\" must use its built-in specification`);\n }\n if (isForbiddenAuthoritativeRelation(input.spec.kind, input.endpoints)) {\n throw new Error('A direct Clip-Content Relation is derived-only and cannot be authoritative');\n }\n if (!input.spec.validateEndpoints(input.endpoints)) {\n throw new Error(`Relation \"${input.spec.kind}\" received invalid endpoints`);\n }\n if (!input.spec.validateMetadata(input.metadata)) {\n throw new Error(`Relation \"${input.spec.kind}\" received invalid metadata`);\n }\n this.assertCanonicalRefAvailable(first);\n this.assertCanonicalRefAvailable(second);\n\n const relation = new RelationEdge<RelationKind, MedeoEntity<EntityKind>, MedeoEntity<EntityKind>, JsonObject>(\n input.relationId,\n input.spec.kind,\n input.endpoints,\n input.metadata,\n input.trace ?? {},\n );\n this.rememberCanonicalRef(first);\n this.rememberCanonicalRef(second);\n this.add(first, relation);\n this.add(second, relation);\n this.byRelationId.set(input.relationId, new WeakRef(relation));\n return relation;\n }\n\n relationsOf(entity: EntityRef): ReadonlySet<RelationAny> {\n this.registerCanonicalRef(entity);\n const relations = this.byEntity.get(entity);\n if (relations == null) return new Set();\n for (const relation of relations) {\n if (relation instanceof RelationEdge && relation.isStale()) this.unlink(relation);\n }\n return new Set(relations);\n }\n\n unlink(relation: RelationAny): void {\n for (const endpoint of relation.endpoints) {\n const ref = endpoint.deref();\n if (ref != null) this.byEntity.get(ref)?.delete(relation);\n }\n if (this.byRelationId.get(relation.relationId)?.deref() === relation) {\n this.byRelationId.delete(relation.relationId);\n }\n }\n\n private add(entity: EntityRef, relation: RelationAny): void {\n const relations = this.byEntity.get(entity) ?? new Set<RelationAny>();\n relations.add(relation);\n this.byEntity.set(entity, relations);\n }\n\n private registerCanonicalRef(entity: EntityRef): void {\n this.assertCanonicalRefAvailable(entity);\n this.rememberCanonicalRef(entity);\n }\n\n private assertCanonicalRefAvailable(entity: EntityRef): void {\n const existing = this.canonicalRefs.get(entity.entityId)?.deref();\n if (existing != null && existing !== entity) {\n throw new Error(`Entity \"${entity.entityId}\" already has a live canonical EntityRef`);\n }\n }\n\n private rememberCanonicalRef(entity: EntityRef): void {\n this.canonicalRefs.set(entity.entityId, new WeakRef(entity));\n }\n\n private assertRelationIdAvailable(relationId: RelationId): void {\n const existing = this.byRelationId.get(relationId)?.deref();\n if (existing != null) throw new Error(`Relation id \"${relationId}\" already exists`);\n this.byRelationId.delete(relationId);\n }\n}\n\nconst builtInSpecByKind: ReadonlyMap<string, object> = new Map(builtInRelationSpecs.map((spec) => [spec.kind, spec]));\n\nfunction isForbiddenAuthoritativeRelation(\n kind: RelationKind,\n endpoints: RelationEndpoints<EntityRef, EntityRef>,\n): boolean {\n if (kind === 'clip-content') return true;\n const first = endpoints[0].current();\n const second = endpoints[1].current();\n return (first.entityKind === 'clip' && hasSequence(second)) || (second.entityKind === 'clip' && hasSequence(first));\n}\n","import { assembleEntityContent } from './composition.ts';\nimport {\n isKnownEntityKind,\n isReservedEntityKind,\n type EntityKind,\n type ExtensionEntityKind,\n type MedeoEntity,\n} from './entities.ts';\nimport { createEntityId, createRelationId, type EntityId, type RelationId } from './ids.ts';\nimport { validateEntityRelationSet, type EntityRelationValidationOptions } from './invariants.ts';\nimport { isJsonObject } from './json-values.ts';\nimport { BiRelationIndex } from './relation-index.ts';\nimport { builtInRelationSpecs } from './relation-specs.ts';\nimport { createEntityRef, type EntityRef, type RelationAny, type RuntimeRelationKindSpec } from './relations.ts';\nimport type { EntityRelationRows, EntityRow } from './rows.ts';\n\nexport interface DecodeEntityRelationRowsOptions extends EntityRelationValidationOptions {\n /** Extension entity kinds must be explicitly registered; the 14 built-ins are always available. */\n readonly entityKinds?: readonly ExtensionEntityKind[];\n /** Specs for extension relation kinds. Built-in names cannot be replaced. */\n readonly relationSpecs?: readonly RuntimeRelationKindSpec[];\n}\n\nexport interface DecodedEntityRelationSet {\n readonly entitiesById: ReadonlyMap<EntityId, EntityRef>;\n readonly relationIndex: BiRelationIndex;\n readonly relations: readonly RelationAny[];\n}\n\nexport class InvalidEntityRelationRowsError extends Error {\n constructor(readonly issues: readonly string[]) {\n super(`Invalid Medeo entity/relation rows:\\n- ${issues.join('\\n- ')}`);\n this.name = 'InvalidEntityRelationRowsError';\n }\n}\n\n/** Decodes database rows into flat entities and validates the complete relation set. */\nexport function decodeEntityRelationRows(\n rows: EntityRelationRows,\n options: DecodeEntityRelationRowsOptions,\n): DecodedEntityRelationSet {\n const issues: string[] = [];\n const entitiesById = new Map<EntityId, EntityRef>();\n const extensionEntityKinds = new Set<string>(options.entityKinds ?? []);\n\n for (const row of rows.entities) {\n let entity = decodeEntityRow(row, extensionEntityKinds, issues);\n if (entity != null) {\n try {\n entity = decodeEntityRow(assembleEntityContent(rows, row.entityId), extensionEntityKinds, issues);\n } catch (error) {\n issues.push(errorMessage(error));\n continue;\n }\n }\n if (entity == null) continue;\n const ref = createEntityRef(entity);\n if (entitiesById.has(ref.entityId)) {\n issues.push(`duplicate entity id \"${ref.entityId}\"`);\n continue;\n }\n entitiesById.set(ref.entityId, ref);\n }\n\n const specsByKind = collectRelationSpecs(options.relationSpecs ?? [], issues);\n const relationIndex = new BiRelationIndex();\n const relations: RelationAny[] = [];\n const relationIds = new Set<string>();\n\n for (const row of rows.relations) {\n let relationId: RelationId;\n try {\n relationId = createRelationId(row.relationId);\n } catch (error) {\n issues.push(errorMessage(error));\n continue;\n }\n if (relationIds.has(relationId)) {\n issues.push(`duplicate relation id \"${relationId}\"`);\n continue;\n }\n relationIds.add(relationId);\n\n if (!isTrimmedNonEmpty(row.relationKind)) {\n issues.push(`relation \"${relationId}\" has an empty or untrimmed kind`);\n continue;\n }\n const spec = specsByKind.get(row.relationKind);\n if (spec == null) {\n issues.push(`relation \"${relationId}\" has no registered spec for kind \"${row.relationKind}\"`);\n continue;\n }\n\n let endpoint0EntityId: EntityId;\n let endpoint1EntityId: EntityId;\n try {\n endpoint0EntityId = createEntityId(row.endpoint0EntityId);\n endpoint1EntityId = createEntityId(row.endpoint1EntityId);\n } catch (error) {\n issues.push(errorMessage(error));\n continue;\n }\n const endpoint0 = entitiesById.get(endpoint0EntityId);\n const endpoint1 = entitiesById.get(endpoint1EntityId);\n if (endpoint0 == null || endpoint1 == null) {\n const missing = [\n endpoint0 == null ? endpoint0EntityId : undefined,\n endpoint1 == null ? endpoint1EntityId : undefined,\n ]\n .filter((value) => value != null)\n .join(', ');\n issues.push(`relation \"${relationId}\" references missing entity id(s): ${missing}`);\n continue;\n }\n if (!isJsonObject(row.metadata) || !isJsonObject(row.trace)) {\n issues.push(`relation \"${relationId}\" metadata and trace must contain only JSON values`);\n continue;\n }\n\n try {\n relations.push(\n relationIndex.linkRuntime({\n relationId,\n spec,\n endpoints: [endpoint0, endpoint1],\n metadata: row.metadata,\n trace: row.trace,\n }),\n );\n } catch (error) {\n issues.push(errorMessage(error));\n }\n }\n\n if (issues.length === 0) {\n for (const issue of validateEntityRelationSet([...entitiesById.values()], relationIndex, options)) {\n issues.push(`${issue.code}: ${issue.message}`);\n }\n }\n if (issues.length > 0) throw new InvalidEntityRelationRowsError(issues);\n\n return { entitiesById, relationIndex, relations };\n}\n\nfunction decodeEntityRow(\n row: EntityRow,\n extensionEntityKinds: ReadonlySet<string>,\n issues: string[],\n): MedeoEntity | undefined {\n let entityId: EntityId;\n try {\n entityId = createEntityId(row.entityId);\n } catch (error) {\n issues.push(errorMessage(error));\n return undefined;\n }\n if (!isTrimmedNonEmpty(row.entityKind)) {\n issues.push(`entity \"${entityId}\" has an empty or untrimmed kind`);\n return undefined;\n }\n if (isReservedEntityKind(row.entityKind)) {\n issues.push(`entity \"${entityId}\" uses reserved kind \"${row.entityKind}\"`);\n return undefined;\n }\n if (!isKnownEntityKind(row.entityKind) && !extensionEntityKinds.has(row.entityKind)) {\n issues.push(`entity \"${entityId}\" has unregistered extension kind \"${row.entityKind}\"`);\n return undefined;\n }\n if (!isJsonObject(row.payload)) {\n issues.push(`entity \"${entityId}\" payload must contain only JSON values`);\n return undefined;\n }\n const reserved = ['entityId', 'entityKind'].filter((key) => Object.hasOwn(row.payload, key));\n if (reserved.length > 0) {\n issues.push(`entity \"${entityId}\" payload contains reserved field(s): ${reserved.join(', ')}`);\n return undefined;\n }\n return { ...row.payload, entityId, entityKind: row.entityKind as EntityKind } as MedeoEntity;\n}\n\nfunction collectRelationSpecs(\n extensionSpecs: readonly RuntimeRelationKindSpec[],\n issues: string[],\n): ReadonlyMap<string, RuntimeRelationKindSpec> {\n const specs = new Map<string, RuntimeRelationKindSpec>();\n for (const spec of builtInRelationSpecs) specs.set(spec.kind, spec);\n for (const spec of extensionSpecs) {\n if (!isTrimmedNonEmpty(spec.kind)) {\n issues.push('extension relation spec has an empty or untrimmed kind');\n continue;\n }\n if (specs.has(spec.kind)) {\n issues.push(`relation spec kind \"${spec.kind}\" is already registered`);\n continue;\n }\n specs.set(spec.kind, spec);\n }\n return specs;\n}\n\nfunction isTrimmedNonEmpty(value: string): boolean {\n return value.length > 0 && value.trim() === value;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import type {\n BusinessEntityFacade,\n BusinessRelationFacade,\n EntityFacade,\n RelationFacade,\n EntityStoreSnapshot,\n SandboxEntity,\n JsonObject,\n} from '../entity/entity-contract.ts';\n\n/** Resource IDs are entity data; physical storage paths remain host-owned. */\nconst infrastructureFields = new Set(['storageKey', 'assetContentHash']);\n\nexport function businessEntity(entity: SandboxEntity): SandboxEntity {\n return {\n ...entity,\n payload: Object.fromEntries(Object.entries(entity.payload).filter(([key]) => !infrastructureFields.has(key))),\n };\n}\n\nexport function businessState(state: EntityStoreSnapshot): EntityStoreSnapshot {\n const assets = new Set(state.entities.filter((row) => row.entity_kind === 'asset').map((row) => row.entity_id));\n return {\n revision: state.revision,\n audioScriptEntityId: state.audioScriptEntityId,\n entities: state.entities.filter((row) => !assets.has(row.entity_id)).map(businessEntity),\n relations: state.relations.filter(\n (row) =>\n row.relation_kind !== 'from-asset' &&\n !assets.has(row.endpoint_0_entity_id) &&\n !assets.has(row.endpoint_1_entity_id),\n ),\n };\n}\n\n/** Keep infrastructure rows available to assembly without exposing their management to scripts. */\nexport function businessFacades(\n entities: EntityFacade,\n relations: RelationFacade,\n onDirectScriptWrite?: (id: string) => void,\n): {\n entities: BusinessEntityFacade;\n relations: BusinessRelationFacade;\n} {\n const isAsset = (id: string) => entities.get(id)?.entity_kind === 'asset';\n const assertBusiness = (id: string) => {\n if (isAsset(id)) throw new Error('Asset entities are managed by host assembly');\n };\n const assertBusinessPayload = (payload: JsonObject) => {\n for (const field of infrastructureFields) {\n if (Object.hasOwn(payload, field)) throw new Error(`Field ${field} is managed by host assembly`);\n }\n if (Array.isArray(payload.baseEntityIds)) {\n for (const id of payload.baseEntityIds) if (typeof id === 'string') assertBusiness(id);\n }\n };\n const visibleRelation = (relation: ReturnType<RelationFacade['list']>[number]) =>\n relation.relation_kind !== 'from-asset' &&\n !isAsset(relation.endpoint_0_entity_id) &&\n !isAsset(relation.endpoint_1_entity_id);\n return {\n entities: {\n list: () =>\n entities\n .list()\n .filter((entity) => entity.entity_kind !== 'asset')\n .map(businessEntity),\n get: (id) => {\n const entity = entities.get(id);\n return entity && !isAsset(id) ? businessEntity(entity) : null;\n },\n create: (input) => {\n if ((input.entity_kind as string) === 'asset') throw new Error('Asset entities are managed by host assembly');\n assertBusinessPayload(input.payload);\n if (input.entity_id && entities.get(input.entity_id))\n throw new Error(`Entity id ${input.entity_id} already exists`);\n const id = entities.create(input);\n if (input.entity_kind === 'audio-script') onDirectScriptWrite?.(id);\n return id;\n },\n update: (input) => {\n assertBusiness(input.entity_id);\n if (!Array.isArray(input.changes)) throw new Error('entities.update requires changes');\n for (const change of input.changes) {\n if (infrastructureFields.has(change.path?.[0] as string))\n throw new Error('Field is managed by host assembly');\n if (change.path?.[0] === 'baseEntityIds' && change.op === 'list.insert' && typeof change.value === 'string')\n assertBusiness(change.value);\n }\n entities.changeFields(input);\n if (\n entities.get(input.entity_id)?.entity_kind === 'audio-script' &&\n input.changes.some((change) => change.path[0] === 'segments')\n )\n onDirectScriptWrite?.(input.entity_id);\n },\n declareFields: (input) => {\n assertBusiness(input.entity_id);\n assertBusinessPayload(input.payload);\n entities.declareFields(input);\n if (entities.get(input.entity_id)?.entity_kind === 'audio-script' && Object.hasOwn(input.payload, 'segments'))\n onDirectScriptWrite?.(input.entity_id);\n },\n delete: (input) => {\n assertBusiness(input.entity_id);\n const incident = relations.of(input.entity_id);\n // Business associations still require explicit handling; only host-owned\n // infrastructure bindings disappear with their deleted business endpoint.\n if (incident.some(visibleRelation)) {\n entities.delete(input);\n return;\n }\n for (const relation of incident) relations.unlink({ relation_id: relation.relation_id });\n entities.delete(input);\n },\n },\n relations: {\n list: () => relations.list().filter(visibleRelation),\n of: (id, kind) => relations.of(id, kind).filter(visibleRelation),\n link: (input) => {\n if ((input.relation_kind as string) === 'from-asset')\n throw new Error('Asset bindings are managed by host assembly');\n assertBusiness(input.endpoint_0_entity_id);\n assertBusiness(input.endpoint_1_entity_id);\n return relations.link(input);\n },\n unlink: (input) => {\n const relation = relations.list().find((row) => row.relation_id === input.relation_id);\n if (relation && !visibleRelation(relation)) throw new Error('Asset bindings are managed by host assembly');\n relations.unlink(input);\n },\n update: (input) => {\n const relation = relations.list().find((row) => row.relation_id === input.relation_id);\n if (relation && !visibleRelation(relation)) throw new Error('Asset bindings are managed by host assembly');\n relations.update(input);\n },\n },\n };\n}\n","import {\n applyFieldChanges,\n assertFieldChanges,\n assertCanonicalEditorResources,\n readDocumentAudioScript,\n ensureEditorFoundation,\n importMediaAsset,\n type MediaAssetFact,\n} from '@mengine/medeo-client';\nimport {\n assembleCaptionContent,\n findComposedAudioScript,\n assembleEntityContent,\n updateEntityFields,\n resolveEntityFieldOwner,\n validateEntity,\n assemblePhoneticScriptContent,\n BiRelationIndex,\n builtInRelationSpecs,\n createEntityId,\n createEntityRef,\n createRelationId,\n decodeEntityRelationRows,\n entityToRow,\n isJsonObject,\n isKnownEntityKind,\n isMediaAssetVariantKind,\n type Audio,\n type AudioScript,\n type PhoneticScript,\n type Clip,\n type EntityRef,\n type EntityRelationRows,\n type GeneratedMedia,\n type JsonObject as DslJsonObject,\n type MedeoEntity,\n type RelationKindSpec,\n type Video,\n} from '@mengine/medeo-dsl';\n\nimport type {\n AuthorableRelationKind,\n CreateEntityInput,\n DeleteEntityInput,\n EntityCommand,\n EntityUpdateInput,\n RelationUpdateInput,\n EntityFacade,\n EntityPlanState,\n EntityStoreSnapshot,\n LinkPhoneticScriptRenderRelationInput,\n LinkAudioScriptSourceRelationInput,\n LinkClipAnchorRelationInput,\n JsonObject,\n LinkGeneratedRelationInput,\n LinkRelationInput,\n RelationFacade,\n ResourceEntityKind,\n SandboxEntity,\n SandboxRelation,\n UnlinkRelationInput,\n UpdateEntityInput,\n} from './entity-contract.ts';\n\nexport type DomainIdFactory = (prefix: 'entity' | 'relation') => string;\n\nexport interface EntitySandboxOptions {\n state?: EntityStoreSnapshot;\n idFactory: DomainIdFactory;\n onCommand?: (command: EntityCommand) => void;\n onTruncate?: (index: number) => void;\n}\n\n/** Mutable entity/relation draft whose only durable product is an explicit command plan. */\nexport class EntitySandbox {\n private readonly original: EntityStoreSnapshot;\n private readonly idFactory: DomainIdFactory;\n private readonly onCommand: ((command: EntityCommand) => void) | undefined;\n private readonly onTruncate: ((index: number) => void) | undefined;\n private state: EntityStoreSnapshot;\n private readonly commands: EntityCommand[] = [];\n\n readonly entities: EntityFacade;\n readonly relations: RelationFacade;\n\n constructor(options: EntitySandboxOptions) {\n this.original = cloneSnapshot(\n options.state ?? { revision: 0, audioScriptEntityId: null, entities: [], relations: [] },\n );\n this.state = cloneSnapshot(this.original);\n this.idFactory = options.idFactory;\n this.onCommand = options.onCommand;\n this.onTruncate = options.onTruncate;\n this.entities = this.buildEntityFacade();\n this.relations = this.buildRelationFacade();\n }\n\n get commandCount(): number {\n return this.commands.length;\n }\n\n getCommands(): readonly EntityCommand[] {\n return this.commands;\n }\n\n /** Host-owned fixed structure is journaled through the same CAS graph as model edits. */\n ensureFoundation(timelinePayload: JsonObject = {}): void {\n const foundation = ensureEditorFoundation(\n toDslRows(this.state),\n this.idFactory,\n timelinePayload,\n this.state.audioScriptEntityId,\n );\n this.appendResourceRows(foundation.rows);\n if (this.state.audioScriptEntityId === null) this.state.audioScriptEntityId = foundation.audioScriptEntityId;\n }\n\n /** Host assembly resolves the text owner before a resource Caption is complete. */\n captionAudioScriptId(entityId: string): string {\n return findComposedAudioScript(toDslRows(this.state), createEntityId(entityId), 'caption').entityId;\n }\n\n /** The Asset an entity was made from; the bytes are named there alone. */\n assetOf(entityId: string): SandboxEntity | null {\n const link = this.state.relations.find(\n (relation) =>\n relation.relation_kind === 'from-asset' &&\n (relation.endpoint_0_entity_id === entityId || relation.endpoint_1_entity_id === entityId),\n );\n if (!link) return null;\n const otherId = link.endpoint_0_entity_id === entityId ? link.endpoint_1_entity_id : link.endpoint_0_entity_id;\n const other = this.entities.get(otherId);\n return other?.entity_kind === 'asset' ? other : null;\n }\n\n get audioScriptEntityId(): string | null {\n return this.state.audioScriptEntityId;\n }\n\n rollbackTo(index: number): void {\n if (!Number.isInteger(index) || index < 0 || index > this.commands.length) {\n throw new Error(`rollbackTo: entity checkpoint index ${index} is past journal length ${this.commands.length}`);\n }\n const prefix = this.commands.slice(0, index);\n this.state = cloneSnapshot(this.original);\n for (const command of prefix) this.apply(command, false);\n this.commands.length = 0;\n this.commands.push(...prefix);\n this.onTruncate?.(index);\n }\n\n /** The working rows, for callers that must ask the graph rather than one row. */\n rows(): EntityRelationRows {\n return toDslRows(this.state);\n }\n\n buildPlan(): EntityPlanState {\n const rows = toDslRows(this.state);\n decodeEntityRelationRows(rows, numericMarkerComparators);\n // A legacy-only script has no Entity state or Entity edits. Initialized\n // projects and every authored Entity graph must satisfy the project contract.\n if (this.state.revision !== 0 || rows.entities.length !== 0 || this.commands.length !== 0) {\n assertCanonicalEditorResources(rows);\n readDocumentAudioScript({ rows, audioScriptEntityId: this.state.audioScriptEntityId });\n }\n const currentEntityIds = new Set(this.state.entities.map((entity) => entity.entity_id));\n const currentRelationIds = new Set(this.state.relations.map((relation) => relation.relation_id));\n return {\n base_revision: this.original.revision,\n commands: this.commands.slice(),\n rows: cloneSnapshot(this.state),\n deleted_entity_ids: this.original.entities\n .map((entity) => entity.entity_id)\n .filter((entityId) => !currentEntityIds.has(entityId))\n .sort(),\n deleted_relation_ids: this.original.relations\n .map((relation) => relation.relation_id)\n .filter((relationId) => !currentRelationIds.has(relationId))\n .sort(),\n };\n }\n\n renderPreview(): string {\n const lines = [\n `Entity plan: base_revision=${this.original.revision} commands=${this.commands.length} entities=${this.state.entities.length} relations=${this.state.relations.length}`,\n ];\n for (const command of this.commands) {\n switch (command.kind) {\n case 'create-entity':\n lines.push(`+ entity ${command.entity.entity_id} kind=${command.entity.entity_kind}`);\n break;\n case 'change-relation':\n lines.push(`~ relation ${command.relation_id} ${command.changes.map((c) => c.op).join(', ')}`);\n break;\n case 'change-entity':\n lines.push(`~ entity ${command.entity_id} ${command.changes.map((c) => c.op).join(', ')}`);\n break;\n case 'update-entity':\n lines.push(`~ entity ${command.entity_id} payload`);\n break;\n case 'delete-entity':\n lines.push(`- entity ${command.entity_id}`);\n break;\n case 'unlink-relation':\n lines.push(`- relation ${command.relation_id}`);\n break;\n case 'link-relation':\n if (command.relation.relation_kind === 'generated') {\n lines.push(\n `+ relation ${command.relation.relation_id} generated(output=${command.relation.endpoint_0_entity_id}, input=${command.relation.endpoint_1_entity_id})`,\n );\n } else {\n lines.push(\n `+ relation ${command.relation.relation_id} kind=${command.relation.relation_kind} endpoints=${command.relation.endpoint_0_entity_id},${command.relation.endpoint_1_entity_id}`,\n );\n }\n break;\n }\n }\n return lines.join('\\n');\n }\n\n private assembledEntity(entity: SandboxEntity): SandboxEntity {\n const assembled = assembleEntityContent(toDslRows(this.state), createEntityId(entity.entity_id));\n return { ...clone(entity), payload: assembled.payload } as SandboxEntity;\n }\n\n private buildEntityFacade(): EntityFacade {\n return {\n list: () => this.state.entities.map((entity) => this.assembledEntity(entity)),\n get: (entityId) => {\n const entity = this.state.entities.find((candidate) => candidate.entity_id === entityId);\n return entity == null ? null : this.assembledEntity(entity);\n },\n findByAssetId: (assetId) => {\n assertTrimmed(assetId, 'assetId');\n // The id names an Asset; what a caller wants is what was made from it.\n const assetIds = new Set(\n this.state.entities\n .filter((entity) => entity.entity_kind === 'asset' && isImportedMemotaAsset(entity.payload, assetId))\n .map((entity) => entity.entity_id),\n );\n const madeIds = new Set(\n this.state.relations\n .filter((relation) => relation.relation_kind === 'from-asset')\n .flatMap((relation) =>\n assetIds.has(relation.endpoint_1_entity_id)\n ? [relation.endpoint_0_entity_id]\n : assetIds.has(relation.endpoint_0_entity_id)\n ? [relation.endpoint_1_entity_id]\n : [],\n ),\n );\n return clone(\n this.state.entities\n .filter((entity) => madeIds.has(entity.entity_id) && isMediaAssetVariantKind(entity.entity_kind))\n .map((entity) => this.assembledEntity(entity) as SandboxEntity<ResourceEntityKind>),\n );\n },\n readCaptionContent: (entityId) => {\n const assembled = assembleCaptionContent(toDslRows(this.state), createEntityId(entityId));\n return clone({\n audio_script_entity_id: assembled.audioScript.entityId,\n segment_index: assembled.segmentIndex,\n text: assembled.text,\n segments: assembled.segments.map((segment) => ({ ...segment })),\n });\n },\n readPhoneticScriptContent: (entityId) => {\n const assembled = assemblePhoneticScriptContent(toDslRows(this.state), createEntityId(entityId));\n const own = assembled.phoneticScript.payload;\n return clone({\n audio_script_entity_id: assembled.audioScript.entityId,\n text: assembled.text,\n segments: assembled.segments.map((segment) => ({ ...segment })),\n ...(typeof own.phonemeScript === 'string' ? { phonemeScript: own.phonemeScript } : {}),\n ...(isJsonObject(own.prosody) ? { prosody: clone(own.prosody) as JsonObject } : {}),\n });\n },\n create: (input) => this.createEntity(input),\n changeFields: (input) => this.changeEntity(input),\n update: (input) => {\n assertTrimmed(input.entity_id, 'entity_id');\n if (!this.state.entities.some((entity) => entity.entity_id === input.entity_id))\n throw new Error(`Entity id \"${input.entity_id}\" does not exist`);\n const updates = updateEntityFields(\n toDslRows(this.state),\n createEntityId(input.entity_id),\n input.payload as DslJsonObject,\n );\n for (const row of updates)\n this.replaceOwnedPayload({ entity_id: row.entityId, payload: row.payload as JsonObject });\n },\n declareFields: (input) => {\n const current = this.state.entities.find((entity) => entity.entity_id === input.entity_id);\n if (current === undefined) throw new Error(`Unknown entity \"${input.entity_id}\"`);\n assembleEntityContent(toDslRows(this.state), createEntityId(input.entity_id));\n const payload = { ...current.payload, ...input.payload };\n const candidate = {\n ...this.state,\n entities: this.state.entities.map((row) =>\n row.entity_id === input.entity_id ? ({ ...row, payload } as SandboxEntity) : row,\n ),\n };\n const rows = toDslRows(candidate);\n for (const row of rows.entities) assembleEntityContent(rows, row.entityId);\n const assembled = assembleEntityContent(rows, createEntityId(input.entity_id));\n const issues = validateEntity(\n createEntityRef({\n ...assembled.payload,\n entityId: assembled.entityId,\n entityKind: assembled.entityKind,\n } as MedeoEntity),\n );\n if (issues.length) throw new Error(issues.map((issue) => issue.message).join('; '));\n this.replaceOwnedPayload({ entity_id: input.entity_id, payload });\n },\n delete: (input) => this.deleteEntity(input),\n ensureMedia: (fact) => this.ensureMedia(fact),\n ensureAsset: (locator) => this.ensureAsset(locator),\n assetIdOf: (entityId) => this.assetOf(entityId)?.entity_id ?? null,\n };\n }\n\n private buildRelationFacade(): RelationFacade {\n return {\n list: () => clone(this.state.relations),\n of: (entityId, relationKind) => {\n assertTrimmed(entityId, 'entityId');\n if (relationKind !== undefined && !builtInRelationSpecs.some((spec) => spec.kind === relationKind)) {\n throw new Error(`Unknown Relation kind \"${relationKind}\"`);\n }\n return clone(\n this.state.relations.filter(\n (relation) =>\n (relation.endpoint_0_entity_id === entityId || relation.endpoint_1_entity_id === entityId) &&\n (relationKind === undefined || relation.relation_kind === relationKind),\n ),\n );\n },\n link: (input) => this.link(input),\n linkGenerated: (input) => this.linkGenerated(input),\n linkClipAnchor: (input) => this.linkClipAnchor(input),\n linkPhoneticScriptRender: (input) => this.linkPhoneticScriptRender(input),\n linkAudioScriptSource: (input) => this.linkAudioScriptSource(input),\n unlink: (input) => this.unlinkRelation(input),\n update: (input) => this.changeRelation(input),\n };\n }\n\n private createEntity(input: CreateEntityInput): string {\n if (!isKnownEntityKind(input.entity_kind)) {\n throw new Error(`Unknown or extension Entity kind \"${String(input.entity_kind)}\"`);\n }\n const payload = clone(input.payload);\n if (!isJsonObject(payload)) throw new Error('Entity payload must contain only JSON values');\n if (input.entity_kind === 'timeline' || input.entity_kind === 'track') {\n const matches = this.state.entities.filter(\n (entity) =>\n entity.entity_kind === input.entity_kind &&\n (input.entity_kind === 'timeline' || entity.payload.role === payload.role),\n );\n if (matches.length > 1) throw new Error(`Ambiguous editor ${input.entity_kind}; resolve existing identities`);\n if (matches[0] !== undefined) return this.reuseEntity(matches[0], input, payload);\n }\n if (input.entity_kind === 'asset' && typeof payload.key === 'string') {\n const matches = this.state.entities.filter(\n (entity) =>\n entity.entity_kind === 'asset' &&\n entity.payload.system === payload.system &&\n entity.payload.key === payload.key,\n );\n if (matches.length > 1) throw new Error(`Ambiguous Assets for ${payload.key}`);\n if (matches[0] !== undefined) return this.reuseEntity(matches[0], input, payload);\n }\n const entityId = input.entity_id ?? this.idFactory('entity');\n assertTrimmed(entityId, 'entity_id');\n const entity: SandboxEntity = {\n entity_id: entityId,\n entity_kind: input.entity_kind,\n payload,\n };\n const decoded = {\n ...entity.payload,\n entityId: createEntityId(entityId),\n entityKind: entity.entity_kind,\n } as MedeoEntity;\n entityToRow(decoded);\n assembleEntityContent(\n toDslRows({ ...this.state, entities: [...this.state.entities, entity] }),\n createEntityId(entityId),\n );\n this.record({ kind: 'create-entity', entity });\n return entityId;\n }\n\n private reuseEntity(existing: SandboxEntity, input: CreateEntityInput, payload: JsonObject): string {\n if (input.entity_id !== undefined && input.entity_id !== existing.entity_id)\n throw new Error(`Entity already exists; reuse ${existing.entity_id}`);\n for (const [key, value] of Object.entries(payload)) {\n if (existing.payload[key] !== undefined && !sameJson(existing.payload[key], value))\n throw new Error(`Resource facts conflict for ${existing.entity_id}: ${key}`);\n }\n const merged = { ...existing.payload, ...payload };\n if (!sameJson(existing.payload, merged))\n this.replaceOwnedPayload({ entity_id: existing.entity_id, payload: merged });\n return existing.entity_id;\n }\n\n /** Host persistence adapter; never exposed as the DSL field update operation. */\n replaceOwnedPayload(input: UpdateEntityInput): void {\n assertTrimmed(input.entity_id, 'entity_id');\n const payload = clone(input.payload);\n if (!isJsonObject(payload)) throw new Error('Entity payload must contain only JSON values');\n this.record({ kind: 'update-entity', entity_id: input.entity_id, payload });\n }\n\n private changeEntity(input: EntityUpdateInput): void {\n assertFieldChanges(input.changes);\n this.record({ kind: 'change-entity', entity_id: input.entity_id, changes: clone(input.changes) });\n }\n\n private changeRelation(input: RelationUpdateInput): void {\n assertFieldChanges(input.changes);\n this.record({ kind: 'change-relation', relation_id: input.relation_id, changes: clone(input.changes) });\n }\n\n private deleteEntity(input: DeleteEntityInput): void {\n assertTrimmed(input.entity_id, 'entity_id');\n this.record({ kind: 'delete-entity', entity_id: input.entity_id });\n }\n\n /** Get or create the one Asset entity naming these bytes. */\n private ensureAsset(locator: { system: 'memota' | 'memota-speech'; key: string; storageKey?: string }): string {\n const found = this.state.entities.find(\n (row) => row.entity_kind === 'asset' && row.payload.system === locator.system && row.payload.key === locator.key,\n );\n if (found) return found.entity_id;\n return this.createEntity({\n entity_kind: 'asset',\n payload: { ...locator, ...(locator.storageKey === undefined ? {} : { storageKey: locator.storageKey }) },\n } as CreateEntityInput);\n }\n\n private ensureMedia(fact: MediaAssetFact): { contentEntityId: string } {\n const checkpoint = this.commandCount;\n try {\n const imported = importMediaAsset(toDslRows(this.state), fact, this.idFactory);\n this.appendResourceRows(imported.rows);\n return { contentEntityId: imported.contentEntityId };\n } catch (error) {\n this.rollbackTo(checkpoint);\n throw error;\n }\n }\n\n private appendResourceRows(rows: EntityRelationRows): void {\n for (const row of rows.entities) {\n const existing = this.state.entities.find((entity) => entity.entity_id === row.entityId);\n if (existing === undefined) {\n this.createEntity({\n entity_id: row.entityId,\n entity_kind: row.entityKind,\n payload: row.payload,\n } as CreateEntityInput);\n } else if (!sameJson(existing.payload, row.payload)) {\n this.replaceOwnedPayload({ entity_id: row.entityId, payload: clone(row.payload) as JsonObject });\n }\n }\n for (const row of rows.relations) {\n if (this.state.relations.some((relation) => relation.relation_id === row.relationId)) continue;\n // Foundation assembly emits timeline-track; a synthesized voiceover import\n // also emits the voice-timbre link to its Voice identity.\n if (\n row.relationKind !== 'timeline-track' &&\n row.relationKind !== 'voice-timbre' &&\n row.relationKind !== 'from-asset'\n )\n throw new Error(`Unexpected resource Relation ${row.relationKind}`);\n this.link({\n relation_id: row.relationId,\n relation_kind: row.relationKind,\n endpoint_0_entity_id: row.endpoint0EntityId,\n endpoint_1_entity_id: row.endpoint1EntityId,\n metadata: clone(row.metadata) as JsonObject,\n trace: clone(row.trace) as JsonObject,\n } as LinkRelationInput);\n }\n }\n\n private link(input: LinkRelationInput): string {\n const spec = builtInRelationSpecs.find((candidate) => candidate.kind === input.relation_kind);\n if (spec == null) throw new Error(`Unknown Relation kind \"${String(input.relation_kind)}\"`);\n const relation = this.relationFromInput(input, input.relation_kind);\n const [first, second] = this.refsFor(relation);\n new BiRelationIndex().linkRuntime({\n relationId: createRelationId(relation.relation_id),\n spec: spec as unknown as RelationKindSpec<AuthorableRelationKind, MedeoEntity, MedeoEntity, DslJsonObject>,\n endpoints: [first, second],\n metadata: relation.metadata,\n trace: relation.trace,\n });\n this.record({ kind: 'link-relation', relation });\n return relation.relation_id;\n }\n\n private linkGenerated(input: LinkGeneratedRelationInput): string {\n const relation = this.relationFromInput(\n {\n ...(input.relation_id !== undefined ? { relation_id: input.relation_id } : {}),\n endpoint_0_entity_id: input.output_entity_id,\n endpoint_1_entity_id: input.input_entity_id,\n metadata: {},\n ...(input.trace !== undefined ? { trace: input.trace } : {}),\n },\n 'generated',\n );\n const [output, source] = this.refsFor(relation);\n new BiRelationIndex().linkGenerated({\n relationId: createRelationId(relation.relation_id),\n output: output as EntityRef<GeneratedMedia>,\n input: source as EntityRef<GeneratedMedia>,\n trace: relation.trace,\n });\n this.record({ kind: 'link-relation', relation });\n return relation.relation_id;\n }\n\n private linkClipAnchor(input: LinkClipAnchorRelationInput): string {\n const relation = this.relationFromInput(\n {\n ...(input.relation_id !== undefined ? { relation_id: input.relation_id } : {}),\n endpoint_0_entity_id: input.child_clip_entity_id,\n endpoint_1_entity_id: input.host_clip_entity_id,\n metadata: {},\n ...(input.trace !== undefined ? { trace: input.trace } : {}),\n },\n 'clip-anchor',\n );\n const [child, host] = this.refsFor(relation);\n new BiRelationIndex().linkClipAnchor({\n relationId: createRelationId(relation.relation_id),\n child: child as EntityRef<Clip>,\n host: host as EntityRef<Clip>,\n trace: relation.trace,\n });\n this.record({ kind: 'link-relation', relation });\n return relation.relation_id;\n }\n\n private linkPhoneticScriptRender(input: LinkPhoneticScriptRenderRelationInput): string {\n const relation = this.relationFromInput(\n {\n ...(input.relation_id !== undefined ? { relation_id: input.relation_id } : {}),\n endpoint_0_entity_id: input.output_entity_id,\n endpoint_1_entity_id: input.phonetic_script_entity_id,\n metadata: {},\n ...(input.trace !== undefined ? { trace: input.trace } : {}),\n },\n 'phonetic-script-render',\n );\n const [output, script] = this.refsFor(relation);\n new BiRelationIndex().linkPhoneticScriptRender({\n relationId: createRelationId(relation.relation_id),\n output: output as EntityRef<Audio>,\n phoneticScript: script as EntityRef<PhoneticScript>,\n trace: relation.trace,\n });\n this.record({ kind: 'link-relation', relation });\n return relation.relation_id;\n }\n\n private linkAudioScriptSource(input: LinkAudioScriptSourceRelationInput): string {\n const relation = this.relationFromInput(\n {\n ...(input.relation_id !== undefined ? { relation_id: input.relation_id } : {}),\n endpoint_0_entity_id: input.script_entity_id,\n endpoint_1_entity_id: input.source_entity_id,\n metadata: {},\n ...(input.trace !== undefined ? { trace: input.trace } : {}),\n },\n 'audio-script-source',\n );\n const [script, source] = this.refsFor(relation);\n new BiRelationIndex().linkAudioScriptSource({\n relationId: createRelationId(relation.relation_id),\n script: script as EntityRef<AudioScript>,\n source: source as EntityRef<Audio | Video>,\n trace: relation.trace,\n });\n this.record({ kind: 'link-relation', relation });\n return relation.relation_id;\n }\n\n private unlinkRelation(input: UnlinkRelationInput): void {\n assertTrimmed(input.relation_id, 'relation_id');\n this.record({ kind: 'unlink-relation', relation_id: input.relation_id });\n }\n\n private relationFromInput(\n input: {\n relation_id?: string;\n endpoint_0_entity_id: string;\n endpoint_1_entity_id: string;\n metadata?: JsonObject;\n trace?: JsonObject;\n },\n relationKind: SandboxRelation['relation_kind'],\n ): SandboxRelation {\n const relationId = input.relation_id ?? this.idFactory('relation');\n assertTrimmed(relationId, 'relation_id');\n assertTrimmed(input.endpoint_0_entity_id, 'endpoint_0_entity_id');\n assertTrimmed(input.endpoint_1_entity_id, 'endpoint_1_entity_id');\n const metadata = clone(input.metadata ?? {});\n const trace = clone(input.trace ?? {});\n if (!isJsonObject(metadata) || !isJsonObject(trace)) {\n throw new Error('Relation metadata and trace must contain only JSON values');\n }\n return {\n relation_id: relationId,\n relation_kind: relationKind,\n endpoint_0_entity_id: input.endpoint_0_entity_id,\n endpoint_1_entity_id: input.endpoint_1_entity_id,\n metadata,\n trace,\n };\n }\n\n private refsFor(relation: SandboxRelation): readonly [EntityRef, EntityRef] {\n const first = this.state.entities.find((entity) => entity.entity_id === relation.endpoint_0_entity_id);\n const second = this.state.entities.find((entity) => entity.entity_id === relation.endpoint_1_entity_id);\n if (first == null || second == null) {\n const missing = [\n first == null ? relation.endpoint_0_entity_id : null,\n second == null ? relation.endpoint_1_entity_id : null,\n ]\n .filter((value) => value != null)\n .join(', ');\n throw new Error(`Relation references missing Entity id(s): ${missing}`);\n }\n return [createEntityRef(toDslEntity(first)), createEntityRef(toDslEntity(second))];\n }\n\n private record(command: EntityCommand): void {\n this.apply(command, true);\n this.commands.push(clone(command));\n this.onCommand?.(clone(command));\n }\n\n private apply(command: EntityCommand, enforceIdentity: boolean): void {\n switch (command.kind) {\n case 'create-entity': {\n if (enforceIdentity && this.state.entities.some((entity) => entity.entity_id === command.entity.entity_id)) {\n throw new Error(`Entity id \"${command.entity.entity_id}\" already exists`);\n }\n const original = this.original.entities.find((entity) => entity.entity_id === command.entity.entity_id);\n if (enforceIdentity && original != null) {\n throw new Error(\n `Entity id \"${command.entity.entity_id}\" was originally kind \"${original.entity_kind}\" and cannot be recreated as \"${command.entity.entity_kind}\"`,\n );\n }\n this.state.entities.push(clone(command.entity));\n if (command.entity.entity_kind === 'audio-script' && this.state.audioScriptEntityId === null) {\n this.state.audioScriptEntityId = command.entity.entity_id;\n }\n return;\n }\n case 'update-entity': {\n const index = this.state.entities.findIndex((entity) => entity.entity_id === command.entity_id);\n if (index < 0) throw new Error(`Entity id \"${command.entity_id}\" does not exist`);\n const current = this.state.entities[index];\n if (current == null) throw new Error(`Entity id \"${command.entity_id}\" does not exist`);\n this.state.entities[index] = { ...current, payload: clone(command.payload) };\n return;\n }\n case 'change-entity': {\n const original = this.state;\n this.state = cloneSnapshot(original);\n try {\n const touched = new Set<string>([command.entity_id]);\n for (const change of command.changes) {\n if (change.path[0] === 'baseEntityIds' && change.op === 'list.move')\n throw new Error('Composition bases are unordered; list.move is not applicable');\n const owner = resolveEntityFieldOwner(\n toDslRows(this.state),\n createEntityId(command.entity_id),\n change.path[0] as string,\n );\n const row = this.state.entities.find((row) => row.entity_id === owner)!;\n row.payload = applyFieldChanges(row.payload, [change]) as SandboxEntity['payload'];\n touched.add(owner);\n }\n const rows = toDslRows(this.state);\n for (const row of rows.entities) {\n const assembled = assembleEntityContent(rows, row.entityId);\n if (touched.has(row.entityId)) {\n const issues = validateEntity(\n createEntityRef({\n ...assembled.payload,\n entityId: row.entityId,\n entityKind: row.entityKind,\n } as MedeoEntity),\n );\n if (issues.length) throw new Error(issues.map((issue) => issue.message).join('; '));\n }\n }\n } catch (error) {\n this.state = original;\n throw error;\n }\n return;\n }\n case 'change-relation': {\n const index = this.state.relations.findIndex((row) => row.relation_id === command.relation_id);\n if (index < 0) throw new Error(`Unknown relation ${command.relation_id}`);\n for (const change of command.changes) {\n if (!['metadata', 'trace'].includes(change.path[0] as string) || change.path.length < 2)\n throw new Error('Relation changes may only edit metadata or trace fields');\n }\n const current = this.state.relations[index]!;\n const fields = applyFieldChanges({ metadata: current.metadata, trace: current.trace }, command.changes);\n const next = { ...current, metadata: fields.metadata as JsonObject, trace: fields.trace as JsonObject };\n const spec = builtInRelationSpecs.find((spec) => spec.kind === next.relation_kind)!;\n new BiRelationIndex().linkRuntime({\n relationId: createRelationId(next.relation_id),\n spec: spec as unknown as RelationKindSpec<AuthorableRelationKind, MedeoEntity, MedeoEntity, DslJsonObject>,\n endpoints: this.refsFor(next),\n metadata: next.metadata,\n trace: next.trace,\n });\n this.state.relations[index] = next;\n return;\n }\n case 'delete-entity': {\n const target = this.state.entities.find((entity) => entity.entity_id === command.entity_id);\n if (target && (target.entity_kind === 'timeline' || target.entity_id === this.state.audioScriptEntityId)) {\n throw new Error('An entity attached to the project editor cannot be deleted');\n }\n const dependents = this.state.entities.filter(\n (entity) =>\n Array.isArray(entity.payload.baseEntityIds) && entity.payload.baseEntityIds.includes(command.entity_id),\n );\n if (dependents.length)\n throw new Error(\n `Entity ${command.entity_id} is still referenced by variants: ${dependents.map((row) => row.entity_id).join(', ')}`,\n );\n const index = this.state.entities.findIndex((entity) => entity.entity_id === command.entity_id);\n if (index < 0) throw new Error(`Entity id \"${command.entity_id}\" does not exist`);\n const incidentRelationIds = this.state.relations\n .filter(\n (relation) =>\n relation.endpoint_0_entity_id === command.entity_id ||\n relation.endpoint_1_entity_id === command.entity_id,\n )\n .map((relation) => relation.relation_id)\n .sort();\n if (incidentRelationIds.length > 0) {\n throw new Error(\n `Entity id \"${command.entity_id}\" still has incident Relation id(s): ${incidentRelationIds.join(', ')}`,\n );\n }\n this.state.entities.splice(index, 1);\n return;\n }\n case 'link-relation':\n if (\n enforceIdentity &&\n this.state.relations.some((relation) => relation.relation_id === command.relation.relation_id)\n ) {\n throw new Error(`Relation id \"${command.relation.relation_id}\" already exists`);\n }\n if (enforceIdentity) {\n const original = this.original.relations.find(\n (relation) => relation.relation_id === command.relation.relation_id,\n );\n if (\n original != null &&\n (original.relation_kind !== command.relation.relation_kind ||\n original.endpoint_0_entity_id !== command.relation.endpoint_0_entity_id ||\n original.endpoint_1_entity_id !== command.relation.endpoint_1_entity_id)\n ) {\n throw new Error(\n `Relation id \"${command.relation.relation_id}\" cannot change its kind or persisted endpoint positions`,\n );\n }\n }\n this.state.relations.push(clone(command.relation));\n return;\n case 'unlink-relation': {\n const index = this.state.relations.findIndex((relation) => relation.relation_id === command.relation_id);\n if (index < 0) throw new Error(`Relation id \"${command.relation_id}\" does not exist`);\n this.state.relations.splice(index, 1);\n return;\n }\n }\n }\n}\n\nfunction isImportedMemotaAsset(payload: JsonObject, assetId: string): boolean {\n return (payload.system === 'memota' || payload.system === 'memota-speech') && payload.key === assetId;\n}\n\nfunction toDslEntity(entity: SandboxEntity): MedeoEntity {\n return {\n ...clone(entity.payload),\n entityId: createEntityId(entity.entity_id),\n entityKind: entity.entity_kind,\n } as MedeoEntity;\n}\n\nexport function toDslRows(state: EntityStoreSnapshot): EntityRelationRows {\n return {\n entities: state.entities.map((entity) => ({\n entityId: createEntityId(entity.entity_id),\n entityKind: entity.entity_kind,\n payload: clone(entity.payload),\n })),\n relations: state.relations.map((relation) => ({\n relationId: createRelationId(relation.relation_id),\n relationKind: relation.relation_kind,\n endpoint0EntityId: createEntityId(relation.endpoint_0_entity_id),\n endpoint1EntityId: createEntityId(relation.endpoint_1_entity_id),\n metadata: clone(relation.metadata),\n trace: clone(relation.trace),\n })),\n };\n}\n\nfunction cloneSnapshot(state: EntityStoreSnapshot): EntityStoreSnapshot {\n return clone(state);\n}\n\nfunction clone<T>(value: T): T {\n return structuredClone(value);\n}\n\nfunction sameJson(left: unknown, right: unknown): boolean {\n if (left === right) return true;\n if (Array.isArray(left) && Array.isArray(right))\n return left.length === right.length && left.every((value, index) => sameJson(value, right[index]));\n if (!isJsonObject(left) || !isJsonObject(right)) return false;\n const keys = Object.keys(left);\n return (\n keys.length === Object.keys(right).length &&\n keys.every((key) => Object.hasOwn(right, key) && sameJson(left[key], right[key]))\n );\n}\n\nfunction assertTrimmed(value: string, label: string): void {\n if (typeof value !== 'string' || value.length === 0 || value.trim() !== value) {\n throw new Error(`${label} must be a non-empty trimmed string`);\n }\n}\n\nconst numericMarkerComparators = {\n compareMarkerPoints: (_marker: unknown, _range: 'source' | 'target', left: unknown, right: unknown) => {\n if (typeof left !== 'number' || !Number.isFinite(left) || typeof right !== 'number' || !Number.isFinite(right)) {\n throw new Error('Sequence Marker points require finite numeric coordinates in the entity sandbox');\n }\n return left - right;\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsDA,MAAa,eAAmE,OAAO,OAAO;CAC5F,SAAS,OAAO,OAAO;EAAC;EAAa;EAAY;EAAU;CAAS,CAAU;CAC9E,UAAU,OAAO,OAAO,CAAC,WAAW,CAAU;CAC9C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