Skip to content

armgit / hypit

Public Imported from GitHub
0

Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.

chore: remove the retained v1 research compiler

kashorin8468355b5a5c
diff --git a/examples/composite-speech-program/README.md b/examples/composite-speech-program/README.md
deleted file mode 100644
index 24a56550..00000000
--- a/examples/composite-speech-program/README.md
+++ /dev/null
@@ -1,45 +0,0 @@
-# Legacy v1 Composite Speech Program executable fixture
-
-This directory is retained as executable v1 regression evidence while the rewrite proceeds. Its
-`.svk` filename is a fixture-local legacy convention, not a v2 package kind, import rule or public
-file suffix. Current v2 sources use self-described Frontend Headers and ordinary package facets;
-see [`../../docs/source-and-run-compilation-v1.md`](../../docs/source-and-run-compilation-v1.md).
-
-This directory proves the implemented `composite-v1` profile.
-
-- `minimal.svml` is the author-facing source.
-- `speech-program.svk` statically expands `speech-assemble` and
- `speech-locator`.
-- `house.svs` configures only public Composite parameters.
-- `alignment.json` is explicit typed Evidence.
-
-For `<speech-program id="voice">`, expansion creates:
-
-```text
-voice::basis → TemporalBasisProduction + ProgramBoundVideoSequence
- │
- └──────────────> voice::locator → CompleteSemanticMap
-
-voice.production = voice::basis.production
-voice.map = voice::locator.map
-voice.facets.visual = voice::basis.facets.visual
-```
-
-The two internal instances, implementation digests, Evidence dependencies and
-outputs remain visible in Plan and lock. The outer ports are aliases; the
-Composite does not copy Artifacts or merge execution boundaries.
-
-`join` and `joinDuration` are author shorthand forwarded to one assembler. Each
-explicit `<join after="...">` may override the corresponding boundary. They do
-not select a compiler family or language-level mode.
-
-The bracket expression in `ports.script.segment[item.id]` is a stable id-keyed
-lookup over finite declared children, not positional indexing. The Composite
-receives Script and Evidence through explicit typed inputs and cannot read
-ambient document state.
-
-```sh
-pnpm svml check examples/composite-speech-program/minimal.svml
-pnpm svml compile examples/composite-speech-program/minimal.svml \
- --out /tmp/svml-composite/index.html
-```
diff --git a/examples/composite-speech-program/alignment.json b/examples/composite-speech-program/alignment.json
deleted file mode 100644
index a23de902..00000000
--- a/examples/composite-speech-program/alignment.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "contract": "svml.speech-timing-evidence.v1",
- "durationSec": 9.5,
- "fps": 30,
- "quality": "measured",
- "units": [
- { "text": "Hello", "startSec": 0.2, "endSec": 0.8, "segmentId": "intro" },
- { "text": "this", "startSec": 1.0, "endSec": 1.5, "segmentId": "intro" },
- { "text": "is", "startSec": 1.6, "endSec": 1.9, "segmentId": "intro" },
- { "text": "SVML", "startSec": 2.0, "endSec": 2.8, "segmentId": "intro" },
- { "text": "Write", "startSec": 4.7, "endSec": 5.2, "segmentId": "close" },
- { "text": "the", "startSec": 5.3, "endSec": 5.6, "segmentId": "close" },
- { "text": "script", "startSec": 5.7, "endSec": 6.2, "segmentId": "close" },
- { "text": "get", "startSec": 6.4, "endSec": 6.7, "segmentId": "close" },
- { "text": "the", "startSec": 6.8, "endSec": 7.1, "segmentId": "close" },
- { "text": "video", "startSec": 7.2, "endSec": 8.0, "segmentId": "close" }
- ],
- "segments": [
- { "id": "intro", "startSec": 0, "endSec": 5 },
- { "id": "close", "startSec": 4.5, "endSec": 9.5 }
- ]
-}
diff --git a/examples/composite-speech-program/house.svs b/examples/composite-speech-program/house.svs
deleted file mode 100644
index 3aed91b3..00000000
--- a/examples/composite-speech-program/house.svs
+++ /dev/null
@@ -1,13 +0,0 @@
-<sheet version="1" id="house">
-
- speech-program.default {
- join: cut;
- join-duration: 0ms;
- }
-
- speech-program.smooth {
- join: crossfade;
- join-duration: 500ms;
- }
-
-</sheet>
diff --git a/examples/composite-speech-program/minimal.svml b/examples/composite-speech-program/minimal.svml
deleted file mode 100644
index 70370f95..00000000
--- a/examples/composite-speech-program/minimal.svml
+++ /dev/null
@@ -1,34 +0,0 @@
-<svml version="1">
- <import from="./speech-program.svk"/>
- <import from="../../stdlib/media-track.svk"/>
- <import from="../../stdlib/film.svk"/>
- <import as="house" from="./house.svs"/>
-
- <script>
- <segment id="intro">
- <HOST> Hello, this is SVML.
- </segment>
-
- <segment id="close">
- <HOST> Write the script, get the video.
- </segment>
- </script>
-
- <video id="host" src="../regen-ranking/assets/avatar-1.mp4"/>
- <audio id="host-audio" src="../regen-ranking/assets/avatar-1.mp3"/>
- <timing id="timing" src="./alignment.json"/>
-
- <speech-program id="voice" script={script} evidence={timing} class="house.default">
- <segment id="intro" visual={host} audio={host-audio} sourceWindow="0s .. 5s"/>
- <segment id="close" visual={host} audio={host-audio} sourceWindow="5s .. 10s"/>
- <join after="intro" overlap="500ms" audio="crossfade" visual="dissolve"/>
- </speech-program>
-
- <media-track id="aroll" z="100">
- <item id="host" source={voice.facets.visual} during="full" playback="program-map"/>
- </media-track>
-
- <film id="main" basis={voice.production} semantic={voice.map} width="1080" height="1920">
- <track ref={aroll.track}/>
- </film>
-</svml>
diff --git a/examples/composite-speech-program/speech-program.svk b/examples/composite-speech-program/speech-program.svk
deleted file mode 100644
index 8b1277db..00000000
--- a/examples/composite-speech-program/speech-program.svk
+++ /dev/null
@@ -1,57 +0,0 @@
-<kernel name="speech-program" abi="1" profile="composite-v1">
- <port name="script" direction="input" type="NarrativeIR" cardinality="one"/>
- <port name="evidence" direction="input" type="SpeechTimingEvidence" cardinality="one"/>
- <port name="production" direction="output" type="TemporalBasisProduction" cardinality="one"/>
- <port name="map" direction="output" type="CompleteSemanticMap" cardinality="one"/>
- <port name="facets.visual" direction="output" type="ProgramBoundVideoSequence" cardinality="one"/>
-
- <param name="join" type="enum(cut,crossfade,gap)" default="cut"/>
- <param name="joinDuration" style="join-duration" type="duration" default="0ms"/>
-
- <child name="segment" cardinality="one-or-more">
- <field name="id" type="id" required="true"/>
- <field name="visual" type="Video"/>
- <field name="audio" type="Audio" required="true"/>
- <field name="sourceWindow" type="SourceRange" required="true"/>
- </child>
-
- <child name="join" cardinality="zero-or-more">
- <field name="after" type="id" required="true"/>
- <field name="overlap" type="duration"/>
- <field name="gap" type="duration"/>
- <field name="audio" type="enum(cut,crossfade)"/>
- <field name="visual" type="enum(cut,dissolve)"/>
- </child>
-
- <import as="assemble" from="../../stdlib/speech-assemble.svk"/>
- <import as="locate" from="../../stdlib/speech-locator.svk"/>
-
- <compose>
- <assemble id="basis" defaultJoin={params.join} defaultJoinDuration={params.joinDuration}>
- <for each={children.segment} as="item">
- <segment
- id={item.id}
- script={ports.script.segment[item.id]}
- visual={item.visual}
- audio={item.audio}
- sourceWindow={item.sourceWindow}
- />
- </for>
- <for each={children.join} as="join">
- <join
- after={join.after}
- overlap={join.overlap}
- gap={join.gap}
- audio={join.audio}
- visual={join.visual}
- />
- </for>
- </assemble>
-
- <locate id="locator" script={ports.script} basis={basis.production} evidence={ports.evidence}/>
-
- <export port="production" value={basis.production}/>
- <export port="map" value={locator.map}/>
- <export port="facets.visual" value={basis.facets.visual}/>
- </compose>
-</kernel>
diff --git a/examples/flat-track-launch/README.md b/examples/flat-track-launch/README.md
deleted file mode 100644
index d6db0113..00000000
--- a/examples/flat-track-launch/README.md
+++ /dev/null
@@ -1,23 +0,0 @@
-# Flat Track Launch executable fixture
-
-This is the end-to-end v1 architecture fixture. It compiles without generation
-providers and exercises the contracts together:
-
-- independent Script Segment endpoints (`2M + 2N`);
-- replaceable Basis Producer and Locator Components;
-- one explicit `ProgramBasis` plus `CompleteSemanticMap`;
-- flat Tracks and absolute `z`, with Film as the only `Track[]` consumer;
-- one continuous A-roll mapping with overlapping Present windows;
-- manual `ProgramSpan`, a `Moment`, B-roll audio and a visual crossfade;
-- a disconnected SelectionSet driving one caption style rule;
-- top-level and nested Component fields configured by `.svs`.
-
-It reuses the checked-in local artifacts and measured speech timing evidence from the
-adjacent `regen-ranking` example. No provider is called.
-
-```sh
-pnpm svml compile examples/flat-track-launch/flat-track-launch.svml \
- --out /tmp/svml-flat-track-launch/index.html
-pnpm svml render examples/flat-track-launch/flat-track-launch.svml \
- --out /tmp/svml-flat-track-launch.mp4
-```
diff --git a/examples/flat-track-launch/flat-track-launch.svml b/examples/flat-track-launch/flat-track-launch.svml
deleted file mode 100644
index 2a513e20..00000000
--- a/examples/flat-track-launch/flat-track-launch.svml
+++ /dev/null
@@ -1,131 +0,0 @@
-<svml version="1">
-
- <import from="../../stdlib/speech-assemble.svk"/>
- <import from="../../stdlib/speech-locator.svk"/>
- <import from="../../stdlib/media-track.svk"/>
- <import from="../../stdlib/broll-track.svk"/>
- <import from="../../stdlib/ranking-column.svk"/>
- <import from="../../stdlib/text-track.svk"/>
- <import from="../../stdlib/caption-planner.svk"/>
- <import from="../../stdlib/caption-track.svk"/>
- <import from="../../stdlib/audio-track.svk"/>
- <import from="../../stdlib/film.svk"/>
- <import as="house" from="./launch.svs"/>
-
- <script>
- @whole
-
- <segment id="scene-1">
- <NARRATOR> @photoshop @emphasis Photoshop @/emphasis.
- <SPEAKER> Powerful, but only if you know how to use it. Otherwise, your new profile
- picture becomes a three-hour design project @/photoshop.
- <NARRATOR> @facetune Facetune.
- <SPEAKER> Fast and great for touch-ups. But it still leaves you with the same awkward
- pose and the same dorm-room background @/facetune.
- </segment>
-
- <segment id="scene-2">
- <NARRATOR> @remini Remini.
- <SPEAKER> Great for blurry photos. It restores detail, but it can't fix the pose,
- outfit, or background. You get the same bad photo in HD @/remini.
- <NARRATOR> @chatgpt ChatGPT.
- <SPEAKER> More flexible. It can create a new shot, but getting your face and the
- details right becomes a prompt-writing group project @/chatgpt.
- </segment>
-
- <segment id="scene-3">
- <NARRATOR> @ranking! @regen ReGen.
- <SPEAKER> Pick a photo you love, and the app @handsome-1 rebuilds it around you with a
- @/handsome-1~ @handsome-2 @emphasis better pose @/emphasis, outfit, and setting. @/handsome-2
- From one selfie, you can make @dating-photo a dating photo, @/dating-photo~
- @linkedin-headshot LinkedIn headshot, @/linkedin-headshot~
- @instagram-post or Instagram post, @/instagram-post
- so you get what you wanted instead of fixing a bad shot @/regen.
- </segment>
-
- @/whole~
- </script>
-
- <!-- These local artifacts are inputs; the example invokes no generation model. -->
- <video id="avatar-1" src="../regen-ranking/assets/avatar-1.mp4"/>
- <video id="avatar-2" src="../regen-ranking/assets/avatar-2.mp4"/>
- <video id="avatar-3" src="../regen-ranking/assets/avatar-3.mp4"/>
- <audio id="avatar-1-audio" src="../regen-ranking/assets/avatar-1.mp3"/>
- <audio id="avatar-2-audio" src="../regen-ranking/assets/avatar-2.mp3"/>
- <audio id="avatar-3-audio" src="../regen-ranking/assets/avatar-3.mp3"/>
- <image id="ranking-icon-1" src="../regen-ranking/assets/ranking-icon-1.jpg"/>
- <image id="ranking-icon-2" src="../regen-ranking/assets/ranking-icon-2.jpg"/>
- <image id="ranking-icon-3" src="../regen-ranking/assets/ranking-icon-3.jpg"/>
- <image id="ranking-icon-4" src="../regen-ranking/assets/ranking-icon-4.jpg"/>
- <image id="ranking-icon-5" src="../regen-ranking/assets/ranking-icon-5.jpg"/>
- <image id="broll-1" src="../regen-ranking/assets/broll-5.png"/>
- <audio id="ranking-appear" src="../regen-ranking/assets/ranking-appear.wav"/>
- <audio id="ranking-move" src="../regen-ranking/assets/ranking-move.wav"/>
- <audio id="music" src="../regen-ranking/assets/background.mp3"/>
- <timing id="timing" src="../regen-ranking/evidence/alignment.json"/>
-
- <!-- The Basis Producer and Locator are replaceable Components with typed outputs. -->
- <speech-assemble id="voice" fps="30" defaultJoin="cut">
- <segment id="scene-1" script={script.segment.scene-1} visual={avatar-1} audio={avatar-1-audio} sourceWindow="0s .. 12.033333333333333s"/>
- <segment id="scene-2" script={script.segment.scene-2} visual={avatar-2} audio={avatar-2-audio} sourceWindow="0s .. 12.033333333333333s"/>
- <segment id="scene-3" script={script.segment.scene-3} visual={avatar-3} audio={avatar-3-audio} sourceWindow="0s .. 12.033333333333333s"/>
- </speech-assemble>
- <speech-locator id="location" script={script} basis={voice.production} evidence={timing}/>
-
- <!-- One source mapping; Present only changes its projection in ProgramSpace. -->
- <media-track id="aroll" z="20">
- <item id="host" source={voice.facets.visual} during={script.selection.whole} class="house.host-full">
- <present id="opening-left" during="0s .. 2.2s" z="31" class="house.face-top-left" exit="fade 200ms"/>
- <present id="opening-right" during="2s .. 4.2s" z="32" class="house.face-top-right" enter="fade 200ms" exit="fade 200ms"/>
- <present id="opening-low" during="4s .. 6.2s" z="33" class="house.face-bottom-right" enter="fade 200ms" exit="fade 200ms"/>
- <present id="opening-full" during="6s .. 8s" z="34" class="house.face-center" enter="fade 200ms"/>
- <present id="photoshop-split" during={script.selection.photoshop} z="35" class="house.host-lower-split"/>
- <present id="regen-pip" during={script.selection.regen} window="start-200ms .. end" z="36" class="house.host-corner-circle" enter="fade 200ms"/>
- </item>
- </media-track>
-
- <!-- B-roll keeps its own source audio and transition sound in the same Track. -->
- <broll-track id="broll" z="100">
- <item id="poster" source={broll-1} during={script.selection.handsome-1} playback="hold" class="house.broll-full"/>
- <item id="product-demo" source={avatar-3} during={script.selection.handsome-2} playback="stretch" sourceDuration="12.033333333333333" audio="source" volume="0.15" class="house.broll-full"/>
- <transition from="poster" to="product-demo" kind="crossfade" duration="200ms" sound={ranking-appear} volume="0.7"/>
- </broll-track>
-
- <!-- A Moment gates one independent Track; every item still owns its Selection. -->
- <ranking-column id="ranking" z="300" at={script.moment.ranking} class="house.ranking"
- appearSound={ranking-appear} moveSound={ranking-move}>
- <item id="regen" rank="1" image={ranking-icon-1} during={script.selection.regen}/>
- <item id="chatgpt" rank="2" image={ranking-icon-2} during={script.selection.chatgpt}/>
- <item id="remini" rank="3" image={ranking-icon-3} during={script.selection.remini}/>
- <item id="facetune" rank="4" image={ranking-icon-4} during={script.selection.facetune}/>
- <item id="photoshop" rank="5" image={ranking-icon-5} during={script.selection.photoshop}/>
- </ranking-column>
-
- <!-- Manual ProgramSpans remain a deliberate escape hatch. -->
- <text-track id="overlays" z="400">
- <item id="opening-title" text="Semantic video starts with meaning." during="0s .. 3s" class="house.title"/>
- <item id="ending-arrow" text="↓" during="end-2s .. end" class="house.arrow"/>
- </text-track>
-
- <!-- The repeated emphasis Selection is disconnected and consumed as one set. -->
- <caption-planner id="caption-plan" script={script} semantic={location.map} maxWords="3"/>
- <caption-track id="captions" z="500" script={script} semantic={location.map} plan={caption-plan.plan} class="house.captions">
- <style id="emphasis" during={script.selection.emphasis} class="house.caption-emphasis"/>
- <style id="narrator" role="NARRATOR" activeColor="#73fbd3"/>
- </caption-track>
-
- <audio-track id="background-music">
- <item id="music" source={music} during="full" volume="0.28" bus="music"/>
- </audio-track>
-
- <!-- Child order is not paint order: absolute z across flat Tracks is authoritative. -->
- <film id="launch" basis={voice.production} semantic={location.map} class="house.vertical">
- <track ref={captions.track}/>
- <track ref={background-music.track}/>
- <track ref={broll.track}/>
- <track ref={overlays.track}/>
- <track ref={aroll.track}/>
- <track ref={ranking.track}/>
- </film>
-
-</svml>
diff --git a/examples/flat-track-launch/launch.svs b/examples/flat-track-launch/launch.svs
deleted file mode 100644
index a1099acd..00000000
--- a/examples/flat-track-launch/launch.svs
+++ /dev/null
@@ -1,126 +0,0 @@
-<sheet version="1" id="house">
-
- film.vertical {
- width: 1080;
- height: 1920;
- frame-rate: 30;
- background: #09090B;
- }
-
- media-track.host-full {
- x: 0;
- y: 0;
- width: 1;
- height: 1;
- fit: cover;
- }
-
- media-track.face-top-left {
- x: 0.05;
- y: 0.06;
- width: 0.30;
- height: 0.30;
- fit: cover;
- mask: circle;
- }
-
- media-track.face-top-right {
- x: 0.65;
- y: 0.06;
- width: 0.30;
- height: 0.30;
- fit: cover;
- mask: circle;
- }
-
- media-track.face-bottom-right {
- x: 0.65;
- y: 0.64;
- width: 0.30;
- height: 0.30;
- fit: cover;
- mask: circle;
- }
-
- media-track.face-center {
- x: 0.35;
- y: 0.35;
- width: 0.30;
- height: 0.30;
- fit: cover;
- mask: circle;
- }
-
- media-track.host-lower-split {
- x: 0;
- y: 0.50;
- width: 1;
- height: 0.50;
- fit: cover;
- }
-
- media-track.host-corner-circle {
- x: 0.68;
- y: 0.70;
- width: 0.27;
- height: 0.27;
- fit: cover;
- mask: circle;
- }
-
- broll-track.broll-full {
- x: 0;
- y: 0;
- width: 1;
- height: 1;
- fit: cover;
- }
-
- ranking-column.ranking {
- x: 0.06;
- y: 0.14;
- width: 0.42;
- row-height: 0.071;
- gap: 0.018;
- stage-x: 0.66;
- stage-y: 0.73;
- stage-size: 0.33;
- }
-
- text-track.title {
- x: 0.06;
- y: 0.08;
- width: 0.88;
- height: 0.12;
- font-family: Inter, Arial, sans-serif;
- font-size: 64;
- font-weight: 850;
- fill: #FFFFFF;
- }
-
- text-track.arrow {
- x: 0.42;
- y: 0.80;
- width: 0.16;
- height: 0.14;
- font-size: 120;
- fill: #A78BFA;
- }
-
- caption-track.captions {
- x: 0.08;
- y: 0.78;
- width: 0.84;
- font-family: Inter, Arial, sans-serif;
- font-size: 56;
- font-weight: 800;
- fill: #FFFFFF;
- }
-
- caption-track.caption-emphasis {
- fill: #FDE047;
- active-fill: #FFFFFF;
- scale: 1.08;
- }
-
-</sheet>
diff --git a/examples/regen-ranking/evidence/alignment.json b/examples/regen-ranking/evidence/alignment.json
deleted file mode 100644
index fd7153c2..00000000
--- a/examples/regen-ranking/evidence/alignment.json
+++ /dev/null
@@ -1,850 +0,0 @@
-{
- "contract": "svml.speech-timing-evidence.v1",
- "durationSec": 36.1,
- "fps": 30,
- "quality": "measured",
- "units": [
- {
- "text": "Photo shop",
- "startSec": 0.08,
- "endSec": 1,
- "segmentId": "scene-1"
- },
- {
- "text": "power full but",
- "startSec": 1,
- "endSec": 1.9,
- "segmentId": "scene-1"
- },
- {
- "text": "on",
- "startSec": 1.9,
- "endSec": 1.945,
- "segmentId": "scene-1"
- },
- {
- "text": "lee",
- "startSec": 1.945,
- "endSec": 1.99,
- "segmentId": "scene-1"
- },
- {
- "text": "of",
- "startSec": 1.99,
- "endSec": 1.995,
- "segmentId": "scene-1"
- },
- {
- "text": "uh",
- "startSec": 1.995,
- "endSec": 2,
- "segmentId": "scene-1"
- },
- {
- "text": "you",
- "startSec": 2,
- "endSec": 2.23,
- "segmentId": "scene-1"
- },
- {
- "text": "know",
- "startSec": 2.23,
- "endSec": 2.36,
- "segmentId": "scene-1"
- },
- {
- "text": "how",
- "startSec": 2.36,
- "endSec": 2.56,
- "segmentId": "scene-1"
- },
- {
- "text": "to",
- "startSec": 2.56,
- "endSec": 2.64,
- "segmentId": "scene-1"
- },
- {
- "text": "use",
- "startSec": 2.64,
- "endSec": 2.79,
- "segmentId": "scene-1"
- },
- {
- "text": "it",
- "startSec": 2.79,
- "endSec": 3.12,
- "segmentId": "scene-1"
- },
- {
- "text": "Otherwise",
- "startSec": 3.12,
- "endSec": 3.6,
- "segmentId": "scene-1"
- },
- {
- "text": "your",
- "startSec": 3.6,
- "endSec": 3.77,
- "segmentId": "scene-1"
- },
- {
- "text": "new",
- "startSec": 3.77,
- "endSec": 4.08,
- "segmentId": "scene-1"
- },
- {
- "text": "profile",
- "startSec": 4.08,
- "endSec": 4.22,
- "segmentId": "scene-1"
- },
- {
- "text": "picture",
- "startSec": 4.22,
- "endSec": 4.68,
- "segmentId": "scene-1"
- },
- {
- "text": "becomes",
- "startSec": 4.68,
- "endSec": 4.84,
- "segmentId": "scene-1"
- },
- {
- "text": "a",
- "startSec": 4.84,
- "endSec": 4.9,
- "segmentId": "scene-1"
- },
- {
- "text": "three-hour",
- "startSec": 4.9,
- "endSec": 5.42,
- "segmentId": "scene-1"
- },
- {
- "text": "design",
- "startSec": 5.42,
- "endSec": 5.84,
- "segmentId": "scene-1"
- },
- {
- "text": "project",
- "startSec": 5.84,
- "endSec": 6.4,
- "segmentId": "scene-1"
- },
- {
- "text": "Facetune",
- "startSec": 6.4,
- "endSec": 7.4,
- "segmentId": "scene-1"
- },
- {
- "text": "Fast",
- "startSec": 7.4,
- "endSec": 7.59,
- "segmentId": "scene-1"
- },
- {
- "text": "and",
- "startSec": 7.59,
- "endSec": 7.71,
- "segmentId": "scene-1"
- },
- {
- "text": "great",
- "startSec": 7.71,
- "endSec": 8,
- "segmentId": "scene-1"
- },
- {
- "text": "for",
- "startSec": 8,
- "endSec": 8.33,
- "segmentId": "scene-1"
- },
- {
- "text": "touch-ups",
- "startSec": 8.33,
- "endSec": 8.64,
- "segmentId": "scene-1"
- },
- {
- "text": "But",
- "startSec": 8.64,
- "endSec": 8.76,
- "segmentId": "scene-1"
- },
- {
- "text": "it",
- "startSec": 8.76,
- "endSec": 8.96,
- "segmentId": "scene-1"
- },
- {
- "text": "still",
- "startSec": 8.96,
- "endSec": 9.04,
- "segmentId": "scene-1"
- },
- {
- "text": "leaves",
- "startSec": 9.04,
- "endSec": 9.29,
- "segmentId": "scene-1"
- },
- {
- "text": "you",
- "startSec": 9.29,
- "endSec": 9.45,
- "segmentId": "scene-1"
- },
- {
- "text": "with",
- "startSec": 9.45,
- "endSec": 9.57,
- "segmentId": "scene-1"
- },
- {
- "text": "the",
- "startSec": 9.57,
- "endSec": 9.69,
- "segmentId": "scene-1"
- },
- {
- "text": "same",
- "startSec": 9.69,
- "endSec": 9.85,
- "segmentId": "scene-1"
- },
- {
- "text": "awkward",
- "startSec": 9.85,
- "endSec": 10.14,
- "segmentId": "scene-1"
- },
- {
- "text": "pose",
- "startSec": 10.14,
- "endSec": 10.48,
- "segmentId": "scene-1"
- },
- {
- "text": "and",
- "startSec": 10.48,
- "endSec": 10.52,
- "segmentId": "scene-1"
- },
- {
- "text": "the",
- "startSec": 10.52,
- "endSec": 10.67,
- "segmentId": "scene-1"
- },
- {
- "text": "same",
- "startSec": 10.67,
- "endSec": 10.87,
- "segmentId": "scene-1"
- },
- {
- "text": "dorm-room",
- "startSec": 10.87,
- "endSec": 11.48,
- "segmentId": "scene-1"
- },
- {
- "text": "background",
- "startSec": 11.48,
- "endSec": 12,
- "segmentId": "scene-1"
- },
- {
- "text": "Remini",
- "startSec": 12.043333333333333,
- "endSec": 13.033333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "Great",
- "startSec": 13.033333333333333,
- "endSec": 13.283333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "for",
- "startSec": 13.283333333333333,
- "endSec": 13.563333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "blurry",
- "startSec": 13.563333333333333,
- "endSec": 13.773333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "photos",
- "startSec": 13.773333333333333,
- "endSec": 14.033333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "It",
- "startSec": 14.033333333333333,
- "endSec": 14.103333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "restores",
- "startSec": 14.103333333333333,
- "endSec": 14.393333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "detail",
- "startSec": 14.393333333333333,
- "endSec": 14.613333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "but",
- "startSec": 14.613333333333333,
- "endSec": 14.763333333333334,
- "segmentId": "scene-2"
- },
- {
- "text": "it",
- "startSec": 14.763333333333334,
- "endSec": 14.793333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "can't",
- "startSec": 14.793333333333333,
- "endSec": 14.973333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "fix",
- "startSec": 14.973333333333333,
- "endSec": 15.083333333333332,
- "segmentId": "scene-2"
- },
- {
- "text": "the",
- "startSec": 15.083333333333332,
- "endSec": 15.213333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "pose",
- "startSec": 15.213333333333333,
- "endSec": 15.373333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "outfit",
- "startSec": 15.373333333333333,
- "endSec": 15.733333333333334,
- "segmentId": "scene-2"
- },
- {
- "text": "or",
- "startSec": 15.733333333333334,
- "endSec": 15.853333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "background",
- "startSec": 15.853333333333333,
- "endSec": 16.633333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "You",
- "startSec": 16.633333333333333,
- "endSec": 16.793333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "get",
- "startSec": 16.793333333333333,
- "endSec": 16.953333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "the",
- "startSec": 16.953333333333333,
- "endSec": 17.163333333333334,
- "segmentId": "scene-2"
- },
- {
- "text": "same",
- "startSec": 17.163333333333334,
- "endSec": 17.373333333333335,
- "segmentId": "scene-2"
- },
- {
- "text": "bad",
- "startSec": 17.373333333333335,
- "endSec": 17.503333333333334,
- "segmentId": "scene-2"
- },
- {
- "text": "photo",
- "startSec": 17.503333333333334,
- "endSec": 17.813333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "in",
- "startSec": 17.813333333333333,
- "endSec": 17.873333333333335,
- "segmentId": "scene-2"
- },
- {
- "text": "HD",
- "startSec": 17.873333333333335,
- "endSec": 18.184444444444445,
- "segmentId": "scene-2"
- },
- {
- "text": "ChatGPT",
- "startSec": 18.184444444444445,
- "endSec": 19.273333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "More",
- "startSec": 19.273333333333333,
- "endSec": 19.53333333333333,
- "segmentId": "scene-2"
- },
- {
- "text": "flexible",
- "startSec": 19.53333333333333,
- "endSec": 20,
- "segmentId": "scene-2"
- },
- {
- "text": "It",
- "startSec": 20,
- "endSec": 20.033,
- "segmentId": "scene-2"
- },
- {
- "text": "can",
- "startSec": 20.033,
- "endSec": 20.133,
- "segmentId": "scene-2"
- },
- {
- "text": "create",
- "startSec": 20.133,
- "endSec": 20.433,
- "segmentId": "scene-2"
- },
- {
- "text": "a",
- "startSec": 20.433,
- "endSec": 20.533,
- "segmentId": "scene-2"
- },
- {
- "text": "new",
- "startSec": 20.533,
- "endSec": 20.7,
- "segmentId": "scene-2"
- },
- {
- "text": "shot",
- "startSec": 20.7,
- "endSec": 20.967,
- "segmentId": "scene-2"
- },
- {
- "text": "but",
- "startSec": 20.967,
- "endSec": 21.133,
- "segmentId": "scene-2"
- },
- {
- "text": "getting",
- "startSec": 21.133,
- "endSec": 21.333,
- "segmentId": "scene-2"
- },
- {
- "text": "your",
- "startSec": 21.333,
- "endSec": 21.5,
- "segmentId": "scene-2"
- },
- {
- "text": "face",
- "startSec": 21.5,
- "endSec": 21.833,
- "segmentId": "scene-2"
- },
- {
- "text": "and",
- "startSec": 21.833,
- "endSec": 21.9,
- "segmentId": "scene-2"
- },
- {
- "text": "the",
- "startSec": 21.9,
- "endSec": 22,
- "segmentId": "scene-2"
- },
- {
- "text": "details",
- "startSec": 22,
- "endSec": 22.433,
- "segmentId": "scene-2"
- },
- {
- "text": "right",
- "startSec": 22.433,
- "endSec": 22.6,
- "segmentId": "scene-2"
- },
- {
- "text": "becomes",
- "startSec": 22.6,
- "endSec": 22.933,
- "segmentId": "scene-2"
- },
- {
- "text": "a",
- "startSec": 22.933,
- "endSec": 23.067,
- "segmentId": "scene-2"
- },
- {
- "text": "prompt-writing",
- "startSec": 23.067,
- "endSec": 23.567,
- "segmentId": "scene-2"
- },
- {
- "text": "group",
- "startSec": 23.567,
- "endSec": 23.733,
- "segmentId": "scene-2"
- },
- {
- "text": "project",
- "startSec": 23.733,
- "endSec": 24.066666666666666,
- "segmentId": "scene-2"
- },
- {
- "text": "ReGen",
- "startSec": 24.076666666666668,
- "endSec": 25.066666666666666,
- "segmentId": "scene-3"
- },
- {
- "text": "Pick",
- "startSec": 25.066666666666666,
- "endSec": 25.266666666666666,
- "segmentId": "scene-3"
- },
- {
- "text": "a",
- "startSec": 25.266666666666666,
- "endSec": 25.306666666666665,
- "segmentId": "scene-3"
- },
- {
- "text": "photo",
- "startSec": 25.306666666666665,
- "endSec": 25.576666666666668,
- "segmentId": "scene-3"
- },
- {
- "text": "you",
- "startSec": 25.576666666666668,
- "endSec": 25.726666666666667,
- "segmentId": "scene-3"
- },
- {
- "text": "love",
- "startSec": 25.726666666666667,
- "endSec": 26.006666666666668,
- "segmentId": "scene-3"
- },
- {
- "text": "and",
- "startSec": 26.006666666666668,
- "endSec": 26.076666666666668,
- "segmentId": "scene-3"
- },
- {
- "text": "the",
- "startSec": 26.076666666666668,
- "endSec": 26.226666666666667,
- "segmentId": "scene-3"
- },
- {
- "text": "app",
- "startSec": 26.226666666666667,
- "endSec": 26.376666666666665,
- "segmentId": "scene-3"
- },
- {
- "text": "rebuilds",
- "startSec": 26.376666666666665,
- "endSec": 26.886666666666667,
- "segmentId": "scene-3"
- },
- {
- "text": "it",
- "startSec": 26.886666666666667,
- "endSec": 26.906666666666666,
- "segmentId": "scene-3"
- },
- {
- "text": "around",
- "startSec": 26.906666666666666,
- "endSec": 27.196666666666665,
- "segmentId": "scene-3"
- },
- {
- "text": "you",
- "startSec": 27.196666666666665,
- "endSec": 27.346666666666668,
- "segmentId": "scene-3"
- },
- {
- "text": "with",
- "startSec": 27.346666666666668,
- "endSec": 27.546666666666667,
- "segmentId": "scene-3"
- },
- {
- "text": "a",
- "startSec": 27.546666666666667,
- "endSec": 27.7,
- "segmentId": "scene-3"
- },
- {
- "text": "better",
- "startSec": 27.7,
- "endSec": 27.906666666666666,
- "segmentId": "scene-3"
- },
- {
- "text": "pose",
- "startSec": 27.906666666666666,
- "endSec": 28.206666666666667,
- "segmentId": "scene-3"
- },
- {
- "text": "outfit",
- "startSec": 28.206666666666667,
- "endSec": 28.706666666666667,
- "segmentId": "scene-3"
- },
- {
- "text": "and",
- "startSec": 28.706666666666667,
- "endSec": 28.926666666666666,
- "segmentId": "scene-3"
- },
- {
- "text": "setting",
- "startSec": 28.926666666666666,
- "endSec": 29.6,
- "segmentId": "scene-3"
- },
- {
- "text": "From",
- "startSec": 29.633,
- "endSec": 29.867,
- "segmentId": "scene-3"
- },
- {
- "text": "one",
- "startSec": 29.867,
- "endSec": 29.967,
- "segmentId": "scene-3"
- },
- {
- "text": "selfie",
- "startSec": 29.967,
- "endSec": 30.4,
- "segmentId": "scene-3"
- },
- {
- "text": "you",
- "startSec": 30.433,
- "endSec": 30.533,
- "segmentId": "scene-3"
- },
- {
- "text": "can",
- "startSec": 30.533,
- "endSec": 30.7,
- "segmentId": "scene-3"
- },
- {
- "text": "make",
- "startSec": 30.7,
- "endSec": 30.833,
- "segmentId": "scene-3"
- },
- {
- "text": "a",
- "startSec": 30.833,
- "endSec": 31.006666666666668,
- "segmentId": "scene-3"
- },
- {
- "text": "dating",
- "startSec": 31.006666666666668,
- "endSec": 31.546666666666667,
- "segmentId": "scene-3"
- },
- {
- "text": "photo",
- "startSec": 31.546666666666667,
- "endSec": 31.71666666666667,
- "segmentId": "scene-3"
- },
- {
- "text": "LinkedIn",
- "startSec": 31.71666666666667,
- "endSec": 32.04666666666667,
- "segmentId": "scene-3"
- },
- {
- "text": "headshot",
- "startSec": 32.04666666666667,
- "endSec": 32.567,
- "segmentId": "scene-3"
- },
- {
- "text": "or",
- "startSec": 32.567,
- "endSec": 32.70666666666666,
- "segmentId": "scene-3"
- },
- {
- "text": "Instagram",
- "startSec": 32.70666666666666,
- "endSec": 33.196666666666665,
- "segmentId": "scene-3"
- },
- {
- "text": "post",
- "startSec": 33.196666666666665,
- "endSec": 33.633,
- "segmentId": "scene-3"
- },
- {
- "text": "so",
- "startSec": 33.667,
- "endSec": 33.767,
- "segmentId": "scene-3"
- },
- {
- "text": "you",
- "startSec": 33.767,
- "endSec": 33.933,
- "segmentId": "scene-3"
- },
- {
- "text": "get",
- "startSec": 33.933,
- "endSec": 34,
- "segmentId": "scene-3"
- },
- {
- "text": "what",
- "startSec": 34,
- "endSec": 34.133,
- "segmentId": "scene-3"
- },
- {
- "text": "you",
- "startSec": 34.133,
- "endSec": 34.267,
- "segmentId": "scene-3"
- },
- {
- "text": "wanted",
- "startSec": 34.267,
- "endSec": 34.6,
- "segmentId": "scene-3"
- },
- {
- "text": "instead",
- "startSec": 34.6,
- "endSec": 34.867,
- "segmentId": "scene-3"
- },
- {
- "text": "of",
- "startSec": 34.867,
- "endSec": 35.067,
- "segmentId": "scene-3"
- },
- {
- "text": "fixing",
- "startSec": 35.067,
- "endSec": 35.433,
- "segmentId": "scene-3"
- },
- {
- "text": "a",
- "startSec": 35.433,
- "endSec": 35.533,
- "segmentId": "scene-3"
- },
- {
- "text": "bad",
- "startSec": 35.533,
- "endSec": 35.767,
- "segmentId": "scene-3"
- },
- {
- "text": "shot",
- "startSec": 35.767,
- "endSec": 36.06666666666666,
- "segmentId": "scene-3"
- }
- ],
- "segments": [
- {
- "id": "scene-1",
- "startSec": 0,
- "endSec": 12.033333333333333
- },
- {
- "id": "scene-2",
- "startSec": 12.033333333333333,
- "endSec": 24.066666666666666
- },
- {
- "id": "scene-3",
- "startSec": 24.066666666666666,
- "endSec": 36.1
- }
- ],
- "provenance": {
- "method": "pinned speech timing with deliberate recognition noise",
- "source": "existing avatar audio; wording is measurement evidence, never corrected transcript truth",
- "timingOverrides": {
- "kind": "reference-recovery",
- "source": "scene transitions in regen ranking Job cmrxqbub800012tjoi2ev2u24",
- "note": "Only boundaries visible in the frozen reference video are overridden."
- }
- }
-}
diff --git a/examples/regen-ranking/evidence/timing-overrides.json b/examples/regen-ranking/evidence/timing-overrides.json
deleted file mode 100644
index 405808b8..00000000
--- a/examples/regen-ranking/evidence/timing-overrides.json
+++ /dev/null
@@ -1,56 +0,0 @@
-{
- "contract": "svml.speech-timing-overrides.v1",
- "units": [
- { "index": 69, "endSec": 20.000 },
- { "index": 70, "startSec": 20.000, "endSec": 20.033 },
- { "index": 71, "startSec": 20.033, "endSec": 20.133 },
- { "index": 72, "startSec": 20.133, "endSec": 20.433 },
- { "index": 73, "startSec": 20.433, "endSec": 20.533 },
- { "index": 74, "startSec": 20.533, "endSec": 20.700 },
- { "index": 75, "startSec": 20.700, "endSec": 20.967 },
- { "index": 76, "startSec": 20.967, "endSec": 21.133 },
- { "index": 77, "startSec": 21.133, "endSec": 21.333 },
- { "index": 78, "startSec": 21.333, "endSec": 21.500 },
- { "index": 79, "startSec": 21.500, "endSec": 21.833 },
- { "index": 80, "startSec": 21.833, "endSec": 21.900 },
- { "index": 81, "startSec": 21.900, "endSec": 22.000 },
- { "index": 82, "startSec": 22.000, "endSec": 22.433 },
- { "index": 83, "startSec": 22.433, "endSec": 22.600 },
- { "index": 84, "startSec": 22.600, "endSec": 22.933 },
- { "index": 85, "startSec": 22.933, "endSec": 23.067 },
- { "index": 86, "startSec": 23.067, "endSec": 23.567 },
- { "index": 87, "startSec": 23.567, "endSec": 23.733 },
- { "index": 88, "startSec": 23.733 },
-
- { "index": 103, "endSec": 27.700 },
- { "index": 104, "startSec": 27.700 },
- { "index": 108, "endSec": 29.600 },
- { "index": 109, "startSec": 29.633, "endSec": 29.867 },
- { "index": 110, "startSec": 29.867, "endSec": 29.967 },
- { "index": 111, "startSec": 29.967, "endSec": 30.400 },
- { "index": 112, "startSec": 30.433, "endSec": 30.533 },
- { "index": 113, "startSec": 30.533, "endSec": 30.700 },
- { "index": 114, "startSec": 30.700, "endSec": 30.833 },
- { "index": 115, "startSec": 30.833 },
- { "index": 119, "endSec": 32.567 },
- { "index": 120, "startSec": 32.567 },
- { "index": 122, "endSec": 33.633 },
- { "index": 123, "startSec": 33.667, "endSec": 33.767 },
- { "index": 124, "startSec": 33.767, "endSec": 33.933 },
- { "index": 125, "startSec": 33.933, "endSec": 34.000 },
- { "index": 126, "startSec": 34.000, "endSec": 34.133 },
- { "index": 127, "startSec": 34.133, "endSec": 34.267 },
- { "index": 128, "startSec": 34.267, "endSec": 34.600 },
- { "index": 129, "startSec": 34.600, "endSec": 34.867 },
- { "index": 130, "startSec": 34.867, "endSec": 35.067 },
- { "index": 131, "startSec": 35.067, "endSec": 35.433 },
- { "index": 132, "startSec": 35.433, "endSec": 35.533 },
- { "index": 133, "startSec": 35.533, "endSec": 35.767 },
- { "index": 134, "startSec": 35.767 }
- ],
- "provenance": {
- "kind": "reference-recovery",
- "source": "scene transitions in regen ranking Job cmrxqbub800012tjoi2ev2u24",
- "note": "Only boundaries visible in the frozen reference video are overridden."
- }
-}
diff --git a/examples/regen-ranking/reference.json b/examples/regen-ranking/reference.json
deleted file mode 100644
index cc68f6fe..00000000
--- a/examples/regen-ranking/reference.json
+++ /dev/null
@@ -1,47 +0,0 @@
-{
- "contract": "svml.reference-video.v1",
- "source": {
- "projectId": "cmrs0yofw00042tlz2t0ygwaw",
- "canvasId": "cmrx7771b00052ts5koz1yy7e",
- "jobId": "cmrxqbub800012tjoi2ev2u24",
- "finalSha256": "986c2b4f81381e5c5ab6df3c7b58f8bcc5324f9ae11ce820ed1cd8e5ee74c8b8"
- },
- "clock": {
- "width": 1080,
- "height": 1920,
- "fps": 30,
- "durationFrames": 1083
- },
- "plan": {
- "root": "regen-ranking",
- "values": 20,
- "instances": 10,
- "edges": 35
- },
- "selectionFrames": {
- "handsome-1": [[791, 831]],
- "handsome-2": [[831, 888]],
- "dating-photo": [[925, 952]],
- "linkedin-headshot": [[952, 977]],
- "instagram-post": [[977, 1009]]
- },
- "locatedOutput": {
- "visualFragments": 154,
- "audioFragments": 14
- },
- "renderComparison": {
- "reference": "/svml-reference/regen-ranking-column-east-asian/final.mp4",
- "durationSec": 36.1,
- "video": {
- "width": 1080,
- "height": 1920,
- "fps": 30,
- "ssimAll": 0.9658
- },
- "audio": {
- "sampleRate": 48000,
- "channels": 2,
- "apsnrDb": [174.207, 174.208]
- }
- }
-}
diff --git a/examples/regen-ranking/regen-ranking.svml b/examples/regen-ranking/regen-ranking.svml
deleted file mode 100644
index e1a9ce76..00000000
--- a/examples/regen-ranking/regen-ranking.svml
+++ /dev/null
@@ -1,174 +0,0 @@
-<svml version="1">
-
- <import from="../../stdlib/speech-assemble.svk"/>
- <import from="../../stdlib/speech-locator.svk"/>
- <import from="../../stdlib/media-track.svk"/>
- <import from="../../stdlib/ranking-column.svk"/>
- <import from="../../stdlib/broll-track.svk"/>
- <import from="../../stdlib/text-track.svk"/>
- <import from="../../stdlib/caption-planner.svk"/>
- <import from="../../stdlib/caption-track.svk"/>
- <import from="../../stdlib/audio-track.svk"/>
- <import from="../../stdlib/film.svk"/>
-
- <script>
- <segment id="scene-1">
- <NARRATOR> @photoshop Photoshop.
- <SPEAKER> Powerful, but only if you know how to use it. Otherwise, your new profile
- picture becomes a three-hour design project @/photoshop.
- <NARRATOR> @facetune Facetune.
- <SPEAKER> Fast and great for touch-ups. But it still leaves you with the same awkward
- pose and the same dorm-room background @/facetune.
- </segment>
-
- <segment id="scene-2">
- <NARRATOR> @remini Remini.
- <SPEAKER> Great for blurry photos. It restores detail, but it can't fix the pose,
- outfit, or background. You get the same bad photo in HD @/remini.
- <NARRATOR> @chatgpt ChatGPT.
- <SPEAKER> More flexible. It can create a new shot, but getting your face and the
- details right becomes a prompt-writing group project @/chatgpt.
- </segment>
-
- <segment id="scene-3">
- <NARRATOR> @regen ReGen.
- <SPEAKER> Pick a photo you love, and the app @handsome-1 rebuilds it around you with a
- @/handsome-1~ @handsome-2 better pose, outfit, and setting. @/handsome-2
- From one selfie, you can make @dating-photo a dating photo, @/dating-photo~
- @linkedin-headshot LinkedIn headshot, @/linkedin-headshot~
- @instagram-post or Instagram post, @/instagram-post
- so you get what you wanted instead of fixing a bad shot @/regen.
- </segment>
- </script>
-
- <video id="avatar-1" src="./assets/avatar-1.mp4"/>
- <video id="avatar-2" src="./assets/avatar-2.mp4"/>
- <video id="avatar-3" src="./assets/avatar-3.mp4"/>
- <audio id="avatar-1-audio" src="./assets/avatar-1.mp3"/>
- <audio id="avatar-2-audio" src="./assets/avatar-2.mp3"/>
- <audio id="avatar-3-audio" src="./assets/avatar-3.mp3"/>
-
- <image id="ranking-icon-1" src="./assets/ranking-icon-1.jpg"/>
- <image id="ranking-icon-2" src="./assets/ranking-icon-2.jpg"/>
- <image id="ranking-icon-3" src="./assets/ranking-icon-3.jpg"/>
- <image id="ranking-icon-4" src="./assets/ranking-icon-4.jpg"/>
- <image id="ranking-icon-5" src="./assets/ranking-icon-5.jpg"/>
-
- <image id="broll-1" src="./assets/broll-1.png"/>
- <image id="broll-2" src="./assets/broll-2.png"/>
- <image id="broll-3" src="./assets/broll-3.png"/>
- <image id="broll-4" src="./assets/broll-4.png"/>
- <image id="broll-5" src="./assets/broll-5.png"/>
-
- <audio id="ranking-appear" src="./assets/ranking-appear.wav"/>
- <audio id="ranking-move" src="./assets/ranking-move.wav"/>
- <audio id="background-music" src="./assets/background.mp3"/>
- <timing id="timing" src="./evidence/alignment.json"/>
-
- <speech-assemble id="voice" fps="30" defaultJoin="cut">
- <segment id="scene-1" script={script.segment.scene-1} visual={avatar-1} audio={avatar-1-audio} sourceWindow="0s .. 12.033333333333333s"/>
- <segment id="scene-2" script={script.segment.scene-2} visual={avatar-2} audio={avatar-2-audio} sourceWindow="0s .. 12.033333333333333s"/>
- <segment id="scene-3" script={script.segment.scene-3} visual={avatar-3} audio={avatar-3-audio} sourceWindow="0s .. 12.033333333333333s"/>
- </speech-assemble>
-
- <speech-locator id="location" script={script} basis={voice.production} evidence={timing}/>
-
- <media-track id="base" z="20">
- <item id="scene-1" source={voice.segment.scene-1.visual} fit="cover"/>
- <item id="scene-2" source={voice.segment.scene-2.visual} fit="cover"/>
- <item id="scene-3" source={voice.segment.scene-3.visual} fit="cover"/>
- </media-track>
-
- <ranking-column
- id="ranking"
- z="42"
- x="0"
- y="0.17"
- width="0.305"
- rowHeight="0.071"
- gap="0.011"
- stageX="0.66"
- stageY="0.73"
- stageSize="0.33"
- appearSound={ranking-appear}
- moveSound={ranking-move}
- appearGain="0.09"
- moveGain="0.10"
- >
- <item id="regen" rank="1" image={ranking-icon-1} during={script.selection.regen} window="start+0.1s .. end-0.3s"/>
- <item id="chatgpt" rank="2" image={ranking-icon-2} during={script.selection.chatgpt} window="start+0.1s .. end-0.3s"/>
- <item id="remini" rank="3" image={ranking-icon-3} during={script.selection.remini} window="start+0.1s .. end-0.3s"/>
- <item id="facetune" rank="4" image={ranking-icon-4} during={script.selection.facetune} window="start+0.1s .. end-0.3s"/>
- <item id="photoshop" rank="5" image={ranking-icon-5} during={script.selection.photoshop} window="start+0.1s .. end-0.3s"/>
- </ranking-column>
-
- <text-track id="title" z="70">
- <item
- id="title"
- text="Ranking AI photo apps for guys with no good pics"
- during="full"
- x="0"
- y="0.09895833333333333"
- width="1"
- height="0.078125"
- font="Poppins, Inter, Arial, sans-serif"
- size="54"
- weight="950"
- lineHeight="0.92"
- letterSpacing="0.2"
- color="#050505"
- background="#ffffff"
- uppercase="true"
- />
- </text-track>
-
- <broll-track id="broll" z="700">
- <item id="handsome-1" source={broll-5} during={script.selection.handsome-1} fit="contain" zoom="1.02"/>
- <item id="handsome-2" source={broll-4} during={script.selection.handsome-2} fit="contain" zoom="1.03"/>
- <item id="dating-photo" source={broll-3} during={script.selection.dating-photo} fit="contain" zoom="1.02"/>
- <item id="linkedin-headshot" source={broll-2} during={script.selection.linkedin-headshot} fit="contain" zoom="1.03"/>
- <item id="instagram-post" source={broll-1} during={script.selection.instagram-post} fit="contain" zoom="1.02"/>
- </broll-track>
-
- <caption-planner id="caption-plan" script={script} semantic={location.map} maxWords="3"/>
-
- <caption-track
- id="captions"
- script={script}
- semantic={location.map}
- plan={caption-plan.plan}
- z="500"
- x="0.37"
- y="0.54"
- width="0.64"
- hold="0.08"
- font="Poppins, Inter, Arial, sans-serif"
- size="50"
- weight="800"
- tracking="-1"
- color="#ffffff"
- highlight="#ffd34d"
- />
-
- <audio-track id="music">
- <item id="background" source={background-music} during="full" volume="0.9"/>
- </audio-track>
-
- <film
- id="regen-ranking"
- basis={voice.production}
- semantic={location.map}
- width="1080"
- height="1920"
- fps="30"
- background="#000000"
- >
- <track ref={base.track}/>
- <track ref={ranking.track}/>
- <track ref={title.track}/>
- <track ref={broll.track}/>
- <track ref={captions.track}/>
- <track ref={music.track}/>
- </film>
-
-</svml>
diff --git a/package.json b/package.json
index eb58370a..aa8444e8 100644
--- a/package.json
+++ b/package.json
@@ -1,38 +1,19 @@
{
- "name": "@svml/compiler",
+ "name": "@svml/workspace",
"version": "0.0.1",
"private": true,
"type": "module",
- "bin": {
- "svml": "./dist/src/cli.js"
- },
"scripts": {
- "build": "tsc -p tsconfig.json && node tools/copy-runtime.mjs",
- "check": "pnpm check:v1 && pnpm check:v2",
- "check:v1": "tsc -p tsconfig.json --noEmit",
- "check:v2": "tsc -p tsconfig.v2.json --noEmit",
- "test": "pnpm test:v1 && pnpm test:v2",
- "test:v1": "node --import tsx --test 'test/**/*.test.ts'",
- "test:v2": "node --import tsx --test 'packages/*/test/**/*.test.ts' 'tools/*.test.mjs'",
+ "check": "tsc -p tsconfig.json --noEmit",
+ "test": "node --import tsx --test 'packages/*/test/**/*.test.ts' 'tools/*.test.mjs'",
"test:whisperx-service": "uv run --project services/whisperx --frozen python -m unittest discover -s services/whisperx/tests -p 'test_*.py'",
"test:image-opencv": "SVML_OPENCV_TESTS=1 SVML_OPENCV_PYTHON=services/image-opencv/.venv/bin/python node --import tsx --test packages/provider-image-opencv-local/test/provider.test.ts",
"smoke:kie": "node --import tsx packages/provider-kie/test/live-smoke.ts",
- "svml": "node --import tsx src/cli.ts",
- "svml:v2": "node --import tsx packages/video-cli/src/cli.ts"
+ "svml": "node --import tsx packages/video-cli/src/cli.ts"
},
- "files": [
- "dist/src",
- "stdlib",
- "spec",
- "docs",
- "README.md"
- ],
"engines": {
"node": ">=22"
},
- "dependencies": {
- "hyperframes": "0.7.84"
- },
"devDependencies": {
"@svml/artifact": "workspace:*",
"@svml/broll": "workspace:*",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9519f00e..0b4f862b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -7,10 +7,6 @@ settings:
importers:
.:
- dependencies:
- hyperframes:
- specifier: 0.7.84
- version: 0.7.84(@types/[email protected])
devDependencies:
'@svml/artifact':
specifier: workspace:*
diff --git a/src/artifacts.ts b/src/artifacts.ts
deleted file mode 100644
index 00639bc4..00000000
--- a/src/artifacts.ts
+++ /dev/null
@@ -1,224 +0,0 @@
-import { readFile } from "node:fs/promises";
-import { dirname, resolve } from "node:path";
-import { fileURLToPath, pathToFileURL } from "node:url";
-import { fail } from "./diagnostics.js";
-import type { KernelRegistry } from "./kernel.js";
-import type { PlanIR } from "./model.js";
-import type { KernelProjection } from "./runtime-contract.js";
-import { sha256, stableJson } from "./util.js";
-
-type ArtifactOutput = {
- type: string;
- uri?: string;
- value?: unknown;
- contentDigest: string;
-};
-
-type ArtifactBinding = {
- instanceIdentity: string;
- executionDigest: string;
- outputs: Record<string, ArtifactOutput>;
-};
-
-type ArtifactFile = {
- contract: "svml.artifacts.v1";
- bindings: ArtifactBinding[];
-};
-
-export type ArtifactResolution = {
- projections: Map<string, KernelProjection>;
- outputDigests: Map<string, string>;
- bindingExecutionDigests: Map<string, string>;
- manifestHash?: string;
- verified: boolean;
-};
-
-function externalUri(value: string): boolean {
- return /^[A-Za-z][A-Za-z0-9+.-]*:/u.test(value);
-}
-
-async function resolveOutput(
- artifactFile: string,
- output: ArtifactOutput,
-): Promise<Record<string, unknown>> {
- if (output.type === "Text") {
- if (typeof output.value !== "string" || output.uri !== undefined) {
- fail("artifact_text", "Text artifact output requires value and forbids uri.");
- }
- const digest = sha256(output.value);
- if (digest !== output.contentDigest) {
- fail("artifact_digest", "Text artifact contentDigest does not match its value.");
- }
- return { type: "Text", value: output.value, contentDigest: digest };
- }
- if (!["Image", "Video", "Audio"].includes(output.type)) {
- if (output.uri !== undefined || output.value === undefined) {
- fail("artifact_typed_value", `${output.type} artifact output requires value and forbids uri.`);
- }
- const digest = sha256(stableJson(output.value));
- if (digest !== output.contentDigest) {
- fail("artifact_digest", `${output.type} artifact contentDigest does not match its value.`);
- }
- return output.value as Record<string, unknown>;
- }
- if (typeof output.uri !== "string" || output.value !== undefined) {
- fail("artifact_media", `${output.type} artifact output requires uri and forbids value.`);
- }
- const uri = externalUri(output.uri)
- ? output.uri
- : pathToFileURL(resolve(dirname(artifactFile), output.uri)).href;
- if (!uri.startsWith("file:")) {
- fail(
- "artifact_unverifiable_uri",
- `Prototype artifact binding requires a local file URI, received "${uri}".`,
- );
- }
- let content: Buffer;
- try {
- content = await readFile(fileURLToPath(uri));
- } catch (error) {
- fail(
- "artifact_read",
- `Could not read bound artifact "${uri}": ${error instanceof Error ? error.message : String(error)}.`,
- );
- }
- const digest = sha256(content);
- if (digest !== output.contentDigest) {
- fail("artifact_digest", `Artifact "${uri}" does not match contentDigest.`);
- }
- return {
- type: output.type,
- source: uri,
- absoluteSource: uri,
- contentDigest: digest,
- };
-}
-
-export async function resolveArtifactFile(
- file: string | undefined,
- plan: PlanIR,
- kernels: KernelRegistry,
-): Promise<ArtifactResolution> {
- const capabilityInstances = plan.instances.filter(
- (instance) => kernels.get(instance.kernel)?.profile === "capability-v1",
- );
- if (!capabilityInstances.length) {
- if (file) {
- fail("artifact_unexpected", "An artifact file was provided, but the Plan has no capability instances.");
- }
- return {
- projections: new Map(),
- outputDigests: new Map(),
- bindingExecutionDigests: new Map(),
- verified: true,
- };
- }
- if (!file) {
- fail(
- "artifact_file_required",
- `Plan contains ${capabilityInstances.length} capability instance(s); provide --artifacts. No provider is invoked implicitly.`,
- );
- }
- const absolute = resolve(file);
- let source: string;
- let parsed: unknown;
- try {
- source = await readFile(absolute, "utf8");
- parsed = JSON.parse(source);
- } catch (error) {
- fail(
- "artifact_file_read",
- `Could not read artifact bindings ${absolute}: ${error instanceof Error ? error.message : String(error)}.`,
- );
- }
- if (
- !parsed
- || typeof parsed !== "object"
- || (parsed as { contract?: string }).contract !== "svml.artifacts.v1"
- || !Array.isArray((parsed as { bindings?: unknown }).bindings)
- ) {
- fail("artifact_contract", `${absolute} is not an svml.artifacts.v1 document.`);
- }
- const artifactFile = parsed as ArtifactFile;
- const byIdentity = new Map<string, ArtifactBinding>();
- for (const binding of artifactFile.bindings) {
- if (byIdentity.has(binding.instanceIdentity)) {
- fail("artifact_duplicate_binding", `Artifact identity "${binding.instanceIdentity}" is repeated.`);
- }
- byIdentity.set(binding.instanceIdentity, binding);
- }
- const projections = new Map<string, KernelProjection>();
- const outputDigests = new Map<string, string>();
- const bindingExecutionDigests = new Map<string, string>();
- for (const instance of capabilityInstances) {
- const manifest = kernels.get(instance.kernel)!;
- const binding = byIdentity.get(instance.identity);
- if (!binding) {
- fail("artifact_binding_missing", `Capability instance "${instance.id}" has no artifact binding.`);
- }
- const outputPorts = manifest.ports.filter((port) => port.direction === "output");
- const unknown = Object.keys(binding.outputs).find(
- (name) => !outputPorts.some((port) => port.name === name),
- );
- if (unknown) {
- fail("artifact_output_unknown", `Capability "${instance.id}" has no output port "${unknown}".`);
- }
- const outputs: Record<string, unknown> = {};
- for (const port of outputPorts) {
- const descriptor = binding.outputs[port.name];
- if (!descriptor) {
- if (port.cardinality === "one" || port.cardinality === "one-or-more") {
- fail("artifact_output_missing", `Capability "${instance.id}" requires output "${port.name}".`);
- }
- continue;
- }
- if (descriptor.type !== port.type) {
- fail(
- "artifact_output_type",
- `Capability "${instance.id}.${port.name}" requires ${port.type}, received ${descriptor.type}.`,
- );
- }
- outputs[port.name] = await resolveOutput(absolute, descriptor);
- }
- projections.set(instance.id, { outputs });
- outputDigests.set(
- instance.id,
- sha256(stableJson(Object.fromEntries(Object.entries(binding.outputs)
- .sort(([left], [right]) => left.localeCompare(right))
- .map(([name, descriptor]) => [
- name,
- { type: descriptor.type, contentDigest: descriptor.contentDigest },
- ])))),
- );
- bindingExecutionDigests.set(instance.id, binding.executionDigest);
- byIdentity.delete(instance.identity);
- }
- if (byIdentity.size) {
- fail(
- "artifact_binding_stale",
- `Artifact file contains ${byIdentity.size} binding(s) outside the reachable capability Plan.`,
- );
- }
- return {
- projections,
- outputDigests,
- bindingExecutionDigests,
- manifestHash: sha256(source),
- verified: true,
- };
-}
-
-export function verifyArtifactExecutionDigests(
- artifacts: ArtifactResolution,
- plan: PlanIR,
-): void {
- for (const [id, expected] of artifacts.bindingExecutionDigests) {
- const instance = plan.instances.find((candidate) => candidate.id === id);
- if (!instance || instance.executionDigest !== expected) {
- fail(
- "artifact_execution_digest",
- `Artifact binding for "${id}" was produced for a different executionDigest.`,
- );
- }
- }
-}
diff --git a/src/cli.ts b/src/cli.ts
deleted file mode 100644
index 266dcb85..00000000
--- a/src/cli.ts
+++ /dev/null
@@ -1,305 +0,0 @@
-#!/usr/bin/env node
-import { spawn } from "node:child_process";
-import { mkdir, writeFile } from "node:fs/promises";
-import { createRequire } from "node:module";
-import { basename, dirname, resolve } from "node:path";
-import {
- checkSource,
- compileSource,
- estimateSource,
- resolveScriptBindings,
-} from "./compiler.js";
-import { SvmlError } from "./diagnostics.js";
-import { formatDocumentScript } from "./format.js";
-import { projectCanvas, projectTimeline } from "./views.js";
-
-type ParsedArgs = {
- command?: string;
- positional: string[];
- options: Map<string, string | true>;
-};
-
-function parseArgs(argv: string[]): ParsedArgs {
- const [command, ...rest] = argv;
- const positional: string[] = [];
- const options = new Map<string, string | true>();
- for (let index = 0; index < rest.length; index += 1) {
- const value = rest[index];
- if (!value?.startsWith("--")) {
- if (value) positional.push(value);
- continue;
- }
- const name = value.slice(2);
- const next = rest[index + 1];
- if (next && !next.startsWith("--")) {
- options.set(name, next);
- index += 1;
- } else {
- options.set(name, true);
- }
- }
- return {
- ...(command ? { command } : {}),
- positional,
- options,
- };
-}
-
-function option(args: ParsedArgs, name: string, required = false): string | undefined {
- const value = args.options.get(name);
- if (typeof value === "string") return value;
- if (required) throw new Error(`--${name} is required`);
- return undefined;
-}
-
-async function writeJson(file: string, value: unknown): Promise<void> {
- const output = resolve(file);
- await mkdir(dirname(output), { recursive: true });
- await writeFile(output, `${JSON.stringify(value, null, 2)}\n`, "utf8");
-}
-
-async function run(): Promise<void> {
- const args = parseArgs(process.argv.slice(2));
- const file = args.positional[0];
- if (args.command === "check") {
- if (!file) throw new Error("usage: svml check <file.svml>");
- const result = await checkSource(file);
- process.stdout.write(`${JSON.stringify({
- ok: true,
- source: result.document.file,
- script: {
- segments: result.narrative.segments.length,
- words: result.narrative.tokens.length,
- selections: Object.keys(result.narrative.selections).length,
- moments: Object.keys(result.narrative.moments).length,
- },
- plan: {
- values: result.plan.values.length,
- instances: result.plan.instances.length,
- edges: result.plan.edges.length,
- root: result.plan.root,
- },
- kernels: result.manifests.map((manifest) => ({
- name: manifest.name,
- abi: manifest.abiVersion,
- manifestHash: manifest.sourceHash,
- implementationHash: manifest.implementationHash,
- })),
- reproducibility: {
- lockRequiredForFrozenBuild: true,
- modules: result.lock.modules.length,
- },
- }, null, 2)}\n`);
- return;
- }
- if (args.command === "lock") {
- if (!file) throw new Error("usage: svml lock <file.svml> [--out svml.lock]");
- const result = await compileSource({
- file,
- ...(option(args, "artifacts")
- ? { artifactsFile: option(args, "artifacts")! }
- : {}),
- });
- const output = option(args, "out") ?? resolve(dirname(resolve(file)), "svml.lock");
- await writeJson(output, result.lock);
- process.stdout.write(`${JSON.stringify({
- ok: true,
- source: result.document.file,
- output: resolve(output),
- modules: result.lock.modules.length,
- kernels: result.lock.kernels.length,
- })}\n`);
- return;
- }
- if (args.command === "script") {
- if (!file) throw new Error("usage: svml script <file.svml> [--out tokens.json]");
- const result = await checkSource(file);
- const payload = {
- projections: result.narrative.projections,
- segments: result.narrative.segments.map((segment) => ({
- id: segment.id,
- tokenStart: segment.tokenStart,
- tokenEnd: segment.tokenEnd,
- })),
- words: result.narrative.tokens.map((token) => ({
- id: token.id,
- text: token.text,
- normalized: token.normalized,
- segmentId: token.segmentId,
- })),
- selections: result.narrative.selections,
- moments: result.narrative.moments,
- };
- const output = option(args, "out");
- if (output) await writeJson(output, payload);
- else process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
- return;
- }
- if (args.command === "plan") {
- if (!file) throw new Error("usage: svml plan <file.svml> [--out plan.json]");
- const result = await checkSource(file);
- const output = option(args, "out");
- if (output) await writeJson(output, result.plan);
- else process.stdout.write(`${JSON.stringify(result.plan, null, 2)}\n`);
- return;
- }
- if (args.command === "fmt") {
- if (!file) throw new Error("usage: svml fmt <file.svml> [--check|--write|--out formatted.svml]");
- const checked = await checkSource(file);
- const formatted = formatDocumentScript(
- checked.document,
- checked.narrative,
- resolveScriptBindings(checked.document),
- );
- if (args.options.has("check")) {
- if (formatted !== checked.document.source) {
- throw new Error(`${resolve(file)} is not canonically formatted`);
- }
- process.stdout.write(`${resolve(file)} is canonically formatted\n`);
- return;
- }
- const output = option(args, "out");
- if (args.options.has("write")) {
- await writeFile(resolve(file), formatted, "utf8");
- } else if (output) {
- await writeFile(resolve(output), formatted, "utf8");
- } else {
- process.stdout.write(formatted);
- }
- return;
- }
- if (args.command === "estimate") {
- if (!file) throw new Error("usage: svml estimate <file.svml> [--out timing.json]");
- const numeric = (name: string): number | undefined => {
- const value = option(args, name);
- if (value === undefined) return undefined;
- const parsed = Number(value);
- if (!Number.isFinite(parsed)) throw new Error(`--${name} requires a finite number`);
- return parsed;
- };
- const result = await estimateSource(file, {
- ...(numeric("syllables-per-second") !== undefined
- ? { syllablesPerSecond: numeric("syllables-per-second")! }
- : {}),
- ...(numeric("word-gap") !== undefined ? { wordGapSec: numeric("word-gap")! } : {}),
- ...(numeric("segment-padding") !== undefined
- ? { segmentPaddingSec: numeric("segment-padding")! }
- : {}),
- ...(numeric("empty-segment-duration") !== undefined
- ? { emptySegmentSec: numeric("empty-segment-duration")! }
- : {}),
- ...(numeric("fps") !== undefined ? { fps: numeric("fps")! } : {}),
- });
- const payload = {
- basis: result.basis,
- map: result.map,
- timeline: result.located,
- };
- const output = option(args, "out");
- if (output) await writeJson(output, payload);
- else process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
- return;
- }
- if (args.command === "canvas") {
- if (!file) throw new Error("usage: svml canvas <file.svml> [--out canvas.json]");
- const result = await checkSource(file);
- const payload = projectCanvas(result.plan);
- const output = option(args, "out");
- if (output) await writeJson(output, payload);
- else process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
- return;
- }
- if (args.command === "timeline") {
- if (!file) {
- throw new Error("usage: svml timeline <file.svml> [--out timeline.json]");
- }
- const compilation = await compileSource({
- file,
- ...(option(args, "lock") ? { lockFile: option(args, "lock")! } : {}),
- ...(option(args, "artifacts")
- ? { artifactsFile: option(args, "artifacts")! }
- : {}),
- });
- const payload = projectTimeline(compilation);
- const output = option(args, "out");
- if (output) await writeJson(output, payload);
- else process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
- return;
- }
- if (args.command === "compile") {
- if (!file) {
- throw new Error("usage: svml compile <file.svml> --out index.html");
- }
- const outputFile = option(args, "out", true);
- const compilation = await compileSource({
- file,
- outputFile: outputFile!,
- ...(option(args, "lock") ? { lockFile: option(args, "lock")! } : {}),
- ...(option(args, "artifacts")
- ? { artifactsFile: option(args, "artifacts")! }
- : {}),
- });
- process.stdout.write(`${JSON.stringify({
- ok: true,
- source: compilation.document.file,
- output: compilation.outputFile,
- durationFrames: compilation.located.durationFrames,
- fps: compilation.located.fps,
- instances: compilation.plan.instances.length,
- reproducible: compilation.reproducible,
- })}\n`);
- return;
- }
- if (args.command === "render") {
- if (!file) throw new Error("usage: svml render <index.html> --out video.mp4");
- const output = option(args, "out", true);
- const cli = createRequire(import.meta.url).resolve("hyperframes/bin/hyperframes.mjs");
- const compositionFile = resolve(file);
- const projectDir = dirname(compositionFile);
- await new Promise<void>((accept, reject) => {
- const command = [
- cli,
- "render",
- projectDir,
- "-o",
- resolve(output!),
- ];
- if (basename(compositionFile) !== "index.html") {
- command.push("--composition", basename(compositionFile));
- }
- const child = spawn(process.execPath, command, {
- stdio: "inherit",
- });
- child.once("error", reject);
- child.once("exit", (code) => code === 0
- ? accept()
- : reject(new Error(`HyperFrames exited with status ${String(code)}`)));
- });
- return;
- }
- process.stdout.write(`SVML compiler
-
-usage:
- svml check <file.svml>
- svml lock <file.svml> [--out svml.lock] [--artifacts artifacts.json]
- svml script <file.svml> [--out narrative.json]
- svml plan <file.svml> [--out plan.json]
- svml fmt <file.svml> [--check|--write|--out formatted.svml]
- svml estimate <file.svml> [--out timing.json] [--fps 30]
- svml canvas <file.svml> [--out canvas.json]
- svml timeline <file.svml> [--out timeline.json] [--lock svml.lock] [--artifacts artifacts.json]
- svml compile <file.svml> --out index.html [--lock svml.lock] [--artifacts artifacts.json]
- svml render <index.html> --out video.mp4
-
-The current runtime is deterministic-only: it has no generation provider host.
-`);
-}
-
-run().catch((error: unknown) => {
- if (error instanceof SvmlError) {
- process.stderr.write(`${JSON.stringify({ ok: false, diagnostics: error.diagnostics }, null, 2)}\n`);
- } else {
- process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
- }
- process.exitCode = 1;
-});
diff --git a/src/compiler.ts b/src/compiler.ts
deleted file mode 100644
index 78cde6dd..00000000
--- a/src/compiler.ts
+++ /dev/null
@@ -1,559 +0,0 @@
-import { copyFile, readFile, writeFile, mkdir } from "node:fs/promises";
-import { basename, dirname, resolve } from "node:path";
-import { fileURLToPath, pathToFileURL } from "node:url";
-import { fail } from "./diagnostics.js";
-import { expandComposites } from "./composite.js";
-import {
- resolveArtifactFile,
- verifyArtifactExecutionDigests,
-} from "./artifacts.js";
-import { attachExecutionDigests } from "./digests.js";
-import { emitHyperframesHtml } from "./hyperframes.js";
-import {
- kernelTemporalContracts,
- loadKernels,
- type KernelManifest,
-} from "./kernel.js";
-import { createLock, freezeLock, verifyLockFile, type SvmlLock } from "./lock.js";
-import type {
- CompleteSemanticMap,
- AttributeValue,
- SpeechTimingEvidence,
- LocatedScript,
- PlanIR,
- SourceDocument,
- SourceElement,
- TemporalBasisProduction,
-} from "./model.js";
-import { buildPlan, topologicalInstances } from "./plan.js";
-import type {
- HyperframesDocument,
- KernelProjection,
- RuntimeValue,
-} from "./runtime-contract.js";
-import { projectKernelIsolated } from "./sandbox.js";
-import { validateKernelProjection } from "./runtime-validation.js";
-import { bindSemanticMap, locateScript } from "./script/locate.js";
-import { estimateSpeechTiming, type EstimateOptions } from "./script/estimate.js";
-import { parseScript } from "./script/parse.js";
-import { loadSourceClosure } from "./source/modules.js";
-import { childElements, textContent } from "./source/query.js";
-import { applyStyleSheets } from "./source/styles.js";
-import { sha256, stableJson } from "./util.js";
-import {
- createProgramBasis,
- semanticMapFromTiming,
- validateSemanticMap,
- validateTemporalBasisProduction,
-} from "./temporal.js";
-
-export type Compilation = {
- document: SourceDocument;
- narrative: ReturnType<typeof parseScript>;
- plan: PlanIR;
- basis: TemporalBasisProduction;
- semanticMap: CompleteSemanticMap;
- located: LocatedScript;
- html: string;
- target: HyperframesDocument;
- outputFile?: string;
- projections: Map<string, KernelProjection>;
- lock: SvmlLock;
- sourceClosureVerified: boolean;
- temporalEvidenceVerified: boolean;
- lockVerified: boolean;
- artifactsVerified: boolean;
- artifactManifestHash?: string;
- reproducible: boolean;
-};
-
-function childById(document: SourceDocument): Map<string, SourceElement> {
- const output = new Map<string, SourceElement>();
- for (const element of childElements(document.root)) {
- const id = element.attributes.id;
- if (typeof id === "string") output.set(id, element);
- }
- return output;
-}
-
-export function resolveScriptBindings(document: SourceDocument): Record<string, string> {
- const script = childElements(document.root, "script")[0];
- if (!script) return {};
- const declarations = childById(document);
- return Object.fromEntries(Object.entries(script.attributes).map(([name, value]) => {
- if (typeof value === "string") return [name, value];
- if (!value || typeof value !== "object" || value.kind !== "reference") {
- fail("script_slot_binding", `Script Slot "${name}" requires literal Text or a Text reference.`);
- }
- const declaration = declarations.get(value.path);
- if (!declaration || declaration.name !== "text") {
- fail(
- "script_slot_binding",
- `Script Slot "${name}" references "${value.path}", which is not a Text declaration.`,
- );
- }
- return [name, textContent(declaration).trim()];
- }));
-}
-
-function nestedValue(value: unknown, path: string[]): unknown {
- let current = value;
- for (const part of path) {
- if (!current || typeof current !== "object") return undefined;
- current = (current as Record<string, unknown>)[part];
- }
- return current;
-}
-
-function isHyperframesDocument(value: unknown): value is HyperframesDocument {
- return !!value
- && typeof value === "object"
- && (value as HyperframesDocument).contract === "svml.hyperframes-document.v1";
-}
-
-function validateTrackOutput(
- instanceId: string,
- portName: string,
- value: unknown,
- durationFrames: number,
-): void {
- if (!value || typeof value !== "object") {
- fail("track_output_shape", `Track output "${instanceId}.${portName}" is not an object.`);
- }
- const track = value as { visuals?: unknown; audios?: unknown; styles?: unknown };
- if (!Array.isArray(track.visuals) || !Array.isArray(track.audios) || !Array.isArray(track.styles)) {
- fail(
- "track_output_shape",
- `Track output "${instanceId}.${portName}" requires flat visuals, audios and styles arrays.`,
- );
- }
- for (const contribution of [...track.visuals, ...track.audios] as Array<{
- id?: unknown;
- startFrame?: unknown;
- endFrameExclusive?: unknown;
- }>) {
- if (
- typeof contribution.id !== "string"
- || !Number.isInteger(contribution.startFrame)
- || !Number.isInteger(contribution.endFrameExclusive)
- || (contribution.startFrame as number) < 0
- || (contribution.endFrameExclusive as number) > durationFrames
- || (contribution.endFrameExclusive as number) <= (contribution.startFrame as number)
- ) {
- fail(
- "track_contribution_window",
- `Track "${instanceId}" contribution "${String(contribution.id)}" has invalid Program range ${String(contribution.startFrame)}..${String(contribution.endFrameExclusive)} for duration ${durationFrames}.`,
- );
- }
- }
-}
-
-async function stageDocumentAssets(
- document: HyperframesDocument,
- outputFile: string,
-): Promise<HyperframesDocument> {
- const assetDirectory = resolve(dirname(outputFile), "assets");
- await mkdir(assetDirectory, { recursive: true });
- const staged = new Map<string, string>();
- const stage = async (source: string): Promise<string> => {
- if (!source.startsWith("file:")) return source;
- const existing = staged.get(source);
- if (existing) return existing;
- const local = fileURLToPath(source);
- const contentHash = sha256(await readFile(local));
- const name = `${contentHash.slice(0, 16)}-${basename(local)}`;
- await copyFile(local, resolve(assetDirectory, name));
- const relative = `./assets/${name}`;
- staged.set(source, relative);
- return relative;
- };
- const visuals = await Promise.all(document.visuals.map(async (fragment) => ({
- ...fragment,
- ...(fragment.source ? { source: await stage(fragment.source) } : {}),
- })));
- const audios = await Promise.all(document.audios.map(async (fragment) => ({
- ...fragment,
- source: await stage(fragment.source),
- })));
- return { ...document, visuals, audios };
-}
-
-export async function checkSource(file: string): Promise<{
- document: SourceDocument;
- narrative: ReturnType<typeof parseScript>;
- plan: PlanIR;
- manifests: KernelManifest[];
- lock: SvmlLock;
-}> {
- const closure = await loadSourceClosure(file);
- const kernels = await loadKernels(closure);
- const styled = await applyStyleSheets(closure, kernels);
- const document = await applyStyleSheets(expandComposites(styled, kernels), kernels);
- const narrative = parseScript(
- document.file,
- document.scriptSource,
- document.scriptOffset,
- resolveScriptBindings(document),
- );
- const plan = buildPlan(document, kernels, narrative);
- await attachExecutionDigests(plan, kernels);
- const manifests = [...kernels.values()];
- return {
- document,
- narrative,
- plan,
- manifests,
- lock: createLock(document, manifests, plan),
- };
-}
-
-export async function estimateSource(
- file: string,
- options: EstimateOptions = {},
-): Promise<{
- evidence: SpeechTimingEvidence;
- basis: ReturnType<typeof createProgramBasis>;
- map: ReturnType<typeof semanticMapFromTiming>;
- located: LocatedScript;
-}> {
- const checked = await checkSource(file);
- const evidence = estimateSpeechTiming(checked.narrative, options);
- const basis = createProgramBasis({
- fps: evidence.fps,
- durationFrames: Math.round(evidence.durationSec * evidence.fps),
- outcomeDigest: sha256(JSON.stringify({
- kind: "svml.estimated-program-basis.v1",
- evidence,
- })),
- });
- const map = semanticMapFromTiming(
- checked.narrative,
- basis,
- evidence,
- );
- return {
- evidence,
- basis,
- map,
- located: bindSemanticMap(checked.narrative, basis, map),
- };
-}
-
-export async function compileSource(args: {
- file: string;
- outputFile?: string;
- lockFile?: string;
- artifactsFile?: string;
-}): Promise<Compilation> {
- const checked = await checkSource(args.file);
- const suppliedLock = args.lockFile
- ? await verifyLockFile(resolve(args.lockFile), checked.lock)
- : undefined;
- const kernels = await loadKernels(checked.document);
- const artifacts = await resolveArtifactFile(args.artifactsFile, checked.plan, kernels);
- await attachExecutionDigests(checked.plan, kernels, artifacts.outputDigests);
- verifyArtifactExecutionDigests(artifacts, checked.plan);
- const elements = childById(checked.document);
- const root = checked.plan.instances.find((instance) => instance.id === checked.plan.root);
- if (!root) fail("runtime_root_missing", `Root instance "${checked.plan.root}" is missing.`);
- const rootElement = elements.get(root.id);
- if (!rootElement) fail("runtime_root_element", `Root element "${root.id}" is missing.`);
- const rootManifest = kernels.get(root.kernel);
- if (!rootManifest) fail("runtime_kernel_missing", `Kernel "${root.kernel}" is missing.`);
- const basisPort = rootManifest.ports.find((port) =>
- port.direction === "input" && port.type.split("|").includes("TemporalBasisProduction"));
- const semanticPort = rootManifest.ports.find((port) =>
- port.direction === "input" && port.type.split("|").includes("CompleteSemanticMap"));
- if (!basisPort || !semanticPort) {
- fail("runtime_composition_contract", "Composition does not expose basis/map input ports.");
- }
- const width = Number(root.attributes.width ?? 1080);
- const height = Number(root.attributes.height ?? 1920);
- if (!Number.isFinite(width) || !Number.isFinite(height)) {
- fail("runtime_dimensions", "Film width and height must be finite numbers.");
- }
-
- const valueEntries = await Promise.all(checked.plan.values.map(async (value) => {
- const absoluteSource = value.source
- ? pathToFileURL(resolve(dirname(value.module), value.source)).href
- : undefined;
- const data = value.type === "SpeechTimingEvidence" && value.source
- ? JSON.parse(await readFile(resolve(dirname(value.module), value.source), "utf8"))
- : undefined;
- return [
- value.id,
- {
- ...value,
- ...(absoluteSource ? { absoluteSource } : {}),
- ...(data !== undefined ? { data } : {}),
- },
- ] as const;
- }));
- const values = new Map<string, RuntimeValue>(valueEntries);
- const results = new Map<string, KernelProjection>();
- let located: LocatedScript | undefined;
-
- const resolvePath = (path: string): unknown => {
- if (path === "script") {
- return checked.narrative;
- }
- if (path.startsWith("script.selection.")) {
- if (!located) fail("runtime_temporal_unbound", `Temporal reference "${path}" is not bound yet.`);
- return located.selections[path.slice("script.selection.".length)];
- }
- if (path.startsWith("script.moment.")) {
- if (!located) fail("runtime_temporal_unbound", `Temporal reference "${path}" is not bound yet.`);
- return located.moments[path.slice("script.moment.".length)];
- }
- if (path.startsWith("script.segment.")) {
- return checked.narrative.segments.find(
- (segment) => segment.id === path.slice("script.segment.".length),
- );
- }
- const declarationIds = [
- ...checked.plan.values.map((value) => value.id),
- ...checked.plan.instances.map((instance) => instance.id),
- ].sort((left, right) => right.length - left.length);
- const owner = declarationIds.find((id) => path === id || path.startsWith(`${id}.`));
- if (!owner) fail("runtime_reference_unknown", `Unknown reference "${path}".`);
- const tail = path === owner ? [] : path.slice(owner.length + 1).split(".");
- const value = values.get(owner);
- if (value) return tail.length ? nestedValue(value, tail) : value;
- const projection = results.get(owner);
- if (!projection) fail("runtime_reference_unready", `Reference "${path}" is not ready.`);
- return tail.length ? nestedValue(projection.outputs, tail) : projection.outputs;
- };
-
- const resolveValue = (value: AttributeValue | undefined): unknown => {
- if (value && typeof value === "object" && value.kind === "reference") {
- return resolvePath(value.path);
- }
- return value;
- };
-
- const resolveNode = (node: SourceElement["children"][number]): unknown => {
- if (node.kind === "text") return { ...node };
- return {
- ...node,
- attributes: Object.fromEntries(Object.entries(node.attributes)
- .map(([name, value]) => [name, resolveValue(value)])),
- children: node.children.map(resolveNode),
- };
- };
-
- const executeInstance = async (instance: PlanIR["instances"][number]): Promise<void> => {
- const manifest = kernels.get(instance.kernel);
- if (!manifest) fail("runtime_kernel_missing", `Kernel "${instance.kernel}" is missing.`);
- if (manifest.abiVersion !== "1") {
- fail(
- "runtime_kernel_abi",
- `Kernel "${manifest.name}" uses unsupported implementation ABI ${manifest.abiVersion}.`,
- );
- }
- if (manifest.profile === "capability-v1") {
- const projection = artifacts.projections.get(instance.id);
- if (!projection) {
- fail("artifact_projection_missing", `Capability "${instance.id}" has no resolved outputs.`);
- }
- results.set(instance.id, projection);
- return;
- }
- const sourceElement = elements.get(instance.id);
- if (!sourceElement) fail("runtime_instance_element", `Element "${instance.id}" is missing.`);
- const element = {
- ...sourceElement,
- attributes: instance.attributes,
- };
- const resolvedElement = {
- ...element,
- attributes: Object.fromEntries(Object.entries(element.attributes)
- .map(([name, value]) => [name, resolveValue(value)])),
- children: element.children.map(resolveNode),
- };
- const context = {
- instance,
- element: resolvedElement,
- temporalContracts: kernelTemporalContracts(manifest),
- ...(located ? {
- program: {
- basisDigest: located.basisDigest,
- fps: located.fps,
- durationFrames: located.durationFrames,
- durationSec: located.durationSec,
- },
- } : {}),
- fps: located?.fps ?? Number(root.attributes.fps ?? 30),
- width,
- height,
- };
- const projection = validateKernelProjection(await projectKernelIsolated(manifest, context));
- if (located) {
- for (const port of manifest.ports.filter((candidate) =>
- candidate.direction === "output"
- && (candidate.type === "Track" || candidate.type === "CaptionTrack"))) {
- validateTrackOutput(instance.id, port.name, projection.outputs[port.name], located.durationFrames);
- }
- }
- results.set(instance.id, projection);
- };
-
- const ordered = topologicalInstances(checked.plan);
- const instanceIds = ordered.map((instance) => instance.id)
- .sort((left, right) => right.length - left.length);
- const producerOf = (value: AttributeValue | undefined, label: string): string => {
- if (!value || typeof value !== "object" || value.kind !== "reference") {
- fail("runtime_composition_reference", `Composition ${label} must be an instance output reference.`);
- }
- const owner = instanceIds.find((id) => value.path === id || value.path.startsWith(`${id}.`));
- if (!owner) fail("runtime_composition_reference", `Composition ${label} has no producer.`);
- return owner;
- };
- const preBinding = new Set<string>();
- const addPreBinding = (id: string): void => {
- if (preBinding.has(id)) return;
- preBinding.add(id);
- const instance = ordered.find((candidate) => candidate.id === id);
- for (const dependency of instance?.dependencies ?? []) {
- if (ordered.some((candidate) => candidate.id === dependency)) addPreBinding(dependency);
- }
- };
- addPreBinding(producerOf(rootElement.attributes[basisPort.name], basisPort.name));
- addPreBinding(producerOf(rootElement.attributes[semanticPort.name], semanticPort.name));
- for (const instance of ordered) {
- if (preBinding.has(instance.id)) await executeInstance(instance);
- }
-
- const production = resolveValue(
- rootElement.attributes[basisPort.name],
- ) as TemporalBasisProduction | undefined;
- const semanticMap = resolveValue(
- rootElement.attributes[semanticPort.name],
- ) as CompleteSemanticMap | undefined;
- if (production?.contract !== "svml.temporal-basis-production.v1") {
- fail("runtime_basis_missing", "Composition root must select one TemporalBasisProduction.");
- }
- if (semanticMap?.contract !== "svml.complete-semantic-map.v1") {
- fail("runtime_semantic_map_missing", "Composition root must select one CompleteSemanticMap.");
- }
- validateTemporalBasisProduction(production);
- validateSemanticMap(checked.narrative, production.basis, semanticMap);
- located = locateScript(checked.narrative, production.basis, semanticMap);
-
- for (const instance of ordered) {
- if (!preBinding.has(instance.id)) await executeInstance(instance);
- }
-
- const rootProjection = results.get(checked.plan.root);
- const documentOutput = rootProjection?.outputs.document;
- if (!isHyperframesDocument(documentOutput)) {
- fail(
- "runtime_root_output",
- `Root Kernel "${root.kernel}" did not output svml.hyperframes-document.v1.`,
- );
- }
- const sourceDigests = new Map<string, string>();
- for (const value of values.values()) {
- const source = value.absoluteSource ?? value.source;
- if (source && value.contentDigest) sourceDigests.set(source, value.contentDigest);
- }
- const collectArtifactSources = (value: unknown): void => {
- if (Array.isArray(value)) {
- value.forEach(collectArtifactSources);
- return;
- }
- if (!value || typeof value !== "object") return;
- const record = value as Record<string, unknown>;
- if (typeof record.source === "string" && typeof record.contentDigest === "string") {
- sourceDigests.set(record.source, record.contentDigest);
- }
- Object.values(record).forEach(collectArtifactSources);
- };
- results.forEach((projection) => collectArtifactSources(projection.outputs));
- const canonicalTarget = {
- ...documentOutput,
- visuals: documentOutput.visuals.map((fragment) => ({
- ...fragment,
- ...(fragment.source
- ? { source: sourceDigests.get(fragment.source) ?? fragment.source }
- : {}),
- })),
- audios: documentOutput.audios.map((fragment) => ({
- ...fragment,
- source: sourceDigests.get(fragment.source) ?? fragment.source,
- })),
- };
- const planDigest = sha256(stableJson({
- root: checked.plan.root,
- instances: checked.plan.instances.map((instance) => ({
- identity: instance.identity,
- executionDigest: instance.executionDigest,
- })),
- edges: checked.plan.edges,
- expansions: checked.plan.expansions,
- }));
- const frozenLock = freezeLock(checked.lock, {
- planDigest,
- ...(artifacts.manifestHash ? { artifactManifestHash: artifacts.manifestHash } : {}),
- basisDigest: production.basis.basisDigest,
- productionDigest: production.productionDigest,
- semanticIndexDigest: semanticMap.semanticIndexDigest,
- semanticMapDigest: semanticMap.mapDigest,
- locatorDigest: semanticMap.locatorDigest,
- evidenceDigests: semanticMap.evidenceDigests,
- quantizationPolicy: semanticMap.quantizationPolicy,
- anchors: semanticMap.anchors.map((anchor) => ({
- identity: anchor.identity,
- frame: anchor.point.frame,
- quality: anchor.quality,
- })),
- programSpace: {
- width: documentOutput.width,
- height: documentOutput.height,
- fps: documentOutput.fps,
- durationFrames: documentOutput.durationFrames,
- },
- targetDigest: sha256(stableJson(canonicalTarget)),
- htmlDigest: sha256(emitHyperframesHtml(canonicalTarget)),
- }, artifacts.verified);
- const temporalEvidenceVerified = !!suppliedLock?.execution
- && stableJson(suppliedLock) === stableJson(frozenLock);
- if (suppliedLock?.execution && !temporalEvidenceVerified) {
- fail(
- "lock_execution_mismatch",
- `${resolve(args.lockFile!)} does not match the compiled Basis, SemanticMap or HyperFrames target.`,
- );
- }
- const outputFile = args.outputFile ? resolve(args.outputFile) : undefined;
- const materializedDocument = outputFile
- ? await stageDocumentAssets(documentOutput, outputFile)
- : documentOutput;
- const html = emitHyperframesHtml(materializedDocument);
- if (args.outputFile) {
- await mkdir(dirname(outputFile!), { recursive: true });
- await writeFile(outputFile!, html, "utf8");
- }
- return {
- document: checked.document,
- narrative: checked.narrative,
- plan: checked.plan,
- basis: production,
- semanticMap,
- located,
- html,
- target: materializedDocument,
- ...(outputFile ? { outputFile } : {}),
- projections: results,
- lock: frozenLock,
- sourceClosureVerified: args.lockFile !== undefined,
- temporalEvidenceVerified,
- lockVerified: temporalEvidenceVerified,
- artifactsVerified: artifacts.verified,
- ...(artifacts.manifestHash
- ? { artifactManifestHash: artifacts.manifestHash }
- : {}),
- reproducible:
- temporalEvidenceVerified
- && frozenLock.reproducible
- && artifacts.verified,
- };
-}
diff --git a/src/composite.ts b/src/composite.ts
deleted file mode 100644
index b03e6e5c..00000000
--- a/src/composite.ts
+++ /dev/null
@@ -1,285 +0,0 @@
-import { pathToFileURL } from "node:url";
-import { fail } from "./diagnostics.js";
-import type { KernelManifest, KernelRegistry } from "./kernel.js";
-import { validateKernelShape } from "./plan.js";
-import type {
- AttributeValue,
- Reference,
- SourceDocument,
- SourceElement,
- SourceNode,
-} from "./model.js";
-import { childElements } from "./source/query.js";
-import { sha256, stableJson } from "./util.js";
-
-type LoopBinding = {
- name: string;
- value: SourceElement;
-};
-
-function reference(value: AttributeValue | undefined): Reference | undefined {
- return value && typeof value === "object" && value.kind === "reference"
- ? value
- : undefined;
-}
-
-function canonicalNode(node: SourceNode): unknown {
- if (node.kind === "text") return { kind: "text", value: node.value };
- return {
- kind: "element",
- name: node.name,
- attributes: node.attributes,
- children: node.children.map(canonicalNode),
- };
-}
-
-function localReference(path: string, outerId: string, localIds: Set<string>): Reference | undefined {
- const owner = [...localIds]
- .sort((left, right) => right.length - left.length)
- .find((candidate) => path === candidate || path.startsWith(`${candidate}.`));
- if (!owner) return undefined;
- return {
- kind: "reference",
- path: `${outerId}::${owner}${path.slice(owner.length)}`,
- };
-}
-
-function evaluate(
- value: AttributeValue,
- args: {
- outer: SourceElement;
- outerId: string;
- localIds: Set<string>;
- loop?: LoopBinding;
- },
-): AttributeValue | undefined {
- const ref = reference(value);
- if (!ref) return value;
- const computedScript = /^ports\.([A-Za-z_][A-Za-z0-9_.:-]*)\.segment\[([A-Za-z_][A-Za-z0-9_.:-]*)\.id\]$/u
- .exec(ref.path);
- if (computedScript) {
- if (!args.loop || args.loop.name !== computedScript[2]) {
- fail("composite_expression", `Composite expression "${ref.path}" has no matching loop.`);
- }
- const script = reference(args.outer.attributes[computedScript[1]!]);
- const id = args.loop.value.attributes.id;
- if (!script || typeof id !== "string") {
- fail("composite_expression", `Composite expression "${ref.path}" requires Script and child id.`);
- }
- return { kind: "reference", path: `${script.path}.segment.${id}` };
- }
- const [head, ...tail] = ref.path.split(".");
- if (head === "params" || head === "ports") {
- const name = tail.join(".");
- return args.outer.attributes[name];
- }
- if (args.loop && head === args.loop.name) {
- return args.loop.value.attributes[tail.join(".")];
- }
- return localReference(ref.path, args.outerId, args.localIds) ?? ref;
-}
-
-function instantiateNode(
- template: SourceNode,
- args: {
- outer: SourceElement;
- outerId: string;
- localIds: Set<string>;
- aliases: ReadonlyMap<string, string>;
- expansionDigest: string;
- definitionFile: string;
- componentRoot: boolean;
- loop?: LoopBinding;
- },
-): SourceNode[] {
- if (template.kind === "text") return template.value.trim() ? [{ ...template }] : [];
- if (template.name === "for") {
- const each = reference(template.attributes.each)?.path;
- const alias = template.attributes.as;
- const match = /^children\.([A-Za-z_][A-Za-z0-9_.:-]*)$/u.exec(each ?? "");
- if (!match || typeof alias !== "string") {
- fail("composite_for", "Composite <for> requires each={children.name} and a quoted as name.");
- }
- return childElements(args.outer, match[1]).flatMap((value) =>
- template.children.flatMap((child) => instantiateNode(child, {
- ...args,
- componentRoot: false,
- loop: { name: alias, value },
- })));
- }
- const name = args.componentRoot
- ? args.aliases.get(template.name) ?? template.name
- : template.name;
- const attributes = Object.fromEntries(Object.entries(template.attributes).flatMap(([key, value]) => {
- const evaluated = evaluate(value, args);
- if (evaluated === undefined) return [];
- if (key === "id" && args.componentRoot) {
- if (typeof evaluated !== "string") fail("composite_id", "Composite internal id must be literal.");
- return [[key, `${args.outerId}::${evaluated}`]];
- }
- return [[key, evaluated]];
- }));
- return [{
- ...template,
- name,
- attributes,
- children: template.children.flatMap((child) => instantiateNode(child, {
- ...args,
- componentRoot: false,
- })),
- origin: {
- file: args.outer.origin?.file ?? "",
- ...(typeof attributes.id === "string" ? { localId: attributes.id } : {}),
- expansionDigest: args.expansionDigest,
- callSite: {
- file: args.outer.origin?.file ?? "",
- start: args.outer.start,
- end: args.outer.end,
- },
- definitionSite: {
- file: args.definitionFile,
- start: template.start,
- end: template.end,
- },
- },
- }];
-}
-
-function rewriteReference(value: AttributeValue, aliases: ReadonlyMap<string, string>): AttributeValue {
- const ref = reference(value);
- if (!ref) return value;
- let path = ref.path;
- for (let pass = 0; pass < 32; pass += 1) {
- const owner = [...aliases.keys()]
- .sort((left, right) => right.length - left.length)
- .find((candidate) => path === candidate || path.startsWith(`${candidate}.`));
- if (!owner) break;
- const next = `${aliases.get(owner)!}${path.slice(owner.length)}`;
- if (next === path) break;
- path = next;
- }
- return { kind: "reference", path };
-}
-
-function rewriteNode(node: SourceNode, aliases: ReadonlyMap<string, string>): SourceNode {
- if (node.kind === "text") return node;
- return {
- ...node,
- attributes: Object.fromEntries(Object.entries(node.attributes)
- .map(([name, value]) => [name, rewriteReference(value, aliases)])),
- children: node.children.map((child) => rewriteNode(child, aliases)),
- };
-}
-
-function expandOne(
- element: SourceElement,
- manifest: KernelManifest,
-): {
- nodes: SourceElement[];
- aliases: Record<string, string>;
- expansion: NonNullable<SourceDocument["expansions"]>[number];
-} {
- const outerId = element.attributes.id;
- if (typeof outerId !== "string") fail("composite_id", `<${manifest.name}> requires a stable id.`);
- validateKernelShape(element, manifest);
- const compose = manifest.compose;
- if (!compose) fail("composite_shape", `Composite "${manifest.name}" has no compose body.`);
- const templates = childElements(compose).filter((child) => child.name !== "export");
- const localIds = new Set(templates.flatMap((template) => {
- const id = template.attributes.id;
- return typeof id === "string" ? [id] : [];
- }));
- const expansionDigest = sha256(stableJson({
- contract: "svml.composite-expansion.v1",
- manifestHash: manifest.sourceHash,
- instanceId: outerId,
- attributes: element.attributes,
- children: element.children.map(canonicalNode),
- }));
- const importAliases = new Map((manifest.compositeImports ?? []).map((item) => {
- if (!item.kernelName) fail("composite_import", `Composite import "${item.alias}" is unresolved.`);
- return [item.alias, item.kernelName];
- }));
- const nodes = templates.flatMap((template) => instantiateNode(template, {
- outer: element,
- outerId,
- localIds,
- aliases: importAliases,
- expansionDigest,
- definitionFile: manifest.sourcePath,
- componentRoot: true,
- })) as SourceElement[];
- const exports: Record<string, string> = {};
- for (const item of childElements(compose, "export")) {
- const port = item.attributes.port;
- const value = item.attributes.value;
- if (typeof port !== "string" || !reference(value)) {
- fail("composite_export", "Composite <export> requires port and reference value attributes.");
- }
- const evaluated = evaluate(value!, { outer: element, outerId, localIds });
- const target = reference(evaluated)?.path;
- if (!target || exports[port]) fail("composite_export", `Invalid or duplicate export "${port}".`);
- exports[port] = target;
- }
- for (const port of manifest.ports.filter((candidate) => candidate.direction === "output")) {
- if (!exports[port.name]) {
- fail("composite_export_missing", `Composite "${manifest.name}" does not export "${port.name}".`);
- }
- }
- return {
- nodes,
- aliases: Object.fromEntries(Object.entries(exports).map(([port, target]) => [
- `${outerId}.${port}`,
- target,
- ])),
- expansion: {
- instanceId: outerId,
- component: manifest.name,
- manifestHash: manifest.sourceHash,
- expansionDigest,
- internalIds: nodes.map((node) => String(node.attributes.id)),
- exports,
- },
- };
-}
-
-export function expandComposites(
- document: SourceDocument,
- kernels: KernelRegistry,
-): SourceDocument {
- let children = document.root.children;
- const aliases = new Map<string, string>();
- const expansions: NonNullable<SourceDocument["expansions"]> = [];
- for (let pass = 0; pass < 32; pass += 1) {
- let changed = false;
- const next = children.flatMap((node): SourceNode[] => {
- if (node.kind !== "element") return [node];
- const manifest = kernels.get(node.name);
- if (manifest?.profile !== "composite-v1") return [node];
- changed = true;
- const expanded = expandOne(node, manifest);
- Object.entries(expanded.aliases).forEach(([from, to]) => aliases.set(from, to));
- expansions.push(expanded.expansion);
- return expanded.nodes;
- });
- children = next.map((node) => rewriteNode(node, aliases));
- if (!changed) {
- const compositeModules = [...kernels.values()]
- .filter((manifest) => manifest.profile === "composite-v1")
- .map((manifest) => ({
- kind: "svk" as const,
- uri: pathToFileURL(manifest.sourcePath).href,
- contentHash: manifest.sourceHash,
- dependencies: (manifest.compositeImports ?? []).map((item) =>
- pathToFileURL(item.sourcePath).href),
- }));
- return {
- ...document,
- root: { ...document.root, children },
- modules: [...(document.modules ?? []), ...compositeModules],
- expansions,
- };
- }
- }
- fail("composite_expansion_limit", "Composite expansion exceeded 32 finite passes.");
-}
diff --git a/src/diagnostics.ts b/src/diagnostics.ts
deleted file mode 100644
index e7f3fc51..00000000
--- a/src/diagnostics.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-export type DiagnosticSeverity = "error" | "warning" | "info";
-
-export type SourceLocation = {
- file: string;
- offset: number;
- line: number;
- column: number;
-};
-
-export type Diagnostic = {
- code: string;
- severity: DiagnosticSeverity;
- message: string;
- location?: SourceLocation;
- notes?: string[];
-};
-
-export class SvmlError extends Error {
- readonly diagnostics: Diagnostic[];
-
- constructor(diagnostics: Diagnostic | Diagnostic[]) {
- const list = Array.isArray(diagnostics) ? diagnostics : [diagnostics];
- super(list.map((item) => `${item.code}: ${item.message}`).join("\n"));
- this.name = "SvmlError";
- this.diagnostics = list;
- }
-}
-
-export function fail(code: string, message: string, location?: SourceLocation): never {
- throw new SvmlError({
- code,
- severity: "error",
- message,
- ...(location ? { location } : {}),
- });
-}
-
-export function sourceLocation(file: string, source: string, offset: number): SourceLocation {
- const bounded = Math.max(0, Math.min(source.length, offset));
- const before = source.slice(0, bounded);
- const lines = before.split("\n");
- return {
- file,
- offset: bounded,
- line: lines.length,
- column: (lines.at(-1)?.length ?? 0) + 1,
- };
-}
diff --git a/src/digests.ts b/src/digests.ts
deleted file mode 100644
index 23d5a94a..00000000
--- a/src/digests.ts
+++ /dev/null
@@ -1,119 +0,0 @@
-import { readFile } from "node:fs/promises";
-import { dirname, isAbsolute, resolve } from "node:path";
-import { fileURLToPath, pathToFileURL } from "node:url";
-import type {
- AttributeValue,
- PlanIR,
- SourceNode,
-} from "./model.js";
-import type { KernelRegistry } from "./kernel.js";
-import { topologicalInstances } from "./plan.js";
-import { sha256, stableJson } from "./util.js";
-
-function externalUri(value: string): boolean {
- return /^[A-Za-z][A-Za-z0-9+.-]*:/u.test(value);
-}
-
-function materialUri(module: string, source: string): string {
- if (source.startsWith("file:")) return source;
- if (externalUri(source)) return source;
- return pathToFileURL(isAbsolute(source) ? source : resolve(dirname(module), source)).href;
-}
-
-async function materialDigest(
- module: string,
- source: string,
-): Promise<{ digest: string; status: "content" | "unresolved-source" }> {
- const uri = materialUri(module, source);
- if (!uri.startsWith("file:")) {
- return {
- digest: sha256(`unresolved\0${uri}`),
- status: "unresolved-source",
- };
- }
- try {
- return {
- digest: sha256(await readFile(fileURLToPath(uri))),
- status: "content",
- };
- } catch {
- return {
- digest: sha256(`unresolved\0${uri}`),
- status: "unresolved-source",
- };
- }
-}
-
-function canonicalNodes(
- nodes: SourceNode[],
- canonicalValue: (value: AttributeValue) => unknown,
-): unknown[] {
- return nodes.map((node) => node.kind === "text"
- ? { kind: "text", value: node.value }
- : {
- kind: "element",
- name: node.name,
- attributes: Object.fromEntries(Object.entries(node.attributes)
- .filter(([name]) => name !== "class")
- .map(([name, value]) => [name, canonicalValue(value)])),
- children: canonicalNodes(node.children, canonicalValue),
- });
-}
-
-export async function attachExecutionDigests(
- plan: PlanIR,
- kernels: KernelRegistry,
- dependencyDigestOverrides: ReadonlyMap<string, string> = new Map(),
-): Promise<void> {
- for (const value of plan.values) {
- if (value.type === "Text") {
- value.contentDigest = sha256(value.value ?? "");
- value.digestStatus = "content";
- continue;
- }
- const material = await materialDigest(value.module, value.source ?? "");
- value.contentDigest = material.digest;
- value.digestStatus = material.status;
- }
-
- const values = new Map(plan.values.map((value) => [value.id, value]));
- const instances = new Map(plan.instances.map((instance) => [instance.id, instance]));
- const declarationIds = [...values.keys(), ...instances.keys()]
- .sort((left, right) => right.length - left.length);
- for (const instance of topologicalInstances(plan)) {
- const manifest = kernels.get(instance.kernel);
- if (!manifest) continue;
- const canonicalValue = (value: AttributeValue): unknown => {
- if (!value || typeof value !== "object" || value.kind !== "reference") return value;
- if (value.path.startsWith("script.")) return { script: value.path };
- const owner = declarationIds.find(
- (id) => value.path === id || value.path.startsWith(`${id}.`),
- );
- if (!owner) return { unresolved: value.path };
- const dependency = values.get(owner) ?? instances.get(owner);
- const identity = dependency?.identity ?? owner;
- const tail = value.path === owner ? "" : value.path.slice(owner.length + 1);
- return { identity, tail };
- };
- const dependencyDigests = instance.dependencies.map((id) => {
- const dependency = values.get(id) ?? instances.get(id);
- return {
- identity: dependency?.identity ?? id,
- digest: dependencyDigestOverrides.get(id) ?? ("contentDigest" in (dependency ?? {})
- ? (dependency as { contentDigest?: string }).contentDigest
- : (dependency as { executionDigest?: string } | undefined)?.executionDigest),
- };
- }).sort((left, right) => left.identity.localeCompare(right.identity));
- instance.executionDigest = sha256(stableJson({
- abi: manifest.abiVersion,
- manifest: manifest.sourceHash,
- implementation: manifest.implementationHash,
- expansion: instance.expansionDigest,
- attributes: Object.fromEntries(Object.entries(instance.attributes)
- .filter(([name]) => !["id", "class"].includes(name))
- .map(([name, value]) => [name, canonicalValue(value)])),
- children: canonicalNodes(instance.children, canonicalValue),
- dependencies: dependencyDigests,
- }));
- }
-}
diff --git a/src/format.ts b/src/format.ts
deleted file mode 100644
index 480b23b5..00000000
--- a/src/format.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-import { fail } from "./diagnostics.js";
-import type { NarrativeIR, SourceDocument } from "./model.js";
-import { parseScript } from "./script/parse.js";
-import { parseDocumentSource } from "./source/parse-document.js";
-import { stableJson } from "./util.js";
-
-function semanticNarrative(narrative: NarrativeIR): unknown {
- return {
- segments: narrative.segments.map((segment) => ({
- id: segment.id,
- tokenStart: segment.tokenStart,
- tokenEnd: segment.tokenEnd,
- atoms: segment.atoms.map((atom) => atom.kind === "role"
- ? { kind: "role", label: atom.label }
- : {
- kind: "text",
- speech: atom.speech.replace(/\s+/gu, " ").trim(),
- caption: atom.caption.replace(/\s+/gu, " ").trim(),
- }),
- })),
- tokens: narrative.tokens.map((token) => ({
- segmentId: token.segmentId,
- text: token.text,
- normalized: token.normalized,
- })),
- selections: Object.fromEntries(Object.entries(narrative.selections).map(([id, occurrences]) => [
- id,
- occurrences.map((occurrence) => ({
- occurrence: occurrence.occurrence,
- open: {
- affinity: occurrence.open.affinity,
- boundary: occurrence.open.boundary,
- },
- close: {
- affinity: occurrence.close.affinity,
- boundary: occurrence.close.boundary,
- },
- })),
- ])),
- moments: Object.fromEntries(Object.entries(narrative.moments).map(([id, occurrences]) => [
- id,
- occurrences.map((occurrence) => ({
- occurrence: occurrence.occurrence,
- affinity: occurrence.affinity,
- boundary: occurrence.boundary,
- })),
- ])),
- captionAtoms: narrative.captionAtoms.map((atom) => ({
- display: atom.display,
- segmentId: atom.segmentId,
- startToken: atom.startToken,
- endTokenExclusive: atom.endTokenExclusive,
- })),
- projections: narrative.projections,
- };
-}
-
-function formatScriptBody(source: string): string {
- const output: string[] = [];
- let insideSegment = false;
- let continuationIndent = 6;
- const pushBlank = (): void => {
- if (output.length && output.at(-1) !== "") output.push("");
- };
- for (const raw of source.replace(/\r\n?/gu, "\n").normalize("NFC").split("\n")) {
- const line = raw.trim();
- if (!line) continue;
- const opens = /^<segment\b[^>]*>$/u.test(line);
- const selfClosing = /^<segment\b[^>]*\/>$/u.test(line);
- const closes = /^<\/segment\s*>$/u.test(line);
- if (
- (!opens && line.includes("<segment"))
- || (!closes && line.includes("</segment"))
- ) {
- fail(
- "format_script_structural_line",
- "Canonical formatting requires Segment tags to be separate from spoken content.",
- );
- }
- if (opens) {
- if (insideSegment) fail("format_script_nested_segment", "Segment elements cannot nest.");
- pushBlank();
- output.push(` ${line}`);
- insideSegment = !selfClosing;
- continuationIndent = 6;
- if (selfClosing) pushBlank();
- continue;
- }
- if (closes) {
- if (!insideSegment) {
- fail("format_script_close_without_open", "Unexpected </segment> while formatting.");
- }
- output.push(` ${line}`);
- insideSegment = false;
- continuationIndent = 6;
- pushBlank();
- continue;
- }
- if (insideSegment) {
- const role = /^(<[\p{L}\p{M}\p{N}_. -]+>)\s+/u.exec(line);
- if (role) continuationIndent = 6 + role[0].length;
- output.push(`${" ".repeat(role ? 6 : continuationIndent)}${line}`);
- } else {
- output.push(` ${line}`);
- }
- }
- if (insideSegment) fail("format_script_unclosed_segment", "Unclosed Segment while formatting.");
- while (output.at(-1) === "") output.pop();
- return `\n${output.join("\n")}\n `;
-}
-
-export function formatDocumentScript(
- document: SourceDocument,
- narrative: NarrativeIR,
- bindings: Record<string, string>,
-): string {
- const body = formatScriptBody(document.scriptSource);
- const formatted = [
- document.source.slice(0, document.scriptOffset),
- body,
- document.source.slice(document.scriptOffset + document.scriptSource.length),
- ].join("");
- const reparsedDocument = parseDocumentSource(document.file, formatted);
- const reparsedNarrative = parseScript(
- document.file,
- reparsedDocument.scriptSource,
- reparsedDocument.scriptOffset,
- bindings,
- );
- if (stableJson(semanticNarrative(narrative)) !== stableJson(semanticNarrative(reparsedNarrative))) {
- fail(
- "format_semantic_change",
- "Formatter refused output because Script semantic IR changed.",
- );
- }
- return formatted;
-}
diff --git a/src/hyperframes.ts b/src/hyperframes.ts
deleted file mode 100644
index bf1c15b5..00000000
--- a/src/hyperframes.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-import type { AudioFragment, VisualFragment } from "./runtime-contract.js";
-import { escapeHtml } from "./util.js";
-
-const TIME_PRECISION = 1_000_000_000;
-
-/**
- * HyperFrames consumes seconds while SVML's Located IR is frame-exact.
- * Flooring, instead of emitting a raw repeating float, keeps the authored
- * interval half-open at frame boundaries:
- *
- * startFrame <= frame < endFrameExclusive
- *
- * A raw value such as 32 / 30 can otherwise compare a few ulps above or below
- * the browser's frame clock and leak one extra rendered frame.
- */
-export function frameSeconds(frame: number, fps: number): string {
- const value = Math.floor((frame / fps) * TIME_PRECISION) / TIME_PRECISION;
- return String(value);
-}
-
-function cssStyle(style: Record<string, string | number> | undefined): string {
- if (!style) return "";
- return Object.entries(style)
- .map(([name, value]) => `${name}:${String(value)}`)
- .join(";");
-}
-
-function attributes(values: Record<string, string> | undefined): string {
- if (!values) return "";
- return Object.entries(values)
- .map(([name, value]) => ` ${name}="${escapeHtml(value)}"`)
- .join("");
-}
-
-function visualHtml(fragment: VisualFragment, fps: number, trackIndex: number): string {
- const start = frameSeconds(fragment.startFrame, fps);
- const duration = frameSeconds(fragment.endFrameExclusive - fragment.startFrame, fps);
- const common = [
- `id="${escapeHtml(fragment.id)}"`,
- 'class="clip svml-fragment"',
- `data-start="${start}"`,
- `data-duration="${duration}"`,
- `data-track-index="${trackIndex}"`,
- `style="${escapeHtml(cssStyle({
- position: "absolute",
- "z-index": fragment.z,
- ...fragment.style,
- }))}"`,
- ].join(" ");
- if (fragment.kind === "html") {
- return `<div ${common}${attributes(fragment.attributes)}>${fragment.html ?? ""}</div>`;
- }
- if (fragment.kind === "image" && fragment.innerStyle) {
- const nestedSource = `${fragment.source ?? ""}#svml-${encodeURIComponent(fragment.id)}`;
- return `<div ${common}${attributes(fragment.attributes)}><img src="${escapeHtml(nestedSource)}" style="${escapeHtml(cssStyle(fragment.innerStyle))}"/></div>`;
- }
- const media = [
- fragment.mediaStartSec !== undefined ? `data-media-start="${fragment.mediaStartSec}"` : "",
- fragment.playbackRate !== undefined ? `data-playback-rate="${fragment.playbackRate}"` : "",
- fragment.kind === "video" && fragment.muted !== false ? "muted" : "",
- fragment.kind === "video" ? "playsinline" : "",
- fragment.kind === "video" && fragment.loop ? "loop" : "",
- ].filter(Boolean).join(" ");
- return `<${fragment.kind} ${common} ${media} src="${escapeHtml(fragment.source ?? "")}"${attributes(fragment.attributes)}></${fragment.kind}>`;
-}
-
-function audioHtml(fragment: AudioFragment, fps: number, trackIndex: number): string {
- const start = frameSeconds(fragment.startFrame, fps);
- const duration = frameSeconds(fragment.endFrameExclusive - fragment.startFrame, fps);
- const volume = fragment.volume ?? 1;
- return [
- `<audio id="${escapeHtml(fragment.id)}"`,
- `data-start="${start}"`,
- `data-duration="${duration}"`,
- `data-track-index="${trackIndex}"`,
- `data-volume="${volume}"`,
- fragment.bus ? `data-bus="${fragment.bus}"` : "",
- fragment.fadeInSec ? `data-fade-in="${fragment.fadeInSec}"` : "",
- fragment.fadeOutSec ? `data-fade-out="${fragment.fadeOutSec}"` : "",
- fragment.mediaStartSec !== undefined ? `data-media-start="${fragment.mediaStartSec}"` : "",
- fragment.playbackRate !== undefined ? `data-playback-rate="${fragment.playbackRate}"` : "",
- `src="${escapeHtml(fragment.source)}"></audio>`,
- ].filter(Boolean).join(" ");
-}
-
-export function emitHyperframesHtml(args: {
- id: string;
- width: number;
- height: number;
- fps: number;
- durationFrames: number;
- background: string;
- visuals: VisualFragment[];
- audios: AudioFragment[];
- styles?: string[];
-}): string {
- const orderedVisuals = [...args.visuals].sort((left, right) =>
- left.z - right.z
- || left.id.localeCompare(right.id));
- const visuals = orderedVisuals.map((fragment, index) =>
- visualHtml(fragment, args.fps, index));
- const audios = args.audios.map((fragment, index) =>
- audioHtml(fragment, args.fps, orderedVisuals.length + index));
- const duration = frameSeconds(args.durationFrames, args.fps);
- return `<!doctype html>
-<html>
-<head>
- <meta charset="utf-8"/>
- <meta name="viewport" content="width=device-width,initial-scale=1"/>
- <style>
- html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: ${args.background}; }
- [data-composition-id] { position: relative; overflow: hidden; background: ${args.background}; }
- .svml-fragment { box-sizing: border-box; }
- ${args.styles?.join("\n") ?? ""}
- ${orderedVisuals.map((item) => item.css ?? "").filter(Boolean).join("\n")}
- </style>
-</head>
-<body>
- <div data-composition-id="${escapeHtml(args.id)}"
- data-start="0"
- data-no-timeline
- data-width="${args.width}"
- data-height="${args.height}"
- data-duration="${duration}"
- data-fps="${args.fps}">
- ${visuals.join("\n ")}
- ${audios.join("\n ")}
- </div>
-</body>
-</html>
-`;
-}
diff --git a/src/kernel.ts b/src/kernel.ts
deleted file mode 100644
index f7bf3022..00000000
--- a/src/kernel.ts
+++ /dev/null
@@ -1,422 +0,0 @@
-import { readFile } from "node:fs/promises";
-import { dirname, resolve } from "node:path";
-import { pathToFileURL } from "node:url";
-import { fail } from "./diagnostics.js";
-import type { AttributeValue, SourceDocument, SourceElement } from "./model.js";
-import { attributeString, childElements } from "./source/query.js";
-import { parseRootSource } from "./source/parse-document.js";
-import { sha256 } from "./util.js";
-
-export type KernelPort = {
- name: string;
- direction: "input" | "output";
- type: string;
- cardinality: string;
- consume?: "one" | "each" | "set";
-};
-
-export type KernelParameter = {
- name: string;
- styleName: string;
- type: string;
- defaultValue?: AttributeValue;
-};
-
-export type KernelField = {
- name: string;
- styleName: string;
- type: string;
- required: boolean;
- consume?: "one" | "each" | "set";
-};
-
-export type KernelChildSchema = {
- name: string;
- cardinality: string;
- text: boolean;
- fields: KernelField[];
- children: KernelChildSchema[];
-};
-
-export type KernelManifest = {
- name: string;
- abiVersion: string;
- root: boolean;
- sourcePath: string;
- sourceHash: string;
- implementationPath?: string;
- implementationHash: string;
- profile: "isolated-projector-v1" | "capability-v1" | "composite-v1";
- capability?: string;
- permissions: string[];
- ports: KernelPort[];
- parameters: KernelParameter[];
- children: KernelChildSchema[];
- compositeImports?: Array<{ alias: string; sourcePath: string; kernelName?: string }>;
- compose?: SourceElement;
-};
-
-export type KernelRegistry = Map<string, KernelManifest>;
-
-export function kernelTemporalContracts(
- manifest: KernelManifest,
-): Record<string, {
- kind: "selection" | "moment";
- consume: "one" | "each" | "set";
-}> {
- const output: Record<string, {
- kind: "selection" | "moment";
- consume: "one" | "each" | "set";
- }> = {};
- const add = (
- path: string,
- type: string,
- consume: "one" | "each" | "set" | undefined,
- ): void => {
- const kind = type.split("|").includes("SelectionSet")
- ? "selection"
- : type.split("|").includes("MomentSet")
- ? "moment"
- : undefined;
- if (!kind || !consume) return;
- const existing = output[path];
- if (existing && (existing.kind !== kind || existing.consume !== consume)) {
- fail(
- "kernel_temporal_contract_ambiguous",
- `Kernel "${manifest.name}" has conflicting temporal contract "${path}".`,
- );
- }
- output[path] = { kind, consume };
- };
- for (const port of manifest.ports) add(port.name, port.type, port.consume);
- const visit = (schemas: KernelChildSchema[]): void => {
- for (const schema of schemas) {
- for (const field of schema.fields) {
- add(`${schema.name}.${field.name}`, field.type, field.consume);
- }
- visit(schema.children);
- }
- };
- visit(manifest.children);
- return output;
-}
-
-function stringAttribute(
- element: SourceElement,
- name: string,
- fallback?: string,
-): string | undefined {
- const value = element.attributes[name];
- if (typeof value === "string") return value;
- if (value === undefined) return fallback;
- fail("kernel_manifest_attribute", `<${element.name}> attribute "${name}" must be a string.`);
-}
-
-function booleanAttribute(
- element: SourceElement,
- name: string,
- fallback: boolean,
-): boolean {
- const value = element.attributes[name];
- if (typeof value === "boolean") return value;
- if (value === undefined) return fallback;
- fail("kernel_manifest_attribute", `<${element.name}> attribute "${name}" must be boolean.`);
-}
-
-function parseParameter(sourcePath: string, element: SourceElement): KernelParameter {
- const name = stringAttribute(element, "name");
- const type = stringAttribute(element, "type");
- if (
- !name
- || !type
- || !(
- ["string", "number", "boolean", "duration"].includes(type)
- || /^enum\([A-Za-z_][A-Za-z0-9_.:-]*(?:,[A-Za-z_][A-Za-z0-9_.:-]*)+\)$/u.test(type)
- )
- ) {
- fail("kernel_manifest_parameter", `${sourcePath} contains an invalid <param>.`);
- }
- let defaultValue = element.attributes.default;
- if (defaultValue !== undefined) {
- if (type === "number" && (typeof defaultValue !== "number" || !Number.isFinite(defaultValue))) {
- fail(
- "kernel_manifest_parameter_default",
- `${sourcePath} parameter ${name} has a non-numeric default.`,
- );
- }
- if (type === "boolean" && typeof defaultValue !== "boolean") {
- fail(
- "kernel_manifest_parameter_default",
- `${sourcePath} parameter ${name} has a non-boolean default.`,
- );
- }
- if (type === "duration" && (
- typeof defaultValue !== "string"
- || !/^[+-]?\d+(?:\.\d+)?(?:ms|s)$/u.test(defaultValue)
- )) {
- fail(
- "kernel_manifest_parameter_default",
- `${sourcePath} parameter ${name} has an invalid duration default.`,
- );
- }
- const enumValues = /^enum\((.+)\)$/u.exec(type)?.[1]?.split(",");
- if (enumValues && (typeof defaultValue !== "string" || !enumValues.includes(defaultValue))) {
- fail(
- "kernel_manifest_parameter_default",
- `${sourcePath} parameter ${name} has an invalid enum default.`,
- );
- }
- if (type === "string" && typeof defaultValue !== "string") {
- defaultValue = String(defaultValue);
- }
- }
- return {
- name,
- styleName: stringAttribute(element, "style", name) ?? name,
- type: type as KernelParameter["type"],
- ...(defaultValue !== undefined ? { defaultValue } : {}),
- };
-}
-
-function parseField(sourcePath: string, element: SourceElement): KernelField {
- const name = stringAttribute(element, "name");
- const type = stringAttribute(element, "type");
- if (!name || !type) {
- fail("kernel_manifest_field", `${sourcePath} contains an incomplete <field>.`);
- }
- const consume = stringAttribute(element, "consume");
- if (consume && !["one", "each", "set"].includes(consume)) {
- fail("kernel_manifest_temporal_consume", `${sourcePath} field ${name} has invalid consume.`);
- }
- if (
- type.split("|").some((candidate) => ["SelectionSet", "MomentSet"].includes(candidate))
- && !consume
- ) {
- fail(
- "kernel_manifest_temporal_consume",
- `${sourcePath} temporal field ${name} must declare consume="one|each|set".`,
- );
- }
- return {
- name,
- styleName: stringAttribute(element, "style", name) ?? name,
- type,
- required: booleanAttribute(element, "required", false),
- ...(consume ? { consume: consume as "one" | "each" | "set" } : {}),
- };
-}
-
-function parseChild(sourcePath: string, element: SourceElement): KernelChildSchema {
- const name = stringAttribute(element, "name");
- if (!name) fail("kernel_manifest_child", `${sourcePath} contains a child without a name.`);
- const fields = childElements(element, "field").map((field) => parseField(sourcePath, field));
- if (new Set(fields.map((field) => field.name)).size !== fields.length) {
- fail("kernel_manifest_field_duplicate", `${sourcePath} repeats a field on child ${name}.`);
- }
- const children = childElements(element, "child").map((child) => parseChild(sourcePath, child));
- if (new Set(children.map((child) => child.name)).size !== children.length) {
- fail("kernel_manifest_child_duplicate", `${sourcePath} repeats child schema ${name}.`);
- }
- return {
- name,
- cardinality: stringAttribute(element, "cardinality", "zero-or-more") ?? "zero-or-more",
- text: booleanAttribute(element, "text", false),
- fields,
- children,
- };
-}
-
-function parseManifest(sourcePath: string, source: string): KernelManifest {
- const root = parseRootSource(sourcePath, source);
- if (root.name !== "kernel") {
- fail("kernel_manifest_root", `${sourcePath} must contain one <kernel> root.`);
- }
- const name = stringAttribute(root, "name");
- const implementation = stringAttribute(root, "implementation");
- const profile = stringAttribute(root, "profile", "isolated-projector-v1");
- if (!name || !/^[A-Za-z_][A-Za-z0-9_.:-]*$/u.test(name)) {
- fail("kernel_manifest_name", `${sourcePath} has an invalid or missing Kernel name.`);
- }
- if (!["isolated-projector-v1", "capability-v1", "composite-v1"].includes(profile ?? "")) {
- fail("kernel_manifest_profile", `${sourcePath} has unsupported profile "${profile ?? ""}".`);
- }
- if (profile === "isolated-projector-v1" && !implementation) {
- fail("kernel_manifest_implementation", `${sourcePath} must declare implementation.`);
- }
- const capability = stringAttribute(root, "capability");
- if (profile === "capability-v1" && !capability) {
- fail("kernel_manifest_capability", `${sourcePath} capability Kernel requires capability.`);
- }
- const ports: KernelPort[] = childElements(root, "port").map((port) => {
- const portName = stringAttribute(port, "name");
- const direction = stringAttribute(port, "direction");
- const type = stringAttribute(port, "type");
- if (!portName || !direction || !type) {
- fail("kernel_manifest_port", `${sourcePath} contains an incomplete <port>.`);
- }
- if (direction !== "input" && direction !== "output") {
- fail("kernel_manifest_port_direction", `${sourcePath} port ${portName} has invalid direction.`);
- }
- const consume = stringAttribute(port, "consume");
- if (consume && !["one", "each", "set"].includes(consume)) {
- fail("kernel_manifest_temporal_consume", `${sourcePath} port ${portName} has invalid consume.`);
- }
- if (
- type.split("|").some((candidate) => ["SelectionSet", "MomentSet"].includes(candidate))
- && !consume
- ) {
- fail(
- "kernel_manifest_temporal_consume",
- `${sourcePath} temporal port ${portName} must declare consume="one|each|set".`,
- );
- }
- return {
- name: portName,
- direction,
- type,
- cardinality: stringAttribute(port, "cardinality", "one") ?? "one",
- ...(consume ? { consume: consume as "one" | "each" | "set" } : {}),
- };
- });
- const parameters = childElements(root, "param").map((parameter) =>
- parseParameter(sourcePath, parameter));
- if (new Set(parameters.map((parameter) => parameter.name)).size !== parameters.length) {
- fail("kernel_manifest_parameter_duplicate", `${sourcePath} repeats a parameter name.`);
- }
- const children = childElements(root, "child").map((child) => parseChild(sourcePath, child));
- if (new Set(children.map((child) => child.name)).size !== children.length) {
- fail("kernel_manifest_child_duplicate", `${sourcePath} repeats a root child schema.`);
- }
- const compositeImports = childElements(root, "import").map((element) => ({
- alias: stringAttribute(element, "as") ?? "",
- sourcePath: resolve(dirname(sourcePath), stringAttribute(element, "from") ?? ""),
- }));
- const compose = childElements(root, "compose")[0];
- if (profile === "composite-v1") {
- if (implementation || capability || !compose || !compositeImports.length) {
- fail(
- "kernel_composite_shape",
- `${sourcePath} composite-v1 requires imports and one <compose>, without implementation/capability.`,
- );
- }
- if (compositeImports.some((item) => !item.alias)) {
- fail("kernel_composite_import", `${sourcePath} Composite imports require explicit aliases.`);
- }
- }
- const known = new Set([
- "port",
- "param",
- "child",
- ...(profile === "composite-v1" ? ["import", "compose"] : []),
- ]);
- const unknown = childElements(root).find((element) => !known.has(element.name));
- if (unknown) {
- fail("kernel_manifest_element", `${sourcePath} contains unknown <${unknown.name}>.`);
- }
- return {
- name,
- abiVersion: String(root.attributes.abi ?? "1"),
- root: booleanAttribute(root, "root", false),
- sourcePath,
- sourceHash: sha256(source),
- ...(implementation ? { implementationPath: resolve(dirname(sourcePath), implementation) } : {}),
- implementationHash: "",
- profile: profile as KernelManifest["profile"],
- ...(capability ? { capability } : {}),
- permissions: (stringAttribute(root, "permissions", "") ?? "")
- .split(/[\s,]+/u)
- .filter(Boolean),
- ports,
- parameters,
- children,
- ...(profile === "composite-v1" ? { compositeImports, compose } : {}),
- };
-}
-
-export async function loadKernels(document: SourceDocument): Promise<KernelRegistry> {
- const registry: KernelRegistry = new Map();
- const imports = childElements(document.root, "import");
- const loading = new Set<string>();
- const definitions = new Map<string, KernelManifest>();
- const load = async (sourcePath: string): Promise<KernelManifest> => {
- sourcePath = resolve(sourcePath);
- if (loading.has(sourcePath)) {
- fail("kernel_import_cycle", `Composite Kernel import cycle at ${sourcePath}.`);
- }
- const byPath = definitions.get(sourcePath);
- if (byPath) return byPath;
- loading.add(sourcePath);
- const manifest = parseManifest(sourcePath, await readFile(sourcePath, "utf8"));
- if (manifest.profile === "composite-v1") {
- for (const imported of manifest.compositeImports ?? []) {
- const nested = await load(imported.sourcePath);
- imported.kernelName = nested.name;
- }
- manifest.implementationHash = sha256(`composite\0${manifest.sourceHash}`);
- } else {
- manifest.implementationHash = manifest.implementationPath
- ? sha256(await readFile(manifest.implementationPath))
- : sha256(`capability\0${manifest.capability ?? manifest.name}`);
- }
- definitions.set(sourcePath, manifest);
- loading.delete(sourcePath);
- return manifest;
- };
- const bind = (binding: string, manifest: KernelManifest): void => {
- if (!/^[A-Za-z_][A-Za-z0-9_.:-]*$/u.test(binding)) {
- fail("kernel_import_alias", `Kernel import alias "${binding}" is invalid.`);
- }
- const existing = registry.get(binding);
- if (existing && existing.sourcePath !== manifest.sourcePath) {
- fail(
- "kernel_duplicate_binding",
- `Kernel binding "${binding}" is defined by both ${existing.sourcePath} and ${manifest.sourcePath}.`,
- );
- }
- registry.set(binding, binding === manifest.name ? manifest : { ...manifest, name: binding });
- };
- const bindCompositeDependencies = (manifest: KernelManifest): void => {
- for (const imported of manifest.compositeImports ?? []) {
- const nested = definitions.get(resolve(imported.sourcePath));
- if (!nested) fail("kernel_import_resolution", `Kernel import ${imported.sourcePath} is unresolved.`);
- bind(nested.name, nested);
- bindCompositeDependencies(nested);
- }
- };
- for (const element of imports) {
- const from = attributeString(element, "from");
- if (!from.endsWith(".svk")) continue;
- const manifest = await load(resolve(dirname(document.file), from));
- bindCompositeDependencies(manifest);
- const alias = element.attributes.as;
- if (alias !== undefined && typeof alias !== "string") {
- fail("kernel_import_alias", `${document.file} Kernel import alias must be a string.`);
- }
- bind(alias ?? manifest.name, manifest);
- }
- return registry;
-}
-
-export async function loadKernelImplementation<T>(
- manifest: KernelManifest,
-): Promise<T> {
- if (!manifest.implementationPath) {
- fail(
- "kernel_implementation_profile",
- `Kernel "${manifest.name}" has no projector implementation.`,
- );
- }
- const moduleUrl = `${pathToFileURL(manifest.implementationPath).href}?kernel=${manifest.sourceHash}-${manifest.implementationHash}`;
- const loaded = await import(moduleUrl) as { default?: T };
- if (!loaded.default) {
- fail(
- "kernel_implementation_default",
- `${manifest.implementationPath} must export a default Kernel implementation.`,
- );
- }
- return loaded.default;
-}
-
-export function kernelElement(document: SourceDocument, id: string): SourceElement | undefined {
- return childElements(document.root).find((element) => element.attributes.id === id);
-}
diff --git a/src/lock.ts b/src/lock.ts
deleted file mode 100644
index 2e9b870b..00000000
--- a/src/lock.ts
+++ /dev/null
@@ -1,184 +0,0 @@
-import { readFile } from "node:fs/promises";
-import { dirname, isAbsolute, resolve } from "node:path";
-import { fileURLToPath } from "node:url";
-import { fail } from "./diagnostics.js";
-import type { KernelManifest } from "./kernel.js";
-import type { PlanIR, SourceDocument } from "./model.js";
-import { portableFileIdentity, stableJson } from "./util.js";
-
-export type SvmlLock = {
- contract: "svml.lock.v1";
- compiler: {
- package: "@svml/compiler";
- version: "0.0.1";
- };
- language: {
- document: "1";
- scriptSurface: "1";
- plan: "svml.plan.v1";
- };
- target: {
- name: "hyperframes";
- version: "0.7.84";
- };
- reproducible: boolean;
- modules: NonNullable<SourceDocument["modules"]>;
- expansions: PlanIR["expansions"];
- execution?: {
- planDigest: string;
- artifactManifestHash?: string;
- basisDigest: string;
- productionDigest: string;
- semanticIndexDigest: string;
- semanticMapDigest: string;
- locatorDigest: string;
- evidenceDigests: string[];
- quantizationPolicy: string;
- anchors: Array<{
- identity: string;
- frame: number;
- quality: string;
- }>;
- programSpace: {
- width: number;
- height: number;
- fps: number;
- durationFrames: number;
- };
- targetDigest: string;
- htmlDigest: string;
- };
- materials: Array<{
- identity: string;
- type: string;
- uri?: string;
- contentDigest: string;
- status: "content" | "unresolved-source";
- }>;
- kernels: Array<{
- name: string;
- abi: string;
- manifestUri: string;
- manifestHash: string;
- implementationUri?: string;
- implementationHash: string;
- capability?: string;
- permissions: string[];
- profile: string;
- }>;
-};
-
-export function createLock(
- document: SourceDocument,
- manifests: KernelManifest[],
- plan: PlanIR,
-): SvmlLock {
- const lockUri = (uri: string): string =>
- uri.startsWith("file:")
- ? portableFileIdentity(document.file, fileURLToPath(uri))
- : uri;
- const materials = plan.values.map((value) => {
- const source = value.source;
- const absolute = source
- ? /^[A-Za-z][A-Za-z0-9+.-]*:/u.test(source)
- ? source
- : isAbsolute(source) ? source : resolve(dirname(value.module), source)
- : undefined;
- const uri = absolute
- ? absolute.startsWith("file:")
- ? lockUri(absolute)
- : /^[A-Za-z][A-Za-z0-9+.-]*:/u.test(absolute)
- ? absolute
- : portableFileIdentity(document.file, absolute)
- : undefined;
- return {
- identity: value.identity,
- type: value.type,
- ...(uri ? { uri } : {}),
- contentDigest: value.contentDigest ?? "",
- status: value.digestStatus ?? "unresolved-source",
- };
- }).sort((left, right) => left.identity.localeCompare(right.identity));
- return {
- contract: "svml.lock.v1",
- compiler: {
- package: "@svml/compiler",
- version: "0.0.1",
- },
- language: {
- document: "1",
- scriptSurface: "1",
- plan: "svml.plan.v1",
- },
- target: {
- name: "hyperframes",
- version: "0.7.84",
- },
- reproducible: false,
- modules: (document.modules ?? []).map((module) => ({
- ...module,
- uri: lockUri(module.uri),
- dependencies: module.dependencies.map(lockUri),
- })).sort((left, right) => left.uri.localeCompare(right.uri)),
- expansions: plan.expansions,
- materials,
- kernels: manifests.map((manifest) => ({
- name: manifest.name,
- abi: manifest.abiVersion,
- manifestUri: portableFileIdentity(document.file, manifest.sourcePath),
- manifestHash: manifest.sourceHash,
- ...(manifest.implementationPath
- ? { implementationUri: portableFileIdentity(document.file, manifest.implementationPath) }
- : {}),
- implementationHash: manifest.implementationHash,
- ...(manifest.capability ? { capability: manifest.capability } : {}),
- permissions: manifest.permissions,
- profile: manifest.profile,
- })).sort((left, right) => left.name.localeCompare(right.name)),
- };
-}
-
-export function freezeLock(
- sourceLock: SvmlLock,
- execution: NonNullable<SvmlLock["execution"]>,
- artifactsVerified: boolean,
-): SvmlLock {
- return {
- ...sourceLock,
- reproducible:
- artifactsVerified
- && sourceLock.materials.every((material) => material.status === "content"),
- execution,
- };
-}
-
-export async function verifyLockFile(
- file: string,
- expected: SvmlLock,
-): Promise<SvmlLock> {
- let actual: unknown;
- try {
- actual = JSON.parse(await readFile(file, "utf8"));
- } catch (error) {
- fail(
- "lock_read",
- `Could not read SVML lock ${file}: ${error instanceof Error ? error.message : String(error)}.`,
- );
- }
- if (!actual || typeof actual !== "object" || (actual as { contract?: string }).contract !== "svml.lock.v1") {
- fail("lock_contract", `${file} is not an svml.lock.v1 document.`);
- }
- const parsed = actual as SvmlLock;
- const sourceOnly: SvmlLock = {
- ...parsed,
- reproducible: false,
- };
- delete sourceOnly.execution;
- if (stableJson(sourceOnly) !== stableJson(expected)) {
- fail(
- "lock_mismatch",
- `${file} does not match the resolved source closure; regenerate it with "svml lock".`,
- );
- }
- return parsed;
-}
diff --git a/src/model.ts b/src/model.ts
deleted file mode 100644
index d84fa62c..00000000
--- a/src/model.ts
+++ /dev/null
@@ -1,439 +0,0 @@
-export type Literal = string | number | boolean;
-
-export type Reference = {
- kind: "reference";
- path: string;
-};
-
-export type AttributeValue = Literal | Reference;
-
-export type ParameterSource = {
- kind: "kernel-default" | "svs-class" | "instance";
- source: string;
- value: AttributeValue;
-};
-
-export type SourceElement = {
- kind: "element";
- name: string;
- attributes: Record<string, AttributeValue>;
- children: SourceNode[];
- start: number;
- end: number;
- origin?: {
- file: string;
- localId?: string;
- expansionDigest?: string;
- callSite?: { file: string; start: number; end: number };
- definitionSite?: { file: string; start: number; end: number };
- };
- parameterSources?: Record<string, ParameterSource[]>;
-};
-
-export type SourceText = {
- kind: "text";
- value: string;
- start: number;
- end: number;
-};
-
-export type SourceNode = SourceElement | SourceText;
-
-export type SourceModuleRecord = {
- kind: "svml" | "svc" | "svs" | "svk";
- uri: string;
- contentHash: string;
- dependencies: string[];
-};
-
-export type SourceDocument = {
- file: string;
- source: string;
- root: SourceElement;
- scriptSource: string;
- scriptOffset: number;
- modules?: SourceModuleRecord[];
- expansions?: Array<{
- instanceId: string;
- component: string;
- manifestHash: string;
- expansionDigest: string;
- internalIds: string[];
- exports: Record<string, string>;
- }>;
-};
-
-export type ScriptAtom =
- | {
- kind: "text";
- speech: string;
- caption: string;
- start: number;
- end: number;
- tokenStart: number;
- tokenEndExclusive: number;
- }
- | { kind: "role"; label: string; start: number; end: number };
-
-export type SpokenTurn = {
- id: string;
- segmentId: string;
- role?: string;
- tokenStart: number;
- tokenEndExclusive: number;
- sourceStart: number;
- sourceEnd: number;
-};
-
-export type ScriptToken = {
- id: string;
- index: number;
- segmentId: string;
- segmentTokenIndex: number;
- startAnchorId: string;
- endAnchorId: string;
- text: string;
- normalized: string;
- sourceStart: number;
- sourceEnd: number;
-};
-
-export type MarkerBoundary = {
- tokenIndex: number;
- segmentId?: string;
- structuralPosition: number;
-};
-
-export type SelectionOccurrence = {
- id: string;
- occurrence: number;
- open: {
- affinity: "left" | "right";
- boundary: MarkerBoundary;
- sourceStart: number;
- };
- close: {
- affinity: "left" | "right";
- boundary: MarkerBoundary;
- sourceStart: number;
- };
-};
-
-export type MomentOccurrence = {
- id: string;
- occurrence: number;
- affinity: "left" | "right";
- boundary: MarkerBoundary;
- sourceStart: number;
-};
-
-export type ScriptSegment = {
- id: string;
- index: number;
- startAnchorId: string;
- endAnchorId: string;
- atoms: ScriptAtom[];
- tokenStart: number;
- tokenEnd: number;
- sourceStart: number;
- sourceEnd: number;
-};
-
-export type SemanticAnchorKind =
- | "segment-start"
- | "token-start"
- | "token-end"
- | "segment-end";
-
-export type SemanticAnchorIdentity = {
- id: string;
- kind: SemanticAnchorKind;
- segmentId: string;
- tokenId?: string;
- segmentTokenIndex?: number;
-};
-
-export type SemanticIndex = {
- contract: "svml.semantic-index.v1";
- anchors: SemanticAnchorIdentity[];
- tokens: Array<{
- id: string;
- segmentId: string;
- segmentTokenIndex: number;
- normalized: string;
- startAnchorId: string;
- endAnchorId: string;
- }>;
- digest: string;
-};
-
-export type CaptionAtom = {
- id: string;
- display: string;
- segmentId: string;
- startToken: number;
- endTokenExclusive: number;
- sourceStart: number;
- sourceEnd: number;
-};
-
-export type NarrativeIR = {
- segments: ScriptSegment[];
- tokens: ScriptToken[];
- turns: SpokenTurn[];
- selections: Record<string, SelectionOccurrence[]>;
- moments: Record<string, MomentOccurrence[]>;
- captionAtoms: CaptionAtom[];
- semanticIndex: SemanticIndex;
- projections: {
- dialogue: string;
- speech: string;
- caption: string;
- };
-};
-
-export type Rational = {
- numerator: number;
- denominator: number;
-};
-
-export type ProgramBasis = {
- contract: "svml.program-basis.v1";
- frameRate: Rational;
- originFrame: 0;
- durationFrames: number;
- basisDigest: string;
-};
-
-export type ProgramPoint = {
- basisDigest: string;
- frame: number;
-};
-
-export type SemanticPointQuality = "estimated" | "derived" | "measured";
-
-export type SemanticAnchorPoint = {
- identity: string;
- point: ProgramPoint;
- quality: SemanticPointQuality;
-};
-
-export type SemanticMapBase = {
- semanticIndexDigest: string;
- basisDigest: string;
- anchors: SemanticAnchorPoint[];
- evidenceDigests: string[];
- locatorDigest: string;
- quantizationPolicy: "nearest-frame";
- mapDigest: string;
-};
-
-export type CompleteSemanticMap = SemanticMapBase & {
- contract: "svml.complete-semantic-map.v1";
-};
-
-export type SemanticMap = CompleteSemanticMap;
-
-export type SourceToProgramMap = {
- id: string;
- sourceId: string;
- sourceDigest: string;
- sourceStartFrame: number;
- sourceEndFrameExclusive: number;
- programStartFrame: number;
- programEndFrameExclusive: number;
-};
-
-export type ProgramAudioContribution = {
- id: string;
- sourceId: string;
- sourceDigest: string;
- source: string;
- sourceMapId: string;
- sourceStartFrame: number;
- sourceEndFrameExclusive: number;
- programStartFrame: number;
- programEndFrameExclusive: number;
- gain: number;
- fadeInFrames?: number;
- fadeOutFrames?: number;
-};
-
-export type TemporalBasisProduction = {
- contract: "svml.temporal-basis-production.v1";
- basis: ProgramBasis;
- alignmentSubjects: Array<{
- id: string;
- sourceId: string;
- sourceDigest: string;
- sourceMapId: string;
- }>;
- sourceMaps: SourceToProgramMap[];
- audio: ProgramAudioContribution[];
- facets: Record<string, unknown>;
- productionDigest: string;
-};
-
-export type SpeechTimingUnit = {
- text: string;
- startSec: number;
- endSec: number;
- segmentId: string;
-};
-
-export type SpeechTimingSegment = {
- id: string;
- startSec: number;
- endSec: number;
-};
-
-export type SpeechTimingEvidence = {
- contract: "svml.speech-timing-evidence.v1";
- durationSec: number;
- fps: number;
- quality: "measured" | "estimated";
- units: SpeechTimingUnit[];
- segments: SpeechTimingSegment[];
- provenance?: Record<string, unknown>;
-};
-
-export type CaptionCue = {
- id: string;
- startToken: number;
- endTokenExclusive: number;
-};
-
-export type CaptionAnnotation = {
- id: string;
- kind: string;
- startToken: number;
- endTokenExclusive: number;
- value?: string;
-};
-
-export type CaptionPlan = {
- contract: "svml.caption-plan.v1";
- semanticIndexDigest: string;
- basisDigest: string;
- cues: CaptionCue[];
- annotations: CaptionAnnotation[];
- plannerDigest: string;
- planDigest: string;
-};
-
-export type ProgramRange = {
- startFrame: number;
- endFrameExclusive: number;
- startSec: number;
- endSec: number;
-};
-
-export type LocatedSelection = {
- id: string;
- ranges: ProgramRange[];
-};
-
-export type LocatedMoment = {
- id: string;
- frames: number[];
-};
-
-export type LocatedCaptionAtom = CaptionAtom & ProgramRange;
-
-export type LocatedScript = {
- contract: "svml.temporal-binding.v1";
- basisDigest: string;
- semanticMapDigest: string;
- durationFrames: number;
- durationSec: number;
- fps: number;
- words: Array<ScriptToken & ProgramRange>;
- segments: Record<string, ProgramRange>;
- selections: Record<string, LocatedSelection>;
- moments: Record<string, LocatedMoment>;
- captionAtoms: LocatedCaptionAtom[];
-};
-
-export type PlanValue = {
- id: string;
- type: "Image" | "Video" | "Audio" | "Text" | "SpeechTimingEvidence";
- source?: string;
- value?: string;
- identity: string;
- module: string;
- localId: string;
- contentDigest?: string;
- digestStatus?: "content" | "unresolved-source";
-};
-
-export type PlanInstance = {
- id: string;
- kernel: string;
- identity: string;
- module: string;
- localId: string;
- attributes: Record<string, AttributeValue>;
- effectiveParameters: Record<string, {
- value: AttributeValue;
- sources: ParameterSource[];
- }>;
- children: SourceNode[];
- dependencies: string[];
- executionDigest?: string;
- expansionDigest?: string;
- sourceMap?: {
- callSite: { file: string; start: number; end: number };
- definitionSite: { file: string; start: number; end: number };
- };
-};
-
-export type PlanIR = {
- contract: "svml.plan.v1";
- source: string;
- values: PlanValue[];
- instances: PlanInstance[];
- kernels: Array<{
- name: string;
- abiVersion: string;
- manifestHash: string;
- implementationHash: string;
- profile: "isolated-projector-v1" | "capability-v1" | "composite-v1";
- capability?: string;
- ports: Array<{
- name: string;
- direction: "input" | "output";
- type: string;
- cardinality: string;
- consume?: "one" | "each" | "set";
- }>;
- parameters: Array<{
- name: string;
- styleName: string;
- type: string;
- defaultValue?: AttributeValue;
- }>;
- children: Array<{
- name: string;
- cardinality: string;
- text: boolean;
- fields: Array<{
- name: string;
- styleName: string;
- type: string;
- required: boolean;
- consume?: "one" | "each" | "set";
- }>;
- children: unknown[];
- }>;
- }>;
- root: string;
- expansions: NonNullable<SourceDocument["expansions"]>;
- edges: Array<{
- from: string;
- to: string;
- via: string;
- fromPort?: string;
- toPort?: string;
- type?: string;
- }>;
-};
diff --git a/src/plan.ts b/src/plan.ts
deleted file mode 100644
index 894056b6..00000000
--- a/src/plan.ts
+++ /dev/null
@@ -1,600 +0,0 @@
-import { fail } from "./diagnostics.js";
-import type {
- AttributeValue,
- PlanIR,
- PlanInstance,
- PlanValue,
- NarrativeIR,
- Reference,
- SourceDocument,
- SourceElement,
- SourceNode,
-} from "./model.js";
-import type {
- KernelChildSchema,
- KernelManifest,
- KernelPort,
- KernelRegistry,
-} from "./kernel.js";
-import { childElements, textContent, walkElements } from "./source/query.js";
-import { portableFileIdentity, sha256 } from "./util.js";
-
-const VALUE_TYPES: Record<string, PlanValue["type"]> = {
- image: "Image",
- video: "Video",
- audio: "Audio",
- text: "Text",
- timing: "SpeechTimingEvidence",
-};
-
-function idOf(element: SourceElement): string {
- const id = element.attributes.id;
- if (typeof id !== "string" || !/^[A-Za-z_][A-Za-z0-9_.:-]*$/u.test(id)) {
- fail("plan_declaration_id", `<${element.name}> requires a stable id.`);
- }
- return id;
-}
-
-function referencesIn(nodes: SourceNode[], attributes: SourceElement["attributes"]): Array<{
- path: string;
- via: string;
-}> {
- const output: Array<{ path: string; via: string }> = [];
- for (const [name, value] of Object.entries(attributes)) {
- if (value && typeof value === "object" && value.kind === "reference") {
- output.push({ path: value.path, via: name });
- }
- }
- for (const element of walkElements(nodes)) {
- for (const [name, value] of Object.entries(element.attributes)) {
- if (value && typeof value === "object" && value.kind === "reference") {
- output.push({ path: value.path, via: `${element.name}.${name}` });
- }
- }
- }
- return output;
-}
-
-function dependencyOf(path: string, declarationIds: Set<string>): string | undefined {
- if (path.startsWith("script.")) return undefined;
- const candidates = [...declarationIds].filter(
- (id) => path === id || path.startsWith(`${id}.`),
- );
- return candidates.sort((left, right) => right.length - left.length)[0];
-}
-
-function cardinalityAccepts(cardinality: string, count: number): boolean {
- if (cardinality === "one") return count === 1;
- if (cardinality === "zero-or-one") return count <= 1;
- if (cardinality === "one-or-more") return count >= 1;
- if (cardinality === "zero-or-more") return true;
- fail("kernel_cardinality", `Unknown cardinality "${cardinality}".`);
-}
-
-function scalarAccepts(type: string, value: AttributeValue): boolean {
- if (type === "string") return typeof value === "string";
- if (type === "number") return typeof value === "number" && Number.isFinite(value);
- if (type === "boolean") return typeof value === "boolean";
- if (type === "id") {
- return typeof value === "string" && /^[A-Za-z_][A-Za-z0-9_.:-]*$/u.test(value);
- }
- if (type === "ProgramSpan" || type === "ProgramPoint") return typeof value === "string";
- if (type === "duration") {
- return typeof value === "string" && /^[+-]?\d+(?:\.\d+)?(?:ms|s)$/u.test(value);
- }
- if (type === "SourceRange") {
- return typeof value === "string" && /^\s*\d+(?:\.\d+)?(?:ms|s)\s*\.\.\s*\d+(?:\.\d+)?(?:ms|s)\s*$/u.test(value);
- }
- const enumValues = /^enum\((.+)\)$/u.exec(type)?.[1]?.split(",");
- if (enumValues) return typeof value === "string" && enumValues.includes(value);
- return false;
-}
-
-function validateTypedValue(
- value: AttributeValue,
- type: string,
- source: string,
-): void {
- if (value && typeof value === "object" && value.kind === "reference") return;
- if (type.split("|").some((candidate) => scalarAccepts(candidate, value))) return;
- fail("kernel_field_type", `${source} expects ${type}.`);
-}
-
-function validateChild(
- element: SourceElement,
- schema: KernelChildSchema,
- owner: string,
-): void {
- const allowed = new Set(["class", ...schema.fields.map((field) => field.name)]);
- for (const [name, value] of Object.entries(element.attributes)) {
- if (!allowed.has(name)) {
- fail(
- "kernel_field_unknown",
- `<${owner}> child <${element.name}> has unknown field "${name}".`,
- );
- }
- const field = schema.fields.find((candidate) => candidate.name === name);
- if (field) validateTypedValue(value, field.type, `<${owner}> <${element.name}>.${name}`);
- }
- for (const field of schema.fields) {
- if (field.required && element.attributes[field.name] === undefined) {
- fail(
- "kernel_field_required",
- `<${owner}> child <${element.name}> requires field "${field.name}".`,
- );
- }
- }
- const children = childElements(element);
- const text = element.children
- .filter((child) => child.kind === "text")
- .map((child) => child.value)
- .join("");
- if (!schema.text && text.trim()) {
- fail("kernel_child_text", `<${owner}> child <${element.name}> does not accept text content.`);
- }
- for (const child of children) {
- const childSchema = schema.children.find((candidate) => candidate.name === child.name);
- if (!childSchema) {
- fail(
- "kernel_child_unknown",
- `<${owner}> child <${element.name}> does not accept <${child.name}>.`,
- );
- }
- validateChild(child, childSchema, owner);
- }
- for (const childSchema of schema.children) {
- const count = children.filter((child) => child.name === childSchema.name).length;
- if (!cardinalityAccepts(childSchema.cardinality, count)) {
- fail(
- "kernel_child_cardinality",
- `<${owner}> <${element.name}> requires ${childSchema.cardinality} <${childSchema.name}> children; received ${count}.`,
- );
- }
- }
-}
-
-export function validateKernelShape(element: SourceElement, manifest: KernelManifest): void {
- const inputPorts = manifest.ports.filter((port) => port.direction === "input");
- const allowed = new Set([
- "id",
- "class",
- ...manifest.parameters.map((parameter) => parameter.name),
- ...inputPorts.map((port) => port.name),
- ]);
- for (const [name, value] of Object.entries(element.attributes)) {
- if (!allowed.has(name)) {
- fail("kernel_parameter_unknown", `<${manifest.name}> has unknown parameter or port "${name}".`);
- }
- const parameter = manifest.parameters.find((candidate) => candidate.name === name);
- if (parameter) validateTypedValue(value, parameter.type, `<${manifest.name}>.${name}`);
- }
- const children = childElements(element);
- const text = element.children
- .filter((child) => child.kind === "text")
- .map((child) => child.value)
- .join("");
- if (text.trim()) {
- fail("kernel_root_text", `<${manifest.name}> does not accept direct text content.`);
- }
- for (const child of children) {
- const schema = manifest.children.find((candidate) => candidate.name === child.name);
- if (!schema) {
- fail("kernel_child_unknown", `<${manifest.name}> does not accept <${child.name}>.`);
- }
- validateChild(child, schema, manifest.name);
- }
- for (const schema of manifest.children) {
- const count = children.filter((child) => child.name === schema.name).length;
- if (!cardinalityAccepts(schema.cardinality, count)) {
- fail(
- "kernel_child_cardinality",
- `<${manifest.name}> requires ${schema.cardinality} <${schema.name}> children; received ${count}.`,
- );
- }
- }
- for (const port of inputPorts) {
- const count = manifest.children.some((schema) => schema.name === port.name)
- ? children.filter((child) => child.name === port.name).length
- : element.attributes[port.name] === undefined ? 0 : 1;
- if (!cardinalityAccepts(port.cardinality, count)) {
- fail(
- "kernel_port_cardinality",
- `<${manifest.name}> input "${port.name}" requires ${port.cardinality}; received ${count}.`,
- );
- }
- }
-}
-
-function outputPortForPath(
- manifest: KernelManifest | undefined,
- tail: string,
-): KernelPort | undefined {
- if (!manifest || !tail) return undefined;
- const target = tail.split(".");
- return manifest.ports
- .filter((port) => port.direction === "output")
- .filter((port) => {
- const pattern = port.name.split(".");
- return pattern.length === target.length
- && pattern.every((part, index) => part === "*" || part === target[index]);
- })
- .sort((left, right) => {
- const leftWildcards = left.name.split(".").filter((part) => part === "*").length;
- const rightWildcards = right.name.split(".").filter((part) => part === "*").length;
- return leftWildcards - rightWildcards;
- })[0];
-}
-
-function childField(
- schemas: KernelChildSchema[],
- elementName: string,
- fieldName: string,
-): KernelChildSchema["fields"][number] | undefined {
- for (const schema of schemas) {
- if (schema.name === elementName) {
- const field = schema.fields.find((candidate) => candidate.name === fieldName);
- if (field) return field;
- }
- const nested = childField(schema.children, elementName, fieldName);
- if (nested) return nested;
- }
- return undefined;
-}
-
-function expectedReferenceType(
- manifest: KernelManifest | undefined,
- via: string,
-): { name: string; type: string } | undefined {
- if (!manifest) return undefined;
- if (!via.includes(".")) {
- const port = manifest.ports.find(
- (candidate) => candidate.direction === "input" && candidate.name === via,
- );
- return port ? { name: port.name, type: port.type } : undefined;
- }
- const [elementName, fieldName] = via.split(".");
- if (!elementName || !fieldName) return undefined;
- const field = childField(manifest.children, elementName, fieldName);
- return field ? { name: via, type: field.type } : undefined;
-}
-
-function compatibleType(actual: string, expected: string): boolean {
- return expected.split("|").includes(actual);
-}
-
-export function buildPlan(
- document: SourceDocument,
- kernels: KernelRegistry,
- narrative: NarrativeIR,
-): PlanIR {
- const declarations = childElements(document.root).filter(
- (element) => !["import", "script"].includes(element.name),
- );
- const ids = declarations.map(idOf);
- const unique = new Set(ids);
- if (unique.size !== ids.length) fail("plan_duplicate_id", "Declaration ids must be unique.");
-
- const values: PlanValue[] = [];
- const instances: PlanInstance[] = [];
- for (const element of declarations) {
- const id = idOf(element);
- const module = element.origin?.file ?? document.file;
- const localId = element.origin?.localId ?? id;
- const moduleIdentity = portableFileIdentity(document.file, module);
- const type = VALUE_TYPES[element.name];
- if (type) {
- const src = element.attributes.src;
- const value = element.name === "text" ? textContent(element).trim() : undefined;
- if (element.name !== "text" && typeof src !== "string") {
- fail("plan_value_source", `<${element.name} id="${id}"> requires src.`);
- }
- values.push({
- id,
- type,
- ...(typeof src === "string" ? { source: src } : {}),
- ...(value !== undefined ? { value } : {}),
- identity: sha256(`${moduleIdentity}\0${localId}`),
- module,
- localId,
- });
- continue;
- }
- const manifest = kernels.get(element.name);
- if (!manifest) {
- fail(
- "plan_unknown_kernel",
- `No imported .svk defines <${element.name}>.`,
- );
- }
- validateKernelShape(element, manifest);
- const dependencies = referencesIn(element.children, element.attributes)
- .map((reference) => dependencyOf(reference.path, unique))
- .filter((value): value is string => value !== undefined && value !== id);
- const defaultAttributes = Object.fromEntries(manifest.parameters
- .filter((parameter) => parameter.defaultValue !== undefined)
- .map((parameter) => [parameter.name, parameter.defaultValue!]));
- const attributes = { ...defaultAttributes, ...element.attributes };
- const effectiveParameters = Object.fromEntries(manifest.parameters.flatMap((parameter) => {
- const value = attributes[parameter.name];
- if (value === undefined) return [];
- const sources = [
- ...(parameter.defaultValue !== undefined
- ? [{
- kind: "kernel-default" as const,
- source: manifest.sourcePath,
- value: parameter.defaultValue,
- }]
- : []),
- ...(element.parameterSources?.[parameter.name] ?? (
- element.attributes[parameter.name] !== undefined
- ? [{
- kind: "instance" as const,
- source: module,
- value: element.attributes[parameter.name]!,
- }]
- : []
- )),
- ];
- return [[parameter.name, { value, sources }]];
- }));
- instances.push({
- id,
- kernel: manifest.name,
- identity: sha256(`${moduleIdentity}\0${localId}`),
- module,
- localId,
- attributes,
- effectiveParameters,
- children: element.children,
- dependencies: [...new Set(dependencies)],
- ...(element.origin?.expansionDigest
- ? { expansionDigest: element.origin.expansionDigest }
- : {}),
- ...(element.origin?.callSite && element.origin.definitionSite
- ? {
- sourceMap: {
- callSite: element.origin.callSite,
- definitionSite: element.origin.definitionSite,
- },
- }
- : {}),
- });
- }
-
- const rootCandidates = instances.filter((instance) => kernels.get(instance.kernel)?.root);
- if (rootCandidates.length !== 1) {
- fail(
- "plan_root_cardinality",
- `Expected exactly one root Kernel instance, received ${rootCandidates.length}.`,
- );
- }
- const root = rootCandidates[0]?.id;
- if (!root) fail("plan_root_missing", "Plan root is missing.");
-
- const instanceIds = new Set(instances.map((instance) => instance.id));
- const valueIds = new Set(values.map((value) => value.id));
- for (const instance of instances) {
- for (const reference of referencesIn(instance.children, instance.attributes)) {
- const consumerManifest = kernels.get(instance.kernel);
- const expected = expectedReferenceType(consumerManifest, reference.via);
- if (reference.path === "script") {
- if (expected && !compatibleType("NarrativeIR", expected.type)) {
- fail(
- "plan_port_type",
- `Reference "script" produces NarrativeIR, but ${instance.id}.${expected.name} requires ${expected.type}.`,
- );
- }
- continue;
- }
- if (reference.path.startsWith("script.")) {
- const temporal = /^(selection|moment|segment)\.([A-Za-z_][A-Za-z0-9_.-]*)$/u.exec(
- reference.path.slice("script.".length),
- );
- const exists = temporal?.[1] === "selection"
- ? narrative.selections[temporal[2]!] !== undefined
- : temporal?.[1] === "moment"
- ? narrative.moments[temporal[2]!] !== undefined
- : temporal?.[1] === "segment"
- ? narrative.segments.some((segment) => segment.id === temporal[2])
- : false;
- if (!exists) {
- fail(
- "plan_script_reference",
- `Instance "${instance.id}" references unknown Script path "${reference.path}".`,
- );
- }
- const actualType = temporal?.[1] === "selection"
- ? "SelectionSet"
- : temporal?.[1] === "moment"
- ? "MomentSet"
- : "ScriptSegment";
- if (expected && !compatibleType(actualType, expected.type)) {
- fail(
- "plan_port_type",
- `Reference "${reference.path}" produces ${actualType}, but ${instance.id}.${expected.name} requires ${expected.type}.`,
- );
- }
- continue;
- }
- const dependency = dependencyOf(reference.path, unique);
- if (!dependency) {
- fail(
- "plan_reference_unknown",
- `Instance "${instance.id}" references unknown declaration "${reference.path}".`,
- );
- }
- if (valueIds.has(dependency)) {
- if (reference.path !== dependency) {
- fail(
- "plan_value_projection",
- `Value "${dependency}" has no output path "${reference.path.slice(dependency.length + 1)}".`,
- );
- }
- const value = values.find((candidate) => candidate.id === dependency);
- if (value && expected && !compatibleType(value.type, expected.type)) {
- fail(
- "plan_port_type",
- `Reference "${reference.path}" produces ${value.type}, but ${instance.id}.${expected.name} requires ${expected.type}.`,
- );
- }
- continue;
- }
- const producer = instances.find((candidate) => candidate.id === dependency);
- const manifest = producer ? kernels.get(producer.kernel) : undefined;
- const tail = reference.path === dependency
- ? ""
- : reference.path.slice(dependency.length + 1);
- const outputPort = outputPortForPath(manifest, tail);
- if (!outputPort) {
- fail(
- "plan_output_port",
- `Reference "${reference.path}" does not name an output port of "${dependency}".`,
- );
- }
- if (expected && !compatibleType(outputPort.type, expected.type)) {
- fail(
- "plan_port_type",
- `Reference "${reference.path}" produces ${outputPort.type}, but ${instance.id}.${expected.name} requires ${expected.type}.`,
- );
- }
- }
- }
-
- const edges: PlanIR["edges"] = [];
- for (const instance of instances) {
- for (const reference of referencesIn(instance.children, instance.attributes)) {
- const dependency = dependencyOf(reference.path, unique);
- if (!dependency) continue;
- if (instanceIds.has(dependency) || valueIds.has(dependency)) {
- const producer = instances.find((candidate) => candidate.id === dependency);
- const producerManifest = producer ? kernels.get(producer.kernel) : undefined;
- const tail = producer && reference.path !== dependency
- ? reference.path.slice(dependency.length + 1)
- : undefined;
- const outputPort = tail
- ? outputPortForPath(producerManifest, tail)
- : undefined;
- const value = values.find((candidate) => candidate.id === dependency);
- const consumerManifest = kernels.get(instance.kernel);
- const input = expectedReferenceType(consumerManifest, reference.via);
- edges.push({
- from: dependency,
- to: instance.id,
- via: reference.via,
- ...(outputPort ? { fromPort: outputPort.name } : value ? { fromPort: "value" } : {}),
- ...(input ? { toPort: input.name } : { toPort: reference.via }),
- ...(outputPort?.type
- ? { type: outputPort.type }
- : value
- ? { type: value.type }
- : {}),
- });
- }
- }
- }
-
- const reachable = new Set<string>();
- const visit = (id: string): void => {
- if (reachable.has(id)) return;
- reachable.add(id);
- const instance = instances.find((item) => item.id === id);
- for (const dependency of instance?.dependencies ?? []) visit(dependency);
- };
- visit(root);
- const reachableInstances = instances.filter((instance) => reachable.has(instance.id));
- const reachableEdges = edges.filter((edge) => reachable.has(edge.from) && reachable.has(edge.to));
- const rootManifest = kernels.get(rootCandidates[0]!.kernel)!;
- const basisInputs = rootManifest.ports.filter((port) =>
- port.direction === "input" && port.type.split("|").includes("TemporalBasisProduction"));
- const semanticInputs = rootManifest.ports.filter((port) =>
- port.direction === "input" && port.type.split("|").includes("CompleteSemanticMap"));
- if (
- basisInputs.length !== 1
- || basisInputs[0]?.cardinality !== "one"
- || semanticInputs.length !== 1
- || semanticInputs[0]?.cardinality !== "one"
- ) {
- fail(
- "composition_temporal_contract",
- `Composition Kernel "${rootManifest.name}" must select exactly one TemporalBasisProduction and one CompleteSemanticMap.`,
- );
- }
- const trackEdges = reachableEdges.filter((edge) =>
- edge.type === "Track" || edge.type === "CaptionTrack");
- const illegalTrackConsumer = trackEdges.find((edge) => edge.to !== root);
- if (illegalTrackConsumer) {
- fail(
- "track_terminal_contract",
- `Track "${illegalTrackConsumer.from}" is consumed by non-Composition instance "${illegalTrackConsumer.to}".`,
- );
- }
- const duplicateTrack = trackEdges.find((edge, index) =>
- trackEdges.findIndex((candidate) => candidate.from === edge.from && candidate.to === edge.to) !== index);
- if (duplicateTrack) {
- fail(
- "duplicate_track_in_composition",
- `Composition "${root}" references Track "${duplicateTrack.from}" more than once.`,
- );
- }
- const captionTracks = reachableInstances.filter((instance) =>
- kernels.get(instance.kernel)?.ports.some((port) =>
- port.direction === "output" && port.type === "CaptionTrack"));
- if (captionTracks.length > 1) {
- fail(
- "caption_track_cardinality",
- `A Composition may contain at most one CaptionTrack; received ${captionTracks.length}.`,
- );
- }
- const usedKernels = new Set(reachableInstances.map((instance) => instance.kernel));
- return {
- contract: "svml.plan.v1",
- source: document.file,
- values: values.filter((value) => reachable.has(value.id)),
- instances: reachableInstances,
- kernels: [...kernels.values()]
- .filter((manifest) => usedKernels.has(manifest.name))
- .map((manifest) => ({
- name: manifest.name,
- abiVersion: manifest.abiVersion,
- manifestHash: manifest.sourceHash,
- implementationHash: manifest.implementationHash,
- profile: manifest.profile,
- ...(manifest.capability ? { capability: manifest.capability } : {}),
- ports: manifest.ports,
- parameters: manifest.parameters,
- children: manifest.children,
- }))
- .sort((left, right) => left.name.localeCompare(right.name)),
- root,
- expansions: document.expansions ?? [],
- edges: reachableEdges,
- };
-}
-
-export function topologicalInstances(plan: PlanIR): PlanInstance[] {
- const byId = new Map(plan.instances.map((instance) => [instance.id, instance]));
- const visiting = new Set<string>();
- const done = new Set<string>();
- const output: PlanInstance[] = [];
- const visit = (id: string): void => {
- if (done.has(id)) return;
- if (visiting.has(id)) fail("plan_cycle", `Cycle detected at "${id}".`);
- visiting.add(id);
- const instance = byId.get(id);
- if (!instance) return;
- for (const dependency of instance.dependencies) {
- if (byId.has(dependency)) visit(dependency);
- }
- visiting.delete(id);
- done.add(id);
- output.push(instance);
- };
- visit(plan.root);
- return output;
-}
-
-export function reference(value: unknown): Reference | undefined {
- return value && typeof value === "object" && (value as Reference).kind === "reference"
- ? value as Reference
- : undefined;
-}
diff --git a/src/runtime-contract.ts b/src/runtime-contract.ts
deleted file mode 100644
index 49ac1bca..00000000
--- a/src/runtime-contract.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-import type {
- AttributeValue,
- PlanInstance,
- PlanValue,
- ProgramRange,
- SourceElement,
-} from "./model.js";
-
-export type VisualFragment = {
- id: string;
- kind: "image" | "video" | "html";
- startFrame: number;
- endFrameExclusive: number;
- z: number;
- source?: string;
- mediaStartSec?: number;
- playbackRate?: number;
- loop?: boolean;
- muted?: boolean;
- html?: string;
- css?: string;
- style?: Record<string, string | number>;
- innerStyle?: Record<string, string | number>;
- attributes?: Record<string, string>;
-};
-
-export type AudioFragment = {
- id: string;
- source: string;
- startFrame: number;
- endFrameExclusive: number;
- mediaStartSec?: number;
- playbackRate?: number;
- volume?: number;
- fadeInSec?: number;
- fadeOutSec?: number;
- bus?: "speech" | "music" | "sfx" | "source";
-};
-
-export type KernelProjection = {
- outputs: Record<string, unknown>;
- visuals?: VisualFragment[];
- audios?: AudioFragment[];
- styles?: string[];
- diagnostics?: Array<{ code: string; message: string }>;
-};
-
-export type HyperframesDocument = {
- contract: "svml.hyperframes-document.v1";
- id: string;
- width: number;
- height: number;
- fps: number;
- durationFrames: number;
- background: string;
- visuals: VisualFragment[];
- audios: AudioFragment[];
- styles?: string[];
-};
-
-export type RuntimeValue = PlanValue & {
- absoluteSource?: string;
- data?: unknown;
-};
-
-export type KernelContext = {
- instance: PlanInstance;
- element: SourceElement;
- resolve: (value: AttributeValue | undefined) => unknown;
- digest: (value: unknown) => string;
- program?: {
- basisDigest: string;
- fps: number;
- durationFrames: number;
- durationSec: number;
- };
- temporalContracts: Record<string, {
- kind: "selection" | "moment";
- consume: "one" | "each" | "set";
- }>;
- selection: (value: AttributeValue | undefined, contract: string) => ProgramRange[];
- moment: (value: AttributeValue | undefined, contract: string) => number[];
- fps: number;
- width: number;
- height: number;
-};
-
-export type KernelImplementation = {
- abiVersion: "1";
- project(context: KernelContext): Promise<KernelProjection> | KernelProjection;
-};
diff --git a/src/runtime-validation.ts b/src/runtime-validation.ts
deleted file mode 100644
index 72b789bf..00000000
--- a/src/runtime-validation.ts
+++ /dev/null
@@ -1,172 +0,0 @@
-import { fail } from "./diagnostics.js";
-import type {
- AudioFragment,
- KernelProjection,
- VisualFragment,
-} from "./runtime-contract.js";
-import { sha256 } from "./util.js";
-
-function cssBlocks(source: string, scope: string): string {
- let output = "";
- let offset = 0;
- while (offset < source.length) {
- const open = source.indexOf("{", offset);
- if (open < 0) {
- if (source.slice(offset).trim()) {
- fail("kernel_css_syntax", "Projector CSS contains a rule without a block.");
- }
- output += source.slice(offset);
- break;
- }
- let depth = 1;
- let cursor = open + 1;
- while (cursor < source.length && depth > 0) {
- if (source[cursor] === "{") depth += 1;
- else if (source[cursor] === "}") depth -= 1;
- cursor += 1;
- }
- if (depth !== 0) fail("kernel_css_syntax", "Projector CSS contains an unclosed block.");
- const header = source.slice(offset, open);
- const body = source.slice(open + 1, cursor - 1);
- const trimmed = header.trim();
- if (/^@(?:import|font-face|page|property)\b/iu.test(trimmed)) {
- fail("kernel_css_capability", `Projector CSS cannot emit ${trimmed.split(/\s/u)[0]}.`);
- }
- if (/^@(?:keyframes|-webkit-keyframes)\b/iu.test(trimmed)) {
- output += `${header}{${body}}`;
- } else if (trimmed.startsWith("@")) {
- output += `${header}{${cssBlocks(body, scope)}}`;
- } else {
- const selectors = header.split(",").map((selector) => selector.trim()).filter(Boolean);
- if (!selectors.length) fail("kernel_css_selector", "Projector CSS has an empty selector.");
- output += `${selectors.map((selector) => `${scope} ${selector}`).join(", ")}{${body}}`;
- }
- offset = cursor;
- }
- return output;
-}
-
-function assertInertHtml(value: string, id: string): void {
- if (
- /<(?:script|style|iframe|object|embed|link|meta|base|form|input|button|textarea|select)\b/iu.test(value)
- || /\son[a-z]+\s*=/iu.test(value)
- || /javascript\s*:/iu.test(value)
- ) {
- fail(
- "kernel_html_capability",
- `Visual fragment "${id}" contains executable or document-global HTML.`,
- );
- }
-}
-
-function assertStyle(
- style: Record<string, string | number> | undefined,
- id: string,
-): void {
- for (const [name, value] of Object.entries(style ?? {})) {
- if (!/^--?[A-Za-z_][A-Za-z0-9_-]*$|^[A-Za-z_][A-Za-z0-9_-]*$/u.test(name)) {
- fail("kernel_style_property", `Visual fragment "${id}" has invalid style property "${name}".`);
- }
- if (/(?:url\s*\(|expression\s*\(|javascript\s*:)/iu.test(String(value))) {
- fail("kernel_style_capability", `Visual fragment "${id}" style "${name}" requests an external capability.`);
- }
- }
-}
-
-function normalizeVisual(
- fragment: VisualFragment,
- sharedStyles: string[],
-): VisualFragment {
- if (
- !Number.isInteger(fragment.startFrame)
- || !Number.isInteger(fragment.endFrameExclusive)
- || fragment.startFrame < 0
- || fragment.endFrameExclusive < fragment.startFrame
- || !Number.isFinite(fragment.z)
- ) {
- fail("kernel_visual_window", `Visual fragment "${fragment.id}" has an invalid frame window or z.`);
- }
- if (!["image", "video", "html"].includes(fragment.kind)) {
- fail("kernel_visual_kind", `Visual fragment "${fragment.id}" has unknown kind.`);
- }
- if (fragment.kind === "html") assertInertHtml(fragment.html ?? "", fragment.id);
- assertStyle(fragment.style, fragment.id);
- assertStyle(fragment.innerStyle, fragment.id);
- for (const name of Object.keys(fragment.attributes ?? {})) {
- if (!/^[A-Za-z_][A-Za-z0-9_.:-]*$/u.test(name) || /^on/iu.test(name)) {
- fail("kernel_fragment_attribute", `Visual fragment "${fragment.id}" has forbidden attribute "${name}".`);
- }
- }
- const existingToken = fragment.attributes?.["data-svml-scope"];
- const token = typeof existingToken === "string"
- ? existingToken
- : sha256(fragment.id).slice(0, 16);
- const selector = `[data-svml-scope="${token}"]`;
- const css = [
- fragment.css
- ? (typeof existingToken === "string" ? fragment.css : cssBlocks(fragment.css, selector))
- : "",
- ...sharedStyles.map((value) => cssBlocks(value, selector)),
- ]
- .filter((value): value is string => typeof value === "string" && value.trim() !== "")
- .join("\n");
- return {
- ...fragment,
- attributes: {
- ...fragment.attributes,
- "data-svml-scope": token,
- },
- ...(css ? { css } : {}),
- };
-}
-
-function validateAudio(fragment: AudioFragment): AudioFragment {
- if (
- !Number.isInteger(fragment.startFrame)
- || !Number.isInteger(fragment.endFrameExclusive)
- || fragment.startFrame < 0
- || fragment.endFrameExclusive < fragment.startFrame
- ) {
- fail("kernel_audio_window", `Audio fragment "${fragment.id}" has an invalid frame window.`);
- }
- if (fragment.bus && !["speech", "music", "sfx", "source"].includes(fragment.bus)) {
- fail("kernel_audio_bus", `Audio fragment "${fragment.id}" uses unknown bus "${fragment.bus}".`);
- }
- return fragment;
-}
-
-function normalizeSurface(value: unknown): void {
- if (!value || typeof value !== "object") return;
- const surface = value as {
- visuals?: VisualFragment[];
- audios?: AudioFragment[];
- styles?: string[];
- };
- if (Array.isArray(surface.visuals) || Array.isArray(surface.audios) || Array.isArray(surface.styles)) {
- const visualIds = (surface.visuals ?? []).map((fragment) => fragment.id);
- if (new Set(visualIds).size !== visualIds.length) {
- fail("kernel_visual_duplicate_id", "A projected visual surface repeats a fragment id.");
- }
- const audioIds = (surface.audios ?? []).map((fragment) => fragment.id);
- if (new Set(audioIds).size !== audioIds.length) {
- fail("kernel_audio_duplicate_id", "A projected audio contribution set repeats a fragment id.");
- }
- const styles = Array.isArray(surface.styles) ? surface.styles : [];
- if (surface.visuals) surface.visuals = surface.visuals.map((fragment) =>
- normalizeVisual(fragment, styles));
- if (surface.audios) surface.audios = surface.audios.map(validateAudio);
- surface.styles = [];
- }
- for (const child of Object.values(value as Record<string, unknown>)) {
- if (child !== surface.visuals && child !== surface.audios && child !== surface.styles) {
- normalizeSurface(child);
- }
- }
-}
-
-export function validateKernelProjection(
- projection: KernelProjection,
-): KernelProjection {
- normalizeSurface(projection);
- return projection;
-}
diff --git a/src/sandbox-worker.mjs b/src/sandbox-worker.mjs
deleted file mode 100644
index b38f2b69..00000000
--- a/src/sandbox-worker.mjs
+++ /dev/null
@@ -1,173 +0,0 @@
-import { readFile, realpath } from "node:fs/promises";
-import { createHash } from "node:crypto";
-import { dirname, relative, resolve } from "node:path";
-import { fileURLToPath, pathToFileURL } from "node:url";
-import vm from "node:vm";
-
-function inside(root, candidate) {
- const path = relative(root, candidate);
- return path === "" || (!path.startsWith("..") && !path.startsWith("/"));
-}
-
-async function stdin() {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- return Buffer.concat(chunks).toString("utf8");
-}
-
-async function main() {
- const implementation = await realpath(resolve(process.argv[2]));
- const packageRoot = await realpath(resolve(process.argv[3] ?? dirname(implementation)));
- if (!inside(packageRoot, implementation)) {
- throw new Error(`Kernel implementation escapes package root: ${implementation}`);
- }
-
- const context = vm.createContext(Object.create(null), {
- name: "svml-kernel-projector",
- codeGeneration: { strings: false, wasm: false },
- });
- context.__svmlSha256 = value => createHash("sha256").update(value).digest("hex");
- new vm.Script(`
- Object.defineProperty(Math, "random", {
- value() { throw new Error("SVK projector cannot use ambient randomness"); },
- writable: false,
- configurable: false
- });
- globalThis.Date = class ForbiddenDate {
- constructor() { throw new Error("SVK projector cannot use wall clock time"); }
- static now() { throw new Error("SVK projector cannot use wall clock time"); }
- };
- globalThis.fetch = undefined;
- globalThis.WebSocket = undefined;
- globalThis.EventSource = undefined;
- globalThis.XMLHttpRequest = undefined;
- globalThis.process = undefined;
- globalThis.require = undefined;
- `).runInContext(context, { timeout: 250 });
-
- const cache = new Map();
- const loadModule = async (file) => {
- const canonical = await realpath(file);
- if (!inside(packageRoot, canonical)) {
- throw new Error(`SVK import escapes package root: ${canonical}`);
- }
- const cached = cache.get(canonical);
- if (cached) return cached;
- const source = await readFile(canonical, "utf8");
- const module = new vm.SourceTextModule(source, {
- context,
- identifier: pathToFileURL(canonical).href,
- initializeImportMeta(meta) {
- meta.url = pathToFileURL(canonical).href;
- },
- importModuleDynamically(specifier) {
- throw new Error(`Dynamic import is forbidden in SVK projectors: ${specifier}`);
- },
- });
- cache.set(canonical, module);
- await module.link(async (specifier, referencing) => {
- if (!specifier.startsWith("./") && !specifier.startsWith("../")) {
- throw new Error(`Only relative SVK imports are allowed: ${specifier}`);
- }
- return loadModule(fileURLToPath(new URL(specifier, referencing.identifier)));
- });
- return module;
- };
-
- const module = await loadModule(implementation);
- await module.evaluate({ timeout: 1000 });
- const implementationObject = module.namespace.default;
- if (!implementationObject || typeof implementationObject.project !== "function") {
- throw new Error(`${implementation} must default-export a projector object`);
- }
- context.__svmlKernel = implementationObject;
- context.__svmlInput = await stdin();
- const output = new vm.Script(`
- (() => {
- const context = JSON.parse(globalThis.__svmlInput);
- context.resolve = value => value;
- const stableJson = value => {
- if (Array.isArray(value)) return "[" + value.map(stableJson).join(",") + "]";
- if (value && typeof value === "object") {
- return "{" + Object.keys(value).sort().map(key => JSON.stringify(key) + ":" + stableJson(value[key])).join(",") + "}";
- }
- return JSON.stringify(value);
- };
- context.digest = value => globalThis.__svmlSha256(stableJson(value));
- const frameRange = (startSec, endSec) => {
- const startFrame = Math.round(startSec * context.fps);
- const endFrameExclusive = Math.round(endSec * context.fps);
- if (endFrameExclusive < startFrame) throw new Error("manual range resolves backwards");
- return {
- startFrame,
- endFrameExclusive,
- startSec: startFrame / context.fps,
- endSec: endFrameExclusive / context.fps
- };
- };
- const endpoint = raw => {
- const value = String(raw).trim();
- if (value === "start") return 0;
- if (value === "end") return context.program.durationSec;
- const relative = /^(start|end)([+-])(\\d+(?:\\.\\d+)?)(ms|s)$/.exec(value);
- if (relative) {
- const base = relative[1] === "start" ? 0 : context.program.durationSec;
- const amount = Number(relative[3]) * (relative[4] === "ms" ? 0.001 : 1);
- return base + (relative[2] === "+" ? amount : -amount);
- }
- const absolute = /^(\\d+(?:\\.\\d+)?)(ms|s)$/.exec(value);
- if (absolute) return Number(absolute[1]) * (absolute[2] === "ms" ? 0.001 : 1);
- throw new Error("unsupported manual time expression: " + value);
- };
- const temporalContract = (path, kind) => {
- const contract = context.temporalContracts && context.temporalContracts[path];
- if (!contract || contract.kind !== kind) {
- throw new Error("undeclared " + kind + " temporal contract: " + String(path));
- }
- return contract;
- };
- context.selection = (value, path) => {
- const contract = temporalContract(path, "selection");
- let ranges;
- if (typeof value === "string") {
- if (value === "full") ranges = [frameRange(0, context.program.durationSec)];
- else {
- const parts = value.split("..");
- if (parts.length !== 2) throw new Error("manual span requires start .. end");
- ranges = [frameRange(endpoint(parts[0]), endpoint(parts[1]))];
- }
- } else {
- ranges = value && value.ranges;
- }
- if (!ranges) throw new Error("expected SelectionSet or ProgramSpan");
- if (contract.consume === "one" && ranges.length !== 1) {
- throw new Error("temporal cardinality expected one, received " + ranges.length);
- }
- return ranges;
- };
- context.moment = (value, path) => {
- const contract = temporalContract(path, "moment");
- const frames = typeof value === "string"
- ? [Math.round(endpoint(value) * context.fps)]
- : value && value.frames;
- if (!frames) throw new Error("expected MomentSet or manual ProgramPoint");
- if (contract.consume === "one" && frames.length !== 1) {
- throw new Error("temporal cardinality expected one, received " + frames.length);
- }
- return frames;
- };
- const result = globalThis.__svmlKernel.project(context);
- if (result && typeof result.then === "function") {
- throw new Error("isolated projector ABI v1 must be synchronous");
- }
- return JSON.stringify(result);
- })()
- `).runInContext(context, { timeout: 2000 });
- if (typeof output !== "string") throw new Error("SVK projector returned no JSON result");
- process.stdout.write(output);
-}
-
-main().catch((error) => {
- process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
- process.exitCode = 1;
-});
diff --git a/src/sandbox.ts b/src/sandbox.ts
deleted file mode 100644
index 5a7f6fbb..00000000
--- a/src/sandbox.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { spawn } from "node:child_process";
-import { dirname } from "node:path";
-import { fileURLToPath } from "node:url";
-import { fail } from "./diagnostics.js";
-import type { KernelManifest } from "./kernel.js";
-import type { KernelProjection } from "./runtime-contract.js";
-
-const MAX_OUTPUT_BYTES = 32 * 1024 * 1024;
-
-export async function projectKernelIsolated(
- manifest: KernelManifest,
- input: unknown,
-): Promise<KernelProjection> {
- const implementationPath = manifest.implementationPath;
- if (!implementationPath || manifest.profile !== "isolated-projector-v1") {
- fail(
- "kernel_projector_profile",
- `Kernel "${manifest.name}" is not an isolated projector.`,
- );
- }
- if (manifest.permissions.length) {
- fail(
- "kernel_permission_unsupported",
- `Kernel "${manifest.name}" requests unsupported projector permissions: ${manifest.permissions.join(", ")}.`,
- );
- }
- const worker = fileURLToPath(new URL("./sandbox-worker.mjs", import.meta.url));
- const packageRoot = dirname(manifest.sourcePath);
- const child = spawn(process.execPath, [
- "--experimental-vm-modules",
- "--permission",
- `--allow-fs-read=${packageRoot}`,
- "--max-old-space-size=128",
- worker,
- implementationPath,
- packageRoot,
- ], {
- stdio: ["pipe", "pipe", "pipe"],
- });
- const stdout: Buffer[] = [];
- const stderr: Buffer[] = [];
- let outputBytes = 0;
- child.stdout.on("data", (chunk: Buffer) => {
- outputBytes += chunk.length;
- if (outputBytes > MAX_OUTPUT_BYTES) child.kill("SIGKILL");
- else stdout.push(chunk);
- });
- child.stderr.on("data", (chunk: Buffer) => stderr.push(chunk));
- const timeout = setTimeout(() => child.kill("SIGKILL"), 5000);
- child.stdin.end(JSON.stringify(input));
- const code = await new Promise<number | null>((accept, reject) => {
- child.once("error", reject);
- child.once("exit", accept);
- });
- clearTimeout(timeout);
- if (code !== 0) {
- fail(
- "kernel_projector_isolation",
- `Kernel "${manifest.name}" failed in isolated projector: ${Buffer.concat(stderr).toString("utf8").trim() || `exit ${String(code)}`}.`,
- );
- }
- try {
- return JSON.parse(Buffer.concat(stdout).toString("utf8")) as KernelProjection;
- } catch {
- fail(
- "kernel_projector_output",
- `Kernel "${manifest.name}" did not return valid JSON from its isolated projector.`,
- );
- }
-}
diff --git a/src/script/estimate.ts b/src/script/estimate.ts
deleted file mode 100644
index 6e8c1496..00000000
--- a/src/script/estimate.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import type {
- NarrativeIR,
- ScriptToken,
- SpeechTimingEvidence,
-} from "../model.js";
-
-export type EstimateOptions = {
- syllablesPerSecond?: number;
- wordGapSec?: number;
- segmentPaddingSec?: number;
- emptySegmentSec?: number;
- fps?: number;
-};
-
-function syllables(token: ScriptToken): number {
- if (/^[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]\p{M}*$/u.test(token.text)) {
- return 1;
- }
- const ascii = token.normalized
- .normalize("NFD")
- .replace(/\p{M}/gu, "")
- .toLocaleLowerCase("en");
- const groups = ascii.match(/[aeiouy]+/gu)?.length ?? 0;
- const silentE = groups > 1 && /[^aeiou]e$/u.test(ascii) ? 1 : 0;
- return Math.max(1, groups - silentE);
-}
-
-export function estimateSpeechTiming(
- narrative: NarrativeIR,
- options: EstimateOptions = {},
-): SpeechTimingEvidence {
- const syllablesPerSecond = options.syllablesPerSecond ?? 6.5;
- const wordGapSec = options.wordGapSec ?? 0.045;
- const segmentPaddingSec = options.segmentPaddingSec ?? 0.12;
- const emptySegmentSec = options.emptySegmentSec ?? 1;
- const fps = Math.max(1, Math.round(options.fps ?? 30));
- for (const [name, value] of Object.entries({
- syllablesPerSecond,
- wordGapSec,
- segmentPaddingSec,
- emptySegmentSec,
- })) {
- if (!Number.isFinite(value) || value < 0 || (name === "syllablesPerSecond" && value === 0)) {
- throw new Error(`invalid estimate option ${name}=${String(value)}`);
- }
- }
-
- let cursor = 0;
- const units: SpeechTimingEvidence["units"] = [];
- const segments: SpeechTimingEvidence["segments"] = [];
- for (const segment of narrative.segments) {
- const segmentTokens = narrative.tokens.slice(segment.tokenStart, segment.tokenEnd);
- const startSec = cursor;
- if (!segmentTokens.length) {
- cursor += emptySegmentSec;
- cursor = Math.ceil(cursor * fps) / fps;
- segments.push({ id: segment.id, startSec, endSec: cursor });
- continue;
- }
- cursor += segmentPaddingSec;
- for (const [index, token] of segmentTokens.entries()) {
- const wordStart = cursor;
- cursor += syllables(token) / syllablesPerSecond;
- units.push({
- text: token.text,
- startSec: wordStart,
- endSec: cursor,
- segmentId: segment.id,
- });
- if (index < segmentTokens.length - 1) cursor += wordGapSec;
- }
- cursor += segmentPaddingSec;
- cursor = Math.ceil(cursor * fps) / fps;
- segments.push({ id: segment.id, startSec, endSec: cursor });
- }
- const durationFrames = Math.max(1, Math.ceil(cursor * fps));
- const durationSec = durationFrames / fps;
- return {
- contract: "svml.speech-timing-evidence.v1",
- durationSec,
- fps,
- quality: "estimated",
- units,
- segments,
- provenance: {
- method: "svml.syllable-estimate.v1",
- measured: false,
- syllablesPerSecond,
- wordGapSec,
- segmentPaddingSec,
- emptySegmentSec,
- },
- };
-}
diff --git a/src/script/locate.ts b/src/script/locate.ts
deleted file mode 100644
index 040acbb4..00000000
--- a/src/script/locate.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-import { fail } from "../diagnostics.js";
-import type {
- CompleteSemanticMap,
- LocatedScript,
- MarkerBoundary,
- NarrativeIR,
- ProgramBasis,
- ProgramRange,
- SemanticMap,
-} from "../model.js";
-import { basisFps, semanticPoints, validateSemanticMap } from "../temporal.js";
-
-function range(
- startFrame: number,
- endFrameExclusive: number,
- basis: ProgramBasis,
- label: string,
- requirePositive = false,
-): ProgramRange {
- if (endFrameExclusive < startFrame || (requirePositive && endFrameExclusive === startFrame)) {
- fail(
- requirePositive ? "locate_nonpositive_range" : "locate_negative_range",
- `${label} resolves to non-positive range ${startFrame}..${endFrameExclusive}.`,
- );
- }
- const fps = basisFps(basis);
- return {
- startFrame,
- endFrameExclusive,
- startSec: startFrame / fps,
- endSec: endFrameExclusive / fps,
- };
-}
-
-export function boundaryAnchor(
- narrative: NarrativeIR,
- boundary: MarkerBoundary,
- affinity: "left" | "right",
-): string {
- if (boundary.segmentId) {
- const segment = narrative.segments.find((item) => item.id === boundary.segmentId);
- if (!segment) fail("locate_boundary_segment", `Unknown Segment "${boundary.segmentId}".`);
- if (affinity === "left") {
- const token = narrative.tokens[boundary.tokenIndex - 1];
- if (token && token.segmentId === segment.id) return token.endAnchorId;
- return segment.startAnchorId;
- }
- const token = narrative.tokens[boundary.tokenIndex];
- if (token && token.segmentId === segment.id) return token.startAnchorId;
- return segment.endAnchorId;
- }
-
- const position = boundary.structuralPosition;
- if (affinity === "left") {
- return narrative.segments[position - 1]?.endAnchorId
- ?? narrative.segments[position]?.startAnchorId
- ?? fail("locate_boundary_empty", "Script has no structural boundary candidate.");
- }
- return narrative.segments[position]?.startAnchorId
- ?? narrative.segments[position - 1]?.endAnchorId
- ?? fail("locate_boundary_empty", "Script has no structural boundary candidate.");
-}
-
-export function locateScript(
- narrative: NarrativeIR,
- basis: ProgramBasis,
- map: CompleteSemanticMap,
-): LocatedScript {
- if (map.contract !== "svml.complete-semantic-map.v1") {
- fail("locate_complete_required", "HTML compilation requires CompleteSemanticMap.");
- }
- return bindSemanticMap(narrative, basis, map);
-}
-
-export function bindSemanticMap(
- narrative: NarrativeIR,
- basis: ProgramBasis,
- map: SemanticMap,
-): LocatedScript {
- validateSemanticMap(narrative, basis, map);
- const points = semanticPoints(map);
- const point = (identity: string): number => {
- const value = points.get(identity);
- if (value === undefined) fail("locate_anchor_missing", `SemanticMap is missing "${identity}".`);
- return value;
- };
- const fps = basisFps(basis);
- const words = narrative.tokens.map((token) => ({
- ...token,
- ...range(
- point(token.startAnchorId),
- point(token.endAnchorId),
- basis,
- `Token "${token.text}"`,
- ),
- }));
- const segments = Object.fromEntries(narrative.segments.map((segment) => [
- segment.id,
- range(
- point(segment.startAnchorId),
- point(segment.endAnchorId),
- basis,
- `Segment "${segment.id}"`,
- ),
- ]));
- const selections = Object.fromEntries(Object.entries(narrative.selections).map(
- ([id, occurrences]) => [
- id,
- {
- id,
- ranges: occurrences.map((occurrence, index) => range(
- point(boundaryAnchor(narrative, occurrence.open.boundary, occurrence.open.affinity)),
- point(boundaryAnchor(narrative, occurrence.close.boundary, occurrence.close.affinity)),
- basis,
- `Selection "${id}" occurrence ${index + 1}`,
- true,
- )),
- },
- ],
- ));
- const moments = Object.fromEntries(Object.entries(narrative.moments).map(
- ([id, occurrences]) => [
- id,
- {
- id,
- frames: occurrences.map((occurrence) => point(
- boundaryAnchor(narrative, occurrence.boundary, occurrence.affinity),
- )),
- },
- ],
- ));
- const captionAtoms = narrative.captionAtoms.map((atom) => {
- const first = words[atom.startToken];
- const last = words[atom.endTokenExclusive - 1];
- if (!first || !last || first.segmentId !== last.segmentId) {
- fail("locate_caption_atom", `Caption atom "${atom.id}" has an invalid speech span.`);
- }
- return {
- ...atom,
- ...range(first.startFrame, last.endFrameExclusive, basis, `Caption atom "${atom.id}"`),
- };
- });
- return {
- contract: "svml.temporal-binding.v1",
- basisDigest: basis.basisDigest,
- semanticMapDigest: map.mapDigest,
- durationFrames: basis.durationFrames,
- durationSec: basis.durationFrames / fps,
- fps,
- words,
- segments,
- selections,
- moments,
- captionAtoms,
- };
-}
diff --git a/src/script/parse.ts b/src/script/parse.ts
deleted file mode 100644
index 09cb6a48..00000000
--- a/src/script/parse.ts
+++ /dev/null
@@ -1,675 +0,0 @@
-import { fail, sourceLocation } from "../diagnostics.js";
-import type {
- MarkerBoundary,
- MomentOccurrence,
- NarrativeIR,
- ScriptAtom,
- ScriptSegment,
- ScriptToken,
- SelectionOccurrence,
-} from "../model.js";
-import { normalizeWord, sha256, stableJson } from "../util.js";
-
-type Marker = {
- id: string;
- kind: "open" | "close" | "moment";
- affinity: "left" | "right";
- length: number;
-};
-
-type MutableSegment = {
- id: string;
- index: number;
- atoms: ScriptAtom[];
- tokenStart: number;
- sourceStart: number;
-};
-
-const WORD =
- /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]\p{M}*|[\p{L}\p{M}\p{N}]+(?:['’.-][\p{L}\p{M}\p{N}]+)*/gu;
-const SEGMENT_OPEN = /^<segment\s+id=(?:"([^"]+)"|'([^']+)')\s*(\/?)>/u;
-const SEGMENT_CLOSE = /^<\/segment\s*>/u;
-const ROLE_LABEL = /^[\p{L}\p{M}\p{N}_](?:[\p{L}\p{M}\p{N}_. -]{0,30}[\p{L}\p{M}\p{N}_.-])?$/u;
-const TEMPORAL_ID = /^[a-z][a-z0-9_-]{0,63}$/u;
-const SEGMENT_ID = /^[a-z][a-z0-9_-]{0,63}$/u;
-
-function parseMarker(source: string, offset: number): Marker | undefined {
- const slice = source.slice(offset);
- const markerName = String.raw`[a-z][a-z0-9_-]{0,63}`;
- const match = new RegExp(
- String.raw`^(~)?@(?:(\/)(${markerName})(~)?|(${markerName})(!)?)(?![A-Za-z0-9_-])`,
- "u",
- ).exec(slice);
- if (!match) return undefined;
- const prefixLeft = match[1] === "~";
- const close = match[2] === "/";
- const id = close ? match[3] : match[5];
- const suffixRight = close && match[4] === "~";
- const moment = !close && match[6] === "!";
- if (!id) return undefined;
- return {
- id,
- kind: moment ? "moment" : close ? "close" : "open",
- affinity: prefixLeft || (!close && !moment ? false : false)
- ? "left"
- : suffixRight
- ? "right"
- : close
- ? "left"
- : "right",
- length: match[0].length,
- };
-}
-
-function cleanProjection(value: string): string {
- return value
- .replace(/\s+/gu, " ")
- .replace(/\s+([,.;:!?])/gu, "$1")
- .replace(/([([{])\s+/gu, "$1")
- .replace(/\s+([)\]}])/gu, "$1")
- .trim();
-}
-
-function joinProjection(parts: string[]): string {
- return cleanProjection(parts.filter((part) => part.trim()).join(" "));
-}
-
-function markerBoundary(
- tokenIndex: number,
- segment: MutableSegment | undefined,
- structuralPosition: number,
-): MarkerBoundary {
- return {
- tokenIndex,
- structuralPosition,
- ...(segment ? { segmentId: segment.id } : {}),
- };
-}
-
-function segmentAnchorId(segmentId: string, edge: "start" | "end"): string {
- return `segment:${segmentId}:${edge}`;
-}
-
-function tokenAnchorId(
- segmentId: string,
- segmentTokenIndex: number,
- edge: "start" | "end",
-): string {
- return `segment:${segmentId}:token:${segmentTokenIndex + 1}:${edge}`;
-}
-
-export function parseScript(
- file: string,
- scriptSource: string,
- sourceOffset = 0,
- bindings: Record<string, string> = {},
-): NarrativeIR {
- scriptSource = scriptSource.replace(/\r\n?/gu, "\n").normalize("NFC");
- const segments: ScriptSegment[] = [];
- const tokens: ScriptToken[] = [];
- const openSelections = new Map<string, Array<{
- affinity: "left" | "right";
- boundary: MarkerBoundary;
- sourceStart: number;
- }>>();
- const selections: Record<string, SelectionOccurrence[]> = {};
- const moments: Record<string, MomentOccurrence[]> = {};
- const captionAtoms: NarrativeIR["captionAtoms"] = [];
- let current: MutableSegment | undefined;
- let offset = 0;
- let structuralPosition = 0;
- let lineStart = true;
-
- const location = (at: number) => sourceLocation(file, scriptSource, at);
-
- const findUnescaped = (value: string, character: string, from = 0): number => {
- for (let index = from; index < value.length; index += 1) {
- if (value[index] !== character) continue;
- let slashes = 0;
- for (let before = index - 1; before >= 0 && value[before] === "\\"; before -= 1) {
- slashes += 1;
- }
- if (slashes % 2 === 0) return index;
- }
- return -1;
- };
-
- const literalPieces = (
- raw: string,
- absoluteStart: number,
- dual = false,
- ): Array<{ value: string; start: number; end: number }> => {
- const pieces: Array<{ value: string; start: number; end: number }> = [];
- let buffer = "";
- let bufferStart = 0;
- const flush = (end: number): void => {
- if (!buffer) {
- bufferStart = end;
- return;
- }
- pieces.push({
- value: buffer,
- start: absoluteStart + bufferStart,
- end: absoluteStart + end,
- });
- buffer = "";
- bufferStart = end;
- };
- for (let index = 0; index < raw.length;) {
- if (raw.startsWith("${", index)) {
- flush(index);
- const close = raw.indexOf("}", index + 2);
- if (close < 0) fail("script_slot_unclosed", "Unclosed Script Slot.", location(absoluteStart + index));
- const id = raw.slice(index + 2, close);
- if (!/^[\p{L}_][\p{L}\p{M}\p{N}_-]{0,63}$/u.test(id)) {
- fail("script_slot_id", `Invalid Script Slot "${id}".`, location(absoluteStart + index));
- }
- const value = bindings[id];
- if (value === undefined) {
- fail("script_slot_unbound", `Script Slot "${id}" is not bound.`, location(absoluteStart + index));
- }
- if (/[\r\n\p{Cc}]/u.test(value)) {
- fail("script_slot_value", `Script Slot "${id}" must be single-line literal text.`);
- }
- pieces.push({
- value,
- start: absoluteStart + index,
- end: absoluteStart + close + 1,
- });
- index = close + 1;
- bufferStart = index;
- continue;
- }
- if (raw[index] === "\\") {
- const known = raw.startsWith("\\${", index)
- ? { value: "${", length: 3 }
- : ["@", "<", "\\", ...(dual ? ["|", ">"] : [])].includes(raw[index + 1] ?? "")
- ? { value: raw[index + 1]!, length: 2 }
- : undefined;
- if (!known) {
- fail(
- "script_unknown_escape",
- `Unknown Script escape "${raw.slice(index, index + 2)}".`,
- location(absoluteStart + index),
- );
- }
- buffer += known.value;
- index += known.length;
- continue;
- }
- buffer += raw[index];
- index += 1;
- }
- flush(raw.length);
- return pieces;
- };
-
- const literalString = (raw: string, absoluteStart: number, dual = false): string =>
- literalPieces(raw, absoluteStart, dual).map((piece) => piece.value).join("");
-
- const addMarker = (marker: Marker, at: number): void => {
- const boundary = markerBoundary(tokens.length, current, structuralPosition);
- if (marker.kind === "moment") {
- if (openSelections.has(marker.id) || selections[marker.id]) {
- fail(
- "script_temporal_type_conflict",
- `Temporal name "${marker.id}" cannot be both Selection and Moment.`,
- location(at),
- );
- }
- const list = moments[marker.id] ?? [];
- list.push({
- id: marker.id,
- occurrence: list.length,
- affinity: marker.affinity,
- boundary,
- sourceStart: sourceOffset + at,
- });
- moments[marker.id] = list;
- return;
- }
- if (marker.kind === "open") {
- if (moments[marker.id]) {
- fail(
- "script_temporal_type_conflict",
- `Temporal name "${marker.id}" cannot be both Moment and Selection.`,
- location(at),
- );
- }
- const list = openSelections.get(marker.id) ?? [];
- if (list.length) {
- fail(
- "script_selection_reopened",
- `Selection "${marker.id}" is opened again before it closes.`,
- location(at),
- );
- }
- list.push({
- affinity: marker.affinity,
- boundary,
- sourceStart: sourceOffset + at,
- });
- openSelections.set(marker.id, list);
- return;
- }
- const opens = openSelections.get(marker.id);
- const open = opens?.shift();
- if (!open) {
- fail(
- "script_selection_close_without_open",
- `Selection "${marker.id}" closes without a matching open marker.`,
- location(at),
- );
- }
- const list = selections[marker.id] ?? [];
- list.push({
- id: marker.id,
- occurrence: list.length,
- open,
- close: {
- affinity: marker.affinity,
- boundary,
- sourceStart: sourceOffset + at,
- },
- });
- selections[marker.id] = list;
- };
-
- const addText = (
- speech: string,
- caption: string,
- start: number,
- end: number,
- ): void => {
- if (!current) {
- if (speech.trim() || caption.trim()) {
- fail(
- "script_text_outside_segment",
- "Natural-language text is only allowed inside <segment>.",
- location(start),
- );
- }
- return;
- }
- const tokenStart = tokens.length;
- WORD.lastIndex = 0;
- let match: RegExpExecArray | null;
- while ((match = WORD.exec(speech))) {
- const normalized = normalizeWord(match[0]);
- if (!normalized) continue;
- const index = tokens.length;
- const segmentTokenIndex = index - current.tokenStart;
- tokens.push({
- id: `w${index + 1}`,
- index,
- segmentId: current.id,
- segmentTokenIndex,
- startAnchorId: tokenAnchorId(current.id, segmentTokenIndex, "start"),
- endAnchorId: tokenAnchorId(current.id, segmentTokenIndex, "end"),
- text: match[0],
- normalized,
- sourceStart: sourceOffset + start + match.index,
- sourceEnd: sourceOffset + start + match.index + match[0].length,
- });
- }
- current.atoms.push({
- kind: "text",
- speech,
- caption,
- start: sourceOffset + start,
- end: sourceOffset + end,
- tokenStart,
- tokenEndExclusive: tokens.length,
- });
- };
-
- const consumeSpeechSide = (
- raw: string,
- absoluteStart: number,
- caption: string,
- ): void => {
- const startToken = tokens.length;
- let partStart = 0;
- let index = 0;
- let emittedCaption = false;
- const addLiteral = (rawPart: string, start: number): void => {
- const pieces = literalPieces(rawPart, start, true);
- for (const piece of pieces) {
- addText(
- piece.value,
- emittedCaption ? "" : caption,
- piece.start,
- piece.end,
- );
- emittedCaption = true;
- }
- };
- while (index < raw.length) {
- if (raw.startsWith("${", index)) {
- const close = raw.indexOf("}", index + 2);
- if (close < 0) fail("script_slot_unclosed", "Unclosed Script Slot.", location(absoluteStart + index));
- index = close + 1;
- continue;
- }
- if (raw[index] === "\\") {
- index += raw.startsWith("\\${", index) ? 3 : 2;
- continue;
- }
- const marker = parseMarker(raw, index);
- if (!marker) {
- if (raw[index] === "@") {
- fail(
- "script_invalid_marker",
- "Unescaped @ must begin a valid Selection or Moment marker.",
- location(absoluteStart + index),
- );
- }
- index += 1;
- continue;
- }
- addLiteral(raw.slice(partStart, index), absoluteStart + partStart);
- addMarker(marker, absoluteStart + index);
- index += marker.length;
- partStart = index;
- }
- addLiteral(raw.slice(partStart), absoluteStart + partStart);
- const endTokenExclusive = tokens.length;
- if (endTokenExclusive > startToken) {
- captionAtoms.push({
- id: `caption-atom-${captionAtoms.length + 1}`,
- display: cleanProjection(caption),
- segmentId: current!.id,
- startToken,
- endTokenExclusive,
- sourceStart: sourceOffset + absoluteStart,
- sourceEnd: sourceOffset + absoluteStart + raw.length,
- });
- }
- };
-
- while (offset < scriptSource.length) {
- if (scriptSource.startsWith("<!--", offset)) {
- const end = scriptSource.indexOf("-->", offset + 4);
- if (end < 0) fail("script_unclosed_comment", "Unclosed Script comment.", location(offset));
- const comment = scriptSource.slice(offset, end + 3);
- lineStart = comment.endsWith("\n") || lineStart;
- offset = end + 3;
- continue;
- }
-
- const segmentOpen = SEGMENT_OPEN.exec(scriptSource.slice(offset));
- if (segmentOpen) {
- if (current) {
- fail("script_nested_segment", "Segment elements cannot nest.", location(offset));
- }
- const id = segmentOpen[1] ?? segmentOpen[2];
- if (!id || !SEGMENT_ID.test(id)) {
- fail("script_invalid_segment_id", `Invalid Segment id "${id ?? ""}".`, location(offset));
- }
- if (segments.some((segment) => segment.id === id)) {
- fail("script_duplicate_segment_id", `Duplicate Segment id "${id}".`, location(offset));
- }
- current = {
- id,
- index: segments.length,
- atoms: [],
- tokenStart: tokens.length,
- sourceStart: sourceOffset + offset,
- };
- offset += segmentOpen[0].length;
- lineStart = true;
- if (segmentOpen[3] === "/") {
- segments.push({
- ...current,
- startAnchorId: segmentAnchorId(current.id, "start"),
- endAnchorId: segmentAnchorId(current.id, "end"),
- tokenEnd: tokens.length,
- sourceEnd: sourceOffset + offset,
- });
- current = undefined;
- structuralPosition += 1;
- }
- continue;
- }
-
- const segmentClose = SEGMENT_CLOSE.exec(scriptSource.slice(offset));
- if (segmentClose) {
- if (!current) {
- fail("script_segment_close_without_open", "Unexpected </segment>.", location(offset));
- }
- offset += segmentClose[0].length;
- segments.push({
- ...current,
- startAnchorId: segmentAnchorId(current.id, "start"),
- endAnchorId: segmentAnchorId(current.id, "end"),
- tokenEnd: tokens.length,
- sourceEnd: sourceOffset + offset,
- });
- current = undefined;
- structuralPosition += 1;
- lineStart = true;
- continue;
- }
-
- const marker = parseMarker(scriptSource, offset);
- if (marker) {
- if (!TEMPORAL_ID.test(marker.id)) {
- fail("script_invalid_temporal_id", `Invalid temporal id "${marker.id}".`, location(offset));
- }
- addMarker(marker, offset);
- offset += marker.length;
- continue;
- }
-
- if (scriptSource[offset] === "@") {
- fail(
- "script_invalid_marker",
- "Unescaped @ must begin a valid Selection or Moment marker.",
- location(offset),
- );
- }
-
- if (scriptSource[offset] === "<" && current) {
- const safeEnd = findUnescaped(scriptSource, ">", offset + 1);
- if (safeEnd < 0) fail("script_unclosed_angle", "Unclosed Script angle construct.", location(offset));
- const inside = scriptSource.slice(offset + 1, safeEnd);
- const pipe = findUnescaped(inside, "|");
- if (pipe >= 0) {
- const display = literalString(inside.slice(0, pipe), offset + 1, true);
- const speech = inside.slice(pipe + 1);
- if (!speech.replace(/~?@\/?[A-Za-z_][A-Za-z0-9_.-]*!?~?/gu, "").trim()) {
- fail("script_dual_speech_empty", "Dual Text speech side must not be empty.", location(offset));
- }
- consumeSpeechSide(speech, offset + 1 + pipe + 1, display);
- offset = safeEnd + 1;
- lineStart = false;
- continue;
- }
- if (lineStart && ROLE_LABEL.test(inside)) {
- const after = scriptSource.slice(safeEnd + 1);
- if (!after.match(/^[^\S\n]*\S/u)) {
- fail(
- "script_role_empty_turn",
- `Role Cue <${inside}> must be followed by spoken content on the same logical line.`,
- location(offset),
- );
- }
- current.atoms.push({
- kind: "role",
- label: inside,
- start: sourceOffset + offset,
- end: sourceOffset + safeEnd + 1,
- });
- offset = safeEnd + 1;
- lineStart = false;
- continue;
- }
- fail(
- "script_unknown_angle_construct",
- `Unknown Script construct <${inside}>.`,
- location(offset),
- );
- }
-
- const textStart = offset;
- while (offset < scriptSource.length) {
- if (
- scriptSource.startsWith("<!--", offset)
- || scriptSource.startsWith("<segment", offset)
- || scriptSource.startsWith("</segment", offset)
- || parseMarker(scriptSource, offset)
- || scriptSource[offset] === "<"
- || scriptSource[offset] === "@"
- ) break;
- if (scriptSource[offset] === "\\") {
- if (scriptSource.startsWith("\\${", offset)) offset += 3;
- else offset += Math.min(2, scriptSource.length - offset);
- continue;
- }
- offset += 1;
- }
- const raw = scriptSource.slice(textStart, offset);
- for (const piece of literalPieces(raw, textStart)) {
- addText(piece.value, piece.value, piece.start, piece.end);
- }
- const lastNewline = raw.lastIndexOf("\n");
- if (lastNewline >= 0) {
- lineStart = raw.slice(lastNewline + 1).trim() === "";
- } else if (raw.trim()) {
- lineStart = false;
- }
- }
-
- if (current) {
- fail("script_unclosed_segment", `Segment "${current.id}" is not closed.`);
- }
- const dangling = [...openSelections.entries()].flatMap(([id, opens]) =>
- opens.map((open) => ({ id, open })));
- if (dangling.length) {
- fail(
- "script_selection_unclosed",
- `Selection "${dangling[0]?.id ?? "unknown"}" is not closed.`,
- );
- }
- if (!segments.length) fail("script_segment_cardinality", "Script requires at least one Segment.");
-
- const speechSegments: string[] = [];
- const captionSegments: string[] = [];
- const dialogueTurns: string[] = [];
- const turns: NarrativeIR["turns"] = [];
- for (const segment of segments) {
- const speechParts: string[] = [];
- const captionParts: string[] = [];
- let activeRole: string | undefined;
- let turnParts: string[] = [];
- let turnTokenStart: number | undefined;
- let turnTokenEndExclusive: number | undefined;
- let turnSourceStart: number | undefined;
- let turnSourceEnd: number | undefined;
- const flushTurn = (): void => {
- const body = joinProjection(turnParts);
- if (body) dialogueTurns.push(activeRole ? `${activeRole}: ${body}` : body);
- if (
- turnTokenStart !== undefined
- && turnTokenEndExclusive !== undefined
- && turnTokenEndExclusive > turnTokenStart
- ) {
- turns.push({
- id: `turn-${turns.length + 1}`,
- segmentId: segment.id,
- ...(activeRole ? { role: activeRole } : {}),
- tokenStart: turnTokenStart,
- tokenEndExclusive: turnTokenEndExclusive,
- sourceStart: turnSourceStart ?? segment.sourceStart,
- sourceEnd: turnSourceEnd ?? segment.sourceEnd,
- });
- }
- turnParts = [];
- turnTokenStart = undefined;
- turnTokenEndExclusive = undefined;
- turnSourceStart = undefined;
- turnSourceEnd = undefined;
- };
- for (const atom of segment.atoms) {
- if (atom.kind === "role") {
- flushTurn();
- activeRole = atom.label;
- } else {
- speechParts.push(atom.speech);
- captionParts.push(atom.caption);
- turnParts.push(atom.speech);
- if (atom.tokenEndExclusive > atom.tokenStart) {
- turnTokenStart ??= atom.tokenStart;
- turnTokenEndExclusive = atom.tokenEndExclusive;
- turnSourceStart ??= atom.start;
- turnSourceEnd = atom.end;
- }
- }
- }
- flushTurn();
- const speech = joinProjection(speechParts);
- const caption = joinProjection(captionParts);
- if (speech) speechSegments.push(speech);
- if (caption) captionSegments.push(caption);
- }
-
- const semanticAnchors = segments.flatMap((segment) => [
- {
- id: segment.startAnchorId,
- kind: "segment-start" as const,
- segmentId: segment.id,
- },
- ...tokens.slice(segment.tokenStart, segment.tokenEnd).flatMap((token) => [
- {
- id: token.startAnchorId,
- kind: "token-start" as const,
- segmentId: segment.id,
- tokenId: token.id,
- segmentTokenIndex: token.segmentTokenIndex,
- },
- {
- id: token.endAnchorId,
- kind: "token-end" as const,
- segmentId: segment.id,
- tokenId: token.id,
- segmentTokenIndex: token.segmentTokenIndex,
- },
- ]),
- {
- id: segment.endAnchorId,
- kind: "segment-end" as const,
- segmentId: segment.id,
- },
- ]);
- const semanticTokens = tokens.map((token) => ({
- id: token.id,
- segmentId: token.segmentId,
- segmentTokenIndex: token.segmentTokenIndex,
- normalized: token.normalized,
- startAnchorId: token.startAnchorId,
- endAnchorId: token.endAnchorId,
- }));
- const semanticIndexPayload = {
- contract: "svml.semantic-index.v1" as const,
- anchors: semanticAnchors,
- tokens: semanticTokens,
- };
-
- return {
- segments,
- tokens,
- turns,
- selections,
- moments,
- captionAtoms,
- semanticIndex: {
- ...semanticIndexPayload,
- digest: sha256(stableJson(semanticIndexPayload)),
- },
- projections: {
- dialogue: dialogueTurns.join("\n"),
- speech: speechSegments.join("\n"),
- caption: captionSegments.join("\n"),
- },
- };
-}
diff --git a/src/source/modules.ts b/src/source/modules.ts
deleted file mode 100644
index 1b9a683c..00000000
--- a/src/source/modules.ts
+++ /dev/null
@@ -1,267 +0,0 @@
-import { readFile } from "node:fs/promises";
-import { dirname, extname, isAbsolute, resolve } from "node:path";
-import { pathToFileURL } from "node:url";
-import { fail } from "../diagnostics.js";
-import type {
- AttributeValue,
- Reference,
- SourceDocument,
- SourceElement,
- SourceModuleRecord,
- SourceNode,
-} from "../model.js";
-import { sha256 } from "../util.js";
-import { attributeString, childElements } from "./query.js";
-import { parseDocument, parseRootSource } from "./parse-document.js";
-
-type LoadedContent = {
- declarations: SourceElement[];
- kernelImports: SourceElement[];
- modules: SourceModuleRecord[];
-};
-
-function isExternalSource(value: string): boolean {
- return /^[A-Za-z][A-Za-z0-9+.-]*:/u.test(value);
-}
-
-function resolvedImport(moduleFile: string, from: string): string {
- return isExternalSource(from) || isAbsolute(from)
- ? from
- : resolve(dirname(moduleFile), from);
-}
-
-function canonicalUri(value: string): string {
- return isExternalSource(value) ? value : pathToFileURL(resolve(value)).href;
-}
-
-function cloneReference(
- value: AttributeValue,
- qualify: (path: string) => string,
-): AttributeValue {
- if (!value || typeof value !== "object" || value.kind !== "reference") return value;
- return { kind: "reference", path: qualify(value.path) } satisfies Reference;
-}
-
-function cloneNode(
- node: SourceNode,
- args: {
- moduleFile: string;
- prefix: string;
- localDeclarations: Set<string>;
- importedNamespaces: Set<string>;
- topLevel: boolean;
- },
-): SourceNode {
- if (node.kind === "text") return { ...node };
- const qualify = (path: string): string => {
- if (path.startsWith("script.")) {
- fail(
- "content_script_dependency",
- `Content module ${args.moduleFile} cannot depend on importer Script reference "${path}".`,
- );
- }
- const owner = path.split(".")[0] ?? "";
- if (args.localDeclarations.has(owner) || args.importedNamespaces.has(owner)) {
- return `${args.prefix}${path}`;
- }
- return path;
- };
- const attributes = Object.fromEntries(
- Object.entries(node.attributes).map(([name, value]) => [
- name,
- cloneReference(value, qualify),
- ]),
- );
- const localId = args.topLevel && typeof node.attributes.id === "string"
- ? node.attributes.id
- : undefined;
- if (localId) attributes.id = `${args.prefix}${localId}`;
- if (
- args.topLevel
- && ["image", "video", "audio", "alignment"].includes(node.name)
- && typeof attributes.src === "string"
- && !isAbsolute(attributes.src)
- && !isExternalSource(attributes.src)
- ) {
- attributes.src = resolve(dirname(args.moduleFile), attributes.src);
- }
- return {
- ...node,
- attributes,
- children: node.children.map((child) => cloneNode(child, {
- ...args,
- topLevel: false,
- })),
- origin: {
- file: args.moduleFile,
- ...(localId ? { localId } : {}),
- },
- };
-}
-
-function absoluteImport(element: SourceElement, moduleFile: string): SourceElement {
- const from = attributeString(element, "from");
- return {
- ...element,
- attributes: {
- ...element.attributes,
- from: resolvedImport(moduleFile, from),
- },
- origin: { file: moduleFile },
- };
-}
-
-async function loadContentModule(
- file: string,
- prefix: string,
- stack: string[],
-): Promise<LoadedContent> {
- const absolute = resolve(file);
- if (stack.includes(absolute)) {
- fail(
- "content_import_cycle",
- `Content import cycle: ${[...stack, absolute].join(" -> ")}`,
- );
- }
- const source = await readFile(absolute, "utf8");
- const root = parseRootSource(absolute, source);
- if (root.name !== "content") {
- fail("content_root", `${absolute} must use a <content> root.`);
- }
- const imports = childElements(root, "import");
- const dependencies = imports.map((element) =>
- canonicalUri(resolvedImport(absolute, attributeString(element, "from"))));
- const declarations = childElements(root).filter((element) => element.name !== "import");
- const localDeclarations = new Set(declarations.map((element) => {
- const id = element.attributes.id;
- if (typeof id !== "string") {
- fail("content_declaration_id", `${absolute} contains <${element.name}> without id.`);
- }
- return id;
- }));
- const importedNamespaces = new Set<string>();
- const nested: LoadedContent[] = [];
- const kernelImports: SourceElement[] = [];
- for (const element of imports) {
- const from = attributeString(element, "from");
- const extension = extname(from);
- if (extension === ".svk") {
- kernelImports.push(absoluteImport(element, absolute));
- continue;
- }
- if (extension === ".svs") {
- fail(
- "content_sheet_import_unsupported",
- `${absolute} imports ${from}; sheet imports inside .svc are not enabled yet.`,
- );
- }
- if (extension !== ".svc") {
- fail("content_import_type", `${absolute} imports unsupported module ${from}.`);
- }
- const alias = element.attributes.as;
- if (alias !== undefined && typeof alias !== "string") {
- fail("content_import_alias", `${absolute} import alias must be a string.`);
- }
- const namespace = alias ?? "";
- if (namespace) importedNamespaces.add(namespace);
- nested.push(await loadContentModule(
- resolve(dirname(absolute), from),
- `${prefix}${namespace ? `${namespace}.` : ""}`,
- [...stack, absolute],
- ));
- }
- const cloned = declarations.map((element) => cloneNode(element, {
- moduleFile: absolute,
- prefix,
- localDeclarations,
- importedNamespaces,
- topLevel: true,
- }) as SourceElement);
- return {
- declarations: [...nested.flatMap((item) => item.declarations), ...cloned],
- kernelImports: [
- ...nested.flatMap((item) => item.kernelImports),
- ...kernelImports,
- ],
- modules: [
- {
- kind: "svc",
- uri: canonicalUri(absolute),
- contentHash: sha256(source),
- dependencies,
- },
- ...nested.flatMap((item) => item.modules),
- ],
- };
-}
-
-function uniqueKernelImports(elements: SourceElement[]): SourceElement[] {
- const output: SourceElement[] = [];
- const seen = new Set<string>();
- for (const element of elements) {
- const from = attributeString(element, "from");
- if (seen.has(from)) continue;
- seen.add(from);
- output.push(element);
- }
- return output;
-}
-
-export async function loadSourceClosure(file: string): Promise<SourceDocument> {
- const document = await parseDocument(file);
- const localChildren: SourceNode[] = [];
- const importedDeclarations: SourceElement[] = [];
- const importedKernels: SourceElement[] = [];
- const modules: SourceModuleRecord[] = [{
- kind: "svml",
- uri: canonicalUri(document.file),
- contentHash: sha256(document.source),
- dependencies: childElements(document.root, "import").map((element) =>
- canonicalUri(resolvedImport(document.file, attributeString(element, "from")))),
- }];
- for (const node of document.root.children) {
- if (node.kind !== "element" || node.name !== "import") {
- localChildren.push(node.kind === "element"
- ? {
- ...node,
- origin: {
- file: document.file,
- ...(typeof node.attributes.id === "string"
- ? { localId: node.attributes.id }
- : {}),
- },
- }
- : node);
- continue;
- }
- const from = attributeString(node, "from");
- if (extname(from) !== ".svc") {
- localChildren.push(absoluteImport(node, document.file));
- continue;
- }
- const alias = node.attributes.as;
- if (alias !== undefined && typeof alias !== "string") {
- fail("content_import_alias", `${document.file} import alias must be a string.`);
- }
- const loaded = await loadContentModule(
- resolve(dirname(document.file), from),
- typeof alias === "string" && alias ? `${alias}.` : "",
- [],
- );
- importedDeclarations.push(...loaded.declarations);
- importedKernels.push(...loaded.kernelImports);
- modules.push(...loaded.modules);
- }
- return {
- ...document,
- root: {
- ...document.root,
- children: [
- ...uniqueKernelImports(importedKernels),
- ...localChildren,
- ...importedDeclarations,
- ],
- },
- modules: [...new Map(modules.map((module) => [module.uri, module])).values()],
- };
-}
diff --git a/src/source/parse-document.ts b/src/source/parse-document.ts
deleted file mode 100644
index 80896096..00000000
--- a/src/source/parse-document.ts
+++ /dev/null
@@ -1,282 +0,0 @@
-import { readFile } from "node:fs/promises";
-import { resolve } from "node:path";
-import { fail, sourceLocation } from "../diagnostics.js";
-import type {
- AttributeValue,
- SourceDocument,
- SourceElement,
- SourceNode,
-} from "../model.js";
-
-type Cursor = {
- file: string;
- source: string;
- offset: number;
-};
-
-const NAME = /[A-Za-z_][A-Za-z0-9_.:-]*/y;
-
-function skipSpace(cursor: Cursor): void {
- while (/\s/u.test(cursor.source[cursor.offset] ?? "")) cursor.offset += 1;
-}
-
-function parseName(cursor: Cursor): string {
- NAME.lastIndex = cursor.offset;
- const match = NAME.exec(cursor.source);
- if (!match) {
- fail(
- "source_expected_name",
- "Expected an element or attribute name.",
- sourceLocation(cursor.file, cursor.source, cursor.offset),
- );
- }
- cursor.offset = NAME.lastIndex;
- return match[0];
-}
-
-function parseQuoted(cursor: Cursor): string {
- const quote = cursor.source[cursor.offset];
- if (quote !== '"' && quote !== "'") {
- fail(
- "source_expected_quoted_value",
- "Attribute literals must be quoted.",
- sourceLocation(cursor.file, cursor.source, cursor.offset),
- );
- }
- const start = ++cursor.offset;
- while (cursor.offset < cursor.source.length && cursor.source[cursor.offset] !== quote) {
- cursor.offset += 1;
- }
- if (cursor.source[cursor.offset] !== quote) {
- fail(
- "source_unclosed_attribute",
- "Unclosed quoted attribute value.",
- sourceLocation(cursor.file, cursor.source, start - 1),
- );
- }
- const value = cursor.source.slice(start, cursor.offset);
- cursor.offset += 1;
- return value;
-}
-
-function parseReference(cursor: Cursor): AttributeValue {
- const start = ++cursor.offset;
- while (cursor.offset < cursor.source.length && cursor.source[cursor.offset] !== "}") {
- cursor.offset += 1;
- }
- if (cursor.source[cursor.offset] !== "}") {
- fail(
- "source_unclosed_reference",
- "Unclosed reference attribute.",
- sourceLocation(cursor.file, cursor.source, start - 1),
- );
- }
- const path = cursor.source.slice(start, cursor.offset).trim();
- cursor.offset += 1;
- if (!/^[A-Za-z_][A-Za-z0-9_.:-]*(?:\[[A-Za-z_][A-Za-z0-9_.:-]*\])?$/u.test(path)) {
- fail(
- "source_invalid_reference",
- `Invalid reference path "${path}".`,
- sourceLocation(cursor.file, cursor.source, start),
- );
- }
- return { kind: "reference", path };
-}
-
-function literalValue(raw: string): AttributeValue {
- if (raw === "true") return true;
- if (raw === "false") return false;
- if (/^-?(?:\d+\.?\d*|\.\d+)$/u.test(raw)) return Number(raw);
- return raw;
-}
-
-function parseAttributes(cursor: Cursor): Record<string, AttributeValue> {
- const attributes: Record<string, AttributeValue> = {};
- while (cursor.offset < cursor.source.length) {
- skipSpace(cursor);
- const next = cursor.source[cursor.offset];
- if (next === ">" || (next === "/" && cursor.source[cursor.offset + 1] === ">")) break;
- const name = parseName(cursor);
- if (Object.hasOwn(attributes, name)) {
- fail(
- "source_duplicate_attribute",
- `Duplicate attribute "${name}".`,
- sourceLocation(cursor.file, cursor.source, cursor.offset),
- );
- }
- skipSpace(cursor);
- if (cursor.source[cursor.offset] !== "=") {
- fail(
- "source_expected_attribute_equals",
- `Attribute "${name}" requires "=".`,
- sourceLocation(cursor.file, cursor.source, cursor.offset),
- );
- }
- cursor.offset += 1;
- skipSpace(cursor);
- const value = cursor.source[cursor.offset] === "{"
- ? parseReference(cursor)
- : literalValue(parseQuoted(cursor));
- attributes[name] = value;
- }
- return attributes;
-}
-
-function skipComment(cursor: Cursor): boolean {
- if (!cursor.source.startsWith("<!--", cursor.offset)) return false;
- const end = cursor.source.indexOf("-->", cursor.offset + 4);
- if (end < 0) {
- fail(
- "source_unclosed_comment",
- "Unclosed source comment.",
- sourceLocation(cursor.file, cursor.source, cursor.offset),
- );
- }
- cursor.offset = end + 3;
- return true;
-}
-
-function parseElement(cursor: Cursor): SourceElement {
- const start = cursor.offset;
- if (cursor.source[cursor.offset] !== "<" || cursor.source[cursor.offset + 1] === "/") {
- fail(
- "source_expected_element",
- "Expected an opening element.",
- sourceLocation(cursor.file, cursor.source, cursor.offset),
- );
- }
- cursor.offset += 1;
- const name = parseName(cursor);
- const attributes = parseAttributes(cursor);
- skipSpace(cursor);
- if (cursor.source.startsWith("/>", cursor.offset)) {
- cursor.offset += 2;
- return { kind: "element", name, attributes, children: [], start, end: cursor.offset };
- }
- if (cursor.source[cursor.offset] !== ">") {
- fail(
- "source_expected_tag_end",
- `Opening <${name}> is not closed.`,
- sourceLocation(cursor.file, cursor.source, cursor.offset),
- );
- }
- cursor.offset += 1;
-
- const children: SourceNode[] = [];
- if (name === "script") {
- const close = cursor.source.indexOf("</script>", cursor.offset);
- if (close < 0) {
- fail(
- "source_unclosed_script",
- "The <script> element is not closed.",
- sourceLocation(cursor.file, cursor.source, start),
- );
- }
- children.push({
- kind: "text",
- value: cursor.source.slice(cursor.offset, close),
- start: cursor.offset,
- end: close,
- });
- cursor.offset = close + "</script>".length;
- return { kind: "element", name, attributes, children, start, end: cursor.offset };
- }
-
- while (cursor.offset < cursor.source.length) {
- if (skipComment(cursor)) continue;
- if (cursor.source.startsWith("</", cursor.offset)) {
- cursor.offset += 2;
- const closeName = parseName(cursor);
- skipSpace(cursor);
- if (cursor.source[cursor.offset] !== ">") {
- fail(
- "source_expected_tag_end",
- `Closing </${closeName}> is not closed.`,
- sourceLocation(cursor.file, cursor.source, cursor.offset),
- );
- }
- cursor.offset += 1;
- if (closeName !== name) {
- fail(
- "source_mismatched_close",
- `Expected </${name}>, received </${closeName}>.`,
- sourceLocation(cursor.file, cursor.source, cursor.offset),
- );
- }
- return { kind: "element", name, attributes, children, start, end: cursor.offset };
- }
- if (cursor.source[cursor.offset] === "<") {
- children.push(parseElement(cursor));
- continue;
- }
- const textStart = cursor.offset;
- const next = cursor.source.indexOf("<", cursor.offset);
- cursor.offset = next < 0 ? cursor.source.length : next;
- children.push({
- kind: "text",
- value: cursor.source.slice(textStart, cursor.offset),
- start: textStart,
- end: cursor.offset,
- });
- }
- fail(
- "source_unclosed_element",
- `The <${name}> element is not closed.`,
- sourceLocation(cursor.file, cursor.source, start),
- );
-}
-
-export function parseRootSource(file: string, source: string): SourceElement {
- const cursor: Cursor = { file, source, offset: 0 };
- skipSpace(cursor);
- while (skipComment(cursor)) skipSpace(cursor);
- const root = parseElement(cursor);
- skipSpace(cursor);
- while (skipComment(cursor)) skipSpace(cursor);
- if (cursor.offset !== source.length) {
- fail(
- "source_trailing_content",
- "Only comments and whitespace may follow the root element.",
- sourceLocation(file, source, cursor.offset),
- );
- }
- return root;
-}
-
-export function parseDocumentSource(file: string, source: string): SourceDocument {
- source = source.replace(/\r\n?/gu, "\n").normalize("NFC");
- const root = parseRootSource(file, source);
- if (root.name !== "svml") {
- fail(
- "source_invalid_root",
- `Expected <svml>, received <${root.name}>.`,
- sourceLocation(file, source, root.start),
- );
- }
- const scripts = root.children.filter(
- (node): node is SourceElement => node.kind === "element" && node.name === "script",
- );
- if (scripts.length !== 1) {
- fail(
- "source_script_cardinality",
- `Expected exactly one <script>, received ${scripts.length}.`,
- sourceLocation(file, source, root.start),
- );
- }
- const scriptText = scripts[0]?.children[0];
- if (!scriptText || scriptText.kind !== "text") {
- fail("source_script_missing_text", "The <script> body could not be read.");
- }
- return {
- file,
- source,
- root,
- scriptSource: scriptText.value,
- scriptOffset: scriptText.start,
- };
-}
-
-export async function parseDocument(file: string): Promise<SourceDocument> {
- const absolute = resolve(file);
- return parseDocumentSource(absolute, await readFile(absolute, "utf8"));
-}
diff --git a/src/source/query.ts b/src/source/query.ts
deleted file mode 100644
index 284fa805..00000000
--- a/src/source/query.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import type { AttributeValue, SourceElement, SourceNode } from "../model.js";
-
-export function childElements(element: SourceElement, name?: string): SourceElement[] {
- return element.children.filter(
- (child): child is SourceElement =>
- child.kind === "element" && (name === undefined || child.name === name),
- );
-}
-
-export function textContent(element: SourceElement): string {
- return element.children
- .map((child) => child.kind === "text" ? child.value : textContent(child))
- .join("");
-}
-
-export function attributeString(
- element: SourceElement,
- name: string,
- fallback?: string,
-): string {
- const value = element.attributes[name];
- if (typeof value === "string") return value;
- if (value === undefined && fallback !== undefined) return fallback;
- throw new Error(`<${element.name}> requires string attribute "${name}"`);
-}
-
-export function attributeNumber(
- element: SourceElement,
- name: string,
- fallback?: number,
-): number {
- const value = element.attributes[name];
- if (typeof value === "number" && Number.isFinite(value)) return value;
- if (typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value))) {
- return Number(value);
- }
- if (value === undefined && fallback !== undefined) return fallback;
- throw new Error(`<${element.name}> requires numeric attribute "${name}"`);
-}
-
-export function attributeBoolean(
- element: SourceElement,
- name: string,
- fallback?: boolean,
-): boolean {
- const value = element.attributes[name];
- if (typeof value === "boolean") return value;
- if (value === undefined && fallback !== undefined) return fallback;
- throw new Error(`<${element.name}> requires boolean attribute "${name}"`);
-}
-
-export function attributeReference(element: SourceElement, name: string): string {
- const value = element.attributes[name];
- if (value && typeof value === "object" && value.kind === "reference") return value.path;
- throw new Error(`<${element.name}> requires reference attribute "${name}"`);
-}
-
-export function referencePath(value: AttributeValue | undefined): string | undefined {
- return value && typeof value === "object" && value.kind === "reference"
- ? value.path
- : undefined;
-}
-
-export function walkElements(nodes: SourceNode[]): SourceElement[] {
- const output: SourceElement[] = [];
- for (const node of nodes) {
- if (node.kind !== "element") continue;
- output.push(node, ...walkElements(node.children));
- }
- return output;
-}
diff --git a/src/source/styles.ts b/src/source/styles.ts
deleted file mode 100644
index 2e08053c..00000000
--- a/src/source/styles.ts
+++ /dev/null
@@ -1,313 +0,0 @@
-import { readFile } from "node:fs/promises";
-import { extname, resolve } from "node:path";
-import { pathToFileURL } from "node:url";
-import { fail } from "../diagnostics.js";
-import type {
- AttributeValue,
- ParameterSource,
- SourceDocument,
- SourceElement,
- SourceNode,
-} from "../model.js";
-import type {
- KernelChildSchema,
- KernelField,
- KernelManifest,
- KernelParameter,
- KernelRegistry,
-} from "../kernel.js";
-import { attributeString, childElements, textContent } from "./query.js";
-import { parseRootSource } from "./parse-document.js";
-import { sha256 } from "../util.js";
-
-type StyleRule = {
- selector: string;
- className: string;
- properties: Array<{ name: string; raw: string }>;
- source: string;
-};
-
-type Sheet = {
- binding: string;
- file: string;
- rules: StyleRule[];
- contentHash: string;
-};
-
-function parseGenericLiteral(raw: string): AttributeValue {
- const value = raw.trim();
- const quoted = /^(?:"([^"]*)"|'([^']*)')$/u.exec(value);
- if (quoted) return quoted[1] ?? quoted[2] ?? "";
- if (value === "true") return true;
- if (value === "false") return false;
- if (/^-?(?:\d+\.?\d*|\.\d+)$/u.test(value)) return Number(value);
- return value;
-}
-
-function typedValue(
- raw: string,
- parameter: KernelParameter | undefined,
- source: string,
-): AttributeValue {
- const value = parseGenericLiteral(raw);
- if (!parameter) return value;
- if (parameter.type === "number") {
- if (typeof value !== "number" || !Number.isFinite(value)) {
- fail("style_parameter_type", `${source} expects numeric ${parameter.styleName}.`);
- }
- } else if (parameter.type === "boolean") {
- if (typeof value !== "boolean") {
- fail("style_parameter_type", `${source} expects boolean ${parameter.styleName}.`);
- }
- } else {
- if (typeof value !== "string") {
- fail("style_parameter_type", `${source} expects string ${parameter.styleName}.`);
- }
- if (
- parameter.type === "duration"
- && !/^[+-]?\d+(?:\.\d+)?(?:ms|s)$/u.test(value)
- ) {
- fail("style_parameter_type", `${source} expects duration ${parameter.styleName}.`);
- }
- const enumValues = /^enum\((.+)\)$/u.exec(parameter.type)?.[1]?.split(",");
- if (enumValues && !enumValues.includes(value)) {
- fail("style_parameter_type", `${source} expects ${parameter.type} ${parameter.styleName}.`);
- }
- }
- return value;
-}
-
-function parseRules(file: string, root: SourceElement): StyleRule[] {
- const source = textContent(root).replaceAll(/\/\*[\s\S]*?\*\//gu, "");
- const rules: StyleRule[] = [];
- const rulePattern = /([A-Za-z_][A-Za-z0-9_:-]*)\.([A-Za-z_][A-Za-z0-9_-]*)\s*\{([^{}]*)\}/gu;
- let consumed = "";
- let lastEnd = 0;
- for (const match of source.matchAll(rulePattern)) {
- const index = match.index ?? 0;
- consumed += source.slice(lastEnd, index).replace(/\s+/gu, "");
- lastEnd = index + match[0].length;
- const properties = (match[3] ?? "")
- .split(";")
- .map((statement) => statement.trim())
- .filter(Boolean)
- .map((statement) => {
- const colon = statement.indexOf(":");
- if (colon <= 0) {
- fail("style_declaration", `${file} has invalid declaration "${statement}".`);
- }
- const name = statement.slice(0, colon).trim();
- const raw = statement.slice(colon + 1).trim();
- if (!/^[A-Za-z_][A-Za-z0-9_-]*$/u.test(name) || !raw) {
- fail("style_declaration", `${file} has invalid declaration "${statement}".`);
- }
- return { name, raw };
- });
- rules.push({
- selector: match[1]!,
- className: match[2]!,
- properties,
- source: `${file}:${match[1]}.${match[2]}`,
- });
- }
- consumed += source.slice(lastEnd).replace(/\s+/gu, "");
- if (consumed) {
- fail("style_syntax", `${file} contains unsupported sheet syntax near "${consumed.slice(0, 40)}".`);
- }
- const keys = rules.map((rule) => `${rule.selector}.${rule.className}`);
- if (new Set(keys).size !== keys.length) {
- fail("style_duplicate_rule", `${file} repeats a selector/class rule.`);
- }
- return rules;
-}
-
-async function loadSheets(document: SourceDocument): Promise<Sheet[]> {
- const sheets: Sheet[] = [];
- for (const element of childElements(document.root, "import")) {
- const from = attributeString(element, "from");
- if (extname(from) !== ".svs") continue;
- const file = resolve(from);
- const source = await readFile(file, "utf8");
- const root = parseRootSource(file, source);
- if (root.name !== "sheet") fail("style_root", `${file} must use a <sheet> root.`);
- const id = root.attributes.id;
- const alias = element.attributes.as;
- if (alias !== undefined && typeof alias !== "string") {
- fail("style_import_alias", `${document.file} sheet alias must be a string.`);
- }
- if (typeof id !== "string" || !id) fail("style_sheet_id", `${file} requires a sheet id.`);
- const binding = typeof alias === "string" && alias ? alias : id;
- sheets.push({
- binding,
- file,
- rules: parseRules(file, root),
- contentHash: sha256(source),
- });
- }
- if (new Set(sheets.map((sheet) => sheet.binding)).size !== sheets.length) {
- fail("style_duplicate_binding", "Imported .svs bindings must be unique.");
- }
- return sheets;
-}
-
-function findRule(
- token: string,
- element: SourceElement,
- sheets: Sheet[],
- selector: string,
-): StyleRule {
- const dot = token.indexOf(".");
- if (dot > 0) {
- const binding = token.slice(0, dot);
- const className = token.slice(dot + 1);
- const sheet = sheets.find((candidate) => candidate.binding === binding);
- if (!sheet) fail("style_unknown_binding", `Unknown style binding "${binding}".`);
- const rule = sheet.rules.find(
- (candidate) => candidate.selector === selector && candidate.className === className,
- );
- if (!rule) {
- fail(
- "style_unknown_class",
- `${sheet.file} does not define ${selector}.${className}.`,
- );
- }
- return rule;
- }
- const matches = sheets.flatMap((sheet) => sheet.rules.filter(
- (candidate) => candidate.selector === selector && candidate.className === token,
- ));
- if (matches.length !== 1) {
- fail(
- "style_ambiguous_class",
- `Unqualified class "${token}" on <${element.name}> resolves to ${matches.length} rules.`,
- );
- }
- return matches[0]!;
-}
-
-function parameterFor(
- manifest: KernelManifest | undefined,
- styleName: string,
-): KernelParameter | undefined {
- if (!manifest) return undefined;
- return manifest.parameters.find(
- (parameter) => parameter.styleName === styleName || parameter.name === styleName,
- );
-}
-
-function fieldFor(
- schemas: KernelChildSchema[],
- elementName: string,
- styleName: string,
-): KernelField | undefined {
- for (const schema of schemas) {
- if (schema.name === elementName) {
- const field = schema.fields.find((candidate) =>
- candidate.styleName === styleName || candidate.name === styleName);
- if (field) return field;
- }
- const nested = fieldFor(schema.children, elementName, styleName);
- if (nested) return nested;
- }
- return undefined;
-}
-
-function styleElement(
- element: SourceElement,
- sheets: Sheet[],
- kernels: KernelRegistry,
- ownerKernel?: KernelManifest,
-): SourceElement {
- const manifest = kernels.get(element.name) ?? ownerKernel;
- if (element.parameterSources) {
- return {
- ...element,
- children: element.children.map((child) => child.kind === "element"
- ? styleElement(child, sheets, kernels, manifest)
- : child),
- };
- }
- const topLevelKernel = kernels.get(element.name);
- const selector = topLevelKernel?.name ?? ownerKernel?.name ?? element.name;
- const classValue = element.attributes.class;
- if (classValue !== undefined && typeof classValue !== "string") {
- fail("style_class_type", `<${element.name}> class must be a string.`);
- }
- const attributes: Record<string, AttributeValue> = {};
- const parameterSources: Record<string, ParameterSource[]> = {};
- for (const token of (classValue ?? "").split(/\s+/u).filter(Boolean)) {
- const rule = findRule(token, element, sheets, selector);
- for (const property of rule.properties) {
- const parameter = topLevelKernel
- ? parameterFor(topLevelKernel, property.name)
- : undefined;
- const field = !topLevelKernel && ownerKernel
- ? fieldFor(ownerKernel.children, element.name, property.name)
- : undefined;
- if ((topLevelKernel || ownerKernel) && !parameter && !field) {
- fail(
- "style_unknown_parameter",
- `${rule.source} configures unknown public parameter "${property.name}".`,
- );
- }
- const schema = parameter ?? (field ? {
- name: field.name,
- styleName: field.styleName,
- type: field.type,
- } : undefined);
- const name = schema?.name ?? property.name;
- const value = typedValue(property.raw, schema, rule.source);
- attributes[name] = value;
- (parameterSources[name] ??= []).push({
- kind: "svs-class",
- source: rule.source,
- value,
- });
- }
- }
- for (const [name, value] of Object.entries(element.attributes)) {
- attributes[name] = value;
- if (name !== "class") {
- (parameterSources[name] ??= []).push({
- kind: "instance",
- source: element.origin?.file ?? "<source>",
- value,
- });
- }
- }
- return {
- ...element,
- attributes,
- parameterSources,
- children: element.children.map((child) => child.kind === "element"
- ? styleElement(child, sheets, kernels, manifest)
- : child),
- };
-}
-
-export async function applyStyleSheets(
- document: SourceDocument,
- kernels: KernelRegistry,
-): Promise<SourceDocument> {
- const sheets = await loadSheets(document);
- if (!sheets.length) return document;
- return {
- ...document,
- root: {
- ...document.root,
- children: document.root.children.map((node: SourceNode) =>
- node.kind === "element" && !["import", "script"].includes(node.name)
- ? styleElement(node, sheets, kernels)
- : node),
- },
- modules: [
- ...(document.modules ?? []),
- ...sheets.map((sheet) => ({
- kind: "svs" as const,
- uri: pathToFileURL(sheet.file).href,
- contentHash: sheet.contentHash,
- dependencies: [],
- })),
- ],
- };
-}
diff --git a/src/temporal.ts b/src/temporal.ts
deleted file mode 100644
index 6f1d36a8..00000000
--- a/src/temporal.ts
+++ /dev/null
@@ -1,580 +0,0 @@
-import { fail } from "./diagnostics.js";
-import type {
- CompleteSemanticMap,
- NarrativeIR,
- ProgramBasis,
- SemanticAnchorPoint,
- SemanticMap,
- SpeechTimingEvidence,
- TemporalBasisProduction,
-} from "./model.js";
-import { normalizeWord, sha256, stableJson } from "./util.js";
-
-const EPSILON = 1e-6;
-
-export function basisFps(basis: ProgramBasis): number {
- return basis.frameRate.numerator / basis.frameRate.denominator;
-}
-
-function integer(value: number, label: string): void {
- if (!Number.isInteger(value)) fail("temporal_integer", `${label} must be an integer.`);
-}
-
-function normalizeFrameRate(fps: number): ProgramBasis["frameRate"] {
- if (!Number.isFinite(fps) || fps <= 0) {
- fail("basis_frame_rate", `ProgramBasis fps must be positive and finite; received ${fps}.`);
- }
- if (Number.isInteger(fps)) return { numerator: fps, denominator: 1 };
- const denominator = 1_000_000;
- const numerator = Math.round(fps * denominator);
- const divisor = gcd(numerator, denominator);
- return { numerator: numerator / divisor, denominator: denominator / divisor };
-}
-
-function gcd(left: number, right: number): number {
- left = Math.abs(left);
- right = Math.abs(right);
- while (right) [left, right] = [right, left % right];
- return left || 1;
-}
-
-export function createProgramBasis(args: {
- fps: number;
- durationFrames: number;
- outcomeDigest: string;
-}): ProgramBasis {
- integer(args.durationFrames, "ProgramBasis durationFrames");
- if (args.durationFrames <= 0) {
- fail("basis_duration", "ProgramBasis durationFrames must be positive.");
- }
- const payload = {
- contract: "svml.program-basis.v1" as const,
- frameRate: normalizeFrameRate(args.fps),
- originFrame: 0 as const,
- durationFrames: args.durationFrames,
- outcomeDigest: args.outcomeDigest,
- };
- return {
- contract: payload.contract,
- frameRate: payload.frameRate,
- originFrame: payload.originFrame,
- durationFrames: payload.durationFrames,
- basisDigest: sha256(stableJson(payload)),
- };
-}
-
-export function validateProgramBasis(basis: ProgramBasis): void {
- if (basis.contract !== "svml.program-basis.v1") {
- fail("basis_contract", `Unsupported ProgramBasis contract "${basis.contract}".`);
- }
- integer(basis.frameRate.numerator, "ProgramBasis frameRate numerator");
- integer(basis.frameRate.denominator, "ProgramBasis frameRate denominator");
- integer(basis.durationFrames, "ProgramBasis durationFrames");
- if (
- basis.originFrame !== 0
- || basis.frameRate.numerator <= 0
- || basis.frameRate.denominator <= 0
- || basis.durationFrames <= 0
- || !/^[a-f0-9]{64}$/u.test(basis.basisDigest)
- ) {
- fail("basis_shape", "ProgramBasis has an invalid clock or digest.");
- }
-}
-
-function canonicalFacet(value: unknown): unknown {
- if (Array.isArray(value)) return value.map(canonicalFacet);
- if (!value || typeof value !== "object") return value;
- return Object.fromEntries(Object.entries(value as Record<string, unknown>)
- .filter(([key]) => !["source", "absoluteSource", "basisDigest"].includes(key))
- .map(([key, nested]) => [key, canonicalFacet(nested)]));
-}
-
-export function basisOutcome(production: TemporalBasisProduction): unknown {
- return {
- contract: "svml.program-basis-outcome.v1",
- frameRate: production.basis.frameRate,
- originFrame: production.basis.originFrame,
- durationFrames: production.basis.durationFrames,
- alignmentSubjects: production.alignmentSubjects,
- sourceMaps: production.sourceMaps,
- audio: production.audio.map(({ source: _source, ...contribution }) => contribution),
- facets: canonicalFacet(production.facets),
- };
-}
-
-function digest(value: string, label: string): void {
- if (!/^[a-f0-9]{64}$/u.test(value)) {
- fail("temporal_digest", `${label} must be a lowercase SHA-256 digest.`);
- }
-}
-
-function uniqueIds(values: Array<{ id: string }>, label: string): void {
- if (new Set(values.map((value) => value.id)).size !== values.length) {
- fail("basis_identity_duplicate", `${label} contains duplicate ids.`);
- }
-}
-
-function validateProgramWindow(
- start: number,
- end: number,
- durationFrames: number,
- label: string,
-): void {
- integer(start, `${label} start`);
- integer(end, `${label} end`);
- if (start < 0 || end <= start || end > durationFrames) {
- fail("basis_program_window", `${label} has invalid Program range ${start}..${end}.`);
- }
-}
-
-function validateFacetAffinity(value: unknown, basisDigest: string, path = "facets"): void {
- if (Array.isArray(value)) {
- value.forEach((nested, index) => validateFacetAffinity(nested, basisDigest, `${path}[${index}]`));
- return;
- }
- if (!value || typeof value !== "object") return;
- const record = value as Record<string, unknown>;
- if ("basisDigest" in record && record.basisDigest !== basisDigest) {
- fail("basis_facet_affinity", `${path} is bound to a different ProgramBasis.`);
- }
- for (const [key, nested] of Object.entries(record)) {
- validateFacetAffinity(nested, basisDigest, `${path}.${key}`);
- }
-}
-
-export function validateTemporalBasisProduction(production: TemporalBasisProduction): void {
- if (production.contract !== "svml.temporal-basis-production.v1") {
- fail("basis_production_contract", "Unsupported TemporalBasisProduction contract.");
- }
- validateProgramBasis(production.basis);
- digest(production.productionDigest, "productionDigest");
- uniqueIds(production.alignmentSubjects, "alignmentSubjects");
- uniqueIds(production.sourceMaps, "sourceMaps");
- uniqueIds(production.audio, "Program audio");
- const maps = new Map(production.sourceMaps.map((map) => [map.id, map]));
- for (const map of production.sourceMaps) {
- digest(map.sourceDigest, `Source map "${map.id}" digest`);
- integer(map.sourceStartFrame, `Source map "${map.id}" source start`);
- integer(map.sourceEndFrameExclusive, `Source map "${map.id}" source end`);
- if (map.sourceStartFrame < 0 || map.sourceEndFrameExclusive <= map.sourceStartFrame) {
- fail("basis_source_window", `Source map "${map.id}" has an invalid source range.`);
- }
- validateProgramWindow(
- map.programStartFrame,
- map.programEndFrameExclusive,
- production.basis.durationFrames,
- `Source map "${map.id}"`,
- );
- }
- for (const subject of production.alignmentSubjects) {
- digest(subject.sourceDigest, `Alignment subject "${subject.id}" digest`);
- const map = maps.get(subject.sourceMapId);
- if (
- !map
- || map.sourceId !== subject.sourceId
- || map.sourceDigest !== subject.sourceDigest
- ) {
- fail("basis_alignment_subject", `Alignment subject "${subject.id}" has no matching source map.`);
- }
- }
- for (const contribution of production.audio) {
- digest(contribution.sourceDigest, `Program audio "${contribution.id}" digest`);
- const map = maps.get(contribution.sourceMapId);
- if (
- !map
- || map.sourceId !== contribution.sourceId
- || map.sourceDigest !== contribution.sourceDigest
- ) {
- fail("basis_audio_source_map", `Program audio "${contribution.id}" has no matching source map.`);
- }
- validateProgramWindow(
- contribution.programStartFrame,
- contribution.programEndFrameExclusive,
- production.basis.durationFrames,
- `Program audio "${contribution.id}"`,
- );
- const duration = contribution.programEndFrameExclusive - contribution.programStartFrame;
- for (const [name, value] of [
- ["fadeInFrames", contribution.fadeInFrames ?? 0],
- ["fadeOutFrames", contribution.fadeOutFrames ?? 0],
- ] as const) {
- integer(value, `Program audio "${contribution.id}" ${name}`);
- if (value < 0 || value > duration) {
- fail("basis_audio_fade", `Program audio "${contribution.id}" has invalid ${name}.`);
- }
- }
- if (!Number.isFinite(contribution.gain) || contribution.gain < 0) {
- fail("basis_audio_gain", `Program audio "${contribution.id}" has invalid gain.`);
- }
- }
- validateFacetAffinity(production.facets, production.basis.basisDigest);
- const expected = sha256(stableJson(basisOutcome(production)));
- if (production.basis.basisDigest !== expected) {
- fail(
- "basis_digest",
- `ProgramBasis digest ${production.basis.basisDigest} does not match canonical outcome ${expected}.`,
- );
- }
-}
-
-function frameAt(seconds: number, basis: ProgramBasis): number {
- return Math.round(seconds * basisFps(basis));
-}
-
-function semanticMapDigest(map: Omit<CompleteSemanticMap, "mapDigest">): string {
- return sha256(stableJson(map));
-}
-
-function validateSpeechTiming(
- narrative: NarrativeIR,
- basis: ProgramBasis,
- evidence: SpeechTimingEvidence,
-): void {
- if (evidence.contract !== "svml.speech-timing-evidence.v1") {
- fail("locator_evidence_contract", `Unsupported speech timing contract "${evidence.contract}".`);
- }
- if (
- !Number.isFinite(evidence.fps)
- || evidence.fps <= 0
- || !Number.isFinite(evidence.durationSec)
- || evidence.durationSec <= 0
- ) {
- fail("locator_evidence_clock", "SpeechTimingEvidence requires positive fps and duration.");
- }
- if (evidence.quality !== "measured" && evidence.quality !== "estimated") {
- fail("locator_evidence_quality", "SpeechTimingEvidence quality must be measured or estimated.");
- }
- if (Math.abs(evidence.fps - basisFps(basis)) > EPSILON) {
- fail(
- "locator_basis_frame_rate",
- `Speech timing fps ${evidence.fps} does not match ProgramBasis fps ${basisFps(basis)}.`,
- );
- }
- if (frameAt(evidence.durationSec, basis) !== basis.durationFrames) {
- fail(
- "locator_basis_duration",
- `Speech timing duration resolves to ${frameAt(evidence.durationSec, basis)} frames; ProgramBasis has ${basis.durationFrames}.`,
- );
- }
- if (evidence.segments.length !== narrative.segments.length) {
- fail(
- "locator_segment_cardinality",
- `Script has ${narrative.segments.length} Segments but speech timing has ${evidence.segments.length}.`,
- );
- }
-
- const segments = new Map(evidence.segments.map((segment) => [segment.id, segment]));
- if (segments.size !== evidence.segments.length) {
- fail("locator_segment_duplicate", "SpeechTimingEvidence repeats a Segment id.");
- }
- for (const [index, segment] of narrative.segments.entries()) {
- const aligned = segments.get(segment.id);
- if (!aligned) fail("locator_segment_missing", `Speech timing is missing Segment "${segment.id}".`);
- if (
- !Number.isFinite(aligned.startSec)
- || !Number.isFinite(aligned.endSec)
- || aligned.startSec < 0
- || aligned.endSec < aligned.startSec
- || aligned.endSec > evidence.durationSec + EPSILON
- ) {
- fail(
- "locator_segment_window",
- `Segment "${segment.id}" has invalid window ${aligned.startSec}..${aligned.endSec}.`,
- );
- }
- const previousScript = narrative.segments[index - 1];
- const previous = previousScript ? segments.get(previousScript.id) : undefined;
- if (
- previous
- && (
- aligned.startSec < previous.startSec - EPSILON
- || aligned.endSec < previous.endSec - EPSILON
- )
- ) {
- fail(
- "locator_segment_order",
- `Segment "${segment.id}" violates source-order start/end monotonicity.`,
- );
- }
- }
-
- const previousBySegment = new Map<string, SpeechTimingEvidence["units"][number]>();
- for (const [index, unit] of evidence.units.entries()) {
- const segment = segments.get(unit.segmentId);
- if (
- !segment
- || typeof unit.text !== "string"
- || !Number.isFinite(unit.startSec)
- || !Number.isFinite(unit.endSec)
- || unit.startSec < segment.startSec - EPSILON
- || unit.endSec < unit.startSec
- || unit.endSec > segment.endSec + EPSILON
- ) {
- fail(
- "locator_word_window",
- `Speech timing unit ${index + 1} falls outside Segment "${unit.segmentId}".`,
- );
- }
- const previous = previousBySegment.get(unit.segmentId);
- if (previous && unit.startSec < previous.endSec - EPSILON) {
- fail(
- "locator_word_overlap",
- `Speech timing unit ${index + 1} overlaps the preceding unit in Segment "${unit.segmentId}".`,
- );
- }
- previousBySegment.set(unit.segmentId, unit);
- }
-}
-
-type TokenFrame = {
- startFrame: number;
- endFrameExclusive: number;
- quality: "estimated" | "derived" | "measured";
-};
-
-function lcsMatches(
- tokens: NarrativeIR["tokens"],
- units: SpeechTimingEvidence["units"],
-): Array<[number, number]> {
- const rows = Array.from({ length: tokens.length + 1 }, () =>
- Array<number>(units.length + 1).fill(0));
- for (let left = tokens.length - 1; left >= 0; left -= 1) {
- for (let right = units.length - 1; right >= 0; right -= 1) {
- rows[left]![right] = tokens[left]!.normalized === normalizeWord(units[right]!.text)
- ? rows[left + 1]![right + 1]! + 1
- : Math.max(rows[left + 1]![right]!, rows[left]![right + 1]!);
- }
- }
- const matches: Array<[number, number]> = [];
- let left = 0;
- let right = 0;
- while (left < tokens.length && right < units.length) {
- if (
- tokens[left]!.normalized === normalizeWord(units[right]!.text)
- && rows[left]![right] === rows[left + 1]![right + 1]! + 1
- ) {
- matches.push([left, right]);
- left += 1;
- right += 1;
- } else if (rows[left + 1]![right]! >= rows[left]![right + 1]!) {
- left += 1;
- } else {
- right += 1;
- }
- }
- return matches;
-}
-
-function distributeFrames(
- tokens: NarrativeIR["tokens"],
- startFrame: number,
- endFrameExclusive: number,
- quality: TokenFrame["quality"],
-): TokenFrame[] {
- if (!tokens.length) return [];
- const weights = tokens.map((token) => Math.max(1, [...token.normalized].length));
- const total = weights.reduce((sum, weight) => sum + weight, 0);
- let accumulated = 0;
- return tokens.map((_, index) => {
- const start = startFrame + Math.round((endFrameExclusive - startFrame) * accumulated / total);
- accumulated += weights[index]!;
- const end = index === tokens.length - 1
- ? endFrameExclusive
- : startFrame + Math.round((endFrameExclusive - startFrame) * accumulated / total);
- return { startFrame: start, endFrameExclusive: Math.max(start, end), quality };
- });
-}
-
-function alignSegment(
- tokens: NarrativeIR["tokens"],
- units: SpeechTimingEvidence["units"],
- segmentStartFrame: number,
- segmentEndFrame: number,
- basis: ProgramBasis,
- evidenceQuality: SpeechTimingEvidence["quality"],
-): TokenFrame[] {
- const output: Array<TokenFrame | undefined> = Array(tokens.length).fill(undefined);
- const matches = lcsMatches(tokens, units);
- let tokenCursor = 0;
- let unitCursor = 0;
- for (let matchIndex = 0; matchIndex <= matches.length; matchIndex += 1) {
- const match = matches[matchIndex];
- const tokenEnd = match?.[0] ?? tokens.length;
- const unitEnd = match?.[1] ?? units.length;
- const tokenRun = tokens.slice(tokenCursor, tokenEnd);
- const unitRun = units.slice(unitCursor, unitEnd);
- if (tokenRun.length) {
- const previous = tokenCursor > 0 ? output[tokenCursor - 1] : undefined;
- const nextUnit = match ? units[unitEnd] : undefined;
- const startFrame = unitRun.length
- ? frameAt(unitRun[0]!.startSec, basis)
- : previous?.endFrameExclusive ?? segmentStartFrame;
- const endFrame = unitRun.length
- ? frameAt(unitRun.at(-1)!.endSec, basis)
- : nextUnit
- ? frameAt(nextUnit.startSec, basis)
- : segmentEndFrame;
- const quality = evidenceQuality === "estimated" || !unitRun.length
- ? "estimated" as const
- : "derived" as const;
- for (const [offset, value] of distributeFrames(
- tokenRun,
- startFrame,
- Math.max(startFrame, endFrame),
- quality,
- ).entries()) output[tokenCursor + offset] = value;
- }
- if (match) {
- const [tokenIndex, unitIndex] = match;
- const unit = units[unitIndex]!;
- output[tokenIndex] = {
- startFrame: frameAt(unit.startSec, basis),
- endFrameExclusive: frameAt(unit.endSec, basis),
- quality: evidenceQuality === "measured" ? "measured" : "estimated",
- };
- tokenCursor = tokenIndex + 1;
- unitCursor = unitIndex + 1;
- }
- }
- return output.map((value, index) => value
- ?? fail("locator_token_unmapped", `Script token ${index + 1} could not be aligned.`));
-}
-
-export function semanticMapFromTiming(
- narrative: NarrativeIR,
- basis: ProgramBasis,
- evidence: SpeechTimingEvidence,
- options: { locatorDigest?: string; evidenceDigest?: string } = {},
-): CompleteSemanticMap {
- validateProgramBasis(basis);
- validateSpeechTiming(narrative, basis, evidence);
- const segmentEvidence = new Map(evidence.segments.map((segment) => [segment.id, segment]));
- const tokenFrames = new Map<string, TokenFrame>();
- for (const segment of narrative.segments) {
- const measuredSegment = segmentEvidence.get(segment.id)!;
- const tokens = narrative.tokens.slice(segment.tokenStart, segment.tokenEnd);
- const units = evidence.units.filter((unit) => unit.segmentId === segment.id);
- const aligned = alignSegment(
- tokens,
- units,
- frameAt(measuredSegment.startSec, basis),
- frameAt(measuredSegment.endSec, basis),
- basis,
- evidence.quality,
- );
- tokens.forEach((token, index) => tokenFrames.set(token.id, aligned[index]!));
- }
- const anchors: SemanticAnchorPoint[] = narrative.semanticIndex.anchors.map((anchor) => {
- const segment = segmentEvidence.get(anchor.segmentId);
- if (!segment) fail("locator_segment_missing", `Speech timing is missing Segment "${anchor.segmentId}".`);
- const token = anchor.tokenId ? tokenFrames.get(anchor.tokenId) : undefined;
- const frame = anchor.kind === "segment-start"
- ? frameAt(segment.startSec, basis)
- : anchor.kind === "segment-end"
- ? frameAt(segment.endSec, basis)
- : anchor.kind === "token-start"
- ? token?.startFrame
- : token?.endFrameExclusive;
- if (frame === undefined) {
- fail("locator_anchor_missing", `No speech timing exists for anchor "${anchor.id}".`);
- }
- return {
- identity: anchor.id,
- point: { basisDigest: basis.basisDigest, frame },
- quality: token?.quality ?? evidence.quality,
- };
- });
- const payload = {
- contract: "svml.complete-semantic-map.v1" as const,
- semanticIndexDigest: narrative.semanticIndex.digest,
- basisDigest: basis.basisDigest,
- anchors,
- evidenceDigests: [options.evidenceDigest ?? sha256(stableJson(evidence))],
- locatorDigest: options.locatorDigest ?? sha256("svml.script-timing-locator.v1"),
- quantizationPolicy: "nearest-frame" as const,
- };
- const map = { ...payload, mapDigest: semanticMapDigest(payload) };
- validateSemanticMap(narrative, basis, map);
- return map;
-}
-
-export function validateSemanticMap(
- narrative: NarrativeIR,
- basis: ProgramBasis,
- map: SemanticMap,
-): void {
- validateProgramBasis(basis);
- if (
- map.contract !== "svml.complete-semantic-map.v1"
- ) {
- fail("semantic_map_contract", "Unsupported SemanticMap contract.");
- }
- if (map.semanticIndexDigest !== narrative.semanticIndex.digest) {
- fail("semantic_map_index", "SemanticMap was produced for a different SemanticIndex.");
- }
- if (map.basisDigest !== basis.basisDigest) {
- fail("semantic_map_basis", "SemanticMap was produced for a different ProgramBasis.");
- }
- const { mapDigest, ...canonicalMap } = map;
- if (semanticMapDigest(canonicalMap) !== mapDigest) {
- fail("semantic_map_digest", "SemanticMap digest does not match its canonical contents.");
- }
- if (map.anchors.length !== narrative.semanticIndex.anchors.length) {
- fail(
- "semantic_map_cardinality",
- `SemanticMap has ${map.anchors.length} anchors; expected ${narrative.semanticIndex.anchors.length}.`,
- );
- }
- const pointById = new Map<string, number>();
- for (const [index, expected] of narrative.semanticIndex.anchors.entries()) {
- const actual = map.anchors[index];
- if (!actual || actual.identity !== expected.id) {
- fail(
- "semantic_map_identity",
- `SemanticMap anchor ${index + 1} must be "${expected.id}".`,
- );
- }
- integer(actual.point.frame, `SemanticMap point ${actual.identity}`);
- if (
- actual.point.basisDigest !== basis.basisDigest
- || actual.point.frame < 0
- || actual.point.frame > basis.durationFrames
- ) {
- fail("semantic_map_point", `SemanticMap anchor "${actual.identity}" is outside ProgramBasis.`);
- }
- if (!["measured", "derived", "estimated"].includes(actual.quality)) {
- fail("semantic_map_quality", `SemanticMap anchor "${actual.identity}" has invalid quality.`);
- }
- if (pointById.has(actual.identity)) {
- fail("semantic_map_duplicate", `SemanticMap repeats anchor "${actual.identity}".`);
- }
- pointById.set(actual.identity, actual.point.frame);
- }
- for (const segment of narrative.segments) {
- const ordered = [
- segment.startAnchorId,
- ...narrative.tokens.slice(segment.tokenStart, segment.tokenEnd)
- .flatMap((token) => [token.startAnchorId, token.endAnchorId]),
- segment.endAnchorId,
- ];
- for (let index = 1; index < ordered.length; index += 1) {
- if (pointById.get(ordered[index]!)! < pointById.get(ordered[index - 1]!)!) {
- fail("semantic_map_segment_order", `SemanticMap runs backwards inside Segment "${segment.id}".`);
- }
- }
- }
- for (let index = 1; index < narrative.segments.length; index += 1) {
- const previous = narrative.segments[index - 1]!;
- const current = narrative.segments[index]!;
- if (
- pointById.get(current.startAnchorId)! < pointById.get(previous.startAnchorId)!
- || pointById.get(current.endAnchorId)! < pointById.get(previous.endAnchorId)!
- ) {
- fail("semantic_map_source_order", `SemanticMap reorders Segment "${current.id}".`);
- }
- }
-}
-
-export function semanticPoints(map: SemanticMap): ReadonlyMap<string, number> {
- return new Map(map.anchors.map((anchor) => [anchor.identity, anchor.point.frame]));
-}
diff --git a/src/util.ts b/src/util.ts
deleted file mode 100644
index 4eda0aa8..00000000
--- a/src/util.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { createHash } from "node:crypto";
-import { dirname, relative, resolve, sep } from "node:path";
-
-export function sha256(value: string | Uint8Array): string {
- return createHash("sha256").update(value).digest("hex");
-}
-
-export function portableFileIdentity(entryFile: string, targetFile: string): string {
- const path = relative(dirname(resolve(entryFile)), resolve(targetFile))
- .split(sep)
- .join("/");
- return `svml-file:${path.startsWith(".") ? path : `./${path}`}`;
-}
-
-export function normalizeWord(value: string): string {
- return value
- .normalize("NFKC")
- .toLocaleLowerCase("en")
- .replace(/[^\p{L}\p{M}\p{N}]+/gu, "");
-}
-
-export function asNumber(value: unknown, fallback?: number): number {
- if (typeof value === "number" && Number.isFinite(value)) return value;
- if (typeof value === "string" && value.trim() !== "") {
- const parsed = Number(value);
- if (Number.isFinite(parsed)) return parsed;
- }
- if (fallback !== undefined) return fallback;
- throw new Error(`expected finite number, received ${String(value)}`);
-}
-
-export function escapeHtml(value: string): string {
- return value
- .replaceAll("&", "&amp;")
- .replaceAll("<", "&lt;")
- .replaceAll(">", "&gt;")
- .replaceAll('"', "&quot;")
- .replaceAll("'", "&#39;");
-}
-
-export function stableJson(value: unknown): string {
- if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
- if (value && typeof value === "object") {
- const record = value as Record<string, unknown>;
- return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`).join(",")}}`;
- }
- return JSON.stringify(value);
-}
diff --git a/src/views.ts b/src/views.ts
deleted file mode 100644
index 51278874..00000000
--- a/src/views.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import type { Compilation } from "./compiler.js";
-import type { PlanIR } from "./model.js";
-
-export type CanvasView = {
- contract: "svml.canvas-view.v1";
- root: string;
- nodes: Array<
- | {
- id: string;
- identity: string;
- kind: "value";
- valueType: string;
- contentDigest?: string;
- }
- | {
- id: string;
- identity: string;
- kind: "kernel";
- kernel: string;
- executionDigest?: string;
- }
- >;
- edges: PlanIR["edges"];
-};
-
-export type TimelineView = {
- contract: "svml.timeline-view.v1";
- fps: number;
- durationFrames: number;
- words: Compilation["located"]["words"];
- segments: Compilation["located"]["segments"];
- selections: Compilation["located"]["selections"];
- moments: Compilation["located"]["moments"];
- visuals: Compilation["target"]["visuals"];
- audios: Compilation["target"]["audios"];
-};
-
-export function projectCanvas(plan: PlanIR): CanvasView {
- return {
- contract: "svml.canvas-view.v1",
- root: plan.root,
- nodes: [
- ...plan.values.map((value) => ({
- id: value.id,
- identity: value.identity,
- kind: "value" as const,
- valueType: value.type,
- ...(value.contentDigest ? { contentDigest: value.contentDigest } : {}),
- })),
- ...plan.instances.map((instance) => ({
- id: instance.id,
- identity: instance.identity,
- kind: "kernel" as const,
- kernel: instance.kernel,
- ...(instance.executionDigest
- ? { executionDigest: instance.executionDigest }
- : {}),
- })),
- ],
- edges: plan.edges,
- };
-}
-
-export function projectTimeline(compilation: Compilation): TimelineView {
- return {
- contract: "svml.timeline-view.v1",
- fps: compilation.located.fps,
- durationFrames: compilation.located.durationFrames,
- words: compilation.located.words,
- segments: compilation.located.segments,
- selections: compilation.located.selections,
- moments: compilation.located.moments,
- visuals: compilation.target.visuals,
- audios: compilation.target.audios,
- };
-}
diff --git a/stdlib/audio-track.svk b/stdlib/audio-track.svk
deleted file mode 100644
index 4eebf238..00000000
--- a/stdlib/audio-track.svk
+++ /dev/null
@@ -1,15 +0,0 @@
-<kernel name="audio-track" abi="1" implementation="./runtime/audio-track.mjs">
- <port name="item" direction="input" type="AudioItem" cardinality="one-or-more"/>
- <port name="track" direction="output" type="Track" cardinality="one"/>
- <child name="item" cardinality="one-or-more">
- <field name="id" type="id" required="true"/>
- <field name="source" type="Audio" required="true"/>
- <field name="during" type="SelectionSet|ProgramSpan" consume="each"/>
- <field name="at" type="MomentSet|ProgramPoint" consume="each"/>
- <field name="duration" type="string"/>
- <field name="volume" type="number"/>
- <field name="fadeIn" type="number"/>
- <field name="fadeOut" type="number"/>
- <field name="bus" type="string"/>
- </child>
-</kernel>
diff --git a/stdlib/broll-track.svk b/stdlib/broll-track.svk
deleted file mode 100644
index f15c0bf8..00000000
--- a/stdlib/broll-track.svk
+++ /dev/null
@@ -1,56 +0,0 @@
-<kernel name="broll-track" abi="1" implementation="./runtime/broll-track.mjs">
- <param name="z" type="number"/>
- <port name="item" direction="input" type="BrollItem" cardinality="one-or-more"/>
- <port name="track" direction="output" type="Track" cardinality="one"/>
- <child name="item" cardinality="one-or-more">
- <field name="id" type="id" required="true"/>
- <field name="source" type="Image|Video|ProgramBoundImage|ProgramBoundVideo" required="true"/>
- <field name="during" type="SelectionSet|ProgramSpan" consume="each"/>
- <field name="window" type="string"/>
- <field name="playback" type="string"/>
- <field name="mediaStart" type="number"/>
- <field name="sourceDuration" type="number"/>
- <field name="kind" type="string"/>
- <field name="zoom" type="number"/>
- <field name="audio" type="boolean|string"/>
- <field name="volume" type="number"/>
- <field name="x" type="number"/>
- <field name="y" type="number"/>
- <field name="width" type="number"/>
- <field name="height" type="number"/>
- <field name="fit" type="string"/>
- <field name="position" type="string"/>
- <field name="shape" style="mask" type="string"/>
- <field name="radius" type="number"/>
- <field name="opacity" type="number"/>
- <field name="background" type="string"/>
- <field name="z" type="number"/>
- <child name="present" cardinality="zero-or-more">
- <field name="id" type="id" required="true"/>
- <field name="during" type="SelectionSet|ProgramSpan" consume="each"/>
- <field name="window" type="string"/>
- <field name="z" type="number"/>
- <field name="x" type="number"/>
- <field name="y" type="number"/>
- <field name="width" type="number"/>
- <field name="height" type="number"/>
- <field name="fit" type="string"/>
- <field name="position" type="string"/>
- <field name="shape" style="mask" type="string"/>
- <field name="radius" type="number"/>
- <field name="opacity" type="number"/>
- <field name="background" type="string"/>
- <field name="enter" type="string"/>
- <field name="exit" type="string"/>
- </child>
- </child>
- <child name="transition" cardinality="zero-or-more">
- <field name="from" type="id" required="true"/>
- <field name="to" type="id" required="true"/>
- <field name="kind" type="string"/>
- <field name="duration" type="string"/>
- <field name="cuePositionRatio" type="number"/>
- <field name="sound" type="Audio"/>
- <field name="volume" type="number"/>
- </child>
-</kernel>
diff --git a/stdlib/caption-planner.svk b/stdlib/caption-planner.svk
deleted file mode 100644
index 934cb4b5..00000000
--- a/stdlib/caption-planner.svk
+++ /dev/null
@@ -1,13 +0,0 @@
-<kernel name="caption-planner" abi="1" implementation="./runtime/caption-planner.mjs">
- <param name="maxWords" style="max-words" type="number" default="3"/>
- <port name="script" direction="input" type="NarrativeIR" cardinality="one"/>
- <port name="semantic" direction="input" type="CompleteSemanticMap" cardinality="one"/>
- <port name="plan" direction="output" type="CaptionPlan" cardinality="one"/>
- <child name="annotate" cardinality="zero-or-more">
- <field name="id" type="id" required="true"/>
- <field name="kind" type="string" required="true"/>
- <field name="value" type="string"/>
- <field name="during" type="SelectionSet|ProgramSpan" consume="set"/>
- <field name="role" type="string"/>
- </child>
-</kernel>
diff --git a/stdlib/caption-track.svk b/stdlib/caption-track.svk
deleted file mode 100644
index 2af1e667..00000000
--- a/stdlib/caption-track.svk
+++ /dev/null
@@ -1,38 +0,0 @@
-<kernel name="caption-track" abi="1" implementation="./runtime/caption-track.mjs">
- <param name="z" type="number"/>
- <param name="x" type="number" default="0.37"/>
- <param name="y" type="number" default="0.54"/>
- <param name="width" type="number" default="0.64"/>
- <param name="hold" type="number" default="0.08"/>
- <param name="cueFade" style="cue-fade" type="number" default="0.12"/>
- <param name="font" style="font-family" type="string" default="Poppins, Inter, Arial, sans-serif"/>
- <param name="size" style="font-size" type="number" default="50"/>
- <param name="weight" style="font-weight" type="number" default="800"/>
- <param name="tracking" style="letter-spacing" type="number" default="-1"/>
- <param name="color" style="fill" type="string" default="#ffffff"/>
- <param name="highlight" type="string" default="#ffd34d"/>
- <param name="strokeWidth" style="stroke-width" type="number" default="0.002"/>
- <param name="strokeColor" style="stroke-color" type="string" default="rgba(0,0,0,.82)"/>
- <param name="shadow" type="string" default="0 2px 9px rgba(0,0,0,.5), 0 0 2px rgba(0,0,0,.68)"/>
- <port name="script" direction="input" type="NarrativeIR" cardinality="one"/>
- <port name="semantic" direction="input" type="CompleteSemanticMap" cardinality="one"/>
- <port name="plan" direction="input" type="CaptionPlan" cardinality="one"/>
- <port name="track" direction="output" type="CaptionTrack" cardinality="one"/>
- <child name="style" cardinality="zero-or-more">
- <field name="id" type="id" required="true"/>
- <field name="during" type="SelectionSet|ProgramSpan" consume="set"/>
- <field name="role" type="string"/>
- <field name="annotation" type="string"/>
- <field name="color" style="fill" type="string"/>
- <field name="activeColor" style="active-fill" type="string"/>
- <field name="background" type="string"/>
- <field name="weight" type="number"/>
- <field name="scale" type="number"/>
- </child>
- <child name="mute" cardinality="zero-or-more">
- <field name="id" type="id" required="true"/>
- <field name="during" type="SelectionSet|ProgramSpan" consume="set"/>
- <field name="role" type="string"/>
- <field name="annotation" type="string"/>
- </child>
-</kernel>
diff --git a/stdlib/film.svk b/stdlib/film.svk
deleted file mode 100644
index 9c36f6ff..00000000
--- a/stdlib/film.svk
+++ /dev/null
@@ -1,13 +0,0 @@
-<kernel name="film" abi="1" root="true" implementation="./runtime/film.mjs">
- <param name="width" type="number"/>
- <param name="height" type="number"/>
- <param name="fps" style="frame-rate" type="number"/>
- <param name="background" type="string" default="#000000"/>
- <port name="basis" direction="input" type="TemporalBasisProduction" cardinality="one"/>
- <port name="semantic" direction="input" type="CompleteSemanticMap" cardinality="one"/>
- <port name="track" direction="input" type="Track|CaptionTrack" cardinality="zero-or-more"/>
- <port name="document" direction="output" type="HyperframesDocument" cardinality="one"/>
- <child name="track" cardinality="zero-or-more">
- <field name="ref" type="Track|CaptionTrack" required="true"/>
- </child>
-</kernel>
diff --git a/stdlib/media-basis.svk b/stdlib/media-basis.svk
deleted file mode 100644
index 3a415a82..00000000
--- a/stdlib/media-basis.svk
+++ /dev/null
@@ -1,9 +0,0 @@
-<kernel name="media-basis" abi="1" implementation="./runtime/media-basis.mjs">
- <param name="fps" type="number" default="30"/>
- <param name="duration" type="duration"/>
- <param name="sourceStart" type="duration" default="0ms"/>
- <port name="audio" direction="input" type="Audio" cardinality="one"/>
- <port name="visual" direction="input" type="Video" cardinality="zero-or-one"/>
- <port name="production" direction="output" type="TemporalBasisProduction" cardinality="one"/>
- <port name="facets.visual" direction="output" type="ProgramBoundVideo" cardinality="zero-or-one"/>
-</kernel>
diff --git a/stdlib/media-track.svk b/stdlib/media-track.svk
deleted file mode 100644
index b32a5a17..00000000
--- a/stdlib/media-track.svk
+++ /dev/null
@@ -1,43 +0,0 @@
-<kernel name="media-track" abi="1" implementation="./runtime/media-track.mjs">
- <param name="z" type="number"/>
- <port name="item" direction="input" type="MediaItem" cardinality="one-or-more"/>
- <port name="track" direction="output" type="Track" cardinality="one"/>
- <child name="item" cardinality="one-or-more">
- <field name="id" type="id" required="true"/>
- <field name="source" type="Image|Video|ProgramBoundImage|ProgramBoundVideo|ProgramBoundVideoSequence" required="true"/>
- <field name="during" type="SelectionSet|ProgramSpan" consume="each"/>
- <field name="window" type="string"/>
- <field name="playback" type="string"/>
- <field name="mediaStart" type="number"/>
- <field name="sourceDuration" type="number"/>
- <field name="x" type="number"/>
- <field name="y" type="number"/>
- <field name="width" type="number"/>
- <field name="height" type="number"/>
- <field name="fit" type="string"/>
- <field name="position" type="string"/>
- <field name="shape" style="mask" type="string"/>
- <field name="radius" type="number"/>
- <field name="opacity" type="number"/>
- <field name="background" type="string"/>
- <field name="z" type="number"/>
- <child name="present" cardinality="zero-or-more">
- <field name="id" type="id" required="true"/>
- <field name="during" type="SelectionSet|ProgramSpan" consume="each"/>
- <field name="window" type="string"/>
- <field name="z" type="number"/>
- <field name="x" type="number"/>
- <field name="y" type="number"/>
- <field name="width" type="number"/>
- <field name="height" type="number"/>
- <field name="fit" type="string"/>
- <field name="position" type="string"/>
- <field name="shape" style="mask" type="string"/>
- <field name="radius" type="number"/>
- <field name="opacity" type="number"/>
- <field name="background" type="string"/>
- <field name="enter" type="string"/>
- <field name="exit" type="string"/>
- </child>
- </child>
-</kernel>
diff --git a/stdlib/ranking-column.svk b/stdlib/ranking-column.svk
deleted file mode 100644
index dc528c42..00000000
--- a/stdlib/ranking-column.svk
+++ /dev/null
@@ -1,25 +0,0 @@
-<kernel name="ranking-column" abi="1" implementation="./runtime/ranking-column.mjs">
- <param name="z" type="number"/>
- <param name="x" type="number" default="0"/>
- <param name="y" type="number" default="0.17"/>
- <param name="width" type="number" default="0.305"/>
- <param name="rowHeight" style="row-height" type="number" default="0.071"/>
- <param name="gap" type="number" default="0.011"/>
- <param name="stageX" style="stage-x" type="number" default="0.66"/>
- <param name="stageY" style="stage-y" type="number" default="0.73"/>
- <param name="stageSize" style="stage-size" type="number" default="0.33"/>
- <param name="appearGain" style="appear-gain" type="number" default="0.09"/>
- <param name="moveGain" style="move-gain" type="number" default="0.1"/>
- <port name="appearSound" direction="input" type="Audio" cardinality="zero-or-one"/>
- <port name="moveSound" direction="input" type="Audio" cardinality="zero-or-one"/>
- <port name="at" direction="input" type="MomentSet|ProgramPoint" cardinality="zero-or-one" consume="one"/>
- <port name="item" direction="input" type="RankingItem" cardinality="one-or-more"/>
- <port name="track" direction="output" type="Track" cardinality="one"/>
- <child name="item" cardinality="one-or-more">
- <field name="id" type="id" required="true"/>
- <field name="rank" type="number" required="true"/>
- <field name="image" type="Image" required="true"/>
- <field name="during" type="SelectionSet" consume="one" required="true"/>
- <field name="window" type="string"/>
- </child>
-</kernel>
diff --git a/stdlib/runtime/audio-track.mjs b/stdlib/runtime/audio-track.mjs
deleted file mode 100644
index 565e4e74..00000000
--- a/stdlib/runtime/audio-track.mjs
+++ /dev/null
@@ -1,48 +0,0 @@
-import {
- durationSeconds,
- elements,
- material,
- numberAttr,
- resolveAttr,
- stringAttr,
- trackOutput,
-} from "./helpers.mjs";
-
-export default {
- abiVersion: "1",
- project(context) {
- const audios = [];
- for (const item of elements(context, "item")) {
- const id = stringAttr(item, "id");
- const source = material(resolveAttr(context, item, "source"), "audio");
- const ranges = item.attributes.at
- ? context.moment(item.attributes.at, "item.at").map((startFrame) => {
- const durationFrames = Math.max(
- 1,
- Math.round(durationSeconds(stringAttr(item, "duration")) * context.fps),
- );
- return {
- startFrame,
- endFrameExclusive: Math.min(
- context.program.durationFrames,
- startFrame + durationFrames,
- ),
- };
- })
- : context.selection(item.attributes.during ?? "full", "item.during");
- for (const [index, range] of ranges.entries()) {
- audios.push({
- id: `${context.instance.id}:${id}:${index}`,
- source: source.source,
- startFrame: range.startFrame,
- endFrameExclusive: range.endFrameExclusive,
- volume: numberAttr(item, "volume", 1),
- fadeInSec: numberAttr(item, "fadeIn", 0),
- fadeOutSec: numberAttr(item, "fadeOut", 0),
- bus: stringAttr(item, "bus", "music"),
- });
- }
- }
- return trackOutput([], audios);
- },
-};
diff --git a/stdlib/runtime/broll-track.mjs b/stdlib/runtime/broll-track.mjs
deleted file mode 100644
index 4e2c50dc..00000000
--- a/stdlib/runtime/broll-track.mjs
+++ /dev/null
@@ -1,193 +0,0 @@
-import {
- durationSeconds,
- elements,
- material,
- mediaTiming,
- numberAttr,
- presentationAnimation,
- presentationStyle,
- resolveItemPresentations,
- resolveAttr,
- stringAttr,
- trackOutput,
-} from "./helpers.mjs";
-
-function appendAnimation(fragment, name, duration) {
- fragment.style.animation = [
- fragment.style.animation,
- `${name} ${duration}s linear both`,
- ].filter(Boolean).join(", ");
-}
-
-export default {
- abiVersion: "1",
- project(context) {
- const z = numberAttr(context.element, "z");
- const visuals = [];
- const audios = [];
- const itemVisuals = new Map();
- const transitionOpacity = new Map();
- for (const item of elements(context, "item")) {
- const id = stringAttr(item, "id");
- const source = material(resolveAttr(context, item, "source"));
- const expectedKind = stringAttr(item, "kind", source.type === "Video" ? "video" : "image");
- if (String(source.type).toLowerCase() !== expectedKind.toLowerCase()) {
- throw new Error(`broll item "${id}" expected ${expectedKind}, received ${source.type}`);
- }
- const presentations = resolveItemPresentations(context, item, source, z);
- for (const [index, presentation] of presentations.entries()) {
- const range = presentation.range;
- const zoom = numberAttr(item, "zoom", 1);
- const keyframes = `svml-broll-${context.instance.id}-${id}-${index}`.replaceAll(/[^A-Za-z0-9_-]/gu, "-");
- const animation = presentationAnimation(
- presentation.element,
- range,
- context.fps,
- `${context.instance.id}-${id}-${presentation.id}-${index}`,
- );
- const duration = (range.endFrameExclusive - range.startFrame) / context.fps;
- const timing = source.type === "Video"
- ? mediaTiming(item, presentation, source, context.fps)
- : {};
- const fragment = {
- id: `${context.instance.id}:${id}:${index}`,
- kind: source.type === "Video" ? "video" : "image",
- source: source.source,
- startFrame: range.startFrame,
- endFrameExclusive: range.endFrameExclusive,
- z: presentation.z,
- // HyperFrames receives source audio as an explicit sibling contribution.
- // Keep the visual element muted so one source can never play twice.
- muted: true,
- ...timing,
- style: {
- ...presentationStyle(presentation.element, item, { fit: "contain" }),
- "transform-origin": "50% 50%",
- animation: [
- `${keyframes} ${duration}s ease-in-out both`,
- animation.animation,
- ].filter(Boolean).join(", "),
- },
- css: [
- `@keyframes ${keyframes} { from { transform: scale(1); } to { transform: scale(${zoom}); } }`,
- animation.css,
- ].filter(Boolean).join("\n"),
- };
- visuals.push(fragment);
- const values = itemVisuals.get(id) ?? [];
- values.push(fragment);
- itemVisuals.set(id, values);
- }
- if (source.type === "Video" && (item.attributes.audio === true || item.attributes.audio === "source")) {
- const parents = new Map(presentations.map((presentation) => [
- presentation.parentIndex,
- presentation.parentRange,
- ]));
- for (const [parentIndex, range] of parents) {
- const timing = mediaTiming(item, { parentRange: range, range }, source, context.fps);
- audios.push({
- id: `${context.instance.id}:${id}:${parentIndex}:audio`,
- source: source.source,
- startFrame: range.startFrame,
- endFrameExclusive: range.endFrameExclusive,
- mediaStartSec: timing.mediaStartSec,
- playbackRate: timing.playbackRate,
- volume: numberAttr(item, "volume", 1),
- bus: "source",
- });
- }
- }
- }
- const occupiedWindows = [];
- for (const [transitionIndex, transition] of elements(context, "transition").entries()) {
- const from = stringAttr(transition, "from");
- const to = stringAttr(transition, "to");
- const kind = stringAttr(transition, "kind", "crossfade");
- if (!["cut", "crossfade"].includes(kind)) {
- throw new Error(`broll transition "${kind}" is not available in projector ABI v1`);
- }
- const outgoingValues = itemVisuals.get(from) ?? [];
- const incomingValues = itemVisuals.get(to) ?? [];
- if (outgoingValues.length !== 1 || incomingValues.length !== 1) {
- throw new Error(`broll transition ${from} -> ${to} requires one resolved visual per item`);
- }
- if (kind === "cut") continue;
- const outgoing = outgoingValues[0];
- const incoming = incomingValues[0];
- const durationFrames = Math.max(
- 1,
- Math.round(durationSeconds(stringAttr(transition, "duration")) * context.fps),
- );
- const cueRatio = numberAttr(transition, "cuePositionRatio", 0);
- if (cueRatio < 0 || cueRatio > 1) {
- throw new Error(`broll transition cuePositionRatio must be between 0 and 1`);
- }
- const cue = incoming.startFrame;
- const startFrame = cue - Math.floor(durationFrames * cueRatio);
- const endFrameExclusive = startFrame + durationFrames;
- if (startFrame < 0 || endFrameExclusive > context.program.durationFrames) {
- throw new Error(`broll transition ${from} -> ${to} leaves the master timeline`);
- }
- if (occupiedWindows.some((window) =>
- startFrame < window.endFrameExclusive && endFrameExclusive > window.startFrame)) {
- throw new Error(`broll transition ${from} -> ${to} overlaps another transition`);
- }
- occupiedWindows.push({ startFrame, endFrameExclusive });
- outgoing.endFrameExclusive = Math.max(outgoing.endFrameExclusive, endFrameExclusive);
- incoming.startFrame = Math.min(incoming.startFrame, startFrame);
- if (incoming.mediaStartSec !== undefined && startFrame < cue) {
- incoming.mediaStartSec = Math.max(
- 0,
- incoming.mediaStartSec - (cue - startFrame) / context.fps,
- );
- }
- const outgoingState = transitionOpacity.get(outgoing) ?? {};
- const incomingState = transitionOpacity.get(incoming) ?? {};
- if (outgoingState.out || incomingState.in) {
- throw new Error(`broll transition repeats an item edge`);
- }
- outgoingState.out = { startFrame, endFrameExclusive };
- incomingState.in = { startFrame, endFrameExclusive };
- transitionOpacity.set(outgoing, outgoingState);
- transitionOpacity.set(incoming, incomingState);
- if (transition.attributes.sound) {
- const sound = material(resolveAttr(context, transition, "sound"), "audio");
- audios.push({
- id: `${context.instance.id}:transition:${transitionIndex}`,
- source: sound.source,
- startFrame,
- endFrameExclusive,
- volume: numberAttr(transition, "volume", 1),
- bus: "sfx",
- });
- }
- }
- for (const [fragment, state] of transitionOpacity) {
- const totalFrames = fragment.endFrameExclusive - fragment.startFrame;
- const points = new Map();
- points.set(0, state.in ? 0 : 1);
- points.set(100, state.out ? 0 : 1);
- if (state.in) {
- points.set((state.in.startFrame - fragment.startFrame) / totalFrames * 100, 0);
- points.set((state.in.endFrameExclusive - fragment.startFrame) / totalFrames * 100, 1);
- }
- if (state.out) {
- points.set((state.out.startFrame - fragment.startFrame) / totalFrames * 100, 1);
- points.set((state.out.endFrameExclusive - fragment.startFrame) / totalFrames * 100, 0);
- }
- const ordered = [...points].sort((left, right) => left[0] - right[0]);
- for (let index = 1; index < ordered.length; index += 1) {
- if (ordered[index][0] < ordered[index - 1][0]) {
- throw new Error(`broll transition windows are not monotonic`);
- }
- }
- const name = `svml-broll-transition-${fragment.id}`.replaceAll(/[^A-Za-z0-9_-]/gu, "-");
- fragment.css = `${fragment.css ?? ""}
-@keyframes ${name} {
-${ordered.map(([percent, opacity]) => `${percent}% { opacity:${opacity}; }`).join("\n")}
-}`;
- appendAnimation(fragment, name, totalFrames / context.fps);
- }
- return trackOutput(visuals, audios);
- },
-};
diff --git a/stdlib/runtime/caption-planner.mjs b/stdlib/runtime/caption-planner.mjs
deleted file mode 100644
index 0fb78dbb..00000000
--- a/stdlib/runtime/caption-planner.mjs
+++ /dev/null
@@ -1,95 +0,0 @@
-import { elements, numberAttr, stringAttr } from "./helpers.mjs";
-
-function fail(message) {
- throw new Error(message);
-}
-
-export default {
- abiVersion: "1",
- project(context) {
- const script = context.resolve(context.element.attributes.script);
- const semantic = context.resolve(context.element.attributes.semantic);
- if (!script?.semanticIndex) fail("caption-planner requires NarrativeIR");
- if (semantic?.contract !== "svml.complete-semantic-map.v1") {
- fail("caption-planner requires CompleteSemanticMap");
- }
- if (semantic.semanticIndexDigest !== script.semanticIndex.digest) {
- fail("caption-planner SemanticMap does not match Script");
- }
- const points = new Map(semantic.anchors.map(anchor => [anchor.identity, anchor.point.frame]));
- const words = script.tokens.map(token => ({
- ...token,
- startFrame: points.get(token.startAnchorId),
- endFrameExclusive: points.get(token.endAnchorId),
- }));
- const maxWords = Math.max(1, Math.round(numberAttr(context.element, "maxWords", 3)));
- const atomsByStart = new Map(script.captionAtoms.map(atom => [atom.startToken, atom]));
- const cues = [];
- for (const segment of script.segments) {
- const units = [];
- let token = segment.tokenStart;
- while (token < segment.tokenEnd) {
- const atom = atomsByStart.get(token);
- if (atom) {
- units.push({ startToken: atom.startToken, endTokenExclusive: atom.endTokenExclusive });
- token = atom.endTokenExclusive;
- } else {
- units.push({ startToken: token, endTokenExclusive: token + 1 });
- token += 1;
- }
- }
- for (let index = 0; index < units.length; index += maxWords) {
- const group = units.slice(index, index + maxWords);
- cues.push({
- id: `cue-${cues.length + 1}`,
- startToken: group[0].startToken,
- endTokenExclusive: group.at(-1).endTokenExclusive,
- });
- }
- }
- const frameRangesForRole = role => script.turns
- .filter(turn => turn.role === role)
- .map(turn => ({
- startFrame: words[turn.tokenStart]?.startFrame,
- endFrameExclusive: words[turn.tokenEndExclusive - 1]?.endFrameExclusive,
- }))
- .filter(range => Number.isInteger(range.startFrame) && Number.isInteger(range.endFrameExclusive));
- const annotations = [];
- for (const item of elements(context, "annotate")) {
- const role = item.attributes.role;
- const during = item.attributes.during;
- if ((role === undefined) === (during === undefined)) {
- fail(`<annotate id="${stringAttr(item, "id")}"> requires exactly one of role or during`);
- }
- const ranges = role !== undefined
- ? frameRangesForRole(stringAttr(item, "role"))
- : context.selection(during, "annotate.during");
- for (const [occurrence, range] of ranges.entries()) {
- const selected = words.filter(word =>
- word.startFrame < range.endFrameExclusive
- && word.endFrameExclusive > range.startFrame);
- if (!selected.length) continue;
- annotations.push({
- id: `${stringAttr(item, "id")}:${occurrence + 1}`,
- kind: stringAttr(item, "kind"),
- startToken: selected[0].index,
- endTokenExclusive: selected.at(-1).index + 1,
- ...(typeof item.attributes.value === "string" ? { value: item.attributes.value } : {}),
- });
- }
- }
- const plannerDigest = context.digest({
- implementation: context.instance.executionDigest,
- maxWords,
- });
- const payload = {
- contract: "svml.caption-plan.v1",
- semanticIndexDigest: script.semanticIndex.digest,
- basisDigest: semantic.basisDigest,
- cues,
- annotations,
- plannerDigest,
- };
- return { outputs: { plan: { ...payload, planDigest: context.digest(payload) } } };
- },
-};
diff --git a/stdlib/runtime/caption-track.mjs b/stdlib/runtime/caption-track.mjs
deleted file mode 100644
index d140dc6b..00000000
--- a/stdlib/runtime/caption-track.mjs
+++ /dev/null
@@ -1,230 +0,0 @@
-import { elements, html, numberAttr, stringAttr, trackOutput } from "./helpers.mjs";
-
-function fail(message) {
- throw new Error(message);
-}
-
-export default {
- abiVersion: "1",
- project(context) {
- const script = context.resolve(context.element.attributes.script);
- const semantic = context.resolve(context.element.attributes.semantic);
- const plan = context.resolve(context.element.attributes.plan);
- if (semantic?.contract !== "svml.complete-semantic-map.v1") {
- fail("caption-track requires CompleteSemanticMap");
- }
- if (plan?.contract !== "svml.caption-plan.v1") fail("caption-track requires CaptionPlan");
- if (
- semantic.basisDigest !== context.program.basisDigest
- || plan.basisDigest !== semantic.basisDigest
- || plan.semanticIndexDigest !== script.semanticIndex.digest
- ) fail("caption-track inputs do not share one Script and ProgramBasis");
- if (!Array.isArray(plan.cues) || !Array.isArray(plan.annotations)) {
- fail("CaptionPlan requires cues and annotations arrays");
- }
- const { planDigest, ...canonicalPlan } = plan;
- if (context.digest(canonicalPlan) !== planDigest) fail("CaptionPlan digest does not match its contents");
- for (const [index, annotation] of plan.annotations.entries()) {
- if (
- typeof annotation.id !== "string"
- || typeof annotation.kind !== "string"
- || !Number.isInteger(annotation.startToken)
- || !Number.isInteger(annotation.endTokenExclusive)
- || annotation.startToken < 0
- || annotation.endTokenExclusive <= annotation.startToken
- || annotation.endTokenExclusive > script.tokens.length
- ) fail(`CaptionPlan annotation ${index + 1} has an invalid Script token range`);
- }
- const points = new Map(semantic.anchors.map(anchor => [anchor.identity, anchor.point.frame]));
- const frameRange = (startFrame, endFrameExclusive) => ({
- startFrame,
- endFrameExclusive,
- startSec: startFrame / context.fps,
- endSec: endFrameExclusive / context.fps,
- });
- const words = script.tokens.map(token => ({
- ...token,
- ...frameRange(points.get(token.startAnchorId), points.get(token.endAnchorId)),
- }));
- const captionAtoms = script.captionAtoms.map(atom => ({
- ...atom,
- ...frameRange(
- words[atom.startToken].startFrame,
- words[atom.endTokenExclusive - 1].endFrameExclusive,
- ),
- }));
- const roleRanges = role => script.turns
- .filter(turn => turn.role === role)
- .map(turn => frameRange(
- words[turn.tokenStart].startFrame,
- words[turn.tokenEndExclusive - 1].endFrameExclusive,
- ));
- const annotationRanges = kind => plan.annotations
- .filter(annotation => annotation.kind === kind)
- .map(annotation => frameRange(
- words[annotation.startToken].startFrame,
- words[annotation.endTokenExclusive - 1].endFrameExclusive,
- ));
- const selectorRanges = (element, label, globalAllowed) => {
- const selectors = ["during", "role", "annotation"]
- .filter(name => element.attributes[name] !== undefined);
- if (selectors.length > 1 || (!globalAllowed && selectors.length !== 1)) {
- fail(`<${label} id="${stringAttr(element, "id")}"> requires ${globalAllowed ? "at most" : "exactly"} one selector`);
- }
- if (!selectors.length) return [frameRange(0, context.program.durationFrames)];
- if (selectors[0] === "during") {
- return context.selection(element.attributes.during, `${label}.during`);
- }
- if (selectors[0] === "role") return roleRanges(stringAttr(element, "role"));
- return annotationRanges(stringAttr(element, "annotation"));
- };
- const styledRanges = elements(context, "style").map(style => ({
- id: stringAttr(style, "id"),
- ranges: selectorRanges(style, "style", true),
- color: style.attributes.color,
- activeColor: style.attributes.activeColor,
- background: style.attributes.background,
- weight: style.attributes.weight,
- scale: style.attributes.scale,
- }));
- const mutedRanges = elements(context, "mute")
- .flatMap(mute => selectorRanges(mute, "mute", false));
- const overlaps = (unit, range) =>
- unit.startFrame < range.endFrameExclusive
- && unit.endFrameExclusive > range.startFrame;
- const inlineStyle = (word, active) => {
- const declarations = {};
- for (const rule of styledRanges) {
- if (!rule.ranges.some(range => overlaps(word, range))) continue;
- if (typeof rule.color === "string") declarations.color = rule.color;
- if (active && typeof rule.activeColor === "string") declarations.color = rule.activeColor;
- if (typeof rule.background === "string") declarations.background = rule.background;
- if (typeof rule.weight === "number") declarations["font-weight"] = rule.weight;
- if (typeof rule.scale === "number") declarations.transform = `scale(${rule.scale})`;
- }
- const body = Object.entries(declarations)
- .map(([name, value]) => `${name}:${String(value)}`).join(";");
- return body ? ` style="${html(body)}"` : "";
- };
- const atomsByStart = new Map(captionAtoms.map(atom => [atom.startToken, atom]));
- const displayUnits = (startToken, endTokenExclusive) => {
- const units = [];
- let index = startToken;
- while (index < endTokenExclusive) {
- const atom = atomsByStart.get(index);
- if (atom) {
- if (atom.endTokenExclusive > endTokenExclusive) {
- fail(`caption cue cuts through Dual Text atom "${atom.id}"`);
- }
- if (atom.display && !mutedRanges.some(range => overlaps(atom, range))) {
- units.push({
- text: atom.display,
- startFrame: atom.startFrame,
- endFrameExclusive: atom.endFrameExclusive,
- });
- }
- index = atom.endTokenExclusive;
- continue;
- }
- const word = words[index];
- if (word && !mutedRanges.some(range => overlaps(word, range))) units.push(word);
- index += 1;
- }
- return units;
- };
- let expectedStart = 0;
- const groups = plan.cues.map((cue, index) => {
- if (
- !Number.isInteger(cue.startToken)
- || !Number.isInteger(cue.endTokenExclusive)
- || cue.startToken !== expectedStart
- || cue.endTokenExclusive <= cue.startToken
- || cue.endTokenExclusive > words.length
- ) fail(`CaptionPlan cue ${index + 1} is not a complete ordered token partition`);
- const first = words[cue.startToken];
- const last = words[cue.endTokenExclusive - 1];
- if (first.segmentId !== last.segmentId) fail(`CaptionPlan cue ${index + 1} crosses Segments`);
- expectedStart = cue.endTokenExclusive;
- return { cue, words: displayUnits(cue.startToken, cue.endTokenExclusive) };
- }).filter(entry => entry.words.length);
- if (expectedStart !== words.length) fail("CaptionPlan does not cover every Script token");
- const visuals = [];
- const z = numberAttr(context.element, "z");
- for (const [groupIndex, entry] of groups.entries()) {
- const group = entry.words;
- const nextCueStart = groups[groupIndex + 1]?.words[0]?.startFrame;
- for (const [activeIndex, word] of group.entries()) {
- const next = group[activeIndex + 1];
- const endFrameExclusive = next?.startFrame
- ?? Math.min(
- context.program.durationFrames,
- nextCueStart ?? context.program.durationFrames,
- word.endFrameExclusive + Math.round(numberAttr(context.element, "hold", 0.08) * context.fps),
- );
- if (endFrameExclusive <= word.startFrame) continue;
- const body = group.map((item, index) => {
- const active = index === activeIndex;
- return `<span class="${active ? "active" : ""}"${inlineStyle(item, active)}>${html(item.text)}</span>`;
- }).join("");
- const fragmentDuration = Math.max(1 / context.fps, (endFrameExclusive - word.startFrame) / context.fps);
- const fadeSec = Math.min(numberAttr(context.element, "cueFade", 0.12), fragmentDuration * 0.45);
- const fadePercent = Math.min(45, fadeSec / fragmentDuration * 100);
- const animationName = `svml-caption-${context.instance.id}-${groupIndex}-${activeIndex}`
- .replaceAll(/[^A-Za-z0-9_-]/gu, "-");
- const first = activeIndex === 0;
- const last = activeIndex === group.length - 1;
- const opacityKeyframes = first && last
- ? `0% { opacity:0; } ${fadePercent}% { opacity:1; } ${100 - fadePercent}% { opacity:1; } 100% { opacity:0; }`
- : first
- ? `0% { opacity:0; } ${fadePercent}% { opacity:1; } 100% { opacity:1; }`
- : last
- ? `0% { opacity:1; } ${100 - fadePercent}% { opacity:1; } 100% { opacity:0; }`
- : "0%, 100% { opacity:1; }";
- visuals.push({
- id: `${context.instance.id}:g${groupIndex}:w${activeIndex}`,
- kind: "html",
- startFrame: word.startFrame,
- endFrameExclusive,
- z,
- html: `<div class="svml-caption-line">${body}</div>`,
- style: {
- left: `${numberAttr(context.element, "x", 0.37) * 100}%`,
- top: `${numberAttr(context.element, "y", 0.54) * 100}%`,
- width: `${numberAttr(context.element, "width", 0.64) * 100}%`,
- height: "auto",
- color: stringAttr(context.element, "color", "#ffffff"),
- "font-family": stringAttr(context.element, "font", "Poppins, Inter, Arial, sans-serif"),
- "font-size": `${numberAttr(context.element, "size", 50)}px`,
- "font-weight": numberAttr(context.element, "weight", 800),
- "line-height": 1.15,
- "letter-spacing": `${numberAttr(context.element, "tracking", -1)}px`,
- "text-align": "center",
- "-webkit-text-stroke": `${context.width * numberAttr(context.element, "strokeWidth", 0.002)}px ${stringAttr(context.element, "strokeColor", "rgba(0,0,0,.82)")}`,
- "paint-order": "stroke fill",
- "text-shadow": stringAttr(context.element, "shadow", "0 2px 9px rgba(0,0,0,.5), 0 0 2px rgba(0,0,0,.68)"),
- animation: `${animationName} ${fragmentDuration}s linear both`,
- },
- css: `@keyframes ${animationName} { ${opacityKeyframes} }`,
- });
- }
- }
- const highlight = stringAttr(context.element, "highlight", "#ffd34d");
- const fontSize = numberAttr(context.element, "size", 50);
- const gap = Math.max(12, Math.round(fontSize * (0.34 + Math.max(
- 0,
- -numberAttr(context.element, "tracking", -1) / fontSize,
- ))));
- return trackOutput(visuals, [], [
- `.svml-caption-line .active { color: ${highlight}; }`,
- `.svml-caption-line {
- width: 100%;
- display: flex;
- justify-content: center;
- align-items: baseline;
- column-gap: ${gap}px;
- white-space: nowrap;
-}`,
- ".svml-caption-line > span { display: inline-block; }",
- ]);
- },
-};
diff --git a/stdlib/runtime/film.mjs b/stdlib/runtime/film.mjs
deleted file mode 100644
index 5552a7cc..00000000
--- a/stdlib/runtime/film.mjs
+++ /dev/null
@@ -1,64 +0,0 @@
-import { elements, numberAttr, resolveAttr, stringAttr } from "./helpers.mjs";
-
-export default {
- abiVersion: "1",
- project(context) {
- const visuals = [];
- const audios = [];
- const styles = [];
- const production = resolveAttr(context, context.element, "basis");
- const semantic = resolveAttr(context, context.element, "semantic");
- if (production?.contract !== "svml.temporal-basis-production.v1") {
- throw new Error("film requires TemporalBasisProduction");
- }
- if (semantic?.contract !== "svml.complete-semantic-map.v1") {
- throw new Error("film requires CompleteSemanticMap");
- }
- if (semantic.basisDigest !== production.basis.basisDigest) {
- throw new Error("film basis and SemanticMap do not share a basisDigest");
- }
- const basisFps = production.basis.frameRate.numerator
- / production.basis.frameRate.denominator;
- for (const contribution of production.audio ?? []) {
- audios.push({
- id: contribution.id,
- source: contribution.source,
- startFrame: contribution.programStartFrame,
- endFrameExclusive: contribution.programEndFrameExclusive,
- mediaStartSec: contribution.sourceStartFrame / basisFps,
- playbackRate: (contribution.sourceEndFrameExclusive - contribution.sourceStartFrame)
- / Math.max(1, contribution.programEndFrameExclusive - contribution.programStartFrame),
- volume: contribution.gain,
- ...(contribution.fadeInFrames ? { fadeInSec: contribution.fadeInFrames / basisFps } : {}),
- ...(contribution.fadeOutFrames ? { fadeOutSec: contribution.fadeOutFrames / basisFps } : {}),
- bus: "speech",
- });
- }
- for (const trackElement of elements(context, "track")) {
- const track = resolveAttr(context, trackElement, "ref");
- visuals.push(...(track.visuals ?? []));
- audios.push(...(track.audios ?? []));
- styles.push(...(track.styles ?? []));
- }
- const fps = numberAttr(context.element, "fps", basisFps);
- if (fps !== basisFps) {
- throw new Error(`film frame-rate ${fps} does not match ProgramBasis ${basisFps}`);
- }
- return {
- outputs: {
- document: {
- contract: "svml.hyperframes-document.v1",
- id: context.instance.id,
- width: numberAttr(context.element, "width", context.width),
- height: numberAttr(context.element, "height", context.height),
- fps,
- durationFrames: production.basis.durationFrames,
- background: stringAttr(context.element, "background", "#000000"),
- visuals,
- audios,
- styles,
- },
- },
- };
- },
-};
diff --git a/stdlib/runtime/helpers.mjs b/stdlib/runtime/helpers.mjs
deleted file mode 100644
index 9626e99b..00000000
--- a/stdlib/runtime/helpers.mjs
+++ /dev/null
@@ -1,376 +0,0 @@
-export function elements(context, name) {
- return context.element.children.filter((node) => node.kind === "element" && node.name === name);
-}
-
-export function stringAttr(element, name, fallback) {
- const value = element.attributes[name];
- if (typeof value === "string") return value;
- if (value === undefined && fallback !== undefined) return fallback;
- throw new Error(`<${element.name}> requires string attribute "${name}"`);
-}
-
-export function numberAttr(element, name, fallback) {
- const value = element.attributes[name];
- if (typeof value === "number" && Number.isFinite(value)) return value;
- if (typeof value === "string" && value.trim() && Number.isFinite(Number(value))) return Number(value);
- if (value === undefined && fallback !== undefined) return fallback;
- throw new Error(`<${element.name}> requires numeric attribute "${name}"`);
-}
-
-export function boolAttr(element, name, fallback) {
- const value = element.attributes[name];
- if (typeof value === "boolean") return value;
- if (value === undefined && fallback !== undefined) return fallback;
- throw new Error(`<${element.name}> requires boolean attribute "${name}"`);
-}
-
-export function resolveAttr(context, element, name) {
- return context.resolve(element.attributes[name]);
-}
-
-export function material(value, expected) {
- if (!value || typeof value !== "object") throw new Error(`expected ${expected ?? "media"} material`);
- const declaredType = String(value.type ?? value.kind ?? "");
- const programBound = /^ProgramBound(?:Image|Video|Audio)$/u.test(declaredType);
- const type = programBound ? declaredType.slice("ProgramBound".length) : declaredType;
- if (expected && type && type.toLowerCase() !== expected.toLowerCase()) {
- throw new Error(`expected ${expected}, received ${declaredType}`);
- }
- const source = value.absoluteSource ?? value.source;
- if (typeof source !== "string") throw new Error(`${expected ?? "media"} material has no source`);
- return { ...value, type, declaredType, programBound, source };
-}
-
-export function mediaMaterials(value, expected) {
- if (value?.type === "ProgramBoundVideoSequence") {
- const segments = Object.values(value.segments ?? {}).map((segment) => material(segment, expected));
- if (!segments.length) throw new Error("ProgramBoundVideoSequence has no media segments");
- return segments;
- }
- return [material(value, expected)];
-}
-
-function unitSeconds(raw) {
- const match = /^([+-]?\d+(?:\.\d+)?)(ms|s)$/u.exec(raw.trim());
- if (!match) throw new Error(`invalid relative time "${raw}"`);
- return Number(match[1]) * (match[2] === "ms" ? 0.001 : 1);
-}
-
-function endpoint(value, range) {
- const raw = value.trim();
- if (raw === "start") return range.startSec;
- if (raw === "end") return range.endSec;
- const match = /^(start|end)([+-]\d+(?:\.\d+)?(?:ms|s))$/u.exec(raw);
- if (!match) throw new Error(`invalid window endpoint "${value}"`);
- return (match[1] === "start" ? range.startSec : range.endSec) + unitSeconds(match[2]);
-}
-
-export function projectWindow(range, expression, fps) {
- if (!expression) return range;
- const parts = String(expression).split("..");
- if (parts.length !== 2) throw new Error(`invalid window "${expression}"`);
- const startSec = endpoint(parts[0], range);
- const endSec = endpoint(parts[1], range);
- const startFrame = Math.round(startSec * fps);
- const endFrameExclusive = Math.round(endSec * fps);
- if (endFrameExclusive < startFrame) throw new Error(`window "${expression}" resolves backwards`);
- return {
- startFrame,
- endFrameExclusive,
- startSec: startFrame / fps,
- endSec: endFrameExclusive / fps,
- };
-}
-
-export function html(value) {
- return String(value)
- .replaceAll("&", "&amp;")
- .replaceAll("<", "&lt;")
- .replaceAll(">", "&gt;")
- .replaceAll('"', "&quot;")
- .replaceAll("'", "&#39;");
-}
-
-export function trackOutput(visuals = [], audios = [], styles = []) {
- return {
- outputs: { track: { visuals, audios, styles } },
- visuals,
- audios,
- styles,
- };
-}
-
-export function intersectRange(left, right) {
- const startFrame = Math.max(left.startFrame, right.startFrame);
- const endFrameExclusive = Math.min(left.endFrameExclusive, right.endFrameExclusive);
- if (endFrameExclusive <= startFrame) return undefined;
- const fps = Math.round(
- (left.endFrameExclusive - left.startFrame) / Math.max(0.000001, left.endSec - left.startSec),
- );
- return {
- startFrame,
- endFrameExclusive,
- startSec: startFrame / fps,
- endSec: endFrameExclusive / fps,
- };
-}
-
-export function subtractRanges(base, cuts, fps) {
- const relevant = cuts
- .map((cut) => ({
- startFrame: Math.max(base.startFrame, cut.startFrame),
- endFrameExclusive: Math.min(base.endFrameExclusive, cut.endFrameExclusive),
- }))
- .filter((cut) => cut.endFrameExclusive > cut.startFrame)
- .sort((left, right) => left.startFrame - right.startFrame);
- const merged = [];
- for (const cut of relevant) {
- const previous = merged[merged.length - 1];
- if (previous && cut.startFrame <= previous.endFrameExclusive) {
- previous.endFrameExclusive = Math.max(previous.endFrameExclusive, cut.endFrameExclusive);
- } else {
- merged.push({ ...cut });
- }
- }
- const output = [];
- let cursor = base.startFrame;
- for (const cut of merged) {
- if (cut.startFrame > cursor) {
- output.push({
- startFrame: cursor,
- endFrameExclusive: cut.startFrame,
- startSec: cursor / fps,
- endSec: cut.startFrame / fps,
- });
- }
- cursor = Math.max(cursor, cut.endFrameExclusive);
- }
- if (cursor < base.endFrameExclusive) {
- output.push({
- startFrame: cursor,
- endFrameExclusive: base.endFrameExclusive,
- startSec: cursor / fps,
- endSec: base.endFrameExclusive / fps,
- });
- }
- return output;
-}
-
-function inherited(element, parent, name) {
- return element?.attributes[name] ?? parent?.attributes[name];
-}
-
-function inheritedNumber(element, parent, name, fallback) {
- const value = inherited(element, parent, name);
- if (value === undefined) return fallback;
- if (typeof value === "number" && Number.isFinite(value)) return value;
- if (typeof value === "string" && value.trim() && Number.isFinite(Number(value))) return Number(value);
- throw new Error(`<${element?.name ?? parent?.name}> requires numeric attribute "${name}"`);
-}
-
-function inheritedString(element, parent, name, fallback) {
- const value = inherited(element, parent, name);
- if (typeof value === "string") return value;
- if (value === undefined) return fallback;
- throw new Error(`<${element?.name ?? parent?.name}> requires string attribute "${name}"`);
-}
-
-export function presentationStyle(element, parent, defaults = {}) {
- const shape = inheritedString(element, parent, "shape", "rect");
- const radius = shape === "circle"
- ? "50%"
- : `${inheritedNumber(element, parent, "radius", 0)}px`;
- return {
- left: `${inheritedNumber(element, parent, "x", 0) * 100}%`,
- top: `${inheritedNumber(element, parent, "y", 0) * 100}%`,
- width: `${inheritedNumber(element, parent, "width", 1) * 100}%`,
- height: `${inheritedNumber(element, parent, "height", 1) * 100}%`,
- "object-fit": inheritedString(element, parent, "fit", defaults.fit ?? "cover"),
- "object-position": inheritedString(element, parent, "position", "50% 50%"),
- "border-radius": radius,
- opacity: inheritedNumber(element, parent, "opacity", 1),
- overflow: "hidden",
- background: inheritedString(element, parent, "background", defaults.background ?? "transparent"),
- };
-}
-
-export function durationSeconds(value) {
- const match = /^([0-9]+(?:\.[0-9]+)?)(ms|s)$/u.exec(value);
- if (!match) throw new Error(`invalid transition duration "${value}"`);
- return Number(match[1]) * (match[2] === "ms" ? 0.001 : 1);
-}
-
-function fadeSpec(raw) {
- if (raw === undefined) return 0;
- const match = /^fade\s+([0-9]+(?:\.[0-9]+)?(?:ms|s))$/u.exec(String(raw).trim());
- if (!match) throw new Error(`only "fade <duration>" is supported, received "${String(raw)}"`);
- return durationSeconds(match[1]);
-}
-
-export function presentationAnimation(element, range, fps, id) {
- const durationFrames = Math.max(1, range.endFrameExclusive - range.startFrame);
- const enterFrames = Math.min(durationFrames, Math.round(fadeSpec(element?.attributes.enter) * fps));
- const exitFrames = Math.min(
- durationFrames - enterFrames,
- Math.round(fadeSpec(element?.attributes.exit) * fps),
- );
- if (enterFrames <= 0 && exitFrames <= 0) return {};
- const enterPercent = enterFrames / durationFrames * 100;
- const exitPercent = 100 - exitFrames / durationFrames * 100;
- const name = `svml-present-${id}`.replaceAll(/[^A-Za-z0-9_-]/gu, "-");
- const duration = durationFrames / fps;
- return {
- animation: `${name} ${duration}s linear both`,
- css: `@keyframes ${name} {
- 0% { opacity:${enterFrames > 0 ? 0 : 1}; }
- ${enterPercent}% { opacity:1; }
- ${exitPercent}% { opacity:1; }
- 100% { opacity:${exitFrames > 0 ? 0 : 1}; }
- }`,
- };
-}
-
-export function resolveItemPresentations(context, item, source, defaultZ, options = {}) {
- const rawParents = item.attributes.during
- ? context.selection(item.attributes.during, "item.during")
- : source.range
- ? [source.range]
- : [];
- if (!rawParents.length) {
- throw new Error(`item "${stringAttr(item, "id")}" has no temporal range`);
- }
- const parents = rawParents
- .map((range) => projectWindow(range, item.attributes.window, context.fps))
- .map((range) => source.range ? intersectRange(range, source.range) : range)
- .filter(Boolean);
- const presents = elements({ element: item }, "present");
- const explicit = [];
- for (const [presentIndex, present] of presents.entries()) {
- const presentRanges = present.attributes.during
- ? context.selection(present.attributes.during, "present.during")
- : parents;
- for (const projected of presentRanges.map((range) =>
- projectWindow(range, present.attributes.window, context.fps))) {
- for (const [parentIndex, parentRange] of parents.entries()) {
- const range = intersectRange(parentRange, projected);
- if (!range) continue;
- explicit.push({
- id: stringAttr(present, "id"),
- parentIndex,
- parentRange,
- range,
- element: present,
- z: numberAttr(present, "z", numberAttr(item, "z", defaultZ)),
- explicit: true,
- });
- }
- }
- if (!options.allowEmptyPresent && !explicit.some((value) => value.id === stringAttr(present, "id"))) {
- throw new Error(`presentation_empty: Present "${stringAttr(present, "id")}" has no intersection with its Item`);
- }
- }
- const defaults = [];
- for (const [parentIndex, parentRange] of parents.entries()) {
- const cuts = explicit
- .filter((presentation) => presentation.parentIndex === parentIndex)
- .map((presentation) => presentation.range);
- const ranges = presents.length
- ? subtractRanges(parentRange, cuts, context.fps)
- : [parentRange];
- for (const range of ranges) {
- defaults.push({
- id: "default",
- parentIndex,
- parentRange,
- range,
- element: undefined,
- z: numberAttr(item, "z", defaultZ),
- explicit: false,
- });
- }
- }
- for (let left = 0; left < explicit.length; left += 1) {
- for (let right = left + 1; right < explicit.length; right += 1) {
- const a = explicit[left];
- const b = explicit[right];
- if (
- a.z === b.z
- && a.range.startFrame < b.range.endFrameExclusive
- && b.range.startFrame < a.range.endFrameExclusive
- ) {
- throw new Error(`presentation_z_ambiguous: Present "${a.id}" and "${b.id}" overlap at z=${a.z}`);
- }
- }
- }
- return [...defaults, ...explicit];
-}
-
-export function mediaTiming(item, presentation, source, fps) {
- const playback = stringAttr(item, "playback", source.programBound ? "program-map" : "sync");
- const mappingRange = source.programBound && source.range
- ? source.range
- : presentation.parentRange;
- const offsetFrames = presentation.range.startFrame - mappingRange.startFrame;
- const mediaStart = numberAttr(item, "mediaStart", source.mediaStartSec ?? 0);
- if (playback === "program-map") {
- if (!source.programBound) {
- throw new Error(`playback "program-map" requires ProgramBound media`);
- }
- return {
- mediaStartSec: mediaStart + offsetFrames / fps * (source.playbackRate ?? 1),
- playbackRate: source.playbackRate ?? 1,
- };
- }
- if (playback === "sync") {
- return {
- mediaStartSec: mediaStart + offsetFrames / fps,
- playbackRate: 1,
- };
- }
- if (playback === "loop") {
- return {
- mediaStartSec: mediaStart + offsetFrames / fps,
- playbackRate: 1,
- loop: true,
- };
- }
- if (playback === "stretch") {
- const sourceDuration = numberAttr(item, "sourceDuration");
- const parentFrames = Math.max(
- 1,
- presentation.parentRange.endFrameExclusive - presentation.parentRange.startFrame,
- );
- return {
- mediaStartSec: mediaStart + sourceDuration * (offsetFrames / parentFrames),
- playbackRate: sourceDuration / (parentFrames / fps),
- };
- }
- if (playback === "hold" && source.type === "Image") return {};
- throw new Error(`unsupported playback "${playback}" for ${source.type}`);
-}
-
-export function programBoundAnimation(source, range, fps, id) {
- if (!source.programBound || (!source.fadeInFrames && !source.fadeOutFrames)) return {};
- const totalFrames = Math.max(1, range.endFrameExclusive - range.startFrame);
- const sourceStart = source.range.startFrame;
- const sourceEnd = source.range.endFrameExclusive;
- const fadeInEnd = sourceStart + (source.fadeInFrames ?? 0);
- const fadeOutStart = sourceEnd - (source.fadeOutFrames ?? 0);
- const points = new Map([[0, 1], [100, 1]]);
- const percent = (frameValue) => Math.max(0, Math.min(100,
- (frameValue - range.startFrame) / totalFrames * 100));
- if (source.fadeInFrames && range.startFrame < fadeInEnd) {
- points.set(0, Math.max(0, (range.startFrame - sourceStart) / source.fadeInFrames));
- points.set(percent(Math.min(range.endFrameExclusive, fadeInEnd)), 1);
- }
- if (source.fadeOutFrames && range.endFrameExclusive > fadeOutStart) {
- points.set(percent(Math.max(range.startFrame, fadeOutStart)), 1);
- points.set(100, Math.max(0, (sourceEnd - range.endFrameExclusive) / source.fadeOutFrames));
- }
- const name = `svml-program-bound-${id}`.replaceAll(/[^A-Za-z0-9_-]/gu, "-");
- return {
- animation: `${name} ${totalFrames / fps}s linear both`,
- css: `@keyframes ${name} { ${[...points].sort((a, b) => a[0] - b[0])
- .map(([at, opacity]) => `${at}% { opacity:${opacity}; }`).join(" ")} }`,
- };
-}
diff --git a/stdlib/runtime/media-basis.mjs b/stdlib/runtime/media-basis.mjs
deleted file mode 100644
index 369bf3b0..00000000
--- a/stdlib/runtime/media-basis.mjs
+++ /dev/null
@@ -1,133 +0,0 @@
-import { material, numberAttr, resolveAttr, stringAttr } from "./helpers.mjs";
-
-function seconds(value) {
- const match = /^(\d+(?:\.\d+)?)(ms|s)$/u.exec(String(value).trim());
- if (!match) throw new Error(`invalid duration "${String(value)}"`);
- return Number(match[1]) * (match[2] === "ms" ? 0.001 : 1);
-}
-
-function canonicalFacet(value) {
- if (Array.isArray(value)) return value.map(canonicalFacet);
- if (!value || typeof value !== "object") return value;
- return Object.fromEntries(Object.entries(value)
- .filter(([key]) => !["source", "absoluteSource", "basisDigest"].includes(key))
- .map(([key, nested]) => [key, canonicalFacet(nested)]));
-}
-
-function frameRate(fps) {
- if (!Number.isFinite(fps) || fps <= 0) throw new Error("fps must be positive and finite");
- if (Number.isInteger(fps)) return { numerator: fps, denominator: 1 };
- let numerator = Math.round(fps * 1_000_000);
- let denominator = 1_000_000;
- let left = numerator;
- let right = denominator;
- while (right) [left, right] = [right, left % right];
- numerator /= left;
- denominator /= left;
- return { numerator, denominator };
-}
-
-export default {
- abiVersion: "1",
- project(context) {
- const fps = numberAttr(context.element, "fps", 30);
- const rationalFps = frameRate(fps);
- const durationSec = seconds(stringAttr(context.element, "duration"));
- const sourceStartSec = seconds(stringAttr(context.element, "sourceStart", "0ms"));
- const durationFrames = Math.round(durationSec * fps);
- if (durationFrames <= 0) throw new Error("media-basis duration must resolve to positive frames");
- const sourceStartFrame = Math.round(sourceStartSec * fps);
- const sourceEndFrameExclusive = sourceStartFrame + durationFrames;
- const audioValue = material(resolveAttr(context, context.element, "audio"), "audio");
- const visualValue = context.element.attributes.visual
- ? material(resolveAttr(context, context.element, "visual"), "video")
- : undefined;
- const sourceMaps = [{
- id: "program:audio-map",
- sourceId: audioValue.id,
- sourceDigest: audioValue.contentDigest,
- sourceStartFrame,
- sourceEndFrameExclusive,
- programStartFrame: 0,
- programEndFrameExclusive: durationFrames,
- }];
- if (visualValue) {
- sourceMaps.push({
- id: "program:visual-map",
- sourceId: visualValue.id,
- sourceDigest: visualValue.contentDigest,
- sourceStartFrame,
- sourceEndFrameExclusive,
- programStartFrame: 0,
- programEndFrameExclusive: durationFrames,
- });
- }
- const alignmentSubjects = [{
- id: "program:audio",
- sourceId: audioValue.id,
- sourceDigest: audioValue.contentDigest,
- sourceMapId: "program:audio-map",
- }];
- const audio = [{
- id: "program:audio",
- sourceId: audioValue.id,
- sourceDigest: audioValue.contentDigest,
- source: audioValue.source,
- sourceMapId: "program:audio-map",
- sourceStartFrame,
- sourceEndFrameExclusive,
- programStartFrame: 0,
- programEndFrameExclusive: durationFrames,
- gain: 1,
- }];
- const unboundVisual = visualValue ? {
- type: "ProgramBoundVideo",
- source: visualValue.source,
- sourceId: visualValue.id,
- sourceDigest: visualValue.contentDigest,
- range: {
- startFrame: 0,
- endFrameExclusive: durationFrames,
- startSec: 0,
- endSec: durationFrames / fps,
- },
- mediaStartSec: sourceStartSec,
- playbackRate: 1,
- sourceMapId: "program:visual-map",
- } : undefined;
- const outcome = {
- contract: "svml.program-basis-outcome.v1",
- frameRate: rationalFps,
- originFrame: 0,
- durationFrames,
- alignmentSubjects,
- sourceMaps,
- audio: audio.map(({ source: _source, ...contribution }) => contribution),
- facets: canonicalFacet({ ...(unboundVisual ? { visual: unboundVisual } : {}) }),
- };
- const basisDigest = context.digest(outcome);
- const basis = {
- contract: "svml.program-basis.v1",
- frameRate: outcome.frameRate,
- originFrame: 0,
- durationFrames,
- basisDigest,
- };
- const facets = unboundVisual
- ? { visual: { ...unboundVisual, basisDigest } }
- : {};
- const production = {
- contract: "svml.temporal-basis-production.v1",
- basis,
- alignmentSubjects,
- sourceMaps,
- audio,
- facets,
- productionDigest: context.digest({
- implementation: context.instance.executionDigest,
- outcome,
- }),
- };
- return { outputs: { production, facets } };
- },
-};
diff --git a/stdlib/runtime/media-track.mjs b/stdlib/runtime/media-track.mjs
deleted file mode 100644
index ad28359d..00000000
--- a/stdlib/runtime/media-track.mjs
+++ /dev/null
@@ -1,79 +0,0 @@
-import {
- elements,
- mediaMaterials,
- mediaTiming,
- numberAttr,
- presentationAnimation,
- programBoundAnimation,
- presentationStyle,
- resolveItemPresentations,
- resolveAttr,
- stringAttr,
- trackOutput,
-} from "./helpers.mjs";
-
-export default {
- abiVersion: "1",
- project(context) {
- const z = numberAttr(context.element, "z");
- const visuals = [];
- for (const item of elements(context, "item")) {
- const id = stringAttr(item, "id");
- const sources = mediaMaterials(resolveAttr(context, item, "source"));
- const itemVisuals = [];
- const resolvedPresentIds = new Set();
- for (const [sourceIndex, source] of sources.entries()) {
- const presentations = resolveItemPresentations(context, item, source, z, { allowEmptyPresent: true });
- for (const [index, presentation] of presentations.entries()) {
- if (presentation.explicit) resolvedPresentIds.add(presentation.id);
- const range = presentation.range;
- const animation = presentationAnimation(
- presentation.element,
- range,
- context.fps,
- `${context.instance.id}-${id}-${presentation.id}-${index}`,
- );
- const sourceAnimation = programBoundAnimation(
- source,
- range,
- context.fps,
- `${context.instance.id}-${id}-${sourceIndex}-${presentation.id}-${index}`,
- );
- const timing = source.type === "Video"
- ? mediaTiming(item, presentation, source, context.fps)
- : {};
- itemVisuals.push({
- id: `${context.instance.id}:${id}:${sourceIndex}:${index}`,
- kind: source.type === "Image" ? "image" : "video",
- source: source.source,
- startFrame: range.startFrame,
- endFrameExclusive: range.endFrameExclusive,
- z: presentation.z,
- muted: true,
- ...timing,
- style: {
- ...presentationStyle(presentation.element, item),
- ...((animation.animation || sourceAnimation.animation) ? {
- animation: [animation.animation, sourceAnimation.animation].filter(Boolean).join(", "),
- } : {}),
- },
- ...((animation.css || sourceAnimation.css) ? {
- css: [animation.css, sourceAnimation.css].filter(Boolean).join("\n"),
- } : {}),
- });
- }
- }
- if (!itemVisuals.length) {
- throw new Error(`item_empty: Item "${id}" has no intersection with its source`);
- }
- for (const present of elements({ element: item }, "present")) {
- const presentId = stringAttr(present, "id");
- if (!resolvedPresentIds.has(presentId)) {
- throw new Error(`presentation_empty: Present "${presentId}" has no intersection with its Item`);
- }
- }
- visuals.push(...itemVisuals);
- }
- return trackOutput(visuals);
- },
-};
diff --git a/stdlib/runtime/ranking-column.mjs b/stdlib/runtime/ranking-column.mjs
deleted file mode 100644
index 8b4fe5eb..00000000
--- a/stdlib/runtime/ranking-column.mjs
+++ /dev/null
@@ -1,289 +0,0 @@
-import {
- elements,
- html,
- material,
- numberAttr,
- projectWindow,
- resolveAttr,
- stringAttr,
- trackOutput,
-} from "./helpers.mjs";
-
-const GRADIENT_STOPS = [
- "#ff3f56",
- "#ff741f",
- "#ffb832",
- "#ffd82f",
- "#d4df24",
- "#94c93a",
- "#52bea0",
- "#31add0",
-];
-
-function hexToRgb(hex) {
- const value = Number.parseInt(hex.slice(1), 16);
- return [(value >> 16) & 255, (value >> 8) & 255, value & 255];
-}
-
-function mixHex(a, b, progress) {
- const from = hexToRgb(a);
- const to = hexToRgb(b);
- const mixed = from.map((value, index) =>
- Math.round(value + (to[index] - value) * progress));
- return `rgb(${mixed[0]}, ${mixed[1]}, ${mixed[2]})`;
-}
-
-function rankColor(index, total) {
- const progress = total <= 1 ? 0 : index / Math.max(1, total - 1);
- const scaled = progress * (GRADIENT_STOPS.length - 1);
- const stop = Math.min(GRADIENT_STOPS.length - 2, Math.floor(scaled));
- return mixHex(GRADIENT_STOPS[stop], GRADIENT_STOPS[stop + 1], scaled - stop);
-}
-
-function clamp01(value) {
- return Math.max(0, Math.min(1, value));
-}
-
-function lerp(from, to, progress) {
- return from + (to - from) * progress;
-}
-
-function easeInOutCubic(value) {
- return value < 0.5
- ? 4 * value * value * value
- : 1 - ((-2 * value + 2) ** 3) / 2;
-}
-
-function outBack(value) {
- const c1 = 1.70158;
- const c3 = c1 + 1;
- return 1 + c3 * ((value - 1) ** 3) + c1 * ((value - 1) ** 2);
-}
-
-function activeKeyframes(args) {
- const {
- durationFrames,
- durationSec,
- fps,
- stageCx,
- stageCy,
- stageSize,
- targetCx,
- targetCy,
- targetSize,
- frameHeight,
- } = args;
- const enterPart = Math.min(1, 0.45 / Math.max(0.001, durationSec));
- const exitStart = Math.min(
- 1,
- Math.max(enterPart, 1 - 0.55 / Math.max(0.001, durationSec)),
- );
- const frames = [];
- for (let frame = 0; frame <= durationFrames; frame += 1) {
- const local = clamp01(frame / Math.max(1, durationFrames));
- let centerX = stageCx;
- let centerY = stageCy;
- let size = stageSize;
- let opacity = 1;
- let breathe = 1;
- let rotate = 0;
- let shadow = "0 12px 30px rgba(0,0,0,.22)";
- if (local < enterPart) {
- const progress = outBack(clamp01(local / enterPart));
- centerY = lerp(frameHeight + stageSize * 0.25, stageCy, progress);
- opacity = Math.min(1, progress * 2.2);
- breathe = 0.96 + 0.04 * progress;
- } else if (local < exitStart) {
- const idle = (local - enterPart) / Math.max(0.001, exitStart - enterPart);
- const wave = Math.sin(idle * Math.PI * 2);
- const wave2 = Math.sin(idle * Math.PI * 2 + Math.PI / 2);
- centerY = stageCy - 1.8 * wave;
- centerX = stageCx + 0.8 * wave2;
- breathe = 1.004 + 0.003 * wave2;
- rotate = 0.12 * wave;
- shadow = "0 14px 34px rgba(0,0,0,.24)";
- } else {
- const progress = easeInOutCubic(
- clamp01((local - exitStart) / Math.max(0.001, 1 - exitStart)),
- );
- centerX = lerp(stageCx, targetCx, progress);
- centerY = lerp(stageCy, targetCy, progress);
- size = lerp(stageSize, targetSize, progress);
- breathe = 1 - 0.02 * Math.sin(progress * Math.PI);
- }
- frames.push(
- `${(frame / Math.max(1, durationFrames) * 100).toFixed(5)}% {`
- + `left:${(centerX - size / 2).toFixed(3)}px;`
- + `top:${(centerY - size / 2).toFixed(3)}px;`
- + `width:${size.toFixed(3)}px;`
- + `height:${size.toFixed(3)}px;`
- + `opacity:${opacity.toFixed(5)};`
- + `transform:scale(${breathe.toFixed(6)}) rotate(${rotate.toFixed(5)}deg);`
- + `box-shadow:${shadow};`
- + "}",
- );
- }
- return frames.join("\n");
-}
-
-export default {
- abiVersion: "1",
- project(context) {
- const z = numberAttr(context.element, "z");
- const x = Math.round(context.width * numberAttr(context.element, "x", 0));
- const y = Math.round(context.height * numberAttr(context.element, "y", 0.17));
- const rowH = Math.round(context.height * numberAttr(context.element, "rowHeight", 0.071));
- const gap = Math.round(context.height * numberAttr(context.element, "gap", 0.011));
- const width = Math.round(context.width * numberAttr(context.element, "width", 0.305));
- const pad = Math.max(8, Math.round(rowH * 0.13));
- const total = elements(context, "item").length;
- const boardH = total * rowH + Math.max(0, total - 1) * gap + pad * 2;
- const stageSize = Math.round(context.width * numberAttr(context.element, "stageSize", 0.33));
- const stageCx = Math.round(context.width * numberAttr(context.element, "stageX", 0.66));
- const stageCy = Math.round(context.height * numberAttr(context.element, "stageY", 0.73));
- const boardStartFrame = context.element.attributes.at
- ? context.moment(context.element.attributes.at, "at")[0]
- : 0;
- const cellLeft = x + pad + rowH + Math.max(8, Math.round(rowH * 0.16));
- const rows = Array.from({ length: total }, (_, index) => {
- const top = pad + index * (rowH + gap);
- return `<div style="position:absolute;left:${pad}px;top:${top}px;width:${rowH}px;height:${rowH}px;border-radius:${Math.round(rowH * 0.075)}px;background:${rankColor(index, total)};display:flex;align-items:center;justify-content:center;color:white;font:900 ${Math.round(rowH * 0.48)}px/1 Arial,sans-serif;letter-spacing:-0.04em;text-shadow:0 1px 1px rgba(0,0,0,.12)"><span style="display:inline-block;transform:scaleX(1.02);transform-origin:center center">${index + 1}</span></div>
-<div style="position:absolute;left:${pad + rowH + Math.max(8, Math.round(rowH * 0.16))}px;top:${top}px;width:${rowH}px;height:${rowH}px;border-radius:${Math.round(rowH * 0.23)}px;border:1.5px solid rgba(255,255,255,.18);background:rgba(0,0,0,.72);overflow:hidden"></div>`;
- }).join("");
- const visuals = [{
- id: `${context.instance.id}:board`,
- kind: "html",
- startFrame: boardStartFrame,
- endFrameExclusive: context.program.durationFrames,
- z,
- html: rows,
- style: {
- left: `${x}px`,
- top: `${y}px`,
- width: `${width}px`,
- height: `${boardH}px`,
- "border-radius": `${Math.round(rowH * 0.16)}px`,
- background: "rgba(7,8,12,.94)",
- padding: `${pad}px`,
- "box-shadow": "0 6px 18px rgba(0,0,0,.35)",
- },
- }];
- const audios = [];
- const appear = context.element.attributes.appearSound
- ? material(resolveAttr(context, context.element, "appearSound"), "audio")
- : undefined;
- const move = context.element.attributes.moveSound
- ? material(resolveAttr(context, context.element, "moveSound"), "audio")
- : undefined;
- for (const item of elements(context, "item")) {
- const id = stringAttr(item, "id");
- const image = material(resolveAttr(context, item, "image"), "image");
- const rank = Math.max(1, Math.min(total, numberAttr(item, "rank")));
- const base = context.selection(item.attributes.during, "item.during")[0];
- const range = projectWindow(base, item.attributes.window, context.fps);
- const visibleRange = {
- ...range,
- startFrame: Math.max(boardStartFrame, range.startFrame),
- };
- const top = y + pad + (rank - 1) * (rowH + gap);
- const settledStartFrame = Math.max(boardStartFrame, range.endFrameExclusive);
- const endDuration = (context.program.durationFrames - settledStartFrame) / context.fps;
- if (endDuration > 0) {
- visuals.push({
- id: `${context.instance.id}:${id}:settled`,
- kind: "image",
- source: image.source,
- startFrame: settledStartFrame,
- endFrameExclusive: context.program.durationFrames,
- z: z + 1,
- style: {
- left: `${cellLeft}px`,
- top: `${top}px`,
- width: `${rowH}px`,
- height: `${rowH}px`,
- "border-radius": `${Math.round(rowH * 0.23)}px`,
- background: "rgba(255,255,255,.98)",
- overflow: "hidden",
- },
- innerStyle: {
- width: "100%",
- height: "100%",
- "object-fit": "cover",
- transform: "scale(1.1)",
- },
- });
- }
- if (visibleRange.endFrameExclusive <= visibleRange.startFrame) continue;
- const keyframes = `svml-rank-${context.instance.id}-${id}`.replaceAll(/[^A-Za-z0-9_-]/gu, "-");
- const durationFrames = Math.max(1, visibleRange.endFrameExclusive - visibleRange.startFrame);
- const duration = durationFrames / context.fps;
- const targetCx = cellLeft + rowH / 2;
- const targetCy = top + rowH / 2;
- visuals.push({
- id: `${context.instance.id}:${id}:active`,
- kind: "image",
- source: image.source,
- startFrame: visibleRange.startFrame,
- endFrameExclusive: visibleRange.endFrameExclusive,
- z: z + 2,
- style: {
- left: `${stageCx - stageSize / 2}px`,
- top: `${stageCy - stageSize / 2}px`,
- width: `${stageSize}px`,
- height: `${stageSize}px`,
- "border-radius": `${Math.round(stageSize * 0.23)}px`,
- background: "rgba(255,255,255,.98)",
- "box-shadow": "0 14px 34px rgba(0,0,0,.24)",
- "transform-origin": "center center",
- overflow: "hidden",
- animation: `${keyframes} ${duration}s linear both`,
- },
- innerStyle: {
- width: "100%",
- height: "100%",
- "object-fit": "cover",
- transform: "scale(1.1)",
- },
- css: `@keyframes ${keyframes} {
-${activeKeyframes({
- durationFrames,
- durationSec: duration,
- fps: context.fps,
- stageCx,
- stageCy,
- stageSize,
- targetCx,
- targetCy,
- targetSize: rowH,
- frameHeight: context.height,
-})}
-}`,
- });
- if (appear) {
- audios.push({
- id: `${context.instance.id}:${id}:appear`,
- source: appear.source,
- startFrame: visibleRange.startFrame,
- endFrameExclusive: Math.min(
- context.program.durationFrames,
- visibleRange.startFrame + Math.round(0.247021 * context.fps),
- ),
- volume: numberAttr(context.element, "appearGain", 0.09),
- bus: "sfx",
- });
- }
- if (move) {
- const moveFrames = Math.round(0.6 * context.fps);
- audios.push({
- id: `${context.instance.id}:${id}:move`,
- source: move.source,
- startFrame: Math.max(visibleRange.startFrame, visibleRange.endFrameExclusive - Math.round(0.55 * context.fps)),
- endFrameExclusive: Math.min(context.program.durationFrames, visibleRange.endFrameExclusive - Math.round(0.55 * context.fps) + moveFrames),
- volume: numberAttr(context.element, "moveGain", 0.1),
- bus: "sfx",
- });
- }
- }
- return trackOutput(visuals, audios);
- },
-};
diff --git a/stdlib/runtime/speech-assemble.mjs b/stdlib/runtime/speech-assemble.mjs
deleted file mode 100644
index 7384308b..00000000
--- a/stdlib/runtime/speech-assemble.mjs
+++ /dev/null
@@ -1,310 +0,0 @@
-import { elements, material, numberAttr, resolveAttr, stringAttr } from "./helpers.mjs";
-
-function seconds(raw) {
- const match = /^([+-]?\d+(?:\.\d+)?)(ms|s)$/u.exec(String(raw).trim());
- if (!match) throw new Error(`invalid duration "${String(raw)}"`);
- return Number(match[1]) * (match[2] === "ms" ? 0.001 : 1);
-}
-
-function sourceWindow(raw) {
- const parts = String(raw).split("..");
- if (parts.length !== 2) throw new Error(`sourceWindow requires start .. end, received "${raw}"`);
- const startSec = seconds(parts[0]);
- const endSec = seconds(parts[1]);
- if (startSec < 0 || endSec <= startSec) throw new Error(`invalid sourceWindow "${raw}"`);
- return { startSec, endSec, durationSec: endSec - startSec };
-}
-
-function defaultJoin(element) {
- const kind = stringAttr(element, "defaultJoin", "cut");
- const duration = seconds(stringAttr(element, "defaultJoinDuration", "0ms"));
- if (kind === "cut") return { temporal: "cut", durationSec: 0, audio: "cut", visual: "cut" };
- if (kind === "crossfade") {
- if (duration <= 0) throw new Error("crossfade defaultJoinDuration must be positive");
- return { temporal: "overlap", durationSec: duration, audio: "crossfade", visual: "dissolve" };
- }
- if (kind === "gap") {
- if (duration <= 0) throw new Error("gap defaultJoinDuration must be positive");
- return { temporal: "gap", durationSec: duration, audio: "cut", visual: "cut" };
- }
- throw new Error(`unsupported defaultJoin "${kind}"`);
-}
-
-function explicitJoin(element, fallback) {
- const overlap = element.attributes.overlap;
- const gap = element.attributes.gap;
- if (overlap !== undefined && gap !== undefined) {
- throw new Error(`<join after="${stringAttr(element, "after")}"> cannot declare both overlap and gap`);
- }
- const temporal = overlap !== undefined ? "overlap" : gap !== undefined ? "gap" : "cut";
- const durationSec = overlap !== undefined
- ? seconds(overlap)
- : gap !== undefined
- ? seconds(gap)
- : 0;
- if (temporal !== "cut" && durationSec <= 0) throw new Error(`${temporal} duration must be positive`);
- const audio = stringAttr(element, "audio", temporal === "overlap" ? fallback.audio : "cut");
- const visual = stringAttr(element, "visual", temporal === "overlap" ? fallback.visual : "cut");
- if (!["cut", "crossfade"].includes(audio)) throw new Error(`unsupported audio join "${audio}"`);
- if (!["cut", "dissolve"].includes(visual)) throw new Error(`unsupported visual join "${visual}"`);
- if (temporal !== "overlap" && (audio === "crossfade" || visual === "dissolve")) {
- throw new Error(`${audio}/${visual} requires a temporal overlap`);
- }
- return {
- temporal,
- durationSec,
- audio,
- visual,
- };
-}
-
-function frame(secondsValue, fps) {
- return Math.round(secondsValue * fps);
-}
-
-function rationalFrameRate(fps) {
- if (!Number.isFinite(fps) || fps <= 0) throw new Error("fps must be positive and finite");
- if (Number.isInteger(fps)) return { numerator: fps, denominator: 1 };
- let numerator = Math.round(fps * 1_000_000);
- let denominator = 1_000_000;
- let left = numerator;
- let right = denominator;
- while (right) [left, right] = [right, left % right];
- numerator /= left;
- denominator /= left;
- return { numerator, denominator };
-}
-
-function canonicalFacet(value) {
- if (Array.isArray(value)) return value.map(canonicalFacet);
- if (!value || typeof value !== "object") return value;
- return Object.fromEntries(Object.entries(value)
- .filter(([key]) => !["source", "absoluteSource", "basisDigest"].includes(key))
- .map(([key, nested]) => [key, canonicalFacet(nested)]));
-}
-
-export default {
- abiVersion: "1",
- project(context) {
- const fps = numberAttr(context.element, "fps", 30);
- const rationalFps = rationalFrameRate(fps);
- const segmentElements = elements(context, "segment");
- const ids = segmentElements.map(segment => stringAttr(segment, "id"));
- if (new Set(ids).size !== ids.length) throw new Error("speech-assemble Segment ids must be unique");
- const fallback = defaultJoin(context.element);
- const overrides = new Map();
- for (const join of elements(context, "join")) {
- const after = stringAttr(join, "after");
- if (overrides.has(after)) throw new Error(`duplicate join after "${after}"`);
- if (!ids.includes(after) || ids.at(-1) === after) {
- throw new Error(`join after "${after}" must name a non-final Segment`);
- }
- overrides.set(after, explicitJoin(join, fallback));
- }
-
- const segments = [];
- const joins = [];
- let nextStartSec = 0;
- for (const [index, element] of segmentElements.entries()) {
- const id = ids[index];
- const script = resolveAttr(context, element, "script");
- if (!script || script.id !== id) throw new Error(`Segment "${id}" does not match its ScriptSegment`);
- const audio = material(resolveAttr(context, element, "audio"), "audio");
- const visual = element.attributes.visual
- ? material(resolveAttr(context, element, "visual"), "video")
- : undefined;
- const window = sourceWindow(stringAttr(element, "sourceWindow"));
- const startSec = nextStartSec;
- const endSec = startSec + window.durationSec;
- segments.push({ id, script, audio, visual, window, startSec, endSec });
- if (index >= segmentElements.length - 1) continue;
- const join = overrides.get(id) ?? fallback;
- joins.push({ after: id, ...join });
- nextStartSec = join.temporal === "overlap"
- ? endSec - join.durationSec
- : join.temporal === "gap"
- ? endSec + join.durationSec
- : endSec;
- if (nextStartSec < startSec) throw new Error(`join after "${id}" overlaps more than the Segment duration`);
- }
-
- const durationFrames = Math.max(...segments.map(segment => frame(segment.endSec, fps)));
- const frameRate = rationalFps;
- const sourceMaps = [];
- const alignmentSubjects = [];
- const audio = [];
- const unboundSegmentOutputs = {};
- for (const [index, segment] of segments.entries()) {
- const programStartFrame = frame(segment.startSec, fps);
- const programEndFrameExclusive = frame(segment.endSec, fps);
- const sourceStartFrame = frame(segment.window.startSec, fps);
- const sourceEndFrameExclusive = frame(segment.window.endSec, fps);
- const previousJoin = joins[index - 1];
- const nextJoin = joins[index];
- const audioMap = {
- id: `segment:${segment.id}:audio-map`,
- sourceId: segment.audio.id,
- sourceDigest: segment.audio.contentDigest,
- sourceStartFrame,
- sourceEndFrameExclusive,
- programStartFrame,
- programEndFrameExclusive,
- };
- sourceMaps.push(audioMap);
- alignmentSubjects.push({
- id: `segment:${segment.id}:speech`,
- sourceId: segment.audio.id,
- sourceDigest: segment.audio.contentDigest,
- sourceMapId: audioMap.id,
- });
-
- let audioEndFrameExclusive = programEndFrameExclusive;
- if (nextJoin?.temporal === "overlap" && nextJoin.audio === "cut") {
- audioEndFrameExclusive = frame(segments[index + 1].startSec, fps);
- }
- const fadeInFrames = previousJoin?.temporal === "overlap" && previousJoin.audio === "crossfade"
- ? frame(previousJoin.durationSec, fps)
- : 0;
- const fadeOutFrames = nextJoin?.temporal === "overlap" && nextJoin.audio === "crossfade"
- ? frame(nextJoin.durationSec, fps)
- : 0;
- const audioContribution = {
- id: `segment:${segment.id}:program-audio`,
- sourceId: segment.audio.id,
- sourceDigest: segment.audio.contentDigest,
- source: segment.audio.source,
- sourceMapId: audioMap.id,
- sourceStartFrame,
- sourceEndFrameExclusive: sourceStartFrame + (audioEndFrameExclusive - programStartFrame),
- programStartFrame,
- programEndFrameExclusive: audioEndFrameExclusive,
- gain: 1,
- ...(fadeInFrames ? { fadeInFrames } : {}),
- ...(fadeOutFrames ? { fadeOutFrames } : {}),
- };
- audio.push(audioContribution);
-
- const audioRange = {
- startFrame: programStartFrame,
- endFrameExclusive: audioEndFrameExclusive,
- startSec: programStartFrame / fps,
- endSec: audioEndFrameExclusive / fps,
- };
- const output = {
- audio: {
- type: "ProgramBoundAudio",
- source: segment.audio.source,
- sourceId: segment.audio.id,
- sourceDigest: segment.audio.contentDigest,
- range: audioRange,
- mediaStartSec: segment.window.startSec,
- playbackRate: 1,
- sourceMapId: audioMap.id,
- ...(fadeInFrames ? { fadeInFrames } : {}),
- ...(fadeOutFrames ? { fadeOutFrames } : {}),
- },
- };
- if (segment.visual) {
- const visualMap = {
- id: `segment:${segment.id}:visual-map`,
- sourceId: segment.visual.id,
- sourceDigest: segment.visual.contentDigest,
- sourceStartFrame,
- sourceEndFrameExclusive,
- programStartFrame,
- programEndFrameExclusive,
- };
- sourceMaps.push(visualMap);
- let visualEndFrameExclusive = programEndFrameExclusive;
- if (nextJoin?.temporal === "overlap" && nextJoin.visual === "cut") {
- visualEndFrameExclusive = frame(segments[index + 1].startSec, fps);
- }
- const visualFadeInFrames = previousJoin?.temporal === "overlap" && previousJoin.visual === "dissolve"
- ? frame(previousJoin.durationSec, fps)
- : 0;
- const visualFadeOutFrames = nextJoin?.temporal === "overlap" && nextJoin.visual === "dissolve"
- ? frame(nextJoin.durationSec, fps)
- : 0;
- output.visual = {
- type: "ProgramBoundVideo",
- source: segment.visual.source,
- sourceId: segment.visual.id,
- sourceDigest: segment.visual.contentDigest,
- range: {
- startFrame: programStartFrame,
- endFrameExclusive: visualEndFrameExclusive,
- startSec: programStartFrame / fps,
- endSec: visualEndFrameExclusive / fps,
- },
- mediaStartSec: segment.window.startSec,
- playbackRate: 1,
- sourceMapId: visualMap.id,
- ...(visualFadeInFrames ? { fadeInFrames: visualFadeInFrames } : {}),
- ...(visualFadeOutFrames ? { fadeOutFrames: visualFadeOutFrames } : {}),
- };
- }
- unboundSegmentOutputs[segment.id] = output;
- }
- const unboundFacets = {
- visual: {
- type: "ProgramBoundVideoSequence",
- segments: Object.fromEntries(Object.entries(unboundSegmentOutputs)
- .filter(([, value]) => value.visual)
- .map(([id, value]) => [id, value.visual])),
- },
- };
- const outcome = {
- contract: "svml.program-basis-outcome.v1",
- frameRate,
- originFrame: 0,
- durationFrames,
- alignmentSubjects,
- sourceMaps,
- audio: audio.map(({ source: _source, ...contribution }) => contribution),
- facets: canonicalFacet(unboundFacets),
- };
- const basisDigest = context.digest(outcome);
- const basis = {
- contract: "svml.program-basis.v1",
- frameRate,
- originFrame: 0,
- durationFrames,
- basisDigest,
- };
- const segmentOutputs = Object.fromEntries(Object.entries(unboundSegmentOutputs).map(([id, output]) => [
- id,
- {
- audio: { ...output.audio, basisDigest },
- ...(output.visual ? { visual: { ...output.visual, basisDigest } } : {}),
- },
- ]));
- const facets = {
- visual: {
- type: "ProgramBoundVideoSequence",
- basisDigest,
- segments: Object.fromEntries(Object.entries(segmentOutputs)
- .filter(([, value]) => value.visual)
- .map(([id, value]) => [id, value.visual])),
- },
- };
- const production = {
- contract: "svml.temporal-basis-production.v1",
- basis,
- alignmentSubjects,
- sourceMaps,
- audio,
- facets,
- productionDigest: context.digest({
- implementation: context.instance.executionDigest,
- outcome,
- }),
- };
- return {
- outputs: {
- production,
- facets: production.facets,
- segment: segmentOutputs,
- },
- };
- },
-};
diff --git a/stdlib/runtime/speech-locator.mjs b/stdlib/runtime/speech-locator.mjs
deleted file mode 100644
index 427efe95..00000000
--- a/stdlib/runtime/speech-locator.mjs
+++ /dev/null
@@ -1,208 +0,0 @@
-function normalizeWord(value) {
- return String(value)
- .normalize("NFKC")
- .toLocaleLowerCase("en")
- .replace(/[^\p{L}\p{M}\p{N}]+/gu, "");
-}
-
-function fail(message) {
- throw new Error(message);
-}
-
-function lcsMatches(tokens, units) {
- const rows = Array.from({ length: tokens.length + 1 }, () =>
- Array(units.length + 1).fill(0));
- for (let left = tokens.length - 1; left >= 0; left -= 1) {
- for (let right = units.length - 1; right >= 0; right -= 1) {
- rows[left][right] = tokens[left].normalized === normalizeWord(units[right].text)
- ? rows[left + 1][right + 1] + 1
- : Math.max(rows[left + 1][right], rows[left][right + 1]);
- }
- }
- const matches = [];
- let left = 0;
- let right = 0;
- while (left < tokens.length && right < units.length) {
- if (
- tokens[left].normalized === normalizeWord(units[right].text)
- && rows[left][right] === rows[left + 1][right + 1] + 1
- ) {
- matches.push([left, right]);
- left += 1;
- right += 1;
- } else if (rows[left + 1][right] >= rows[left][right + 1]) {
- left += 1;
- } else {
- right += 1;
- }
- }
- return matches;
-}
-
-function distributeFrames(tokens, startFrame, endFrameExclusive, quality) {
- const weights = tokens.map(token => Math.max(1, [...token.normalized].length));
- const total = weights.reduce((sum, value) => sum + value, 0);
- let accumulated = 0;
- return tokens.map((_, index) => {
- const start = startFrame + Math.round((endFrameExclusive - startFrame) * accumulated / total);
- accumulated += weights[index];
- const end = index === tokens.length - 1
- ? endFrameExclusive
- : startFrame + Math.round((endFrameExclusive - startFrame) * accumulated / total);
- return { startFrame: start, endFrameExclusive: Math.max(start, end), quality };
- });
-}
-
-function alignSegment(tokens, units, segment, fps, evidenceQuality) {
- const output = Array(tokens.length).fill(undefined);
- const matches = lcsMatches(tokens, units);
- let tokenCursor = 0;
- let unitCursor = 0;
- for (let matchIndex = 0; matchIndex <= matches.length; matchIndex += 1) {
- const match = matches[matchIndex];
- const tokenEnd = match?.[0] ?? tokens.length;
- const unitEnd = match?.[1] ?? units.length;
- const tokenRun = tokens.slice(tokenCursor, tokenEnd);
- const unitRun = units.slice(unitCursor, unitEnd);
- if (tokenRun.length) {
- const previous = tokenCursor > 0 ? output[tokenCursor - 1] : undefined;
- const nextUnit = match ? units[unitEnd] : undefined;
- const startFrame = unitRun.length
- ? Math.round(unitRun[0].startSec * fps)
- : previous?.endFrameExclusive ?? Math.round(segment.startSec * fps);
- const endFrame = unitRun.length
- ? Math.round(unitRun.at(-1).endSec * fps)
- : nextUnit
- ? Math.round(nextUnit.startSec * fps)
- : Math.round(segment.endSec * fps);
- const quality = evidenceQuality === "estimated" || !unitRun.length
- ? "estimated"
- : "derived";
- for (const [offset, value] of distributeFrames(
- tokenRun,
- startFrame,
- Math.max(startFrame, endFrame),
- quality,
- ).entries()) output[tokenCursor + offset] = value;
- }
- if (match) {
- const [tokenIndex, unitIndex] = match;
- const unit = units[unitIndex];
- output[tokenIndex] = {
- startFrame: Math.round(unit.startSec * fps),
- endFrameExclusive: Math.round(unit.endSec * fps),
- quality: evidenceQuality === "measured" ? "measured" : "estimated",
- };
- tokenCursor = tokenIndex + 1;
- unitCursor = unitIndex + 1;
- }
- }
- if (output.some(value => !value)) fail(`could not align every Script token in Segment ${segment.id}`);
- return output;
-}
-
-function validate(narrative, basis, evidence) {
- if (evidence?.contract !== "svml.speech-timing-evidence.v1") {
- fail("speech-locator requires SpeechTimingEvidence");
- }
- if (!['measured', 'estimated'].includes(evidence.quality)) fail("invalid speech timing quality");
- const fps = basis.frameRate.numerator / basis.frameRate.denominator;
- if (Math.abs(evidence.fps - fps) > 1e-6) fail("speech timing fps does not match ProgramBasis");
- if (Math.round(evidence.durationSec * fps) !== basis.durationFrames) {
- fail("speech timing duration does not match ProgramBasis");
- }
- if (evidence.segments.length !== narrative.segments.length) {
- fail("speech timing Segment cardinality mismatch");
- }
- const segments = new Map(evidence.segments.map(segment => [segment.id, segment]));
- if (segments.size !== evidence.segments.length) fail("speech timing repeats a Segment id");
- for (const [index, scriptSegment] of narrative.segments.entries()) {
- const segment = segments.get(scriptSegment.id);
- if (!segment) fail(`speech timing is missing Segment ${scriptSegment.id}`);
- if (
- !Number.isFinite(segment.startSec)
- || !Number.isFinite(segment.endSec)
- || segment.startSec < 0
- || segment.endSec < segment.startSec
- || segment.endSec > evidence.durationSec + 1e-6
- ) fail(`invalid speech timing window for Segment ${scriptSegment.id}`);
- const previousScript = narrative.segments[index - 1];
- const previous = previousScript ? segments.get(previousScript.id) : undefined;
- if (previous && (segment.startSec < previous.startSec - 1e-6 || segment.endSec < previous.endSec - 1e-6)) {
- fail(`speech timing reorders Segment ${scriptSegment.id}`);
- }
- }
- const previousBySegment = new Map();
- for (const [index, unit] of evidence.units.entries()) {
- const segment = segments.get(unit.segmentId);
- if (
- !segment
- || typeof unit.text !== "string"
- || !Number.isFinite(unit.startSec)
- || !Number.isFinite(unit.endSec)
- || unit.startSec < segment.startSec - 1e-6
- || unit.endSec < unit.startSec
- || unit.endSec > segment.endSec + 1e-6
- ) fail(`speech timing unit ${index + 1} falls outside its Segment`);
- const previous = previousBySegment.get(unit.segmentId);
- if (previous && unit.startSec < previous.endSec - 1e-6) {
- fail(`speech timing units overlap inside Segment ${unit.segmentId}`);
- }
- previousBySegment.set(unit.segmentId, unit);
- }
- return { fps, segments };
-}
-
-export default {
- abiVersion: "1",
- project(context) {
- const narrative = context.element.attributes.script;
- const production = context.element.attributes.basis;
- const evidenceValue = context.element.attributes.evidence;
- const evidence = evidenceValue?.data ?? evidenceValue;
- if (!narrative?.semanticIndex) fail("speech-locator requires NarrativeIR");
- if (production?.contract !== "svml.temporal-basis-production.v1") {
- fail("speech-locator requires TemporalBasisProduction");
- }
- const basis = production.basis;
- const { fps, segments } = validate(narrative, basis, evidence);
- const tokenFrames = new Map();
- for (const scriptSegment of narrative.segments) {
- const segment = segments.get(scriptSegment.id);
- const tokens = narrative.tokens.slice(scriptSegment.tokenStart, scriptSegment.tokenEnd);
- const units = evidence.units.filter(unit => unit.segmentId === scriptSegment.id);
- const aligned = alignSegment(tokens, units, segment, fps, evidence.quality);
- tokens.forEach((token, index) => tokenFrames.set(token.id, aligned[index]));
- }
- const anchors = narrative.semanticIndex.anchors.map(anchor => {
- const segment = segments.get(anchor.segmentId);
- const token = anchor.tokenId ? tokenFrames.get(anchor.tokenId) : undefined;
- const frame = anchor.kind === "segment-start"
- ? Math.round(segment.startSec * fps)
- : anchor.kind === "segment-end"
- ? Math.round(segment.endSec * fps)
- : anchor.kind === "token-start"
- ? token?.startFrame
- : token?.endFrameExclusive;
- if (frame === undefined) fail(`speech timing is missing anchor ${anchor.id}`);
- return {
- identity: anchor.id,
- point: { basisDigest: basis.basisDigest, frame },
- quality: token?.quality ?? evidence.quality,
- };
- });
- const payload = {
- contract: "svml.complete-semantic-map.v1",
- semanticIndexDigest: narrative.semanticIndex.digest,
- basisDigest: basis.basisDigest,
- anchors,
- evidenceDigests: [evidenceValue.contentDigest ?? context.digest(evidence)],
- locatorDigest: context.digest({
- implementation: context.instance.executionDigest,
- quantizationPolicy: "nearest-frame",
- }),
- quantizationPolicy: "nearest-frame",
- };
- return { outputs: { map: { ...payload, mapDigest: context.digest(payload) } } };
- },
-};
diff --git a/stdlib/runtime/text-track.mjs b/stdlib/runtime/text-track.mjs
deleted file mode 100644
index 7f3d3006..00000000
--- a/stdlib/runtime/text-track.mjs
+++ /dev/null
@@ -1,56 +0,0 @@
-import {
- elements,
- html,
- numberAttr,
- stringAttr,
- trackOutput,
-} from "./helpers.mjs";
-
-export default {
- abiVersion: "1",
- project(context) {
- const z = numberAttr(context.element, "z");
- const visuals = [];
- for (const item of elements(context, "item")) {
- const id = stringAttr(item, "id");
- const ranges = context.selection(item.attributes.during ?? "full", "item.during");
- for (const [index, range] of ranges.entries()) {
- const text = stringAttr(item, "text");
- visuals.push({
- id: `${context.instance.id}:${id}:${index}`,
- kind: "html",
- startFrame: range.startFrame,
- endFrameExclusive: range.endFrameExclusive,
- z,
- html: `<div class="svml-text-inner">${html(item.attributes.uppercase === true ? text.toUpperCase() : text)}</div>`,
- style: {
- left: `${numberAttr(item, "x", 0) * 100}%`,
- top: `${numberAttr(item, "y", 0) * 100}%`,
- width: `${numberAttr(item, "width", 1) * 100}%`,
- height: `${numberAttr(item, "height", 0.1) * 100}%`,
- display: "flex",
- "align-items": "center",
- "justify-content": "center",
- color: stringAttr(item, "color", "#050505"),
- background: "transparent",
- "font-family": stringAttr(item, "font", "Inter, Arial, sans-serif"),
- "font-size": `${numberAttr(item, "size", 54)}px`,
- "font-weight": numberAttr(item, "weight", 900),
- "line-height": numberAttr(item, "lineHeight", 0.92),
- "text-align": "center",
- "letter-spacing": `${numberAttr(item, "letterSpacing", 0)}px`,
- },
- css: `.svml-text-inner {
- display: inline;
- padding: 0.08em 0;
- background: ${stringAttr(item, "background", "transparent")};
- box-decoration-break: clone;
- -webkit-box-decoration-break: clone;
- text-shadow: 0 2px 0 rgba(255,255,255,.9), 0 4px 7px rgba(0,0,0,.32);
-}`,
- });
- }
- }
- return trackOutput(visuals);
- },
-};
diff --git a/stdlib/speech-assemble.svk b/stdlib/speech-assemble.svk
deleted file mode 100644
index 20a5b5c2..00000000
--- a/stdlib/speech-assemble.svk
+++ /dev/null
@@ -1,23 +0,0 @@
-<kernel name="speech-assemble" abi="1" implementation="./runtime/speech-assemble.mjs">
- <param name="fps" type="number" default="30"/>
- <param name="defaultJoin" style="default-join" type="string" default="cut"/>
- <param name="defaultJoinDuration" style="default-join-duration" type="string" default="0ms"/>
- <port name="production" direction="output" type="TemporalBasisProduction" cardinality="one"/>
- <port name="facets.visual" direction="output" type="ProgramBoundVideoSequence" cardinality="zero-or-one"/>
- <port name="segment.*.visual" direction="output" type="ProgramBoundVideo" cardinality="zero-or-one"/>
- <port name="segment.*.audio" direction="output" type="ProgramBoundAudio" cardinality="one"/>
- <child name="segment" cardinality="one-or-more">
- <field name="id" type="id" required="true"/>
- <field name="script" type="ScriptSegment" required="true"/>
- <field name="visual" type="Video"/>
- <field name="audio" type="Audio" required="true"/>
- <field name="sourceWindow" type="string" required="true"/>
- </child>
- <child name="join" cardinality="zero-or-more">
- <field name="after" type="id" required="true"/>
- <field name="overlap" type="string"/>
- <field name="gap" type="string"/>
- <field name="audio" type="string"/>
- <field name="visual" type="string"/>
- </child>
-</kernel>
diff --git a/stdlib/speech-locator.svk b/stdlib/speech-locator.svk
deleted file mode 100644
index a7bd5758..00000000
--- a/stdlib/speech-locator.svk
+++ /dev/null
@@ -1,6 +0,0 @@
-<kernel name="speech-locator" abi="1" implementation="./runtime/speech-locator.mjs">
- <port name="script" direction="input" type="NarrativeIR" cardinality="one"/>
- <port name="basis" direction="input" type="TemporalBasisProduction" cardinality="one"/>
- <port name="evidence" direction="input" type="SpeechTimingEvidence" cardinality="one"/>
- <port name="map" direction="output" type="CompleteSemanticMap" cardinality="one"/>
-</kernel>
diff --git a/stdlib/text-track.svk b/stdlib/text-track.svk
deleted file mode 100644
index e25358b8..00000000
--- a/stdlib/text-track.svk
+++ /dev/null
@@ -1,22 +0,0 @@
-<kernel name="text-track" abi="1" implementation="./runtime/text-track.mjs">
- <param name="z" type="number"/>
- <port name="item" direction="input" type="TextItem" cardinality="one-or-more"/>
- <port name="track" direction="output" type="Track" cardinality="one"/>
- <child name="item" cardinality="one-or-more">
- <field name="id" type="id" required="true"/>
- <field name="text" type="string" required="true"/>
- <field name="during" type="SelectionSet|ProgramSpan" consume="each"/>
- <field name="x" type="number"/>
- <field name="y" type="number"/>
- <field name="width" type="number"/>
- <field name="height" type="number"/>
- <field name="font" style="font-family" type="string"/>
- <field name="size" style="font-size" type="number"/>
- <field name="weight" style="font-weight" type="number"/>
- <field name="lineHeight" style="line-height" type="number"/>
- <field name="letterSpacing" style="letter-spacing" type="number"/>
- <field name="color" style="fill" type="string"/>
- <field name="background" type="string"/>
- <field name="uppercase" type="boolean"/>
- </child>
-</kernel>
diff --git a/test/artifacts.test.ts b/test/artifacts.test.ts
deleted file mode 100644
index b7a362b0..00000000
--- a/test/artifacts.test.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-import assert from "node:assert/strict";
-import { readFile, writeFile } from "node:fs/promises";
-import { mkdtemp } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import test from "node:test";
-import { fileURLToPath, pathToFileURL } from "node:url";
-import { checkSource, compileSource } from "../src/compiler.js";
-import { sha256, stableJson } from "../src/util.js";
-
-const fixture = fileURLToPath(new URL("./fixtures/artifacts/", import.meta.url));
-const pinnedImage = fileURLToPath(
- new URL("./fixtures/collision/left/image.png", import.meta.url),
-);
-const alternateImage = fileURLToPath(
- new URL("./fixtures/collision/right/image.png", import.meta.url),
-);
-
-test("capability instances require exact verified artifacts and never invoke a provider", async () => {
- const file = `${fixture}/main.svml`;
- const checked = await checkSource(file);
- const capability = checked.plan.instances.find((instance) => instance.id === "poster");
- assert.equal(
- checked.plan.kernels.find((kernel) => kernel.name === "pinned-image")?.profile,
- "capability-v1",
- );
- await assert.rejects(
- compileSource({
- file,
- }),
- /artifact_file_required/u,
- );
-
- const directory = await mkdtemp(join(tmpdir(), "svml-artifacts-"));
- const lock = join(directory, "svml.lock");
- const artifacts = join(directory, "artifacts.json");
- const output = join(directory, "index.html");
- await writeFile(lock, `${JSON.stringify(checked.lock, null, 2)}\n`, "utf8");
- await writeFile(artifacts, `${JSON.stringify({
- contract: "svml.artifacts.v1",
- bindings: [{
- instanceIdentity: capability?.identity,
- executionDigest: capability?.executionDigest,
- outputs: {
- image: {
- type: "Image",
- uri: pathToFileURL(pinnedImage).href,
- contentDigest: sha256(await readFile(pinnedImage)),
- },
- },
- }],
- }, null, 2)}\n`, "utf8");
-
- const compilation = await compileSource({
- file,
- lockFile: lock,
- artifactsFile: artifacts,
- outputFile: output,
- });
- assert.equal(compilation.artifactsVerified, true);
- assert.equal(compilation.sourceClosureVerified, true);
- assert.equal(compilation.temporalEvidenceVerified, false);
- assert.equal(compilation.reproducible, false);
- assert.match(compilation.html, /bound-image/u);
- assert.match(compilation.html, /\.\/assets\/[a-f0-9]{16}-image\.png/u);
-
- await writeFile(lock, `${JSON.stringify(compilation.lock, null, 2)}\n`, "utf8");
- const frozen = await compileSource({
- file,
- lockFile: lock,
- artifactsFile: artifacts,
- });
- assert.equal(frozen.lockVerified, true);
- assert.equal(frozen.temporalEvidenceVerified, true);
- assert.equal(frozen.reproducible, true);
-
- const alternateArtifacts = join(directory, "alternate-artifacts.json");
- await writeFile(alternateArtifacts, `${JSON.stringify({
- contract: "svml.artifacts.v1",
- bindings: [{
- instanceIdentity: capability?.identity,
- executionDigest: capability?.executionDigest,
- outputs: {
- image: {
- type: "Image",
- uri: pathToFileURL(alternateImage).href,
- contentDigest: sha256(await readFile(alternateImage)),
- },
- },
- }],
- }, null, 2)}\n`, "utf8");
- const alternate = await compileSource({
- file,
- artifactsFile: alternateArtifacts,
- });
- assert.equal(
- compilation.plan.instances.find((instance) => instance.id === "poster")?.executionDigest,
- alternate.plan.instances.find((instance) => instance.id === "poster")?.executionDigest,
- );
- assert.notEqual(
- compilation.plan.instances.find((instance) => instance.id === "film")?.executionDigest,
- alternate.plan.instances.find((instance) => instance.id === "film")?.executionDigest,
- );
-});
-
-test("a Locator capability returns CompleteSemanticMap through the same typed Artifact ABI", async () => {
- const source = fileURLToPath(
- new URL("../examples/composite-speech-program/minimal.svml", import.meta.url),
- );
- const reference = await compileSource({ file: source });
- const directory = await mkdtemp(join(tmpdir(), "svml-locator-artifact-"));
- const svml = join(directory, "main.svml");
- const assemble = fileURLToPath(new URL("../stdlib/speech-assemble.svk", import.meta.url));
- const film = fileURLToPath(new URL("../stdlib/film.svk", import.meta.url));
- const locator = fileURLToPath(
- new URL("./fixtures/artifacts/pinned-locator.svk", import.meta.url),
- );
- const avatar = fileURLToPath(
- new URL("../examples/regen-ranking/assets/avatar-1.mp4", import.meta.url),
- );
- const audio = fileURLToPath(
- new URL("../examples/regen-ranking/assets/avatar-1.mp3", import.meta.url),
- );
- const evidence = fileURLToPath(
- new URL("../examples/composite-speech-program/alignment.json", import.meta.url),
- );
- await writeFile(svml, `<svml version="1">
- <import from="${assemble}"/>
- <import from="${locator}"/>
- <import from="${film}"/>
- <script>
- <segment id="intro"><HOST> Hello, this is SVML.</segment>
- <segment id="close"><HOST> Write the script, get the video.</segment>
- </script>
- <video id="host" src="${avatar}"/>
- <audio id="host-audio" src="${audio}"/>
- <timing id="timing" src="${evidence}"/>
- <speech-assemble id="voice" fps="30" defaultJoin="cut">
- <segment id="intro" script={script.segment.intro} visual={host} audio={host-audio} sourceWindow="0s .. 5s"/>
- <segment id="close" script={script.segment.close} visual={host} audio={host-audio} sourceWindow="5s .. 10s"/>
- <join after="intro" overlap="500ms" audio="crossfade" visual="dissolve"/>
- </speech-assemble>
- <pinned-locator id="location" script={script} basis={voice.production} evidence={timing}/>
- <film id="film" basis={voice.production} semantic={location.map}/>
-</svml>\n`, "utf8");
- const checked = await checkSource(svml);
- const instance = checked.plan.instances.find((item) => item.id === "location");
- const artifacts = join(directory, "artifacts.json");
- await writeFile(artifacts, `${JSON.stringify({
- contract: "svml.artifacts.v1",
- bindings: [{
- instanceIdentity: instance?.identity,
- executionDigest: instance?.executionDigest,
- outputs: {
- map: {
- type: "CompleteSemanticMap",
- value: reference.semanticMap,
- contentDigest: sha256(stableJson(reference.semanticMap)),
- },
- },
- }],
- }, null, 2)}\n`, "utf8");
- const compilation = await compileSource({ file: svml, artifactsFile: artifacts });
- assert.equal(compilation.semanticMap.mapDigest, reference.semanticMap.mapDigest);
- assert.equal(compilation.semanticMap.basisDigest, compilation.basis.basis.basisDigest);
-});
diff --git a/test/composite.test.ts b/test/composite.test.ts
deleted file mode 100644
index 3c4c7613..00000000
--- a/test/composite.test.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-import { fileURLToPath } from "node:url";
-import { checkSource, compileSource } from "../src/compiler.js";
-
-const fixture = fileURLToPath(
- new URL("../examples/composite-speech-program/minimal.svml", import.meta.url),
-);
-
-test("composite-v1 expands finite internal Basis/Locator instances with audited aliases", async () => {
- const checked = await checkSource(fixture);
- assert.deepEqual(
- checked.plan.instances.map((instance) => instance.id).sort(),
- ["aroll", "main", "voice::basis", "voice::locator"],
- );
- assert.equal(checked.plan.expansions.length, 1);
- assert.deepEqual(checked.plan.expansions[0]?.internalIds, [
- "voice::basis",
- "voice::locator",
- ]);
- assert.deepEqual(checked.plan.expansions[0]?.exports, {
- production: "voice::basis.production",
- map: "voice::locator.map",
- "facets.visual": "voice::basis.facets.visual",
- });
- assert.equal(checked.lock.expansions[0]?.expansionDigest.length, 64);
- const internal = checked.plan.instances.find((instance) => instance.id === "voice::basis");
- assert.match(internal?.sourceMap?.callSite.file ?? "", /minimal\.svml$/u);
- assert.match(internal?.sourceMap?.definitionSite.file ?? "", /speech-program\.svk$/u);
-
- const compilation = await compileSource({ file: fixture });
- assert.equal(compilation.plan.kernels.some((kernel) =>
- kernel.ports.some((port) => port.type === "CaptionTrack")), false);
- assert.equal(compilation.located.durationFrames, 285);
- assert.equal(compilation.basis.sourceMaps.length, 4);
- assert.equal(compilation.basis.audio[0]?.fadeOutFrames, 15);
- assert.equal(compilation.basis.audio[1]?.fadeInFrames, 15);
-
- const visuals = compilation.projections.get("aroll")?.visuals ?? [];
- assert.deepEqual(
- visuals.map((visual) => [visual.startFrame, visual.endFrameExclusive, visual.mediaStartSec]),
- [[0, 150, 0], [135, 285, 5]],
- );
- assert.ok(visuals.every((visual) => visual.z === 100));
- assert.ok(visuals.every((visual) => /svml-program-bound/u.test(visual.css ?? "")));
-});
-
-test("a precomposed media Basis reuses the same Locator and Composition contracts", async () => {
- const file = fileURLToPath(new URL("./fixtures/media-basis/main.svml", import.meta.url));
- const compilation = await compileSource({ file });
- assert.equal(compilation.basis.basis.durationFrames, 30);
- assert.equal(compilation.basis.alignmentSubjects.length, 1);
- assert.equal(compilation.basis.sourceMaps.length, 2);
- assert.equal(compilation.semanticMap.anchors.length, 4);
- assert.equal(compilation.target.audios.length, 1);
-});
diff --git a/test/fixtures/artifacts/alignment.json b/test/fixtures/artifacts/alignment.json
deleted file mode 100644
index eaf3c0ce..00000000
--- a/test/fixtures/artifacts/alignment.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "contract": "svml.speech-timing-evidence.v1",
- "durationSec": 1,
- "fps": 30,
- "quality": "measured",
- "units": [
- {
- "text": "Hello",
- "startSec": 0,
- "endSec": 0.8,
- "segmentId": "main"
- }
- ],
- "segments": [
- {
- "id": "main",
- "startSec": 0,
- "endSec": 1
- }
- ]
-}
diff --git a/test/fixtures/artifacts/artifact-film.mjs b/test/fixtures/artifacts/artifact-film.mjs
deleted file mode 100644
index 5368690a..00000000
--- a/test/fixtures/artifacts/artifact-film.mjs
+++ /dev/null
@@ -1,29 +0,0 @@
-export default {
- abiVersion: "1",
- project(context) {
- const image = context.resolve(context.element.attributes.image);
- const production = context.resolve(context.element.attributes.basis);
- return {
- outputs: {
- document: {
- contract: "svml.hyperframes-document.v1",
- id: context.instance.id,
- width: 64,
- height: 64,
- fps: production.basis.frameRate.numerator / production.basis.frameRate.denominator,
- durationFrames: production.basis.durationFrames,
- background: "#000000",
- visuals: [{
- id: "bound-image",
- kind: "image",
- source: image.absoluteSource ?? image.source,
- startFrame: 0,
- endFrameExclusive: production.basis.durationFrames,
- z: 0,
- }],
- audios: [],
- },
- },
- };
- },
-};
diff --git a/test/fixtures/artifacts/artifact-film.svk b/test/fixtures/artifacts/artifact-film.svk
deleted file mode 100644
index 8908a8f4..00000000
--- a/test/fixtures/artifacts/artifact-film.svk
+++ /dev/null
@@ -1,11 +0,0 @@
-<kernel
- name="artifact-film"
- abi="1"
- root="true"
- implementation="./artifact-film.mjs"
->
- <port name="image" direction="input" type="Image" cardinality="one"/>
- <port name="basis" direction="input" type="TemporalBasisProduction" cardinality="one"/>
- <port name="semantic" direction="input" type="CompleteSemanticMap" cardinality="one"/>
- <port name="document" direction="output" type="HyperframesDocument" cardinality="one"/>
-</kernel>
diff --git a/test/fixtures/artifacts/main.svml b/test/fixtures/artifacts/main.svml
deleted file mode 100644
index 219bb0c2..00000000
--- a/test/fixtures/artifacts/main.svml
+++ /dev/null
@@ -1,20 +0,0 @@
-<svml version="1">
- <import from="./pinned-image.svk"/>
- <import from="./artifact-film.svk"/>
- <import from="../../../stdlib/speech-assemble.svk"/>
- <import from="../../../stdlib/speech-locator.svk"/>
-
- <script>
- <segment id="main">Hello.</segment>
- </script>
-
- <audio id="voice-audio" src="./alignment.json"/>
- <timing id="timing" src="./alignment.json"/>
- <speech-assemble id="speech" fps="30">
- <segment id="main" script={script.segment.main} audio={voice-audio} sourceWindow="0s .. 1s"/>
- </speech-assemble>
- <speech-locator id="location" script={script} basis={speech.production} evidence={timing}/>
-
- <pinned-image id="poster" prompt="A pinned result; never call a provider."/>
- <artifact-film id="film" image={poster.image} basis={speech.production} semantic={location.map}/>
-</svml>
diff --git a/test/fixtures/artifacts/pinned-image.svk b/test/fixtures/artifacts/pinned-image.svk
deleted file mode 100644
index 2303e44f..00000000
--- a/test/fixtures/artifacts/pinned-image.svk
+++ /dev/null
@@ -1,9 +0,0 @@
-<kernel
- name="pinned-image"
- abi="1"
- profile="capability-v1"
- capability="image.generate"
->
- <param name="prompt" type="string"/>
- <port name="image" direction="output" type="Image" cardinality="one"/>
-</kernel>
diff --git a/test/fixtures/artifacts/pinned-locator.svk b/test/fixtures/artifacts/pinned-locator.svk
deleted file mode 100644
index 855cdabb..00000000
--- a/test/fixtures/artifacts/pinned-locator.svk
+++ /dev/null
@@ -1,6 +0,0 @@
-<kernel name="pinned-locator" abi="1" profile="capability-v1" capability="semantic-locate">
- <port name="script" direction="input" type="NarrativeIR" cardinality="one"/>
- <port name="basis" direction="input" type="TemporalBasisProduction" cardinality="one"/>
- <port name="evidence" direction="input" type="SpeechTimingEvidence" cardinality="one"/>
- <port name="map" direction="output" type="CompleteSemanticMap" cardinality="one"/>
-</kernel>
diff --git a/test/fixtures/collision/alignment.json b/test/fixtures/collision/alignment.json
deleted file mode 100644
index f1dd6006..00000000
--- a/test/fixtures/collision/alignment.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "contract": "svml.speech-timing-evidence.v1",
- "durationSec": 2,
- "fps": 30,
- "quality": "measured",
- "units": [
- { "text": "Left", "startSec": 0.1, "endSec": 0.5, "segmentId": "main" },
- { "text": "and", "startSec": 0.6, "endSec": 0.9, "segmentId": "main" },
- { "text": "right", "startSec": 1, "endSec": 1.5, "segmentId": "main" }
- ],
- "segments": [
- { "id": "main", "startSec": 0, "endSec": 2 }
- ]
-}
diff --git a/test/fixtures/collision/main.svml b/test/fixtures/collision/main.svml
deleted file mode 100644
index b915620f..00000000
--- a/test/fixtures/collision/main.svml
+++ /dev/null
@@ -1,34 +0,0 @@
-<svml version="1">
- <import from="../../../stdlib/speech-assemble.svk"/>
- <import from="../../../stdlib/speech-locator.svk"/>
- <import from="../../../stdlib/broll-track.svk"/>
- <import from="../../../stdlib/film.svk"/>
-
- <script>
- <segment id="main">
- @left Left @/left and @right right @/right.
- </segment>
- </script>
-
- <video id="avatar" src="./avatar.mp4"/>
- <audio id="voice-audio" src="./avatar.mp4"/>
- <timing id="timing" src="./alignment.json"/>
- <image id="left-image" src="./left/image.png"/>
- <image id="right-image" src="./right/image.png"/>
-
- <speech-assemble id="speech" fps="30">
- <segment id="main" script={script.segment.main} visual={avatar} audio={voice-audio} sourceWindow="0s .. 2s"/>
- </speech-assemble>
-
- <speech-locator id="location" script={script} basis={speech.production} evidence={timing}/>
-
- <broll-track id="broll" z="100">
- <item id="left" source={left-image} during={script.selection.left}/>
- <item id="right" source={right-image} during={script.selection.right}/>
- <transition from="left" to="right" kind="crossfade" duration="200ms"/>
- </broll-track>
-
- <film id="collision" basis={speech.production} semantic={location.map}>
- <track ref={broll.track}/>
- </film>
-</svml>
diff --git a/test/fixtures/disconnected/alignment.json b/test/fixtures/disconnected/alignment.json
deleted file mode 100644
index 5d28c064..00000000
--- a/test/fixtures/disconnected/alignment.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "contract": "svml.speech-timing-evidence.v1",
- "durationSec": 3,
- "fps": 30,
- "quality": "measured",
- "units": [
- { "text": "Alpha", "startSec": 0, "endSec": 0.7, "segmentId": "main" },
- { "text": "gap", "startSec": 1, "endSec": 1.5, "segmentId": "main" },
- { "text": "omega", "startSec": 2, "endSec": 2.7, "segmentId": "main" }
- ],
- "segments": [
- { "id": "main", "startSec": 0, "endSec": 3 }
- ]
-}
diff --git a/test/fixtures/disconnected/captions.svml b/test/fixtures/disconnected/captions.svml
deleted file mode 100644
index eeb0c7d5..00000000
--- a/test/fixtures/disconnected/captions.svml
+++ /dev/null
@@ -1,34 +0,0 @@
-<svml version="1">
- <import from="../../../stdlib/speech-assemble.svk"/>
- <import from="../../../stdlib/speech-locator.svk"/>
- <import from="../../../stdlib/caption-planner.svk"/>
- <import from="../../../stdlib/caption-track.svk"/>
- <import from="../../../stdlib/film.svk"/>
-
- <script>
- <segment id="main">
- <A> @pick Alpha @/pick @silent gap @/silent
- <B> @pick omega @/pick.
- </segment>
- </script>
-
- <audio id="voice-audio" src="../presentation/long.mp4"/>
- <timing id="timing" src="./alignment.json"/>
- <speech-assemble id="speech" fps="30">
- <segment id="main" script={script.segment.main} audio={voice-audio} sourceWindow="0s .. 3s"/>
- </speech-assemble>
- <speech-locator id="location" script={script} basis={speech.production} evidence={timing}/>
-
- <caption-planner id="caption-plan" script={script} semantic={location.map} maxWords="3">
- <annotate id="picked" kind="accent" during={script.selection.pick}/>
- </caption-planner>
- <caption-track id="captions" script={script} semantic={location.map} plan={caption-plan.plan} z="10">
- <style id="speaker-a" role="A" background="#0000ff"/>
- <style id="picked" annotation="accent" color="#ff0000" activeColor="#00ff00" scale="1.1"/>
- <mute id="silent" during={script.selection.silent}/>
- </caption-track>
-
- <film id="film" basis={speech.production} semantic={location.map}>
- <track ref={captions.track}/>
- </film>
-</svml>
diff --git a/test/fixtures/disconnected/duplicate-captions.svml b/test/fixtures/disconnected/duplicate-captions.svml
deleted file mode 100644
index 39286f14..00000000
--- a/test/fixtures/disconnected/duplicate-captions.svml
+++ /dev/null
@@ -1,22 +0,0 @@
-<svml version="1">
- <import from="../../../stdlib/speech-assemble.svk"/>
- <import from="../../../stdlib/speech-locator.svk"/>
- <import from="../../../stdlib/caption-planner.svk"/>
- <import from="../../../stdlib/caption-track.svk"/>
- <import from="../../../stdlib/film.svk"/>
-
- <script><segment id="main">Alpha omega.</segment></script>
- <audio id="voice-audio" src="../presentation/long.mp4"/>
- <timing id="timing" src="./alignment.json"/>
- <speech-assemble id="speech" fps="30">
- <segment id="main" script={script.segment.main} audio={voice-audio} sourceWindow="0s .. 3s"/>
- </speech-assemble>
- <speech-locator id="location" script={script} basis={speech.production} evidence={timing}/>
- <caption-planner id="caption-plan" script={script} semantic={location.map}/>
- <caption-track id="captions-a" script={script} semantic={location.map} plan={caption-plan.plan} z="10"/>
- <caption-track id="captions-b" script={script} semantic={location.map} plan={caption-plan.plan} z="11"/>
- <film id="film" basis={speech.production} semantic={location.map}>
- <track ref={captions-a.track}/>
- <track ref={captions-b.track}/>
- </film>
-</svml>
diff --git a/test/fixtures/disconnected/each.svml b/test/fixtures/disconnected/each.svml
deleted file mode 100644
index d2f60278..00000000
--- a/test/fixtures/disconnected/each.svml
+++ /dev/null
@@ -1,27 +0,0 @@
-<svml version="1">
- <import from="../../../stdlib/speech-assemble.svk"/>
- <import from="../../../stdlib/speech-locator.svk"/>
- <import from="../../../stdlib/media-track.svk"/>
- <import from="../../../stdlib/film.svk"/>
-
- <script>
- <segment id="main">@pick Alpha @/pick gap @pick omega @/pick.</segment>
- </script>
-
- <video id="avatar" src="../presentation/long.mp4"/>
- <audio id="voice-audio" src="../presentation/long.mp4"/>
- <timing id="timing" src="./alignment.json"/>
-
- <speech-assemble id="speech" fps="30">
- <segment id="main" script={script.segment.main} visual={avatar} audio={voice-audio} sourceWindow="0s .. 3s"/>
- </speech-assemble>
- <speech-locator id="location" script={script} basis={speech.production} evidence={timing}/>
-
- <media-track id="media" z="1">
- <item id="picked" source={avatar} during={script.selection.pick}/>
- </media-track>
-
- <film id="film" basis={speech.production} semantic={location.map}>
- <track ref={media.track}/>
- </film>
-</svml>
diff --git a/test/fixtures/disconnected/one.svml b/test/fixtures/disconnected/one.svml
deleted file mode 100644
index 86ceafbf..00000000
--- a/test/fixtures/disconnected/one.svml
+++ /dev/null
@@ -1,28 +0,0 @@
-<svml version="1">
- <import from="../../../stdlib/speech-assemble.svk"/>
- <import from="../../../stdlib/speech-locator.svk"/>
- <import from="../../../stdlib/ranking-column.svk"/>
- <import from="../../../stdlib/film.svk"/>
-
- <script>
- <segment id="main">@pick Alpha @/pick gap @pick omega @/pick.</segment>
- </script>
-
- <video id="avatar" src="../presentation/long.mp4"/>
- <audio id="voice-audio" src="../presentation/long.mp4"/>
- <image id="icon" src="../collision/left/image.png"/>
- <timing id="timing" src="./alignment.json"/>
-
- <speech-assemble id="speech" fps="30">
- <segment id="main" script={script.segment.main} visual={avatar} audio={voice-audio} sourceWindow="0s .. 3s"/>
- </speech-assemble>
- <speech-locator id="location" script={script} basis={speech.production} evidence={timing}/>
-
- <ranking-column id="ranking" z="1">
- <item id="picked" rank="1" image={icon} during={script.selection.pick}/>
- </ranking-column>
-
- <film id="film" basis={speech.production} semantic={location.map}>
- <track ref={ranking.track}/>
- </film>
-</svml>
diff --git a/test/fixtures/disconnected/selection-set.mjs b/test/fixtures/disconnected/selection-set.mjs
deleted file mode 100644
index 99842bf0..00000000
--- a/test/fixtures/disconnected/selection-set.mjs
+++ /dev/null
@@ -1,17 +0,0 @@
-export default {
- abiVersion: "1",
- project(context) {
- const item = context.element.children.find(
- (child) => child.kind === "element" && child.name === "item",
- );
- const ranges = context.selection(item.attributes.during, "item.during");
- const track = { visuals: [], audios: [], styles: [] };
- return {
- outputs: { track },
- diagnostics: [{
- code: "selection_set_count",
- message: String(ranges.length),
- }],
- };
- },
-};
diff --git a/test/fixtures/disconnected/selection-set.svk b/test/fixtures/disconnected/selection-set.svk
deleted file mode 100644
index 1e8b2adb..00000000
--- a/test/fixtures/disconnected/selection-set.svk
+++ /dev/null
@@ -1,8 +0,0 @@
-<kernel name="selection-set" abi="1" implementation="./selection-set.mjs">
- <port name="item" direction="input" type="SelectionRule" cardinality="one"/>
- <port name="track" direction="output" type="Track" cardinality="one"/>
- <child name="item" cardinality="one">
- <field name="id" type="id" required="true"/>
- <field name="during" type="SelectionSet" consume="set" required="true"/>
- </child>
-</kernel>
diff --git a/test/fixtures/disconnected/set.svml b/test/fixtures/disconnected/set.svml
deleted file mode 100644
index ff951c22..00000000
--- a/test/fixtures/disconnected/set.svml
+++ /dev/null
@@ -1,27 +0,0 @@
-<svml version="1">
- <import from="../../../stdlib/speech-assemble.svk"/>
- <import from="../../../stdlib/speech-locator.svk"/>
- <import from="./selection-set.svk"/>
- <import from="../../../stdlib/film.svk"/>
-
- <script>
- <segment id="main">@pick Alpha @/pick gap @pick omega @/pick.</segment>
- </script>
-
- <video id="avatar" src="../presentation/long.mp4"/>
- <audio id="voice-audio" src="../presentation/long.mp4"/>
- <timing id="timing" src="./alignment.json"/>
-
- <speech-assemble id="speech" fps="30">
- <segment id="main" script={script.segment.main} visual={avatar} audio={voice-audio} sourceWindow="0s .. 3s"/>
- </speech-assemble>
- <speech-locator id="location" script={script} basis={speech.production} evidence={timing}/>
-
- <selection-set id="styles">
- <item id="highlight" during={script.selection.pick}/>
- </selection-set>
-
- <film id="film" basis={speech.production} semantic={location.map}>
- <track ref={styles.track}/>
- </film>
-</svml>
diff --git a/test/fixtures/media-basis/main.svml b/test/fixtures/media-basis/main.svml
deleted file mode 100644
index 7f0b36d0..00000000
--- a/test/fixtures/media-basis/main.svml
+++ /dev/null
@@ -1,14 +0,0 @@
-<svml version="1">
- <import from="../../../stdlib/media-basis.svk"/>
- <import from="../../../stdlib/speech-locator.svk"/>
- <import from="../../../stdlib/film.svk"/>
-
- <script><segment id="main">Hello.</segment></script>
- <video id="visual" src="../collision/avatar.mp4"/>
- <audio id="audio" src="../collision/avatar.mp4"/>
- <timing id="timing" src="../artifacts/alignment.json"/>
-
- <media-basis id="program" visual={visual} audio={audio} duration="1s"/>
- <speech-locator id="location" script={script} basis={program.production} evidence={timing}/>
- <film id="film" basis={program.production} semantic={location.map}/>
-</svml>
diff --git a/test/fixtures/modules/alignment.json b/test/fixtures/modules/alignment.json
deleted file mode 100644
index 02f6b18e..00000000
--- a/test/fixtures/modules/alignment.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "contract": "svml.speech-timing-evidence.v1",
- "durationSec": 1,
- "fps": 30,
- "quality": "measured",
- "units": [
- {
- "text": "Hello",
- "startSec": 0.1,
- "endSec": 0.8,
- "segmentId": "main"
- }
- ],
- "segments": [
- {
- "id": "main",
- "startSec": 0,
- "endSec": 1
- }
- ]
-}
diff --git a/test/fixtures/modules/brand.svc b/test/fixtures/modules/brand.svc
deleted file mode 100644
index a644c95d..00000000
--- a/test/fixtures/modules/brand.svc
+++ /dev/null
@@ -1,11 +0,0 @@
-<content version="1" id="brand">
- <import from="./identity-image.svk"/>
-
- <image id="logo" src="./logo.png"/>
-
- <text id="tagline">
- A #1 semantic video language.
- </text>
-
- <identity-image id="poster" source={logo}/>
-</content>
diff --git a/test/fixtures/modules/house.svs b/test/fixtures/modules/house.svs
deleted file mode 100644
index ee3945d1..00000000
--- a/test/fixtures/modules/house.svs
+++ /dev/null
@@ -1,24 +0,0 @@
-<sheet version="1" id="house">
- broll-track.full {
- z: 100;
- }
-
- caption-track.launch {
- z: 510;
- font-size: 44;
- fill: #fefefe;
- }
-
- subtitles.launch {
- z: 510;
- font-size: 44;
- fill: #fefefe;
- }
-
- film.vertical {
- width: 1080;
- height: 1920;
- frame-rate: 30;
- background: #112233;
- }
-</sheet>
diff --git a/test/fixtures/modules/identity-image.mjs b/test/fixtures/modules/identity-image.mjs
deleted file mode 100644
index b853ee94..00000000
--- a/test/fixtures/modules/identity-image.mjs
+++ /dev/null
@@ -1,11 +0,0 @@
-export default {
- abiVersion: "1",
- project(context) {
- const source = context.resolve(context.element.attributes.source);
- return {
- outputs: {
- image: source,
- },
- };
- },
-};
diff --git a/test/fixtures/modules/identity-image.svk b/test/fixtures/modules/identity-image.svk
deleted file mode 100644
index d759a8de..00000000
--- a/test/fixtures/modules/identity-image.svk
+++ /dev/null
@@ -1,4 +0,0 @@
-<kernel name="identity-image" abi="1" implementation="./identity-image.mjs">
- <port name="source" direction="input" type="Image" cardinality="one"/>
- <port name="image" direction="output" type="Image" cardinality="one"/>
-</kernel>
diff --git a/test/fixtures/modules/main-renamed-alias.svml b/test/fixtures/modules/main-renamed-alias.svml
deleted file mode 100644
index 25f8b8d8..00000000
--- a/test/fixtures/modules/main-renamed-alias.svml
+++ /dev/null
@@ -1,38 +0,0 @@
-<svml version="1">
- <import from="../../../stdlib/speech-assemble.svk"/>
- <import from="../../../stdlib/speech-locator.svk"/>
- <import from="../../../stdlib/broll-track.svk"/>
- <import from="../../../stdlib/caption-planner.svk"/>
- <import as="subtitles" from="../../../stdlib/caption-track.svk"/>
- <import from="../../../stdlib/film.svk"/>
- <import as="assets" from="./brand.svc"/>
- <import as="house" from="./house.svs"/>
-
- <script>
- <segment id="main">
- @poster Hello @/poster.
- </segment>
- </script>
-
- <video id="avatar" src="./avatar.mp4"/>
- <audio id="voice-audio" src="./avatar.mp4"/>
- <timing id="timing" src="./alignment.json"/>
-
- <speech-assemble id="speech" fps="30">
- <segment id="main" script={script.segment.main} visual={avatar} audio={voice-audio} sourceWindow="0s .. 1s"/>
- </speech-assemble>
-
- <speech-locator id="location" script={script} basis={speech.production} evidence={timing}/>
-
- <broll-track id="broll" class="house.full">
- <item id="poster" source={assets.poster.image} during={script.selection.poster}/>
- </broll-track>
-
- <caption-planner id="caption-plan" script={script} semantic={location.map}/>
- <subtitles id="captions" script={script} semantic={location.map} plan={caption-plan.plan} class="house.launch" size="48"/>
-
- <film id="main-film" class="house.vertical" basis={speech.production} semantic={location.map}>
- <track ref={broll.track}/>
- <track ref={captions.track}/>
- </film>
-</svml>
diff --git a/test/fixtures/modules/main.svml b/test/fixtures/modules/main.svml
deleted file mode 100644
index 68e0afc4..00000000
--- a/test/fixtures/modules/main.svml
+++ /dev/null
@@ -1,38 +0,0 @@
-<svml version="1">
- <import from="../../../stdlib/speech-assemble.svk"/>
- <import from="../../../stdlib/speech-locator.svk"/>
- <import from="../../../stdlib/broll-track.svk"/>
- <import from="../../../stdlib/caption-planner.svk"/>
- <import from="../../../stdlib/caption-track.svk"/>
- <import from="../../../stdlib/film.svk"/>
- <import as="brand" from="./brand.svc"/>
- <import as="house" from="./house.svs"/>
-
- <script>
- <segment id="main">
- @poster Hello @/poster.
- </segment>
- </script>
-
- <video id="avatar" src="./avatar.mp4"/>
- <audio id="voice-audio" src="./avatar.mp4"/>
- <timing id="timing" src="./alignment.json"/>
-
- <speech-assemble id="speech" fps="30">
- <segment id="main" script={script.segment.main} visual={avatar} audio={voice-audio} sourceWindow="0s .. 1s"/>
- </speech-assemble>
-
- <speech-locator id="location" script={script} basis={speech.production} evidence={timing}/>
-
- <broll-track id="broll" class="house.full">
- <item id="poster" source={brand.poster.image} during={script.selection.poster}/>
- </broll-track>
-
- <caption-planner id="caption-plan" script={script} semantic={location.map}/>
- <caption-track id="captions" script={script} semantic={location.map} plan={caption-plan.plan} class="house.launch" size="48"/>
-
- <film id="main-film" class="house.vertical" basis={speech.production} semantic={location.map}>
- <track ref={broll.track}/>
- <track ref={captions.track}/>
- </film>
-</svml>
diff --git a/test/fixtures/presentation/alignment.json b/test/fixtures/presentation/alignment.json
deleted file mode 100644
index 581dec35..00000000
--- a/test/fixtures/presentation/alignment.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "contract": "svml.speech-timing-evidence.v1",
- "durationSec": 3,
- "fps": 30,
- "quality": "measured",
- "units": [
- { "text": "One", "startSec": 0.2, "endSec": 0.6, "segmentId": "main" },
- { "text": "two", "startSec": 1.1, "endSec": 1.5, "segmentId": "main" },
- { "text": "three", "startSec": 2.1, "endSec": 2.7, "segmentId": "main" }
- ],
- "segments": [
- { "id": "main", "startSec": 0, "endSec": 3 }
- ]
-}
diff --git a/test/fixtures/presentation/empty-present.svml b/test/fixtures/presentation/empty-present.svml
deleted file mode 100644
index 7644c3e8..00000000
--- a/test/fixtures/presentation/empty-present.svml
+++ /dev/null
@@ -1,31 +0,0 @@
-<svml version="1">
- <import from="../../../stdlib/speech-assemble.svk"/>
- <import from="../../../stdlib/speech-locator.svk"/>
- <import from="../../../stdlib/media-track.svk"/>
- <import from="../../../stdlib/film.svk"/>
-
- <script>
- <segment id="main">
- One @pop! two three.
- </segment>
- </script>
-
- <video id="long-video" src="./long.mp4"/>
- <audio id="voice-audio" src="./long.mp4"/>
- <timing id="timing" src="./alignment.json"/>
-
- <speech-assemble id="speech" fps="30">
- <segment id="main" script={script.segment.main} visual={long-video} audio={voice-audio} sourceWindow="0s .. 3s"/>
- </speech-assemble>
- <speech-locator id="location" script={script} basis={speech.production} evidence={timing}/>
-
- <media-track id="aroll" z="200">
- <item id="host" source={long-video} during="full">
- <present id="outside" during="end+1s .. end+2s" z="230"/>
- </item>
- </media-track>
-
- <film id="presentation" basis={speech.production} semantic={location.map}>
- <track ref={aroll.track}/>
- </film>
-</svml>
diff --git a/test/fixtures/presentation/main.svml b/test/fixtures/presentation/main.svml
deleted file mode 100644
index e74783c6..00000000
--- a/test/fixtures/presentation/main.svml
+++ /dev/null
@@ -1,58 +0,0 @@
-<svml version="1">
- <import from="../../../stdlib/speech-assemble.svk"/>
- <import from="../../../stdlib/speech-locator.svk"/>
- <import from="../../../stdlib/media-track.svk"/>
- <import from="../../../stdlib/audio-track.svk"/>
- <import from="../../../stdlib/film.svk"/>
-
- <script>
- <segment id="main">
- One @pop! two three.
- </segment>
- </script>
-
- <video id="long-video" src="./long.mp4"/>
- <audio id="voice-audio" src="./long.mp4"/>
- <audio id="pop-sound" src="./pop.wav"/>
- <timing id="timing" src="./alignment.json"/>
-
- <speech-assemble id="speech" fps="30">
- <segment id="main" script={script.segment.main} visual={long-video} audio={voice-audio} sourceWindow="0s .. 3s"/>
- </speech-assemble>
-
- <speech-locator id="location" script={script} basis={speech.production} evidence={timing}/>
-
- <media-track id="aroll" z="200">
- <item id="host" source={long-video} during="full" fit="cover">
- <present
- id="top-circle"
- during="start .. start+1.2s"
- z="210"
- x="0.05"
- y="0.05"
- width="0.3"
- height="0.3"
- shape="circle"
- />
- <present
- id="lower-split"
- during="start+1s .. start+2s"
- z="220"
- x="0"
- y="0.5"
- width="1"
- height="0.5"
- enter="fade 200ms"
- />
- </item>
- </media-track>
-
- <audio-track id="sfx">
- <item id="pop" source={pop-sound} at={script.moment.pop} duration="200ms" bus="sfx"/>
- </audio-track>
-
- <film id="presentation" basis={speech.production} semantic={location.map}>
- <track ref={aroll.track}/>
- <track ref={sfx.track}/>
- </film>
-</svml>
diff --git a/test/fixtures/unsafe/alignment.json b/test/fixtures/unsafe/alignment.json
deleted file mode 100644
index 568a3efb..00000000
--- a/test/fixtures/unsafe/alignment.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "contract": "svml.speech-timing-evidence.v1",
- "durationSec": 1,
- "fps": 30,
- "quality": "measured",
- "units": [
- { "text": "Hello", "startSec": 0.1, "endSec": 0.8, "segmentId": "main" }
- ],
- "segments": [
- { "id": "main", "startSec": 0, "endSec": 1 }
- ]
-}
diff --git a/test/fixtures/unsafe/main.svml b/test/fixtures/unsafe/main.svml
deleted file mode 100644
index b7f7b962..00000000
--- a/test/fixtures/unsafe/main.svml
+++ /dev/null
@@ -1,18 +0,0 @@
-<svml version="1">
- <import from="./unsafe.svk"/>
- <import from="../../../stdlib/speech-assemble.svk"/>
- <import from="../../../stdlib/speech-locator.svk"/>
-
- <script>
- <segment id="main">Hello.</segment>
- </script>
-
- <audio id="voice-audio" src="./alignment.json"/>
- <timing id="timing" src="./alignment.json"/>
- <speech-assemble id="speech" fps="30">
- <segment id="main" script={script.segment.main} audio={voice-audio} sourceWindow="0s .. 1s"/>
- </speech-assemble>
- <speech-locator id="location" script={script} basis={speech.production} evidence={timing}/>
-
- <unsafe id="main" basis={speech.production} semantic={location.map}/>
-</svml>
diff --git a/test/fixtures/unsafe/unsafe.mjs b/test/fixtures/unsafe/unsafe.mjs
deleted file mode 100644
index fc79bd67..00000000
--- a/test/fixtures/unsafe/unsafe.mjs
+++ /dev/null
@@ -1,9 +0,0 @@
-import fs from "node:fs";
-
-export default {
- abiVersion: "1",
- project() {
- fs.readFileSync("/etc/passwd");
- return { outputs: {} };
- },
-};
diff --git a/test/fixtures/unsafe/unsafe.svk b/test/fixtures/unsafe/unsafe.svk
deleted file mode 100644
index d7ca9692..00000000
--- a/test/fixtures/unsafe/unsafe.svk
+++ /dev/null
@@ -1,5 +0,0 @@
-<kernel name="unsafe" abi="1" root="true" implementation="./unsafe.mjs">
- <port name="basis" direction="input" type="TemporalBasisProduction" cardinality="one"/>
- <port name="semantic" direction="input" type="CompleteSemanticMap" cardinality="one"/>
- <port name="document" direction="output" type="HyperframesDocument" cardinality="one"/>
-</kernel>
diff --git a/test/flat-track-launch.test.ts b/test/flat-track-launch.test.ts
deleted file mode 100644
index 67211e76..00000000
--- a/test/flat-track-launch.test.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-import { fileURLToPath } from "node:url";
-import { compileSource } from "../src/compiler.js";
-import type { SourceElement } from "../src/model.js";
-
-const example = fileURLToPath(new URL("../examples/flat-track-launch/flat-track-launch.svml", import.meta.url));
-
-function elements(nodes: SourceElement["children"], name: string): SourceElement[] {
- return nodes.filter((node): node is SourceElement => node.kind === "element" && node.name === name);
-}
-
-test("the flat Track launch fixture closes the complete v1 compilation contract", async () => {
- const compilation = await compileSource({ file: example });
-
- assert.equal(compilation.located.durationFrames, 1083);
- assert.equal(
- compilation.narrative.semanticIndex.anchors.length,
- compilation.narrative.tokens.length * 2 + compilation.narrative.segments.length * 2,
- );
- assert.equal(compilation.located.selections.emphasis?.ranges.length, 2);
- assert.equal(compilation.target.width, 1080);
- assert.equal(compilation.target.height, 1920);
-
- const arroll = compilation.plan.instances.find((instance) => instance.id === "aroll");
- const item = elements(arroll?.children ?? [], "item")[0];
- const openingLeft = elements(item?.children ?? [], "present")
- .find((present) => present.attributes.id === "opening-left");
- assert.equal(openingLeft?.attributes.shape, "circle");
- assert.equal(openingLeft?.attributes.width, 0.3);
-
- const overlays = compilation.plan.instances.find((instance) => instance.id === "overlays");
- const title = elements(overlays?.children ?? [], "item")
- .find((candidate) => candidate.attributes.id === "opening-title");
- assert.equal(title?.attributes.size, 64);
- assert.equal(title?.attributes.color, "#FFFFFF");
-
- const broll = compilation.projections.get("broll");
- const productVisual = broll?.visuals?.find((fragment) => fragment.id.includes(":product-demo:"));
- const productAudio = broll?.audios?.find((fragment) => fragment.id.includes(":product-demo:"));
- assert.equal(productAudio?.playbackRate, productVisual?.playbackRate);
- assert.equal(productVisual?.muted, true);
- assert.equal(broll?.audios?.some((fragment) => fragment.bus === "sfx"), true);
-
- const board = compilation.projections.get("ranking")?.visuals
- ?.find((fragment) => fragment.id === "ranking:board");
- assert.equal(board?.startFrame, compilation.located.moments.ranking?.frames[0]);
-
- const text = compilation.projections.get("overlays")?.visuals ?? [];
- assert.deepEqual(
- text.map((fragment) => [fragment.id, fragment.startFrame, fragment.endFrameExclusive]),
- [
- ["overlays:opening-title:0", 0, 90],
- ["overlays:ending-arrow:0", 1023, 1083],
- ],
- );
-
- const captions = compilation.projections.get("captions")?.visuals ?? [];
- assert.ok(captions.some((fragment) => /#FDE047/u.test(fragment.html ?? "")));
- assert.ok(captions.some((fragment) => /scale\(1\.08\)/u.test(fragment.html ?? "")));
- assert.match(compilation.html, /data-composition-id="launch"/u);
-});
diff --git a/test/hyperframes.test.ts b/test/hyperframes.test.ts
deleted file mode 100644
index 4fe5c066..00000000
--- a/test/hyperframes.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-import { emitHyperframesHtml, frameSeconds } from "../src/hyperframes.js";
-
-test("frame lowering preserves half-open intervals for repeating seconds", () => {
- assert.equal(frameSeconds(977, 30), "32.566666666");
- assert.equal(frameSeconds(32, 30), "1.066666666");
-
- const html = emitHyperframesHtml({
- id: "floating-boundary",
- width: 1080,
- height: 1920,
- fps: 30,
- durationFrames: 1083,
- background: "#000",
- visuals: [{
- id: "instagram-post",
- kind: "image",
- source: "./post.png",
- startFrame: 977,
- endFrameExclusive: 1009,
- z: 1,
- }],
- audios: [],
- });
-
- assert.match(html, /data-start="32\.566666666"/u);
- assert.match(html, /data-duration="1\.066666666"/u);
-});
diff --git a/test/kernel-contracts.test.ts b/test/kernel-contracts.test.ts
deleted file mode 100644
index 495b7ae9..00000000
--- a/test/kernel-contracts.test.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import assert from "node:assert/strict";
-import { mkdtemp, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import test from "node:test";
-import { fileURLToPath } from "node:url";
-import { checkSource } from "../src/compiler.js";
-
-const brollKernel = fileURLToPath(
- new URL("../stdlib/broll-track.svk", import.meta.url),
-);
-const unsafeKernel = fileURLToPath(
- new URL("./fixtures/artifacts/artifact-film.svk", import.meta.url),
-);
-
-async function checkBody(body: string): Promise<ReturnType<typeof checkSource>> {
- const directory = await mkdtemp(join(tmpdir(), "svml-kernel-contract-"));
- const file = join(directory, "main.svml");
- await writeFile(file, `<svml version="1">
- <import from="${brollKernel}"/>
- <import from="${unsafeKernel}"/>
- <script><segment id="main">Hello.</segment></script>
- <audio id="sound" src="./missing.wav"/>
- ${body}
- <artifact-film id="root" image={sound} basis={sound} semantic={sound}/>
-</svml>
-`, "utf8");
- return checkSource(file);
-}
-
-test("Kernel child schemas reject unknown fields, wrong references and cardinality", async () => {
- await assert.rejects(
- checkBody('<broll-track id="broll" z="1"/>'),
- /kernel_child_cardinality/u,
- );
- await assert.rejects(
- checkBody(`
- <broll-track id="broll" z="1">
- <item id="one" source={sound} during="full"/>
- </broll-track>
- `),
- /plan_port_type/u,
- );
- await assert.rejects(
- checkBody(`
- <broll-track id="broll" z="1">
- <item id="one" source={sound} during="full" zoon="1"/>
- </broll-track>
- `),
- /kernel_field_unknown/u,
- );
-});
diff --git a/test/modules.test.ts b/test/modules.test.ts
deleted file mode 100644
index 0d901df5..00000000
--- a/test/modules.test.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-import { mkdir, mkdtemp, readFile, readdir, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { fileURLToPath } from "node:url";
-import { checkSource, compileSource } from "../src/compiler.js";
-import { SvmlError } from "../src/diagnostics.js";
-import { portableFileIdentity } from "../src/util.js";
-
-const fixtures = fileURLToPath(new URL("./fixtures/modules/", import.meta.url));
-
-test(".svc content DAG and .svs parameter classes bind into one source closure", async () => {
- const file = `${fixtures}/main.svml`;
- const checked = await checkSource(file);
-
- assert.deepEqual(
- checked.plan.instances.map((instance) => instance.id).sort(),
- ["brand.poster", "broll", "caption-plan", "captions", "location", "main-film", "speech"],
- );
- assert.deepEqual(
- checked.plan.values.map((value) => value.id).sort(),
- ["avatar", "brand.logo", "timing", "voice-audio"],
- );
- const logo = checked.plan.values.find((value) => value.id === "brand.logo");
- assert.equal(logo?.localId, "logo");
- assert.match(logo?.module ?? "", /brand\.svc$/u);
- assert.ok(!checked.plan.values.some((value) => value.id === "brand.tagline"));
-
- const captions = checked.plan.instances.find((instance) => instance.id === "captions");
- assert.equal(captions?.attributes.z, 510);
- assert.equal(captions?.attributes.size, 48);
- assert.equal(captions?.attributes.color, "#fefefe");
- assert.deepEqual(
- captions?.effectiveParameters.size?.sources.map((source) => source.kind),
- ["kernel-default", "svs-class", "instance"],
- );
-
- const film = checked.plan.instances.find((instance) => instance.id === "main-film");
- assert.equal(film?.attributes.background, "#112233");
- assert.equal(film?.attributes.fps, 30);
-
- const compilation = await compileSource({
- file,
- });
- assert.match(compilation.html, /data-composition-id="main-film"/u);
- assert.match(compilation.html, /#112233/u);
- assert.match(compilation.html, /logo\.png/u);
-});
-
-test("import aliases do not change imported instance identity or execution digest", async () => {
- const original = await checkSource(`${fixtures}/main.svml`);
- const renamed = await checkSource(`${fixtures}/main-renamed-alias.svml`);
- const before = original.plan.instances.find((instance) => instance.localId === "poster");
- const after = renamed.plan.instances.find((instance) => instance.localId === "poster");
-
- assert.equal(before?.identity, after?.identity);
- assert.equal(before?.executionDigest, after?.executionDigest);
-});
-
-test("svml.lock verifies the exact source closure and Kernel implementations", async () => {
- const file = `${fixtures}/main.svml`;
- const checked = await checkSource(file);
- assert.ok(checked.lock.modules.every((module) => module.uri.startsWith("svml-file:")));
- assert.ok(checked.lock.kernels.every((kernel) =>
- kernel.manifestUri.startsWith("svml-file:")
- && (kernel.implementationUri?.startsWith("svml-file:") ?? true)));
- assert.ok(checked.lock.materials
- .filter((material) => material.uri?.startsWith("svml-file:"))
- .every((material) => !material.uri?.includes(process.cwd())));
- const directory = await mkdtemp(join(tmpdir(), "svml-lock-"));
- const lock = join(directory, "svml.lock");
- await writeFile(lock, `${JSON.stringify(checked.lock, null, 2)}\n`, "utf8");
-
- const verified = await compileSource({
- file,
- lockFile: lock,
- });
- assert.equal(verified.sourceClosureVerified, true);
- assert.equal(verified.lockVerified, false);
- await writeFile(lock, `${JSON.stringify(verified.lock, null, 2)}\n`, "utf8");
- const frozen = await compileSource({ file, lockFile: lock });
- assert.equal(frozen.lockVerified, true);
- assert.equal(frozen.lock.execution?.htmlDigest.length, 64);
-
- const changed = structuredClone(checked.lock);
- changed.kernels[0]!.implementationHash = "0".repeat(64);
- await writeFile(lock, `${JSON.stringify(changed, null, 2)}\n`, "utf8");
- await assert.rejects(
- compileSource({
- file,
- lockFile: lock,
- }),
- (error: unknown) =>
- error instanceof SvmlError
- && error.diagnostics.some((diagnostic) => diagnostic.code === "lock_mismatch"),
- );
-});
-
-test("portable file identity survives relocating the complete source closure", () => {
- assert.equal(
- portableFileIdentity("/checkout-a/project/main.svml", "/checkout-a/project/content/brand.svc"),
- portableFileIdentity("/checkout-b/project/main.svml", "/checkout-b/project/content/brand.svc"),
- );
-});
-
-test("asset staging uses content-addressed names and never overwrites equal basenames", async () => {
- const collision = fileURLToPath(new URL("./fixtures/collision/", import.meta.url));
- const directory = await mkdtemp(join(tmpdir(), "svml-assets-"));
- const output = join(directory, "index.html");
- await mkdir(directory, { recursive: true });
- await compileSource({
- file: `${collision}/main.svml`,
- outputFile: output,
- });
-
- const assets = await readdir(join(directory, "assets"));
- const images = assets.filter((name) => name.endsWith("-image.png"));
- assert.equal(images.length, 2);
- assert.notEqual(images[0], images[1]);
- const html = await readFile(output, "utf8");
- for (const image of images) assert.match(html, new RegExp(image, "u"));
-});
diff --git a/test/presentation.test.ts b/test/presentation.test.ts
deleted file mode 100644
index 327d359c..00000000
--- a/test/presentation.test.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-import { fileURLToPath } from "node:url";
-import { compileSource } from "../src/compiler.js";
-import type { VisualFragment } from "../src/runtime-contract.js";
-
-test("Present ranges intersect the Item, overlap by absolute z, and keep one source-time map", async () => {
- const fixture = fileURLToPath(new URL("./fixtures/presentation/", import.meta.url));
- const compilation = await compileSource({
- file: `${fixture}/main.svml`,
- });
- const visuals = compilation.projections.get("aroll")?.visuals ?? [];
- assert.equal(visuals.length, 3);
- assert.deepEqual(
- visuals.map((fragment) => [
- fragment.startFrame,
- fragment.endFrameExclusive,
- fragment.z,
- fragment.mediaStartSec,
- ]),
- [
- [60, 90, 200, 2],
- [0, 36, 210, 0],
- [30, 60, 220, 1],
- ],
- );
- assert.equal(visuals[1]?.style?.["border-radius"], "50%");
- assert.match(visuals[2]?.css ?? "", /@keyframes svml-present/u);
- const sfx = compilation.projections.get("sfx")?.audios ?? [];
- assert.deepEqual(
- sfx.map((fragment) => [
- fragment.startFrame,
- fragment.endFrameExclusive,
- fragment.bus,
- ]),
- [[33, 39, "sfx"]],
- );
-});
-
-test("a Present with no parent intersection fails instead of disappearing", async () => {
- const fixture = fileURLToPath(new URL("./fixtures/presentation/", import.meta.url));
- await assert.rejects(
- compileSource({ file: `${fixture}/empty-present.svml` }),
- /presentation_empty/u,
- );
-});
-
-test("B-roll crossfade extends only the visual surfaces and leaves source audio independent", async () => {
- const fixture = fileURLToPath(new URL("./fixtures/collision/", import.meta.url));
- const compilation = await compileSource({
- file: `${fixture}/main.svml`,
- });
- const broll = compilation.projections.get("broll");
- const visuals = (broll?.visuals ?? []) as VisualFragment[];
- const left = visuals.find((fragment) => fragment.id.includes(":left:"));
- const right = visuals.find((fragment) => fragment.id.includes(":right:"));
- assert.equal(left?.endFrameExclusive, 36);
- assert.equal(right?.startFrame, 30);
- assert.match(left?.css ?? "", /svml-broll-transition/u);
- assert.match(right?.css ?? "", /svml-broll-transition/u);
- assert.equal(broll?.audios?.length ?? 0, 0);
-});
-
-test("temporal one/each cardinality is declared by the Kernel contract", async () => {
- const fixture = fileURLToPath(new URL("./fixtures/disconnected/", import.meta.url));
- const each = await compileSource({
- file: `${fixture}/each.svml`,
- });
- assert.equal(each.projections.get("media")?.visuals?.length, 2);
- const media = each.plan.kernels.find((kernel) => kernel.name === "media-track");
- assert.equal(media?.children[0]?.fields.find((field) => field.name === "during")?.consume, "each");
-
- const set = await compileSource({
- file: `${fixture}/set.svml`,
- });
- assert.deepEqual(set.projections.get("styles")?.diagnostics, [{
- code: "selection_set_count",
- message: "2",
- }]);
-
- await assert.rejects(
- compileSource({
- file: `${fixture}/one.svml`,
- }),
- /temporal cardinality expected one, received 2/u,
- );
-});
-
-test("disconnected SelectionSet drives one caption style rule without losing occurrences", async () => {
- const fixture = fileURLToPath(new URL("./fixtures/disconnected/", import.meta.url));
- const compilation = await compileSource({ file: `${fixture}/captions.svml` });
- const captions = compilation.projections.get("captions")?.visuals ?? [];
- assert.ok(captions.length > 0);
- assert.ok(captions.some((fragment) => /color:#ff0000/u.test(fragment.html ?? "")));
- assert.ok(captions.some((fragment) => /color:#00ff00/u.test(fragment.html ?? "")));
- assert.ok(captions.some((fragment) => /scale\(1\.1\)/u.test(fragment.html ?? "")));
- assert.ok(captions.some((fragment) => /background:#0000ff/u.test(fragment.html ?? "")));
- assert.ok(captions.every((fragment) => !/gap/u.test(fragment.html ?? "")));
- const plan = compilation.projections.get("caption-plan")?.outputs.plan as {
- annotations?: Array<{ kind: string }>;
- };
- assert.deepEqual(plan.annotations?.map((annotation) => annotation.kind), ["accent", "accent"]);
-});
-
-test("a Composition rejects a second CaptionTrack but permits no CaptionTrack", async () => {
- const fixture = fileURLToPath(new URL("./fixtures/disconnected/", import.meta.url));
- await assert.rejects(
- compileSource({ file: `${fixture}/duplicate-captions.svml` }),
- /caption_track_cardinality/u,
- );
-});
diff --git a/test/regen-ranking.test.ts b/test/regen-ranking.test.ts
deleted file mode 100644
index 6bbd53d0..00000000
--- a/test/regen-ranking.test.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import assert from "node:assert/strict";
-import { readFile } from "node:fs/promises";
-import test from "node:test";
-import { fileURLToPath } from "node:url";
-import { compileSource, estimateSource } from "../src/compiler.js";
-import { projectCanvas, projectTimeline } from "../src/views.js";
-
-type Reference = {
- clock: { fps: number; durationFrames: number };
- plan: { root: string; values: number; instances: number; edges: number };
- selectionFrames: Record<string, Array<[number, number]>>;
- locatedOutput: { visualFragments: number; audioFragments: number };
-};
-
-const example = fileURLToPath(new URL("../examples/regen-ranking/", import.meta.url));
-
-test("regen ranking compiles to the frozen production timing contract", async () => {
- const reference = JSON.parse(
- await readFile(new URL("../examples/regen-ranking/reference.json", import.meta.url), "utf8"),
- ) as Reference;
- const compilation = await compileSource({
- file: `${example}/regen-ranking.svml`,
- });
-
- assert.equal(compilation.located.fps, reference.clock.fps);
- assert.equal(compilation.located.durationFrames, reference.clock.durationFrames);
- assert.deepEqual(
- {
- root: compilation.plan.root,
- values: compilation.plan.values.length,
- instances: compilation.plan.instances.length,
- edges: compilation.plan.edges.length,
- },
- reference.plan,
- );
-
- for (const [id, expected] of Object.entries(reference.selectionFrames)) {
- assert.deepEqual(
- compilation.located.selections[id]?.ranges.map(
- (range) => [range.startFrame, range.endFrameExclusive],
- ),
- expected,
- id,
- );
- }
-
- const document = compilation.projections.get(compilation.plan.root)?.outputs.document as {
- visuals?: unknown[];
- audios?: unknown[];
- };
- assert.equal(document.visuals?.length, reference.locatedOutput.visualFragments);
- assert.equal(document.audios?.length, reference.locatedOutput.audioFragments);
- assert.match(compilation.html, /data-composition-id="regen-ranking"/u);
- assert.match(compilation.html, /data-duration="36\.1"/u);
- assert.match(compilation.html, />Powerful</u);
- assert.doesNotMatch(compilation.html, /power full but|>uh</u);
- assert.ok(compilation.semanticMap.anchors.some((anchor) => anchor.quality === "derived"));
-
- const canvas = projectCanvas(compilation.plan);
- assert.equal(canvas.root, reference.plan.root);
- assert.equal(canvas.nodes.length, reference.plan.values + reference.plan.instances);
- assert.equal(canvas.edges.length, reference.plan.edges);
- const brollContract = compilation.plan.kernels.find(
- (kernel) => kernel.name === "broll-track",
- );
- assert.deepEqual(
- brollContract?.children.map((child) => child.name),
- ["item", "transition"],
- );
-
- const timeline = projectTimeline(compilation);
- assert.equal(timeline.durationFrames, reference.clock.durationFrames);
- assert.equal(timeline.visuals.length, reference.locatedOutput.visualFragments);
- assert.equal(timeline.audios.length, reference.locatedOutput.audioFragments);
-
- const estimate = await estimateSource(`${example}/regen-ranking.svml`);
- assert.ok(Math.abs(estimate.evidence.durationSec - reference.clock.durationFrames / 30) < 0.5);
-});
diff --git a/test/runtime-security.test.ts b/test/runtime-security.test.ts
deleted file mode 100644
index be80afba..00000000
--- a/test/runtime-security.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-import { fileURLToPath } from "node:url";
-import { compileSource } from "../src/compiler.js";
-import { SvmlError } from "../src/diagnostics.js";
-import { validateKernelProjection } from "../src/runtime-validation.js";
-
-test("projector CSS is scoped and active HTML is rejected", () => {
- const projection = validateKernelProjection({
- outputs: {},
- visuals: [{
- id: "safe",
- kind: "html",
- html: '<div class="label">Hello</div>',
- css: ".label { color: red; }",
- startFrame: 0,
- endFrameExclusive: 1,
- z: 1,
- }],
- });
- assert.match(projection.visuals?.[0]?.css ?? "", /^\[data-svml-scope="[a-f0-9]+"\] \.label/u);
- assert.throws(
- () => validateKernelProjection({
- outputs: {},
- visuals: [{
- id: "active",
- kind: "html",
- html: "<script>document.body.remove()</script>",
- startFrame: 0,
- endFrameExclusive: 1,
- z: 1,
- }],
- }),
- (error: unknown) =>
- error instanceof SvmlError
- && error.diagnostics.some((diagnostic) => diagnostic.code === "kernel_html_capability"),
- );
-});
-
-test("isolated projector ABI rejects Node builtin imports", async () => {
- const fixture = fileURLToPath(new URL("./fixtures/unsafe/", import.meta.url));
- await assert.rejects(
- compileSource({
- file: `${fixture}/main.svml`,
- }),
- (error: unknown) =>
- error instanceof SvmlError
- && error.diagnostics.some((diagnostic) => diagnostic.code === "kernel_projector_isolation"),
- );
-});
diff --git a/test/script.test.ts b/test/script.test.ts
deleted file mode 100644
index 6fa6bb8c..00000000
--- a/test/script.test.ts
+++ /dev/null
@@ -1,382 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-import type { NarrativeIR, SpeechTimingEvidence } from "../src/model.js";
-import { locateScript } from "../src/script/locate.js";
-import { estimateSpeechTiming } from "../src/script/estimate.js";
-import { parseScript } from "../src/script/parse.js";
-import { formatDocumentScript } from "../src/format.js";
-import { parseDocumentSource } from "../src/source/parse-document.js";
-import {
- createProgramBasis,
- semanticMapFromTiming,
- validateSemanticMap,
-} from "../src/temporal.js";
-import { sha256, stableJson } from "../src/util.js";
-
-function locateTiming(narrative: NarrativeIR, evidence: SpeechTimingEvidence) {
- const basis = createProgramBasis({
- fps: evidence.fps,
- durationFrames: Math.round(evidence.durationSec * evidence.fps),
- outcomeDigest: sha256(stableJson(evidence)),
- });
- const map = semanticMapFromTiming(narrative, basis, evidence);
- assert.equal(map.contract, "svml.complete-semantic-map.v1");
- return locateScript(narrative, basis, map);
-}
-
-test("Script Surface projects role, dual text, selections and moments", () => {
- const narrative = parseScript("fixture.svml", `
- @whole
- <segment id="one">
- <A> I just @laugh @pop! <lmao | laughed my @punch ass out @/punch> @/laugh.
- </segment>
- @/whole~
- `);
- assert.equal(narrative.projections.dialogue, "A: I just laughed my ass out.");
- assert.equal(narrative.projections.speech, "I just laughed my ass out.");
- assert.equal(narrative.projections.caption, "I just lmao.");
- assert.deepEqual(narrative.turns.map((turn) => [turn.role, turn.tokenStart, turn.tokenEndExclusive]), [
- ["A", 0, 6],
- ]);
- assert.equal(narrative.selections.whole?.length, 1);
- assert.equal(narrative.selections.laugh?.length, 1);
- assert.equal(narrative.selections.punch?.length, 1);
- assert.equal(narrative.moments.pop?.length, 1);
- assert.deepEqual(
- narrative.captionAtoms.map((atom) => [
- atom.display,
- atom.startToken,
- atom.endTokenExclusive,
- ]),
- [["lmao", 2, 6]],
- );
-});
-
-test("Script v1 builds independent 2M + 2N anchor identities", () => {
- const narrative = parseScript("fixture.svml", `
- <segment id="a">Alpha beta.</segment>
- <segment id="b"/>
- <segment id="c">Gamma.</segment>
- `);
- assert.equal(narrative.tokens.length, 3);
- assert.equal(narrative.segments.length, 3);
- assert.equal(narrative.semanticIndex.anchors.length, 2 * 3 + 2 * 3);
- assert.deepEqual(
- narrative.semanticIndex.anchors.map((anchor) => anchor.id),
- [
- "segment:a:start",
- "segment:a:token:1:start",
- "segment:a:token:1:end",
- "segment:a:token:2:start",
- "segment:a:token:2:end",
- "segment:a:end",
- "segment:b:start",
- "segment:b:end",
- "segment:c:start",
- "segment:c:token:1:start",
- "segment:c:token:1:end",
- "segment:c:end",
- ],
- );
- assert.notEqual(
- narrative.segments[0]?.endAnchorId,
- narrative.segments[1]?.startAnchorId,
- );
- assert.match(narrative.semanticIndex.digest, /^[a-f0-9]{64}$/u);
-});
-
-test("overlapping Segments retain distinct boundary affinity on one ProgramBasis", () => {
- const narrative = parseScript("fixture.svml", `
- <segment id="a">Alpha.</segment>
- ~@left! @right!
- <segment id="b">Beta.</segment>
- `);
- const evidence: SpeechTimingEvidence = {
- contract: "svml.speech-timing-evidence.v1",
- durationSec: 8,
- fps: 30,
- quality: "measured",
- units: [
- { text: "Alpha", startSec: 0.2, endSec: 4.8, segmentId: "a" },
- { text: "Beta", startSec: 4.6, endSec: 7.8, segmentId: "b" },
- ],
- segments: [
- { id: "a", startSec: 0, endSec: 5 },
- { id: "b", startSec: 4.5, endSec: 8 },
- ],
- };
- const located = locateTiming(narrative, evidence);
- assert.deepEqual(located.moments.left?.frames, [150]);
- assert.deepEqual(located.moments.right?.frames, [135]);
- assert.equal(located.segments.a?.endFrameExclusive, 150);
- assert.equal(located.segments.b?.startFrame, 135);
-});
-
-test("SemanticMap rejects source-order reversal, wrong basis and digest tampering", () => {
- const narrative = parseScript(
- "fixture.svml",
- `<segment id="a">Alpha.</segment><segment id="b">Beta.</segment>`,
- );
- const evidence: SpeechTimingEvidence = {
- contract: "svml.speech-timing-evidence.v1",
- durationSec: 5,
- fps: 30,
- quality: "measured",
- units: [
- { text: "Alpha", startSec: 1.1, endSec: 1.8, segmentId: "a" },
- { text: "Beta", startSec: 0.2, endSec: 0.8, segmentId: "b" },
- ],
- segments: [
- { id: "a", startSec: 1, endSec: 2 },
- { id: "b", startSec: 0, endSec: 1 },
- ],
- };
- const basis = createProgramBasis({
- fps: 30,
- durationFrames: 150,
- outcomeDigest: sha256("reordered"),
- });
- assert.throws(
- () => semanticMapFromTiming(narrative, basis, evidence),
- /locator_segment_order/u,
- );
-
- const validEvidence: SpeechTimingEvidence = {
- ...evidence,
- units: [
- { text: "Alpha", startSec: 0.1, endSec: 0.8, segmentId: "a" },
- { text: "Beta", startSec: 1.1, endSec: 1.8, segmentId: "b" },
- ],
- segments: [
- { id: "a", startSec: 0, endSec: 1 },
- { id: "b", startSec: 1, endSec: 2 },
- ],
- };
- const validMap = semanticMapFromTiming(
- narrative,
- basis,
- validEvidence,
- );
- assert.throws(
- () => validateSemanticMap(narrative, basis, {
- ...validMap,
- anchors: validMap.anchors.map((anchor, index) => index === 0
- ? { ...anchor, point: { ...anchor.point, frame: anchor.point.frame + 1 } }
- : anchor),
- }),
- /semantic_map_digest/u,
- );
- const otherBasis = createProgramBasis({
- fps: 30,
- durationFrames: 150,
- outcomeDigest: sha256("other"),
- });
- assert.throws(
- () => validateSemanticMap(narrative, otherBasis, validMap),
- /semantic_map_basis/u,
- );
-});
-
-test("Dual Text owns its complete speech span without entering SemanticMap", () => {
- const narrative = parseScript(
- "fixture.svml",
- `<segment id="one">I just <lmao | laughed my ass out>.</segment>`,
- );
- const evidence: SpeechTimingEvidence = {
- contract: "svml.speech-timing-evidence.v1",
- durationSec: 2,
- fps: 30,
- quality: "measured",
- units: [
- { text: "I", startSec: 0, endSec: 0.1, segmentId: "one" },
- { text: "just", startSec: 0.2, endSec: 0.4, segmentId: "one" },
- { text: "laughed", startSec: 0.5, endSec: 0.8, segmentId: "one" },
- { text: "my", startSec: 0.9, endSec: 1, segmentId: "one" },
- { text: "ass", startSec: 1.1, endSec: 1.3, segmentId: "one" },
- { text: "out", startSec: 1.4, endSec: 1.7, segmentId: "one" },
- ],
- segments: [{ id: "one", startSec: 0, endSec: 2 }],
- };
- const located = locateTiming(narrative, evidence);
- assert.deepEqual(
- located.captionAtoms.map((atom) => [
- atom.display,
- atom.startFrame,
- atom.endFrameExclusive,
- ]),
- [["lmao", 15, 51]],
- );
-});
-
-test("Slots bind after parsing and escaped reserved syntax stays literal", () => {
- const narrative = parseScript(
- "fixture.svml",
- "<segment id=\"one\">Meet <${display} | ${spoken}> at \\@openai and \\<tag>. ${literal}</segment>",
- 0,
- {
- display: "Hypit",
- spoken: "high pit",
- literal: "@/not-a-marker",
- },
- );
- assert.equal(narrative.projections.speech, "Meet high pit at @openai and <tag>. @/not-a-marker");
- assert.equal(narrative.projections.caption, "Meet Hypit at @openai and <tag>. @/not-a-marker");
- assert.equal(Object.keys(narrative.selections).length, 0);
- assert.throws(
- () => parseScript("fixture.svml", '<segment id="one">${missing}</segment>'),
- /script_slot_unbound/u,
- );
-});
-
-test("Selection and Moment names cannot conflict or reopen", () => {
- assert.throws(
- () => parseScript("fixture.svml", '<segment id="one">@x! one @x two @/x.</segment>'),
- /script_temporal_type_conflict/u,
- );
- assert.throws(
- () => parseScript("fixture.svml", '<segment id="one">@x one @x two @/x @/x.</segment>'),
- /script_selection_reopened/u,
- );
-});
-
-test("the same Selection id may produce a disconnected set", () => {
- const narrative = parseScript("fixture.svml", `
- <segment id="one">
- @pick Alpha @/pick then @pick omega @/pick.
- </segment>
- `);
- assert.equal(narrative.selections.pick?.length, 2);
-});
-
-test("selection endpoints must close", () => {
- assert.throws(
- () => parseScript("fixture.svml", `<segment id="one">@x hello.</segment>`),
- /script_selection_unclosed/u,
- );
-});
-
-test("direct Script-to-timing alignment handles N:1, 1:N, extras and missing units", () => {
- const narrative = parseScript(
- "fixture.svml",
- `<segment id="one">We really love hyper frames cannot now.</segment>`,
- );
- const evidence: SpeechTimingEvidence = {
- contract: "svml.speech-timing-evidence.v1",
- durationSec: 2.4,
- fps: 30,
- quality: "measured",
- units: [
- { text: "We", startSec: 0.1, endSec: 0.2, segmentId: "one" },
- { text: "reallylovehyper", startSec: 0.4, endSec: 0.9, segmentId: "one" },
- { text: "frames", startSec: 1, endSec: 1.3, segmentId: "one" },
- { text: "can", startSec: 1.4, endSec: 1.55, segmentId: "one" },
- { text: "not", startSec: 1.56, endSec: 1.8, segmentId: "one" },
- { text: "um", startSec: 1.81, endSec: 1.85, segmentId: "one" },
- { text: "now", startSec: 1.9, endSec: 2.1, segmentId: "one" },
- ],
- segments: [{ id: "one", startSec: 0, endSec: 2.4 }],
- };
- const basis = createProgramBasis({
- fps: evidence.fps,
- durationFrames: Math.round(evidence.durationSec * evidence.fps),
- outcomeDigest: sha256(stableJson(evidence)),
- });
- const map = semanticMapFromTiming(narrative, basis, evidence);
- const located = locateScript(narrative, basis, map);
- assert.deepEqual(located.words.map((word) => word.text),
- ["We", "really", "love", "hyper", "frames", "cannot", "now"]);
- assert.deepEqual(
- map.anchors.filter((anchor) => anchor.identity.includes(":token:") && anchor.identity.endsWith(":start"))
- .map((anchor) => anchor.quality),
- ["measured", "derived", "derived", "derived", "measured", "derived", "measured"],
- );
- assert.deepEqual(
- [located.words[1]?.startFrame, located.words[3]?.endFrameExclusive],
- [12, 27],
- );
-
- const missing = locateTiming(narrative, {
- ...evidence,
- units: [evidence.units[0]!, evidence.units[2]!, evidence.units.at(-1)!],
- });
- assert.equal(missing.words[1]?.startFrame, 6);
- assert.equal(missing.words[3]?.endFrameExclusive, 30);
-});
-
-test("Script normalizes newlines and NFC while tokenizing East Asian writing per character", () => {
- const narrative = parseScript(
- "fixture.svml",
- "<segment id=\"one\">Cafe\u0301\r\n中文かなカナ words.</segment>",
- );
- assert.equal(narrative.projections.speech, "Café 中文かなカナ words.");
- assert.deepEqual(
- narrative.tokens.map((token) => token.text),
- ["Café", "中", "文", "か", "な", "カ", "ナ", "words"],
- );
-});
-
-test("reserved @ syntax and non-canonical ids fail closed", () => {
- assert.throws(
- () => parseScript("fixture.svml", '<segment id="one">[email protected]</segment>'),
- /script_(?:invalid_marker|selection_unclosed)/u,
- );
- assert.throws(
- () => parseScript("fixture.svml", '<segment id="One">Hello.</segment>'),
- /script_invalid_segment_id/u,
- );
- assert.throws(
- () => parseScript("fixture.svml", '<segment id="one">@NotCanonical! Hello.</segment>'),
- /script_invalid_marker/u,
- );
-});
-
-test("syllable Estimate produces deterministic SpeechTimingEvidence including silence", () => {
- const narrative = parseScript("fixture.svml", `
- <segment id="speech">Hello 中文.</segment>
- <segment id="silence"/>
- `);
- const first = estimateSpeechTiming(narrative, {
- fps: 30,
- syllablesPerSecond: 4,
- emptySegmentSec: 2,
- });
- const second = estimateSpeechTiming(narrative, {
- fps: 30,
- syllablesPerSecond: 4,
- emptySegmentSec: 2,
- });
- assert.deepEqual(first, second);
- assert.deepEqual(first.units.map((unit) => unit.text), ["Hello", "中", "文"]);
- assert.equal(first.segments[1]?.endSec! - first.segments[1]?.startSec!, 2);
- assert.equal(first.quality, "estimated");
- assert.equal(first.provenance?.method, "svml.syllable-estimate.v1");
-});
-
-test("canonical Script formatter is semantic-preserving and idempotent", () => {
- const source = `<svml version="1">
- <script>
- @whole
- <segment id="one">
- <A> Hello @pop! <world | wonderful world>.
- </segment>
- @/whole~
- </script>
- <text id="unused">value</text>
-</svml>
-`;
- const document = parseDocumentSource("fixture.svml", source);
- const narrative = parseScript(
- document.file,
- document.scriptSource,
- document.scriptOffset,
- );
- const formatted = formatDocumentScript(document, narrative, {});
- assert.match(formatted, /\n @whole\n\n <segment id="one">\n <A>/u);
- const secondDocument = parseDocumentSource("fixture.svml", formatted);
- const secondNarrative = parseScript(
- secondDocument.file,
- secondDocument.scriptSource,
- secondDocument.scriptOffset,
- );
- assert.equal(formatDocumentScript(secondDocument, secondNarrative, {}), formatted);
-});
diff --git a/tools/copy-runtime.mjs b/tools/copy-runtime.mjs
deleted file mode 100644
index 9086e251..00000000
--- a/tools/copy-runtime.mjs
+++ /dev/null
@@ -1,7 +0,0 @@
-import { copyFile, mkdir } from "node:fs/promises";
-
-await mkdir(new URL("../dist/src/", import.meta.url), { recursive: true });
-await copyFile(
- new URL("../src/sandbox-worker.mjs", import.meta.url),
- new URL("../dist/src/sandbox-worker.mjs", import.meta.url),
-);
diff --git a/tsconfig.json b/tsconfig.json
index e42ee52a..80784b3b 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -3,7 +3,10 @@
"target": "ES2023",
"module": "NodeNext",
"moduleResolution": "NodeNext",
- "lib": ["ES2023", "DOM"],
+ "lib": [
+ "ES2023",
+ "DOM"
+ ],
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
@@ -11,9 +14,201 @@
"declaration": true,
"sourceMap": true,
"rootDir": ".",
- "outDir": "dist",
- "skipLibCheck": true
+ "skipLibCheck": true,
+ "noEmit": true,
+ "baseUrl": ".",
+ "paths": {
+ "@svml/protocol": [
+ "packages/protocol/src/index.ts"
+ ],
+ "@svml/core": [
+ "packages/core/src/index.ts"
+ ],
+ "@svml/component-kit": [
+ "packages/component-kit/src/index.ts"
+ ],
+ "@svml/endpoint-kit": [
+ "packages/endpoint-kit/src/index.ts"
+ ],
+ "@svml/contracts": [
+ "packages/contracts/src/index.ts"
+ ],
+ "@svml/media": [
+ "packages/media/src/index.ts"
+ ],
+ "@svml/driver-node": [
+ "packages/driver-node/src/index.ts"
+ ],
+ "@svml/script": [
+ "packages/script/src/index.ts"
+ ],
+ "@svml/text": [
+ "packages/text/src/index.ts"
+ ],
+ "@svml/speech-align": [
+ "packages/speech-align/src/index.ts"
+ ],
+ "@svml/whisperx": [
+ "packages/whisperx/src/index.ts"
+ ],
+ "@svml/caption": [
+ "packages/caption/src/index.ts"
+ ],
+ "@svml/speech-take": [
+ "packages/speech-take/src/index.ts"
+ ],
+ "@svml/elaborator": [
+ "packages/elaborator/src/index.ts"
+ ],
+ "@svml/realization": [
+ "packages/realization/src/index.ts"
+ ],
+ "@svml/run": [
+ "packages/run/src/index.ts"
+ ],
+ "@svml/run-text": [
+ "packages/run-text/src/index.ts"
+ ],
+ "@svml/runtime": [
+ "packages/runtime/src/index.ts"
+ ],
+ "@svml/runtime-adapter": [
+ "packages/runtime-adapter/src/index.ts"
+ ],
+ "@svml/runtime-adapter-node": [
+ "packages/runtime-adapter-node/src/index.ts"
+ ],
+ "@svml/store-sqlite": [
+ "packages/store-sqlite/src/index.ts"
+ ],
+ "@svml/artifact-store-fs": [
+ "packages/artifact-store-fs/src/index.ts"
+ ],
+ "@svml/artifact-store-s3": [
+ "packages/artifact-store-s3/src/index.ts"
+ ],
+ "@svml/credential-store-env": [
+ "packages/credential-store-env/src/index.ts"
+ ],
+ "@svml/local": [
+ "packages/local/src/index.ts"
+ ],
+ "@svml/generation": [
+ "packages/generation/src/index.ts"
+ ],
+ "@svml/model-kit": [
+ "packages/model-kit/src/index.ts"
+ ],
+ "@svml/prompt-kit": [
+ "packages/prompt-kit/src/index.ts"
+ ],
+ "@svml/seedance": [
+ "packages/seedance/src/index.ts"
+ ],
+ "@svml/minimax-h3": [
+ "packages/minimax-h3/src/index.ts"
+ ],
+ "@svml/gemini-omni": [
+ "packages/gemini-omni/src/index.ts"
+ ],
+ "@svml/grok-imagine": [
+ "packages/grok-imagine/src/index.ts"
+ ],
+ "@svml/gpt-image": [
+ "packages/gpt-image/src/index.ts"
+ ],
+ "@svml/nano-banana": [
+ "packages/nano-banana/src/index.ts"
+ ],
+ "@svml/seedream": [
+ "packages/seedream/src/index.ts"
+ ],
+ "@svml/provider-kie": [
+ "packages/provider-kie/src/index.ts"
+ ],
+ "@svml/media-pipeline": [
+ "packages/media-pipeline/src/index.ts"
+ ],
+ "@svml/provider-media-local": [
+ "packages/provider-media-local/src/index.ts"
+ ],
+ "@svml/provider-hyperframes-local": [
+ "packages/provider-hyperframes-local/src/index.ts"
+ ],
+ "@svml/provider-whisperx-local": [
+ "packages/provider-whisperx-local/src/index.ts"
+ ],
+ "@svml/provider-google-vertex": [
+ "packages/provider-google-vertex/src/index.ts"
+ ],
+ "@svml/image-transform": [
+ "packages/image-transform/src/index.ts"
+ ],
+ "@svml/provider-image-opencv-local": [
+ "packages/provider-image-opencv-local/src/index.ts"
+ ],
+ "@svml/transport-aws-lambda": [
+ "packages/transport-aws-lambda/src/index.ts"
+ ],
+ "@svml/transport-process": [
+ "packages/transport-process/src/index.ts"
+ ],
+ "@svml/transport": [
+ "packages/transport/src/index.ts"
+ ],
+ "@svml/speech-program": [
+ "packages/speech-program/src/index.ts"
+ ],
+ "@svml/estimate": [
+ "packages/estimate/src/index.ts"
+ ],
+ "@svml/hyperframes": [
+ "packages/hyperframes/src/index.ts"
+ ],
+ "@svml/hyperframes-render": [
+ "packages/hyperframes-render/src/index.ts"
+ ],
+ "@svml/broll": [
+ "packages/broll/src/index.ts"
+ ],
+ "@svml/film": [
+ "packages/film/src/index.ts"
+ ],
+ "@svml/text-track": [
+ "packages/text-track/src/index.ts"
+ ],
+ "@svml/svs": [
+ "packages/svs/src/index.ts"
+ ],
+ "@svml/compiler-node": [
+ "packages/compiler-node/src/index.ts"
+ ],
+ "@svml/package-loader-node": [
+ "packages/package-loader-node/src/index.ts"
+ ],
+ "@svml/cli": [
+ "packages/cli/src/index.ts"
+ ],
+ "@svml/validation": [
+ "packages/validation/src/index.ts"
+ ],
+ "@svml/host": [
+ "packages/host/src/index.ts"
+ ],
+ "@svml/source": [
+ "packages/source/src/index.ts"
+ ],
+ "@svml/workspace-fs-node": [
+ "packages/workspace-fs-node/src/index.ts"
+ ]
+ }
},
- "include": ["src/**/*.ts", "test/**/*.ts"],
- "exclude": ["dist", "node_modules"]
+ "include": [
+ "packages/**/*.ts"
+ ],
+ "exclude": [
+ "dist",
+ "node_modules",
+ "packages/*/dist"
+ ]
}
diff --git a/tsconfig.v2.json b/tsconfig.v2.json
deleted file mode 100644
index ead3b398..00000000
--- a/tsconfig.v2.json
+++ /dev/null
@@ -1,73 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "noEmit": true,
- "rootDir": ".",
- "baseUrl": ".",
- "paths": {
- "@svml/protocol": ["packages/protocol/src/index.ts"],
- "@svml/core": ["packages/core/src/index.ts"],
- "@svml/component-kit": ["packages/component-kit/src/index.ts"],
- "@svml/endpoint-kit": ["packages/endpoint-kit/src/index.ts"],
- "@svml/contracts": ["packages/contracts/src/index.ts"],
- "@svml/media": ["packages/media/src/index.ts"],
- "@svml/driver-node": ["packages/driver-node/src/index.ts"],
- "@svml/script": ["packages/script/src/index.ts"],
- "@svml/text": ["packages/text/src/index.ts"],
- "@svml/speech-align": ["packages/speech-align/src/index.ts"],
- "@svml/whisperx": ["packages/whisperx/src/index.ts"],
- "@svml/caption": ["packages/caption/src/index.ts"],
- "@svml/speech-take": ["packages/speech-take/src/index.ts"],
- "@svml/elaborator": ["packages/elaborator/src/index.ts"],
- "@svml/realization": ["packages/realization/src/index.ts"],
- "@svml/run": ["packages/run/src/index.ts"],
- "@svml/run-text": ["packages/run-text/src/index.ts"],
- "@svml/runtime": ["packages/runtime/src/index.ts"],
- "@svml/runtime-adapter": ["packages/runtime-adapter/src/index.ts"],
- "@svml/runtime-adapter-node": ["packages/runtime-adapter-node/src/index.ts"],
- "@svml/store-sqlite": ["packages/store-sqlite/src/index.ts"],
- "@svml/artifact-store-fs": ["packages/artifact-store-fs/src/index.ts"],
- "@svml/artifact-store-s3": ["packages/artifact-store-s3/src/index.ts"],
- "@svml/credential-store-env": ["packages/credential-store-env/src/index.ts"],
- "@svml/local": ["packages/local/src/index.ts"],
- "@svml/generation": ["packages/generation/src/index.ts"],
- "@svml/model-kit": ["packages/model-kit/src/index.ts"],
- "@svml/prompt-kit": ["packages/prompt-kit/src/index.ts"],
- "@svml/seedance": ["packages/seedance/src/index.ts"],
- "@svml/minimax-h3": ["packages/minimax-h3/src/index.ts"],
- "@svml/gemini-omni": ["packages/gemini-omni/src/index.ts"],
- "@svml/grok-imagine": ["packages/grok-imagine/src/index.ts"],
- "@svml/gpt-image": ["packages/gpt-image/src/index.ts"],
- "@svml/nano-banana": ["packages/nano-banana/src/index.ts"],
- "@svml/seedream": ["packages/seedream/src/index.ts"],
- "@svml/provider-kie": ["packages/provider-kie/src/index.ts"],
- "@svml/media-pipeline": ["packages/media-pipeline/src/index.ts"],
- "@svml/provider-media-local": ["packages/provider-media-local/src/index.ts"],
- "@svml/provider-hyperframes-local": ["packages/provider-hyperframes-local/src/index.ts"],
- "@svml/provider-whisperx-local": ["packages/provider-whisperx-local/src/index.ts"],
- "@svml/provider-google-vertex": ["packages/provider-google-vertex/src/index.ts"],
- "@svml/image-transform": ["packages/image-transform/src/index.ts"],
- "@svml/provider-image-opencv-local": ["packages/provider-image-opencv-local/src/index.ts"],
- "@svml/transport-aws-lambda": ["packages/transport-aws-lambda/src/index.ts"],
- "@svml/transport-process": ["packages/transport-process/src/index.ts"],
- "@svml/transport": ["packages/transport/src/index.ts"],
- "@svml/speech-program": ["packages/speech-program/src/index.ts"],
- "@svml/estimate": ["packages/estimate/src/index.ts"],
- "@svml/hyperframes": ["packages/hyperframes/src/index.ts"],
- "@svml/hyperframes-render": ["packages/hyperframes-render/src/index.ts"],
- "@svml/broll": ["packages/broll/src/index.ts"],
- "@svml/film": ["packages/film/src/index.ts"],
- "@svml/text-track": ["packages/text-track/src/index.ts"],
- "@svml/svs": ["packages/svs/src/index.ts"],
- "@svml/compiler-node": ["packages/compiler-node/src/index.ts"],
- "@svml/package-loader-node": ["packages/package-loader-node/src/index.ts"],
- "@svml/cli": ["packages/cli/src/index.ts"],
- "@svml/validation": ["packages/validation/src/index.ts"],
- "@svml/host": ["packages/host/src/index.ts"],
- "@svml/source": ["packages/source/src/index.ts"],
- "@svml/workspace-fs-node": ["packages/workspace-fs-node/src/index.ts"]
- }
- },
- "include": ["packages/**/*.ts"],
- "exclude": ["dist", "node_modules", "packages/*/dist"]
-}