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.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
feat: generate one picture for a package asset
rponecaeed71a08ed
diff --git a/examples/ranking-typewriter-reverse/build.svrun b/examples/ranking-typewriter-reverse/build.svrunnew file mode 100644index 00000000..23902b3f--- /dev/null+++ b/examples/ranking-typewriter-reverse/build.svrun@@ -0,0 +1,7 @@+<?svml using="@hypit/run-markup@1"?>++<svrun version="1">+ <author source="./main.svml"/>++ <target output="final.video"/>+</svrun>diff --git a/examples/ranking-typewriter-reverse/hypit.runtime.json b/examples/ranking-typewriter-reverse/hypit.runtime.jsonnew file mode 100644index 00000000..727ef57a--- /dev/null+++ b/examples/ranking-typewriter-reverse/hypit.runtime.json@@ -0,0 +1,48 @@+{+ "format": "hypit.runtime-profile@1",+ "runtime": {+ "use": "@hypit/runtime-local",+ "config": {+ "dataRoot": ".hypit/runtimes/local",+ "artifacts": { "use": "@hypit/artifact-store-fs", "config": { "path": "artifacts" } },+ "credentials": {+ "environment": { "use": "@hypit/credential-store-env" }+ },+ "endpoints": {+ "kie.ranking-typewriter": {+ "use": "@hypit/provider-kie",+ "pool": "generation",+ "config": {+ "apiKey": { "store": "env", "key": "KIE_API_KEY" },+ "defaultConcurrency": 2+ }+ },+ "media.ranking-typewriter": {+ "use": "@hypit/provider-media-local",+ "pool": "media",+ "config": { "defaultConcurrency": 2 }+ },+ "whisperx.ranking-typewriter": {+ "use": "@hypit/provider-whisperx-local",+ "pool": "alignment",+ "config": { "defaultConcurrency": 1 }+ },+ "hyperframes.ranking-typewriter": {+ "use": "@hypit/provider-hyperframes-local",+ "pool": "render",+ "config": { "defaultConcurrency": 1 }+ },+ "vertex.ranking-typewriter": {+ "use": "@hypit/provider-google-vertex",+ "pool": "planning",+ "config": {+ "projectEnv": "GOOGLE_CLOUD_PROJECT",+ "location": "global",+ "credentials": { "store": "env", "key": "GOOGLE_VERTEX_CREDENTIALS_JSON" },+ "defaultConcurrency": 1+ }+ }+ }+ }+ }+}diff --git a/examples/ranking-typewriter-reverse/images.svrun b/examples/ranking-typewriter-reverse/images.svrunnew file mode 100644index 00000000..5e5b0ce4--- /dev/null+++ b/examples/ranking-typewriter-reverse/images.svrun@@ -0,0 +1,16 @@+<?svml using="@hypit/run-markup@1"?>++<!-- Gate 1: only the generated reference pictures, so every one can be reviewed+ before anything downstream is paid for. -->+<svrun version="1">+ <author source="./main.svml"/>++ <target output="presenter.image"/>+ <target output="paper.image"/>+ <target output="meme-post.image"/>+ <target output="thumbnail.image"/>+ <target output="newsletter.image"/>+ <target output="apple.image"/>+ <target output="microsoft.image"/>+ <target output="nasa.image"/>+</svrun>diff --git a/examples/ranking-typewriter-reverse/kits/speaker-v1.svs b/examples/ranking-typewriter-reverse/kits/speaker-v1.svsnew file mode 100644index 00000000..4537dd20--- /dev/null+++ b/examples/ranking-typewriter-reverse/kits/speaker-v1.svs@@ -0,0 +1,136 @@+<?svml using="@hypit/text/svs@1"?>++<sheet version="1" id="speaker-v1">+ text-template.speaker-v1 {+ separator: paragraph;+ default-composition-stability: soft-locked;+ default-camera-motion: none;+ default-edit-rhythm: continuous-take;+ default-performance: natural-explainer;+ default-gesture: natural;+ }++ text-template.speaker-v1.block.base {+ kind: fixed;+ order: 10;+ text: "Create a realistic vertical phone-shot talking-head video. @image1 is the visible speaker and scene reference. Preserve the person's identity, face, outfit, setting, lighting, lens feel, and broad composition. @audio1 is the speaker's voice-timbre reference.";+ }++ text-template.speaker-v1.block.script-contract {+ kind: fixed;+ order: 20;+ text: "Deliver the supplied script exactly in order with clear lip-sync. The visible person speaks every line. Do not rewrite, summarize, add, remove, or reorder words.";+ }++ text-template.speaker-v1.block.composition-stability {+ kind: axis;+ order: 30;+ parameter: composition-stability;+ }++ text-template.speaker-v1.choice.composition-stability.flexible-ugc {+ text: "COMPOSITION: preserve the reference person and setup while allowing normal lively creator-video framing variation.";+ }++ text-template.speaker-v1.choice.composition-stability.soft-locked {+ text: "COMPOSITION: keep the speaker in the same general region and preserve the reference composition, allowing natural posture changes and tiny crop or scale breathing.";+ }++ text-template.speaker-v1.choice.composition-stability.strict-locked {+ text: "COMPOSITION: preserve subject placement, perspective, left-right orientation, background relationship, and framing envelope throughout the shot.";+ }++ text-template.speaker-v1.block.camera-motion {+ kind: axis;+ order: 40;+ parameter: camera-motion;+ }++ text-template.speaker-v1.choice.camera-motion.none {+ text: "CAMERA: hold a steady fixed framing.";+ }++ text-template.speaker-v1.choice.camera-motion.subtle-punch-in-return {+ text: "CAMERA: use one subtle push-in on the most important phrase, then return smoothly to the original framing.";+ }++ text-template.speaker-v1.block.edit-rhythm {+ kind: axis;+ order: 50;+ parameter: edit-rhythm;+ }++ text-template.speaker-v1.choice.edit-rhythm.continuous-take {+ text: "EDIT RHYTHM: one continuous creator explanation with natural breath timing.";+ }++ text-template.speaker-v1.choice.edit-rhythm.pause-trim-jump-cuts {+ text: "EDIT RHYTHM: polished pause-trim jump cuts at phrase boundaries while keeping the framing coherent.";+ }++ text-template.speaker-v1.block.performance {+ kind: axis;+ order: 60;+ parameter: performance;+ }++ text-template.speaker-v1.choice.performance.natural-explainer {+ text: "PERFORMANCE: natural explainer energy with clear eye focus, expressive eyebrows, small nods, and a friendly conversational rhythm.";+ }++ text-template.speaker-v1.choice.performance.high-energy-ugc {+ text: "PERFORMANCE: vivid high-energy short-form delivery with expressive face changes on key words.";+ }++ text-template.speaker-v1.choice.performance.calm-authority {+ text: "PERFORMANCE: composed, confident, precise, and trustworthy, with deliberate emphasis.";+ }++ text-template.speaker-v1.choice.performance.reactive-playful {+ text: "PERFORMANCE: playful and reactive, with amused looks, quick smiles, skeptical eyebrows, and lively timing.";+ }++ text-template.speaker-v1.block.gesture {+ kind: axis;+ order: 70;+ parameter: gesture;+ }++ text-template.speaker-v1.choice.gesture.restrained {+ text: "GESTURE: restrained body language; let face, eyes, and voice carry the meaning.";+ }++ text-template.speaker-v1.choice.gesture.compact {+ text: "GESTURE: compact explanatory hand movement close to the torso and inside the frame.";+ }++ text-template.speaker-v1.choice.gesture.natural {+ text: "GESTURE: natural creator gestures such as open palms, small pointing beats, nods, and posture shifts where the script calls for them.";+ }++ text-template.speaker-v1.choice.gesture.expressive {+ text: "GESTURE: richer hand, shoulder, and posture changes that support the spoken idea while remaining physically coherent.";+ }++ text-template.speaker-v1.block.hygiene {+ kind: fixed;+ order: 80;+ text: "Keep face, hands, skin texture, lighting, and motion photoreal and stable. Add no subtitles, captions, labels, logos, UI text, floating words, or other readable on-screen text.";+ }++ text-template.speaker-v1.block.dialogue {+ kind: slot;+ order: 90;+ slot: dialogue;+ optional: false;+ label: "SCRIPT TO DELIVER:";+ }++ text-template.speaker-v1.block.action {+ kind: slot;+ order: 100;+ slot: action;+ optional: true;+ label: "ACTION DIRECTION:";+ }+</sheet>diff --git a/examples/ranking-typewriter-reverse/main.svml b/examples/ranking-typewriter-reverse/main.svmlnew file mode 100644index 00000000..8d6dd53e--- /dev/null+++ b/examples/ranking-typewriter-reverse/main.svml@@ -0,0 +1,344 @@+<?svml using="@hypit/markup@1"?>++<svml>+ <import from="@hypit/script@1"/>+ <import as="copy" from="@hypit/text@1"/>+ <import as="estimate" from="@hypit/estimate@1"/>+ <import as="nano" from="@hypit/nano-banana@1"/>+ <import as="remove" from="@hypit/background-removal@1"/>+ <import as="mediaop" from="@hypit/media-pipeline@1"/>+ <import as="seedance" from="@hypit/seedance@1"/>+ <import as="speech" from="@hypit/speech-spine@1"/>+ <import as="whisperx" from="@hypit/whisperx@1"/>+ <import as="caption" from="@hypit/caption@1"/>+ <import as="caption-fine" from="@hypit/caption-fine@1"/>+ <import as="caption-ai" from="@hypit/caption-gemini@1"/>+ <import as="fonts" from="@hypit/fonts-open@1"/>+ <import as="media-track" from="@hypit/media-track@1"/>+ <import as="notes" from="@hypit/local-notepad-list@1"/>+ <import as="space" from="@hypit/spatial@1"/>+ <import as="film" from="@hypit/film@1"/>+ <import as="render" from="@hypit/render-hyperframes@1"/>+ <import as="studio" source="./studio.svs"/>+ <import as="speaker-kit" source="./kits/speaker-v1.svs"/>++ <!-- One Script for the whole video. The paper list returns five times, so+ `board` is one Selection with five occurrences and `write` is one Moment+ with five; `opening` is the sentence the title writes itself over before+ the paper is ever seen. -->+ <script id="story">+ <hook>+ <HOST> @opening Here are the top five most popular ways to learn AI. @/opening+ @board Number five is @write!Instagram. @/board+ @memes It's mostly just viral AI memes, @/memes zero actual education on+ how to use this stuff for real work.+ </hook>++ <courses>+ <HOST> @board Number four, @write!AI courses. @/board Courses can't keep up+ with how fast AI is progressing. They're all outdated by the time you+ finish the course.+ </courses>++ <youtube>+ <HOST> @board Number three, @write!YouTube. @/board Every video is,+ @thumbnail this will change everything, @/thumbnail but it's just another+ sponsorship deal. @board Number two, @write!Twitter. @/board+ </youtube>++ <twitter>+ <HOST> Smart people share gold here, but you're gonna end up wasting two+ plus hours every day scrolling through bots to find what's actually+ meaningful. And no one has time for that.+ </twitter>++ <rundown>+ <HOST> @board Number one is @write!the rundown~@settled!. @/board+ @news It's a free newsletter. It takes five minutes to read. And it+ actually teaches you the AI tools that really matter. @/news+ </rundown>++ <close>+ <HOST> And this is how two million people at companies like @apple!Apple,+ @microsoft!Microsoft, and @nasa!NASA, well, they use this to keep up with+ AI. I added the link to this post if you wanna sign up for free.+ </close>+ </script>++ <!-- Depicted material. Every picture the video must show and does not already+ own is generated once, at the aspect ratio it is used at, carrying only+ what it depicts. -->+ <copy:Value id="presenter-look">+ A realistic podcast video frame of a white man in his early thirties with short dark+ hair swept back, wearing clear-rimmed round glasses, large black over-ear headphones and+ a plain black zip-up jacket. He sits at a wooden studio desk behind a large black+ condenser microphone on a boom arm, turned slightly to his right, mouth open mid-sentence.+ Behind him a softly out-of-focus room glows magenta and purple, with a bright monitor+ showing blurred pink and blue blobs over his left shoulder and a warm amber light strip+ along the desk edge. Waist-up framing, shallow depth of field, natural skin texture,+ warm key light from the front left.+ </copy:Value>++ <copy:Value id="paper-look">+ A flat overhead photograph of a single sheet of warm off-white graph paper, faintly cream+ coloured, filling the whole picture edge to edge with no edges or background visible. The+ sheet lies perfectly smooth and flat under soft even light, with no creases, wrinkles, folds+ or shadows anywhere. A square grid is printed across it in a faint, soft-edged purple-grey,+ low in contrast and slightly blurred, with about ten large squares across the width and+ every line the same weight. Photographed a little out of focus. Blank paper only.+ </copy:Value>++ <copy:Value id="meme-post-look">+ A screenshot of a social media post on a black background, in portrait shape. At the top,+ two short lines of small white text: the first reads Me: "Explain it like I'm a five-year old",+ the second reads ChatGPT:. Below them a photograph fills the rest of the post: a white+ plastic humanoid robot with a smooth featureless face and glowing eyes, seated indoors at a+ table in a warmly lit room, shot from the chest up. A tiny grey watermark sits in the+ bottom-left corner of the photograph.+ </copy:Value>++ <copy:Value id="thumbnail-look">+ A widescreen video thumbnail. A dark blue server room recedes into the distance behind rows+ of glowing racks and cables. On the right side, a young man with dark hair and a black+ T-shirt leans in with a wide open-mouthed excited expression and points with his index+ finger back toward the racks. Across the upper left, in very large heavy white condensed+ capitals with a thin dark outline, two stacked lines read THIS WILL CHANGE and EVERYTHING.+ Saturated, high-contrast, glossy thumbnail styling.+ </copy:Value>++ <copy:Value id="newsletter-look">+ A tall screenshot of an email newsletter web page on a white background, in a very narrow+ portrait shape, as though the whole page has been captured in one long strip. At the top, a+ black banner carries a small white trophy mark and the words The Rundown AI, with a tiny+ line of grey text beneath it. Under the banner, several paragraphs of small dark grey body+ text with a few words in blue underlined link styling. Then a bold heading line, a bulleted+ list of five short items, a narrow black bar carrying the words LATEST DEVELOPMENTS in white+ capitals, a blue underlined article headline, and a small blue and grey bar chart with a+ caption beneath it. Further down, another black bar reading QUICK HITS, a short bulleted+ list with tiny coloured icons, and a final blue underlined heading. Clean, dense, readable+ editorial layout with generous white space.+ </copy:Value>++ <copy:Value id="apple-look">+ The Apple logo: one solid white silhouette of an apple with a bite taken from its right side+ and a small separate leaf angled to the right above it, centred on a plain flat black+ background with wide empty margins.+ </copy:Value>++ <copy:Value id="microsoft-look">+ The Microsoft logo: four equal solid squares arranged in a two by two grid with a thin gap+ between them, the top-left square orange-red, the top-right square green, the bottom-left+ square blue and the bottom-right square yellow, centred on a plain flat black background+ with wide empty margins.+ </copy:Value>++ <copy:Value id="nasa-look">+ The NASA insignia: a deep blue circle carrying the white letters NASA across its middle, a+ swoosh of small white stars behind them and a thin red chevron sweeping across the circle+ from lower left to upper right, centred on a plain flat black background with wide empty+ margins.+ </copy:Value>++ <nano:Image id="presenter" prompt={presenter-look} aspect-ratio="9:16" resolution="2K" output-format="png"/>+ <nano:Image id="paper" prompt={paper-look} aspect-ratio="9:16" resolution="2K" output-format="png"/>+ <nano:Image id="meme-post" prompt={meme-post-look} aspect-ratio="3:4" resolution="2K" output-format="png"/>+ <nano:Image id="thumbnail" prompt={thumbnail-look} aspect-ratio="16:9" resolution="2K" output-format="png"/>+ <nano:Image id="newsletter" prompt={newsletter-look} aspect-ratio="1:4" resolution="2K" output-format="png"/>+ <nano:Image id="apple-plate" prompt={apple-look} aspect-ratio="1:1" resolution="1K" output-format="png"/>+ <nano:Image id="microsoft-plate" prompt={microsoft-look} aspect-ratio="1:1" resolution="1K" output-format="png"/>+ <nano:Image id="nasa-plate" prompt={nasa-look} aspect-ratio="1:1" resolution="1K" output-format="png"/>++ <!-- The logos sit straight on the picture with nothing behind them, so each+ generated plate loses its background before it reaches a Frame. -->+ <remove:Background id="apple" source={apple-plate.image}/>+ <remove:Background id="microsoft" source={microsoft-plate.image}/>+ <remove:Background id="nasa" source={nasa-plate.image}/>++ <!-- One speaking performance, cut into six takes at the reference's own jump+ cuts. Every take keeps the same reference frame, and the takes after the+ first reuse the first take's voice so the timbre does not drift. -->+ <estimate:Speech id="hook-duration" source={story.segment.hook.speech} policy={studio.speech.normal}/>+ <estimate:Speech id="courses-duration" source={story.segment.courses.speech} policy={studio.speech.normal}/>+ <estimate:Speech id="youtube-duration" source={story.segment.youtube.speech} policy={studio.speech.normal}/>+ <estimate:Speech id="twitter-duration" source={story.segment.twitter.speech} policy={studio.speech.normal}/>+ <estimate:Speech id="rundown-duration" source={story.segment.rundown.speech} policy={studio.speech.normal}/>+ <estimate:Speech id="close-duration" source={story.segment.close.speech} policy={studio.speech.normal}/>++ <copy:Value id="hook-action">+ Open with direct eye contact and a small counting gesture, then settle back toward the microphone.+ </copy:Value>+ <copy:Value id="courses-action">+ Lift one open hand on the objection, then let it drop as the sentence lands.+ </copy:Value>+ <copy:Value id="youtube-action">+ Flatten the delivery into dry sarcasm on the quoted line, then shrug it off.+ </copy:Value>+ <copy:Value id="twitter-action">+ Build mild exasperation across the sentence and end on a short, tired half-smile.+ </copy:Value>+ <copy:Value id="rundown-action">+ Brighten on the recommendation and keep the pace quick and warm.+ </copy:Value>+ <copy:Value id="close-action">+ Deliver the names evenly, then finish with a relaxed, inviting close to camera.+ </copy:Value>++ <copy:Render id="hook-prompt" template={speaker-kit.speaker-v1} recipe={studio.speaker.host}>+ <copy:Set name="dialogue" text={story.segment.hook.dialogue}/>+ <copy:Set name="action" text={hook-action}/>+ </copy:Render>+ <copy:Render id="courses-prompt" template={speaker-kit.speaker-v1} recipe={studio.speaker.host}>+ <copy:Set name="dialogue" text={story.segment.courses.dialogue}/>+ <copy:Set name="action" text={courses-action}/>+ </copy:Render>+ <copy:Render id="youtube-prompt" template={speaker-kit.speaker-v1} recipe={studio.speaker.host}>+ <copy:Set name="dialogue" text={story.segment.youtube.dialogue}/>+ <copy:Set name="action" text={youtube-action}/>+ </copy:Render>+ <copy:Render id="twitter-prompt" template={speaker-kit.speaker-v1} recipe={studio.speaker.host}>+ <copy:Set name="dialogue" text={story.segment.twitter.dialogue}/>+ <copy:Set name="action" text={twitter-action}/>+ </copy:Render>+ <copy:Render id="rundown-prompt" template={speaker-kit.speaker-v1} recipe={studio.speaker.host}>+ <copy:Set name="dialogue" text={story.segment.rundown.dialogue}/>+ <copy:Set name="action" text={rundown-action}/>+ </copy:Render>+ <copy:Render id="close-prompt" template={speaker-kit.speaker-v1} recipe={studio.speaker.host}>+ <copy:Set name="dialogue" text={story.segment.close.dialogue}/>+ <copy:Set name="action" text={close-action}/>+ </copy:Render>++ <seedance:ReferenceVideo id="hook-take" model="mini" prompt={hook-prompt}+ duration={hook-duration.duration} resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={presenter.image}/>+ </seedance:ReferenceVideo>++ <mediaop:ExtractAudio id="host-voice" source={hook-take.video} audio="default"/>++ <seedance:ReferenceVideo id="courses-take" model="mini" prompt={courses-prompt}+ duration={courses-duration.duration} resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={presenter.image}/>+ <seedance:Reference audio={host-voice.audio}/>+ </seedance:ReferenceVideo>+ <seedance:ReferenceVideo id="youtube-take" model="mini" prompt={youtube-prompt}+ duration={youtube-duration.duration} resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={presenter.image}/>+ <seedance:Reference audio={host-voice.audio}/>+ </seedance:ReferenceVideo>+ <seedance:ReferenceVideo id="twitter-take" model="mini" prompt={twitter-prompt}+ duration={twitter-duration.duration} resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={presenter.image}/>+ <seedance:Reference audio={host-voice.audio}/>+ </seedance:ReferenceVideo>+ <seedance:ReferenceVideo id="rundown-take" model="mini" prompt={rundown-prompt}+ duration={rundown-duration.duration} resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={presenter.image}/>+ <seedance:Reference audio={host-voice.audio}/>+ </seedance:ReferenceVideo>+ <seedance:ReferenceVideo id="close-take" model="mini" prompt={close-prompt}+ duration={close-duration.duration} resolution="720p" aspect-ratio="9:16" generate-audio="true">+ <seedance:Reference image={presenter.image}/>+ <seedance:Reference audio={host-voice.audio}/>+ </seedance:ReferenceVideo>++ <space:Canvas id="vertical" width="1080" height="1920"/>+ <space:Frame id="full" within={vertical} left="0%" top="0%" right="100%" bottom="100%"/>+ <space:Frame id="meme-frame" within={vertical} left="21%" top="43%" right="80%" bottom="85%"/>+ <space:Frame id="thumbnail-frame" within={vertical} left="8%" top="50%" right="92%" bottom="80%"/>+ <space:Frame id="newsletter-frame" within={vertical} left="13%" top="14%" right="87%" bottom="86%"/>+ <space:Frame id="logo-frame" within={vertical} left="37%" top="55%" right="63%" bottom="70%"/>++ <space:Extent id="meme-extent" width="1536" height="2048"/>+ <space:Extent id="thumbnail-extent" width="2048" height="1152"/>+ <space:Extent id="newsletter-extent" width="1024" height="4096"/>+ <space:Extent id="logo-extent" width="1024" height="1024"/>++ <speech:Spine id="speech" frame-rate="30"+ visual-frame={full} visual-appearance={studio.speech.visual} visual-z="0">+ <speech:Take video={hook-take.video} segment={story.segment.hook}/>+ <speech:Take video={courses-take.video} segment={story.segment.courses}/>+ <speech:Take video={youtube-take.video} segment={story.segment.youtube}/>+ <speech:Take video={twitter-take.video} segment={story.segment.twitter}/>+ <speech:Take video={rundown-take.video} segment={story.segment.rundown}/>+ <speech:Take video={close-take.video} segment={story.segment.close}/>+ </speech:Spine>++ <whisperx:Alignment id="timing" narrative={story} audio={speech.audio}/>++ <!-- The paper list is one system with one Style over its whole life: the title+ writes itself over the speaker first, then the sheet takes over and each+ item is written in beside its number. -->+ <fonts:Stack id="title-face" family="playfair-display" weight="600" style="italic"/>+ <fonts:Stack id="emphasis-face" family="inter" weight="800" style="normal"/>+ <fonts:Stack id="hand-face" family="patrick-hand" weight="400" style="normal"/>++ <notes:ListStyle id="notepad" recipe={studio.notepad.list}+ title-font={title-face} emphasis-font={emphasis-face} row-font={hand-face}/>++ <notes:List id="board" map={timing.map} space={speech.space} frame={full}+ during={story.selection.board} opening={story.selection.opening}+ triggers={story.moment.write} terminal={story.moment.settled}+ title="Top 5 Most Popular Ways to " title-emphasis="learn AI" style={notepad}>+ <notes:Row id="row-instagram" rank="5" label="Instagram"/>+ <notes:Row id="row-courses" rank="4" label="AI Courses"/>+ <notes:Row id="row-youtube" rank="3" label="YouTube"/>+ <notes:Row id="row-twitter" rank="2" label="Twitter/X"/>+ <notes:Row id="row-rundown" rank="1" label="The Rundown" mark="circle"/>+ </notes:List>++ <!-- Every inserted picture is a rectangle on the speaking take, so they all+ share one Media Track. The newsletter is one tall screenshot whose picture+ scrolls up inside its Frame while the Frame stays where it is. -->+ <media-track:Track id="inserts" map={timing.map} space={speech.space} canvas={vertical}>+ <media-track:Item id="meme" image={meme-post.image} extent={meme-extent}+ frame={meme-frame} during={story.selection.memes}+ appearance={studio.media.panel} motion={studio.motion.cut}/>+ <media-track:Item id="thumbnail-card" image={thumbnail.image} extent={thumbnail-extent}+ frame={thumbnail-frame} during={story.selection.thumbnail}+ appearance={studio.media.card} motion={studio.motion.cut}/>+ <media-track:Item id="newsletter-panel" image={newsletter.image} extent={newsletter-extent}+ frame={newsletter-frame} during={story.selection.news}+ appearance={studio.media.sheet} motion={studio.motion.cut}>+ <media-track:Sampling at="start" y="0"/>+ <media-track:Sampling at="end" y="-2600" easing="linear"/>+ </media-track:Item>+ <media-track:Item id="apple-logo" image={apple.image} extent={logo-extent}+ frame={logo-frame} at={story.moment.apple} for="600ms"+ appearance={studio.media.logo} motion={studio.motion.cut}/>+ <media-track:Item id="microsoft-logo" image={microsoft.image} extent={logo-extent}+ frame={logo-frame} at={story.moment.microsoft} for="600ms"+ appearance={studio.media.logo} motion={studio.motion.cut}/>+ <media-track:Item id="nasa-logo" image={nasa.image} extent={logo-extent}+ frame={logo-frame} at={story.moment.nasa} for="600ms"+ appearance={studio.media.logo} motion={studio.motion.cut}/>+ </media-track:Track>++ <!-- One caption system for the whole programme. The words spoken over the+ newsletter are the only ones that change appearance, so they are one+ scoped override inside the same Program. -->+ <fonts:Stack id="caption-face" family="inter" weight="800" style="normal"/>+ <caption-fine:Style id="plain-caption" recipe={studio.caption.plain} font={caption-face}/>+ <caption-fine:Style id="boxed-caption" recipe={studio.caption.boxed} font={caption-face}/>++ <caption:Program id="caption-program" display={story.caption} default={plain-caption}>+ <caption:Use words={story.caption.selection.news} style={boxed-caption}/>+ </caption:Program>++ <caption-ai:Planner id="caption-plan" display={story.caption}+ program={caption-program} model="gemini-2.5-flash"/>++ <caption-fine:Track id="captions" display={story.caption}+ correspondence={story.caption.correspondence}+ map={timing.map} space={speech.space}+ program={caption-program} plan={caption-plan.plan}/>++ <film:Film id="main" canvas={vertical} space={speech.space} appearance={studio.film.vertical}>+ <film:Track source={speech.visual}/>+ <film:Track source={speech.audioTrack}/>+ <film:Track source={inserts.visual}/>+ <film:Track source={board.visual}/>+ <film:Track source={captions.track}/>+ </film:Film>++ <render:Video id="final" composition={main.composition} space={speech.space}/>+</svml>diff --git a/examples/ranking-typewriter-reverse/packages/local-notepad-list/README.md b/examples/ranking-typewriter-reverse/packages/local-notepad-list/README.mdnew file mode 100644index 00000000..e7c1979e--- /dev/null+++ b/examples/ranking-typewriter-reverse/packages/local-notepad-list/README.md@@ -0,0 +1,69 @@+# `@hypit/local-notepad-list`++A project-local author package for one self-contained full-screen graphic composition: a numbered+list written by hand onto a sheet of paper, one row at a time, that leaves and comes back as the+programme returns to it.++It exists because no installed package owns that picture. `@hypit/ranking` owns three progressive+boards — `Column`, `TierBoard` and `TopThree` — and all three draw a rounded, bordered, shadowed+panel with coloured slats or rings, fill from the top down inside one Selection occurrence, and own+no background material of their own. `@hypit/typography-track`, `@hypit/media-track`,+`@hypit/deck-track` and `@hypit/screen-overlay` each own one part of the picture and none of them+owns the whole field, which would scatter one visual system across unrelated tags. The composition+here owns its paper, its title, its slots, its reveal and its annotation together.++```svml+<import as="notes" from="@hypit/local-notepad-list@1"/>++<notes:ListStyle id="notepad" recipe={studio.notepad.list}+ title-font={title-face} emphasis-font={emphasis-face} row-font={hand-face}/>++<notes:List id="board" map={timing.map} space={speech.space} frame={full}+ surface={paper.image} during={story.selection.board} opening={story.selection.opening}+ triggers={story.moment.write} terminal={story.moment.settled}+ title="Top 5 Most Popular Ways to " title-emphasis="learn AI" style={notepad}>+ <notes:Row id="row-instagram" rank="5" label="Instagram"/>+ <notes:Row id="row-courses" rank="4" label="AI Courses"/>+ <notes:Row id="row-youtube" rank="3" label="YouTube"/>+ <notes:Row id="row-twitter" rank="2" label="Twitter/X"/>+ <notes:Row id="row-rundown" rank="1" label="The Rundown" mark="circle"/>+</notes:List>+```++## What it draws++The paper is a picture the package consumes on the `surface` edge; it never generates or embeds one.+Everything else is computed: the title is one wrapping block set in two faces, the rank numbers are+all written from the first frame the sheet appears, and each row's copy is revealed grapheme by+grapheme at its own trigger. `rank` decides where a row sits down the sheet and document order+decides when it is written, so a list can fill from the bottom upward. A row written `mark="circle"`+gains a tilted ellipse that draws itself around the number and copy once that copy has finished.++`during` is read for **every** occurrence of its Selection, because the sheet is one system that+leaves and returns while keeping its state. `opening` is the one window before the paper ever+appears, where the title alone writes itself over whatever is already on screen, in the Recipe's+`opening-*` paint instead of its `title-*` paint.++## Outputs++| Port | Type |+|---|---|+| `schedule` | `NotepadSchedule` — every window, the opening, each row's trigger frame and the terminal frame |+| `program` | `NotepadProgram` — Frame, paper, Style, Schedule, title and ordered rows |+| `visual` | `@hypit/composition@1#VisualTrack` |++There is no audio port: the reference this package was built from carries no sound of its own, so a+sound branch would have nothing to play.++## Preview++`preview/List.png` is rendered by `test/render-still.ts`, which builds the Track and renders it+through the local HyperFrames Runtime:++```bash+node --import tsx examples/ranking-typewriter-reverse/packages/local-notepad-list/test/render-still.ts \+ <paper.png> w5 40 preview/List.png+```++The recipe values that script uses live beside it in `test/notepad-recipe.json` so the preview and+the project's `studio.svs` can be kept in step.diff --git a/examples/ranking-typewriter-reverse/packages/local-notepad-list/package.json b/examples/ranking-typewriter-reverse/packages/local-notepad-list/package.jsonnew file mode 100644index 00000000..6fbd3798--- /dev/null+++ b/examples/ranking-typewriter-reverse/packages/local-notepad-list/package.json@@ -0,0 +1,32 @@+{+ "name": "@hypit/local-notepad-list",+ "version": "0.0.0-dev",+ "license": "SEE LICENSE IN LICENSE",+ "private": true,+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ },+ "hypit": {+ "activation": "./src/activation.ts"+ },+ "dependencies": {+ "@hypit/artifact": "workspace:*",+ "@hypit/component-kit": "workspace:*",+ "@hypit/composition": "workspace:*",+ "@hypit/elaborator": "workspace:*",+ "@hypit/markup": "workspace:*",+ "@hypit/media": "workspace:*",+ "@hypit/narrative": "workspace:*",+ "@hypit/program-space": "workspace:*",+ "@hypit/protocol": "workspace:*",+ "@hypit/semantic-map": "workspace:*",+ "@hypit/spatial": "workspace:*",+ "@hypit/svs": "workspace:*",+ "@hypit/temporal": "workspace:*",+ "@hypit/text": "workspace:*"+ },+ "devDependencies": {+ "@hypit/core": "workspace:*"+ }+}diff --git a/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/activation.ts b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/activation.tsnew file mode 100644index 00000000..a9cf16cf--- /dev/null+++ b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/activation.ts@@ -0,0 +1,28 @@+import { createMarkupSurfaceHostFacet } from "@hypit/markup";++import {+ decodeNotepadListSurface,+ decodeNotepadStyleSurface,+ notepadComponent,+ notepadManifest,+ notepadMarkupSurfaces,+ notepadModuleRef,+} from "./index.js";++const facets = [+ ["notepad-style", decodeNotepadStyleSurface],+ ["notepad-list", decodeNotepadListSurface],+] as const;++export const hypitPackage = {+ format: "hypit.node-package@1" as const,+ modules: [{ manifest: notepadManifest }],+ components: [notepadComponent],+ hostFacets: facets.map(([surface, handler]) => createMarkupSurfaceHostFacet({+ module: notepadModuleRef,+ declaration: notepadMarkupSurfaces.find((item) => item.name === surface)!,+ handler,+ })),+};++export default hypitPackage;diff --git a/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/component.ts b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/component.tsnew file mode 100644index 00000000..ce1c8c29--- /dev/null+++ b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/component.ts@@ -0,0 +1,127 @@+import type { ComponentPackage, ProducerHandlerContext } from "@hypit/component-kit";+import type { NarrativeMomentRef, NarrativeSelectionRef } from "@hypit/narrative";+import type { ProgramSpace } from "@hypit/program-space";+import { canonicalize } from "@hypit/protocol";+import type { BlobRef, StoredValue } from "@hypit/protocol";+import type { CompleteSemanticMap } from "@hypit/semantic-map";+import type { SpatialFrame } from "@hypit/spatial";+import type { Text } from "@hypit/text";++import { notepadProducers, notepadTypes } from "./manifest.js";+import { renderNotepadList } from "./render.js";+import {+ appendNotepadRowSpec,+ assertNotepadProgram,+ assertNotepadSchedule,+ buildNotepadProgram,+ buildNotepadSchedule,+ createNotepadRowSpecSet,+ materializeNotepadRow,+} from "./schedule.js";+import type {+ NotepadHeader,+ NotepadProgram,+ NotepadRowShell,+ NotepadRowSpec,+ NotepadRowSpecSet,+ NotepadSchedule,+ NotepadStyle,+ NotepadTitleSpec,+} from "./types.js";++function inline<T>(value: StoredValue | undefined, label: string): T {+ if (value?.kind !== "inline") throw new Error(`${label} must be inline.`);+ return value.value as unknown as T;+}++function blob(value: StoredValue | undefined, label: string): BlobRef {+ if (value?.kind !== "blob") throw new Error(`${label} must be a blob Artifact.`);+ return value;+}++const output = (value: unknown) => ({ kind: "inline" as const, value: canonicalize(value) });++function scheduleHandler(opened: boolean) {+ return ({ inputs }: ProducerHandlerContext) => ({+ outputs: {+ schedule: output(buildNotepadSchedule({+ header: inline<NotepadHeader>(inputs.header?.value, "NotepadHeader"),+ rows: inline<NotepadRowSpecSet>(inputs.rows?.value, "NotepadRowSpecSet"),+ map: inline<CompleteSemanticMap>(inputs.map?.value, "CompleteSemanticMap"),+ space: inline<ProgramSpace>(inputs.space?.value, "ProgramSpace"),+ during: inline<NarrativeSelectionRef>(inputs.during?.value, "NarrativeSelectionRef"),+ triggers: inline<NarrativeMomentRef>(inputs.triggers?.value, "NarrativeMomentRef"),+ terminal: inline<NarrativeMomentRef>(inputs.terminal?.value, "NarrativeMomentRef"),+ ...(opened+ ? { opening: inline<NarrativeSelectionRef>(inputs.opening?.value, "NarrativeSelectionRef") }+ : {}),+ })),+ },+ needs: {},+ });+}++export const notepadComponent = {+ producers: [+ {+ producer: notepadProducers.createRows,+ handler: ({ inputs }) => ({+ outputs: { set: output(createNotepadRowSpecSet(inline<NotepadHeader>(inputs.header?.value, "NotepadHeader"))) },+ needs: {},+ }),+ },+ {+ producer: notepadProducers.appendRow,+ handler: ({ inputs }) => ({+ outputs: { set: output(appendNotepadRowSpec(+ inline<NotepadRowSpecSet>(inputs.set?.value, "NotepadRowSpecSet"),+ inline<NotepadRowSpec>(inputs.spec?.value, "NotepadRowSpec"),+ )) },+ needs: {},+ }),+ },+ {+ producer: notepadProducers.materializeRow,+ handler: ({ inputs }) => ({+ outputs: { spec: output(materializeNotepadRow(+ inline<NotepadRowShell>(inputs.shell?.value, "NotepadRowShell"),+ inline<Text>(inputs.content?.value, "Text"),+ )) },+ needs: {},+ }),+ },+ { producer: notepadProducers.schedule, handler: scheduleHandler(false) },+ { producer: notepadProducers.openedSchedule, handler: scheduleHandler(true) },+ {+ producer: notepadProducers.program,+ handler: ({ inputs }) => ({+ outputs: { program: output(buildNotepadProgram(+ inline<NotepadHeader>(inputs.header?.value, "NotepadHeader"),+ inline<SpatialFrame>(inputs.frame?.value, "SpatialFrame"),+ blob(inputs.surface?.value, "Notepad surface"),+ inline<NotepadSchedule>(inputs.schedule?.value, "NotepadSchedule"),+ inline<NotepadStyle>(inputs.style?.value, "NotepadStyle"),+ inline<NotepadTitleSpec>(inputs.title?.value, "NotepadTitleSpec"),+ inline<NotepadRowSpecSet>(inputs.rows?.value, "NotepadRowSpecSet"),+ )) },+ needs: {},+ }),+ },+ {+ producer: notepadProducers.render,+ handler: ({ inputs }) => ({+ outputs: { track: output(renderNotepadList(+ inline<ProgramSpace>(inputs.space?.value, "ProgramSpace"),+ inline<NotepadProgram>(inputs.program?.value, "NotepadProgram"),+ )) },+ needs: {},+ }),+ },+ ],+ validators: [+ { type: notepadTypes.schedule,+ handler: ({ value }) => assertNotepadSchedule(inline<NotepadSchedule>(value, "NotepadSchedule")) },+ { type: notepadTypes.program,+ handler: ({ value }) => assertNotepadProgram(inline<NotepadProgram>(value, "NotepadProgram")) },+ ],+} satisfies ComponentPackage;diff --git a/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/fragment.ts b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/fragment.tsnew file mode 100644index 00000000..550645f1--- /dev/null+++ b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/fragment.ts@@ -0,0 +1,108 @@+import { compositionTypes } from "@hypit/composition";+import { sealGraphFragment } from "@hypit/elaborator";+import type { FragmentOperation, GraphFragment } from "@hypit/elaborator";+import { mediaTypes } from "@hypit/media";+import { narrativeTypes } from "@hypit/narrative";+import { programSpaceTypes } from "@hypit/program-space";+import { semanticMapTypes } from "@hypit/semantic-map";+import { spatialTypes } from "@hypit/spatial";+import { textTypes } from "@hypit/text";++import { notepadProducers, notepadTypes } from "./manifest.js";++const input = (name: string) => ({ kind: "fragment-input" as const, name });+const operation = (id: string) => ({ kind: "fragment-operation" as const, operation: id });++export type NotepadFragmentRow = {+ readonly suffix: string;+ readonly specName: string;+ readonly contentName?: string;+};++/**+ * Builds the Row set, resolves the Schedule against the measured map, folds+ * everything into one Program and renders it to a peer VisualTrack.+ */+export function createNotepadFragment(+ rows: readonly NotepadFragmentRow[],+ hasOpening: boolean,+): GraphFragment {+ if (rows.length === 0) throw new Error("Notepad Fragment requires at least one Row.");+ const inputs: Array<GraphFragment["inputs"][number]> = [+ { name: "header", type: notepadTypes.header },+ { name: "map", type: semanticMapTypes.complete },+ { name: "space", type: programSpaceTypes.programSpace },+ { name: "during", type: narrativeTypes.selection },+ { name: "triggers", type: narrativeTypes.moment },+ { name: "terminal", type: narrativeTypes.moment },+ { name: "frame", type: spatialTypes.frame },+ { name: "surface", type: mediaTypes.blobArtifact },+ { name: "style", type: notepadTypes.style },+ { name: "title", type: notepadTypes.title },+ ];+ if (hasOpening) inputs.push({ name: "opening", type: narrativeTypes.selection });++ const operations: FragmentOperation[] = [+ { id: "rows", producer: notepadProducers.createRows, inputs: { header: input("header") }, result: { kind: "output", name: "set" } },+ ];+ let set = operation("rows");+ for (const row of rows) {+ inputs.push({+ name: row.specName,+ type: row.contentName === undefined ? notepadTypes.rowSpec : notepadTypes.rowShell,+ });+ if (row.contentName !== undefined) inputs.push({ name: row.contentName, type: textTypes.text });+ const materializedId = `materialize-${row.suffix}`;+ if (row.contentName !== undefined) operations.push({+ id: materializedId,+ producer: notepadProducers.materializeRow,+ inputs: { shell: input(row.specName), content: input(row.contentName) },+ result: { kind: "output", name: "spec" },+ });+ const resolved = row.contentName === undefined ? input(row.specName) : operation(materializedId);+ const appendId = `row-${row.suffix}`;+ operations.push({+ id: appendId,+ producer: notepadProducers.appendRow,+ inputs: { set, spec: resolved },+ result: { kind: "output", name: "set" },+ });+ set = operation(appendId);+ }++ operations.push({+ id: "schedule",+ producer: hasOpening ? notepadProducers.openedSchedule : notepadProducers.schedule,+ inputs: {+ header: input("header"), rows: set, map: input("map"), space: input("space"),+ during: input("during"), triggers: input("triggers"), terminal: input("terminal"),+ ...(hasOpening ? { opening: input("opening") } : {}),+ },+ result: { kind: "output", name: "schedule" },+ });+ operations.push({+ id: "program",+ producer: notepadProducers.program,+ inputs: {+ header: input("header"), frame: input("frame"), surface: input("surface"),+ schedule: operation("schedule"), style: input("style"), title: input("title"), rows: set,+ },+ result: { kind: "output", name: "program" },+ });+ operations.push({+ id: "visual",+ producer: notepadProducers.render,+ inputs: { space: input("space"), program: operation("program") },+ result: { kind: "output", name: "track" },+ });++ return sealGraphFragment({+ inputs,+ operations,+ exports: [+ { name: "schedule", type: notepadTypes.schedule, root: operation("schedule") },+ { name: "program", type: notepadTypes.program, root: operation("program") },+ { name: "visual", type: compositionTypes.visualTrack, root: operation("visual") },+ ],+ });+}diff --git a/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/index.ts b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/index.tsnew file mode 100644index 00000000..6df4f7d7--- /dev/null+++ b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/index.ts@@ -0,0 +1,42 @@+export {+ appendNotepadRowSpec,+ assertNotepadHeader,+ assertNotepadProgram,+ assertNotepadRowShell,+ assertNotepadRowSpec,+ assertNotepadRowSpecSet,+ assertNotepadSchedule,+ assertNotepadStyle,+ assertNotepadSurface,+ assertNotepadTitleSpec,+ buildNotepadProgram,+ buildNotepadSchedule,+ createNotepadRowSpecSet,+ materializeNotepadRow,+ sealNotepadHeader,+ sealNotepadRowShell,+ sealNotepadTitleSpec,+} from "./schedule.js";+export { decodeNotepadStyle } from "./style.js";+export { renderNotepadList } from "./render.js";+export { notepadComponent } from "./component.js";+export { createNotepadFragment } from "./fragment.js";+export type { NotepadFragmentRow } from "./fragment.js";+export {+ notepadDependency,+ notepadHeaderSchema,+ notepadManifest,+ notepadMarkupSurfaces,+ notepadModuleRef,+ notepadProducers,+ notepadProgramSchema,+ notepadRowShellSchema,+ notepadRowSpecSchema,+ notepadRowSpecSetSchema,+ notepadScheduleSchema,+ notepadStyleSchema,+ notepadTitleSchema,+ notepadTypes,+} from "./manifest.js";+export { decodeNotepadListSurface, decodeNotepadStyleSurface } from "./surface.js";+export type * from "./types.js";diff --git a/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/manifest.ts b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/manifest.tsnew file mode 100644index 00000000..92fb9125--- /dev/null+++ b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/manifest.ts@@ -0,0 +1,358 @@+import { readFile } from "node:fs/promises";++import { artifactDependency } from "@hypit/artifact";+import { compositionDependency, compositionTypes } from "@hypit/composition";+import { mediaDependency, mediaTypes } from "@hypit/media";+import { narrativeDependency, narrativeTypes } from "@hypit/narrative";+import { programSpaceDependency, programSpaceTypes } from "@hypit/program-space";+import type { ModuleManifest, ProducerRef, TypeRef, ValueSchema } from "@hypit/protocol";+import { semanticMapDependency, semanticMapTypes } from "@hypit/semantic-map";+import { spatialDependency, spatialFrameSchema, spatialTypes } from "@hypit/spatial";+import { svsRecipeType } from "@hypit/svs";+import { temporalDependency } from "@hypit/temporal";+import { textDependency, textTypes } from "@hypit/text";++export const notepadModuleRef = { name: "@hypit/local-notepad-list", version: "1" } as const;++export const notepadTypes = {+ header: { module: notepadModuleRef, name: "NotepadHeader" },+ title: { module: notepadModuleRef, name: "NotepadTitleSpec" },+ rowSpec: { module: notepadModuleRef, name: "NotepadRowSpec" },+ rowShell: { module: notepadModuleRef, name: "NotepadRowShell" },+ rowSpecs: { module: notepadModuleRef, name: "NotepadRowSpecSet" },+ schedule: { module: notepadModuleRef, name: "NotepadSchedule" },+ style: { module: notepadModuleRef, name: "NotepadStyle" },+ program: { module: notepadModuleRef, name: "NotepadProgram" },+} satisfies Record<string, TypeRef>;++export const notepadProducers = {+ createRows: { module: notepadModuleRef, name: "create-notepad-rows" },+ appendRow: { module: notepadModuleRef, name: "append-notepad-row" },+ materializeRow: { module: notepadModuleRef, name: "materialize-notepad-row" },+ schedule: { module: notepadModuleRef, name: "build-notepad-schedule" },+ openedSchedule: { module: notepadModuleRef, name: "build-opened-notepad-schedule" },+ program: { module: notepadModuleRef, name: "build-notepad-program" },+ render: { module: notepadModuleRef, name: "render-notepad-list" },+} satisfies Record<string, ProducerRef>;++const string = { kind: "string", minLength: 1 } as const;+const integer = { kind: "number", integer: true } as const;+const unsigned = { kind: "number", integer: true, minimum: 0 } as const;+const object = (+ fields: Readonly<Record<string, { readonly schema: ValueSchema; readonly optional?: boolean }>>,+ allowUnknown = false,+): ValueSchema => ({ kind: "object", fields, ...(allowUnknown ? { allowUnknown: true } : {}) });++const rowBase = {+ id: { schema: string },+ rank: { schema: { kind: "number", integer: true, minimum: 1 } as const },+ mark: { schema: { kind: "string", enum: ["none", "circle"] } as const },+ stackingOrder: { schema: integer, optional: true },+} as const;++export const notepadHeaderSchema: ValueSchema = object({ id: { schema: string } });+export const notepadTitleSchema: ValueSchema = object({+ lead: { schema: string },+ emphasis: { schema: { kind: "string" } as const },+});+export const notepadRowSpecSchema: ValueSchema = object({ ...rowBase, label: { schema: string } });+export const notepadRowShellSchema: ValueSchema = object(rowBase);+export const notepadRowSpecSetSchema: ValueSchema = object({+ rows: { schema: { kind: "array", items: notepadRowSpecSchema } },+});+const frameSpan = object({ startFrame: { schema: unsigned }, endFrameExclusive: { schema: unsigned } });+export const notepadScheduleSchema: ValueSchema = object({+ id: { schema: string },+ windows: { schema: { kind: "array", minItems: 1, items: frameSpan } },+ opening: { schema: frameSpan, optional: true },+ terminalFrame: { schema: unsigned },+ entries: { schema: { kind: "array", minItems: 1, items: object({+ rowId: { schema: string }, triggerFrame: { schema: unsigned },+ }) } },+});+export const notepadStyleSchema: ValueSchema = object({}, true);+export const notepadProgramSchema: ValueSchema = object({+ id: { schema: string },+ frame: { schema: spatialFrameSchema },+ schedule: { schema: notepadScheduleSchema },+ style: { schema: notepadStyleSchema },+ title: { schema: notepadTitleSchema },+ rows: { schema: { kind: "array", minItems: 1, items: notepadRowSpecSchema } },+}, true);++const previewImage = (file: string) => ({+ mediaType: "image/png",+ path: `preview/${file}`,+ open: async () => Uint8Array.from(await readFile(new URL(`../preview/${file}`, import.meta.url))),+});++export const notepadMarkupSurfaces = [+ {+ name: "notepad-style", tag: "ListStyle", mode: "structured",+ outputs: [notepadTypes.style],+ vocabulary: {+ summary: "Compiles one SVS Recipe and three exact faces into the Style a notepad list is drawn in.",+ attributes: [+ { name: "id", kind: "identifier", required: true,+ summary: "Names this Style so a List can reference it." },+ { name: "recipe", kind: "reference", required: true, accepts: [svsRecipeType],+ summary: "Chooses the Recipe carrying the paper treatment, the two title paints, the row geometry, the annotation and the typing rhythm.",+ recipe: [+ { name: "surface-fit", required: false, fallback: "cover", values: ["contain", "cover"],+ summary: "Decides whether the paper picture fits inside the Frame or fills it." },+ { name: "title-x", required: false, fallback: "0.1",+ summary: "Places the title's left edge on the paper, as a fraction of the Frame's width." },+ { name: "title-y", required: false, fallback: "0.19",+ summary: "Places the title's top edge on the paper, as a fraction of the Frame's height." },+ { name: "title-width", required: false, fallback: "0.82",+ summary: "Sets the width the title wraps inside, as a fraction of the Frame's width." },+ { name: "title-size", required: false, fallback: "74",+ summary: "Sets the size in pixels the title is set at on the paper." },+ { name: "title-line-height", required: false, fallback: "1.16",+ summary: "Sets the line height the title is set on, as a multiple of its size." },+ { name: "title-tracking", required: false, fallback: "0",+ summary: "Adjusts the letter spacing in pixels of the title on the paper." },+ { name: "title-color", required: false, fallback: "#1c1c1c",+ summary: "Sets the color the title is drawn in on the paper." },+ { name: "title-underline", required: false, fallback: "0",+ summary: "Sets the thickness in pixels of the rule under the emphasized words on the paper; zero draws none." },+ { name: "opening-x", required: false, fallback: "0.08",+ summary: "Places the opening title's left edge, as a fraction of the Frame's width." },+ { name: "opening-y", required: false, fallback: "0.55",+ summary: "Places the opening title's top edge, as a fraction of the Frame's height." },+ { name: "opening-width", required: false, fallback: "0.86",+ summary: "Sets the width the opening title wraps inside, as a fraction of the Frame's width." },+ { name: "opening-size", required: false, fallback: "74",+ summary: "Sets the size in pixels the opening title is set at." },+ { name: "opening-line-height", required: false, fallback: "1.16",+ summary: "Sets the line height the opening title is set on, as a multiple of its size." },+ { name: "opening-tracking", required: false, fallback: "0",+ summary: "Adjusts the letter spacing in pixels of the opening title." },+ { name: "opening-color", required: false, fallback: "#ffffff",+ summary: "Sets the color the opening title is drawn in." },+ { name: "opening-underline", required: false, fallback: "0",+ summary: "Sets the thickness in pixels of the rule under the emphasized words in the opening; zero draws none." },+ { name: "opening-shadow-x", required: false, fallback: "0",+ summary: "Offsets the opening title's shadow horizontally in pixels." },+ { name: "opening-shadow-y", required: false, fallback: "2",+ summary: "Offsets the opening title's shadow vertically in pixels." },+ { name: "opening-shadow-blur", required: false, fallback: "10",+ summary: "Sets the blur radius in pixels of the opening title's shadow." },+ { name: "opening-shadow-color", required: false, fallback: "#00000080",+ summary: "Sets the color of the opening title's shadow." },+ { name: "row-x", required: false, fallback: "0.21",+ summary: "Places the left edge of the row copy, as a fraction of the Frame's width; the number sits to its left." },+ { name: "row-top", required: false, fallback: "0.36",+ summary: "Places the first row's top edge, as a fraction of the Frame's height." },+ { name: "row-width", required: false, fallback: "0.72",+ summary: "Sets the width a row's copy wraps inside, as a fraction of the Frame's width." },+ { name: "row-gap", required: false, fallback: "96",+ summary: "Sets the distance in pixels between one row's top edge and the next." },+ { name: "row-size", required: false, fallback: "52",+ summary: "Sets the size in pixels the numbers and row copy are set at." },+ { name: "row-line-height", required: false, fallback: "1.2",+ summary: "Sets the line height the row copy is set on, as a multiple of its size." },+ { name: "row-tracking", required: false, fallback: "0",+ summary: "Adjusts the letter spacing in pixels of the row copy." },+ { name: "row-color", required: false, fallback: "#1c1c1c",+ summary: "Sets the color the numbers and row copy are drawn in." },+ { name: "row-number-width", required: false, fallback: "54",+ summary: "Sets the width in pixels of the column the rank numbers are set in." },+ { name: "mark-color", required: false, fallback: "#1c1c1c",+ summary: "Sets the color the annotation is drawn in." },+ { name: "mark-stroke", required: false, fallback: "4",+ summary: "Sets the stroke width in pixels of the annotation." },+ { name: "mark-pad-x", required: false, fallback: "16",+ summary: "Sets the horizontal breathing space in pixels between the annotation and the row it encircles." },+ { name: "mark-pad-y", required: false, fallback: "8",+ summary: "Sets the vertical breathing space in pixels between the annotation and the row it encircles." },+ { name: "mark-rotate", required: false, fallback: "-1.5",+ summary: "Tilts the annotation by this many degrees so it reads as drawn by hand." },+ { name: "mark-frames", required: false, fallback: "8",+ summary: "Sets how many frames the annotation takes to draw itself." },+ { name: "mark-advance", required: false, fallback: "0.5",+ summary: "States the row face's mean glyph advance as a fraction of the row size, which is how wide the annotation knows to be." },+ { name: "title-type-frames", required: false, fallback: "2",+ summary: "Sets how many frames pass between two characters of the opening title." },+ { name: "row-type-frames", required: false, fallback: "2",+ summary: "Sets how many frames pass between two characters of a row's copy." },+ { name: "surface-stack", required: false, fallback: "40",+ summary: "Sets the draw order the paper is placed at." },+ { name: "title-stack", required: false, fallback: "42",+ summary: "Sets the draw order the title is placed at." },+ { name: "row-stack", required: false, fallback: "44",+ summary: "Sets the draw order the numbers and row copy are placed at." },+ { name: "mark-stack", required: false, fallback: "46",+ summary: "Sets the draw order the annotation is placed at, unless the Row overrides it." },+ ] },+ { name: "title-font", kind: "reference", required: true,+ accepts: [mediaTypes.fontArtifact, mediaTypes.fontStack],+ summary: "Chooses the face the title's leading words are set in." },+ { name: "emphasis-font", kind: "reference", required: true,+ accepts: [mediaTypes.fontArtifact, mediaTypes.fontStack],+ summary: "Chooses the face the title's emphasized words are set in." },+ { name: "row-font", kind: "reference", required: true,+ accepts: [mediaTypes.fontArtifact, mediaTypes.fontStack],+ summary: "Chooses the face the row copy is set in." },+ { name: "number-font", kind: "reference", required: false,+ accepts: [mediaTypes.fontArtifact, mediaTypes.fontStack],+ summary: "Chooses the face the rank numbers are set in, which falls back to the row face." },+ ],+ ports: [+ { name: "", type: notepadTypes.style,+ summary: "The compiled Style, addressed by the element's own id." },+ ],+ example: `<notes:ListStyle id="notepad" recipe={studio.notepad.list}+ title-font={title-face} emphasis-font={emphasis-face}+ row-font={hand-face} number-font={hand-light-face}/>`,+ notes: [+ "The element is empty; it accepts no children and no text.",+ "The Recipe accepts exactly the properties listed here; every other property is refused by name.",+ "The font edges are separate because the composition sets several different faces at once, and weight lives on the face rather than in the Recipe.",+ ],+ },+ },+ {+ name: "notepad-list", tag: "List", mode: "structured",+ outputs: [+ notepadTypes.header, notepadTypes.title, notepadTypes.rowSpec, notepadTypes.rowShell,+ notepadTypes.schedule, notepadTypes.program, compositionTypes.visualTrack,+ // The sheet this package ships, admitted as an ordinary Artifact when no+ // Source names a different one.+ mediaTypes.blobArtifact,+ ],+ vocabulary: {+ summary: "Writes a numbered list onto a sheet of paper one row at a time, returning to it on each occurrence of a Selection, and publishes the composition and the Track it renders to.",+ appearance:+ "One full-frame sheet of paper carrying the whole picture: no other content is behind it. Its title sits near the top in two faces on one wrapping block — the leading words in the title face, the closing words in the emphasis face, optionally ruled underneath — and beneath it every rank number the list will ever hold is already written down the sheet in a fixed left column, each on its own line, with the space beside it blank. On each trigger occurrence one row's copy writes itself in beside its number, one character at a time at the Recipe's rhythm, and stays written for the rest of the list's life; rows written in earlier windows are already complete when the sheet returns. The row order down the sheet is the rank each Row declares, while the order they are written in is the order the Rows are authored, so a list can fill from the bottom upward. A Row asking for the circle annotation gains a hand-tilted ellipse that draws itself around the number and copy once that copy has finished writing. Before the paper ever appears the title alone can write itself over whatever the picture already shows, in the opening paint rather than the paper paint.",+ preview: previewImage("List.png"),+ attributes: [+ { name: "id", kind: "identifier", required: true,+ summary: "Names this list so its Schedule, Program and Track can be referenced elsewhere in the Source." },+ { name: "map", kind: "reference", required: true, accepts: [semanticMapTypes.complete],+ summary: "Chooses the measured SemanticMap that gives every window and trigger its frame." },+ { name: "space", kind: "reference", required: true, accepts: [programSpaceTypes.programSpace],+ summary: "Chooses the ProgramSpace the list is timed and rendered against." },+ { name: "frame", kind: "reference", required: true, accepts: [spatialTypes.frame],+ summary: "Chooses the Frame the whole sheet occupies." },+ { name: "surface", kind: "reference", required: false, accepts: [mediaTypes.blobArtifact],+ summary: "Replaces the ruled paper this package draws on by default. The component ships its own sheet, so a Source only names one to deliberately write on something else." },+ { name: "during", kind: "reference", required: true, accepts: [narrativeTypes.selection],+ summary: "Chooses the Selection whose every occurrence is one window the sheet is on screen for." },+ { name: "triggers", kind: "reference", required: true, accepts: [narrativeTypes.moment],+ summary: "Chooses the Moment whose occurrences write one Row each, in document order." },+ { name: "terminal", kind: "reference", required: true, accepts: [narrativeTypes.moment],+ summary: "Chooses the Moment the completed list settles on." },+ { name: "opening", kind: "reference", required: false, accepts: [narrativeTypes.selection],+ summary: "Chooses the Selection the title writes itself over before the paper first appears." },+ { name: "title", kind: "literal", required: true,+ summary: "Sets the title's leading words, drawn in the Style's title face." },+ { name: "title-emphasis", kind: "literal", required: false,+ summary: "Sets the title's closing words, drawn in the Style's emphasis face; an omitted value writes none." },+ { name: "style", kind: "reference", required: true, accepts: [notepadTypes.style],+ summary: "Chooses the ListStyle this sheet is drawn in." },+ ],+ children: [+ { tag: "Row", cardinality: "many",+ summary: "One row of the list, written at its own trigger occurrence in document order; it is empty.",+ attributes: [+ { name: "id", kind: "identifier", required: false,+ summary: "Names this row within the list; an omitted id is generated from the row's position." },+ { name: "rank", kind: "literal", required: true,+ summary: "Sets the number printed beside the row and the slot it occupies down the sheet." },+ { name: "label", kind: "expression", required: true, accepts: [textTypes.text],+ summary: "Sets the row's copy, written literally or chosen from an existing Text." },+ { name: "mark", kind: "literal", required: false, values: ["none", "circle"],+ summary: "Decides whether the row gains a hand-drawn ellipse once its copy is written, and defaults to none." },+ { name: "stack", kind: "literal", required: false,+ summary: "Overrides the Style's annotation draw order for this row alone." },+ ] },+ ],+ ports: [+ { name: "schedule", type: notepadTypes.schedule,+ summary: "The resolved Schedule: every window, the optional opening, each Row's trigger frame and the terminal frame." },+ { name: "program", type: notepadTypes.program,+ summary: "The resolved sheet: its Frame, paper, Style, Schedule, title and ordered Rows." },+ { name: "visual", type: compositionTypes.visualTrack,+ summary: "The rendered sheet, an ordinary peer VisualTrack." },+ ],+ example: `<notes:ListStyle id="notepad" recipe={studio.notepad.list}+ title-font={title-face} emphasis-font={emphasis-face} row-font={hand-face}/>+<notes:List id="board" map={timing.map} space={speech.space} frame={full}+ surface={paper.image} during={story.selection.board} opening={story.selection.opening}+ triggers={story.moment.write} terminal={story.moment.settled}+ title="Top 5 Most Popular Ways to " title-emphasis="learn AI" style={notepad}>+ <notes:Row id="row-five" rank="5" label="Instagram"/>+ <notes:Row id="row-one" rank="1" label="The Rundown" mark="circle"/>+</notes:List>`,+ notes: [+ "The list requires at least one Row, accepts no other child and no text of its own, and Row ids and ranks must both be unique within it.",+ "The trigger Moment must occur exactly once per Row, and every trigger must fall inside one of the Selection's windows.",+ "The `during` Selection may occur many times; the sheet is drawn once per occurrence and remembers every Row written before it.",+ "A `label` written as a reference materializes the row from that exact Text before the list is scheduled; the title is editorial copy the composition owns and is written literally.",+ ],+ },+ },+] as const;++export const notepadManifest: ModuleManifest = {+ format: "hypit.module@1",+ name: notepadModuleRef.name,+ version: notepadModuleRef.version,+ dependencies: [+ artifactDependency, mediaDependency, narrativeDependency, semanticMapDependency,+ programSpaceDependency, spatialDependency, temporalDependency, compositionDependency, textDependency,+ ],+ types: [+ { name: notepadTypes.header.name },+ { name: notepadTypes.title.name },+ { name: notepadTypes.rowSpec.name },+ { name: notepadTypes.rowShell.name },+ { name: notepadTypes.rowSpecs.name },+ { name: notepadTypes.schedule.name },+ { name: notepadTypes.style.name },+ { name: notepadTypes.program.name },+ ],+ capabilities: [],+ producers: [+ { name: notepadProducers.materializeRow.name,+ inputs: [{ name: "shell", type: notepadTypes.rowShell }, { name: "content", type: textTypes.text }],+ outputs: [{ name: "spec", type: notepadTypes.rowSpec }], needs: [] },+ { name: notepadProducers.createRows.name,+ inputs: [{ name: "header", type: notepadTypes.header }],+ outputs: [{ name: "set", type: notepadTypes.rowSpecs }], needs: [] },+ { name: notepadProducers.appendRow.name,+ inputs: [{ name: "set", type: notepadTypes.rowSpecs }, { name: "spec", type: notepadTypes.rowSpec }],+ outputs: [{ name: "set", type: notepadTypes.rowSpecs }], needs: [] },+ ...([+ [notepadProducers.schedule, false],+ [notepadProducers.openedSchedule, true],+ ] as const).map(([producer, opened]) => ({+ name: producer.name,+ inputs: [+ { name: "header", type: notepadTypes.header }, { name: "rows", type: notepadTypes.rowSpecs },+ { name: "map", type: semanticMapTypes.complete }, { name: "space", type: programSpaceTypes.programSpace },+ { name: "during", type: narrativeTypes.selection }, { name: "triggers", type: narrativeTypes.moment },+ { name: "terminal", type: narrativeTypes.moment },+ ...(opened ? [{ name: "opening", type: narrativeTypes.selection }] : []),+ ],+ outputs: [{ name: "schedule", type: notepadTypes.schedule }], needs: [],+ })),+ { name: notepadProducers.program.name,+ inputs: [+ { name: "header", type: notepadTypes.header }, { name: "frame", type: spatialTypes.frame },+ { name: "surface", type: mediaTypes.blobArtifact }, { name: "schedule", type: notepadTypes.schedule },+ { name: "style", type: notepadTypes.style }, { name: "title", type: notepadTypes.title },+ { name: "rows", type: notepadTypes.rowSpecs },+ ],+ outputs: [{ name: "program", type: notepadTypes.program }], needs: [] },+ { name: notepadProducers.render.name,+ inputs: [+ { name: "space", type: programSpaceTypes.programSpace },+ { name: "program", type: notepadTypes.program },+ ],+ outputs: [{ name: "track", type: compositionTypes.visualTrack }], needs: [] },+ ],+};++export const notepadDependency = { module: notepadModuleRef } as const;diff --git a/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/render.ts b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/render.tsnew file mode 100644index 00000000..0487f97e--- /dev/null+++ b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/render.ts@@ -0,0 +1,455 @@+import { assertVisualTrackIdentity, sealVisualTrack } from "@hypit/composition";+import type {+ FrameSpan,+ VisualElement,+ VisualPresent,+ VisualStyleDeclaration,+ VisualTextDocument,+ VisualTextFlow,+ VisualTextPaintLayer,+ VisualTextSequenceAnimation,+ VisualTextTypography,+ VisualTrack,+} from "@hypit/composition";+import type { FontArtifactRef } from "@hypit/media";+import { assertProgramSpaceIdentity } from "@hypit/program-space";+import type { ProgramSpace } from "@hypit/program-space";++import { assertNotepadProgram } from "./schedule.js";+import type {+ NotepadProgram,+ NotepadRowSpec,+ NotepadStyle,+ NotepadTitlePaint,+} from "./types.js";++function assert(condition: unknown, message: string): asserts condition {+ if (!condition) throw new Error(message);+}++function px(value: number): string {+ return `${Math.round(value * 1_000_000) / 1_000_000}px`;+}++/** Grapheme count as the browser sequence renderer counts it. */+function graphemeCount(value: string): number {+ return [...new Intl.Segmenter("en", { granularity: "grapheme" }).segment(value)].length;+}++function typography(+ fonts: readonly FontArtifactRef[],+ sizePx: number,+ lineHeight: number,+ trackingPx: number,+): VisualTextTypography {+ const face = fonts[0]!;+ return {+ fonts: structuredClone(fonts),+ sizePx,+ weight: face.weight,+ style: face.style,+ axes: [],+ features: [],+ synthesis: "none",+ kerning: "auto",+ trackingPx,+ wordSpacingPx: 0,+ lineHeight,+ direction: "ltr",+ writingMode: "horizontal-tb",+ baselineShiftPx: 0,+ tabSize: 4,+ indentationPx: 0,+ paragraphBeforePx: 0,+ paragraphAfterPx: 0,+ transform: "none",+ variantCaps: "normal",+ verticalAlign: "baseline",+ decorations: [],+ cjk: { textSpacing: "normal", punctuationTrim: "none" },+ };+}++function paints(color: string, shadow?: NotepadTitlePaint["shadow"]): VisualTextPaintLayer[] {+ const layers: VisualTextPaintLayer[] = [];+ if (shadow !== undefined) layers.push({+ kind: "shadow",+ paint: { kind: "solid", color: shadow.color },+ offsetX: shadow.offsetX,+ offsetY: shadow.offsetY,+ blurPx: shadow.blurPx,+ spreadPx: 0,+ });+ layers.push({ kind: "fill", paint: { kind: "solid", color } });+ return layers;+}++function areaFlow(inlineAlign: "start" | "center" | "end"): VisualTextFlow {+ return {+ form: { kind: "area" },+ inlineSize: "fixed",+ blockSize: "hug",+ paddingPx: { inlineStart: 0, inlineEnd: 0, blockStart: 0, blockEnd: 0 },+ inlineAlign,+ blockAlign: "start",+ wrap: "word",+ overflow: "visible",+ clipToFrame: false,+ columns: 1,+ columnGapPx: 0,+ metricEdge: "line-box",+ };+}++/** A grapheme-by-grapheme reveal: nothing is drawn until its own character is typed. */+function typewriter(+ id: string,+ characters: number,+ startFrame: number,+ staggerFrames: number,+): VisualTextSequenceAnimation {+ return {+ id,+ unit: "grapheme",+ range: { start: 0, endExclusive: characters },+ order: "forward",+ startFrame,+ unitDurationFrames: 1,+ staggerFrames,+ cycles: 1,+ keyframes: [+ { atProgress: 0, style: [{ name: "opacity", value: 0 }] },+ { atProgress: 1, style: [{ name: "opacity", value: 1 }] },+ ],+ };+}++function box(input: {+ readonly id: string;+ readonly order: number;+ readonly parent?: string;+ readonly x: number;+ readonly y: number;+ readonly width: number;+ readonly height: number;+ readonly style?: readonly VisualStyleDeclaration[];+}): VisualElement {+ return {+ id: input.id,+ ...(input.parent === undefined ? {} : { parent: input.parent }),+ order: input.order,+ kind: "box",+ style: [+ { name: "height", value: px(input.height) },+ { name: "left", value: px(input.x) },+ { name: "position", value: "absolute" },+ { name: "top", value: px(input.y) },+ { name: "width", value: px(input.width) },+ ...(input.style ?? []),+ ],+ };+}++function flowText(input: {+ readonly id: string;+ readonly order: number;+ readonly parent: string;+ readonly x: number;+ readonly y: number;+ readonly width: number;+ readonly document: VisualTextDocument;+ readonly typography: VisualTextTypography;+ readonly paints: readonly VisualTextPaintLayer[];+ readonly align?: "start" | "center" | "end";+ readonly sequences?: readonly VisualTextSequenceAnimation[];+}): VisualElement {+ return {+ id: input.id,+ parent: input.parent,+ order: input.order,+ kind: "text-flow",+ document: input.document,+ typography: input.typography,+ paints: [...input.paints],+ flow: areaFlow(input.align ?? "start"),+ sequences: [...(input.sequences ?? [])],+ style: [+ { name: "left", value: px(input.x) },+ { name: "position", value: "absolute" },+ { name: "top", value: px(input.y) },+ { name: "width", value: px(input.width) },+ ],+ };+}++/** The one title document: an italic lead run followed by the emphasized run. */+function titleDocument(+ program: NotepadProgram,+ paint: NotepadTitlePaint,+): { readonly document: VisualTextDocument; readonly characters: number } {+ const { style, title } = program;+ const emphasis = typography(style.emphasisFonts, paint.sizePx, paint.lineHeight, paint.trackingPx);+ const document: VisualTextDocument = {+ paragraphs: [{+ id: `${program.id}-title`,+ inlines: [+ { kind: "text", id: `${program.id}-title-lead`, text: title.lead },+ ...(title.emphasis.length === 0 ? [] : [{+ kind: "text" as const,+ id: `${program.id}-title-emphasis`,+ text: title.emphasis,+ style: {+ typography: {+ fonts: emphasis.fonts,+ weight: emphasis.weight,+ style: emphasis.style,+ ...(paint.underlinePx > 0+ ? {+ decorations: [{+ line: "underline" as const,+ paint: { kind: "solid" as const, color: paint.color },+ style: "solid" as const,+ thicknessPx: paint.underlinePx,+ skipInk: false,+ }],+ }+ : {}),+ },+ },+ }]),+ ],+ }],+ };+ return { document, characters: graphemeCount(title.lead) + graphemeCount(title.emphasis) };+}++function rowDocument(program: NotepadProgram, row: NotepadRowSpec, id: string): VisualTextDocument {+ return { paragraphs: [{ id: `${id}-p`, inlines: [{ kind: "text", id: `${id}-run`, text: row.label }] }] };+}++function rowTop(style: NotepadStyle, frameHeight: number, index: number): number {+ return frameHeight * style.row.topFraction + index * style.row.gapPx;+}++function present(input: {+ readonly id: string;+ readonly span: FrameSpan;+ readonly stacking: number;+ readonly tieBreak: string;+ readonly elements: readonly VisualElement[];+}): VisualPresent {+ return {+ id: input.id,+ span: { startFrame: input.span.startFrame, endFrameExclusive: input.span.endFrameExclusive },+ stacking: { order: input.stacking, tieBreak: input.tieBreak },+ elements: input.elements,+ };+}++/**+ * Draws the notepad list: the paper, the title, every numbered slot, the copy+ * already written and the copy typing itself in, plus the annotation drawn+ * around the row that carries one.+ */+export function renderNotepadList(space: ProgramSpace, program: NotepadProgram): VisualTrack {+ assertProgramSpaceIdentity(space);+ assertNotepadProgram(program);+ const { frame, style, schedule } = program;+ const presents: VisualPresent[] = [];+ const ordered = [...program.rows].sort((left, right) => left.rank - right.rank);++ if (schedule.opening !== undefined) {+ const paint = style.opening;+ const built = titleDocument(program, paint);+ const root = `${program.id}-opening`;+ presents.push(present({+ id: `${program.id}:opening`,+ span: schedule.opening,+ stacking: style.stacking.title,+ tieBreak: `${program.id}:0000:opening`,+ elements: [+ box({ id: root, order: 0, x: frame.xPx, y: frame.yPx, width: frame.widthPx, height: frame.heightPx }),+ flowText({+ id: `${root}-text`, order: 1, parent: root,+ x: frame.widthPx * paint.xFraction,+ y: frame.heightPx * paint.yFraction,+ width: frame.widthPx * paint.widthFraction,+ document: built.document,+ typography: typography(style.leadFonts, paint.sizePx, paint.lineHeight, paint.trackingPx),+ paints: paints(paint.color, paint.shadow),+ sequences: [typewriter(+ `${root}-type`, built.characters,+ 0, style.typing.titleFramesPerCharacter,+ )],+ }),+ ],+ }));+ }++ for (const [windowIndex, window] of schedule.windows.entries()) {+ const suffix = String(windowIndex).padStart(4, "0");+ presents.push(present({+ id: `${program.id}:paper:${suffix}`,+ span: window,+ stacking: style.stacking.surface,+ tieBreak: `${program.id}:${suffix}:paper`,+ elements: [{+ id: `${program.id}-paper-${suffix}`,+ order: 0,+ kind: "image",+ artifact: structuredClone(program.surface),+ style: [+ { name: "height", value: px(frame.heightPx) },+ { name: "left", value: px(frame.xPx) },+ { name: "object-fit", value: style.surfaceFit },+ { name: "position", value: "absolute" },+ { name: "top", value: px(frame.yPx) },+ { name: "width", value: px(frame.widthPx) },+ ],+ }],+ }));++ const titlePaint = style.title;+ const titleBuilt = titleDocument(program, titlePaint);+ const titleRoot = `${program.id}-title-${suffix}`;+ presents.push(present({+ id: `${program.id}:title:${suffix}`,+ span: window,+ stacking: style.stacking.title,+ tieBreak: `${program.id}:${suffix}:title`,+ elements: [+ box({ id: titleRoot, order: 0, x: frame.xPx, y: frame.yPx, width: frame.widthPx, height: frame.heightPx }),+ flowText({+ id: `${titleRoot}-text`, order: 1, parent: titleRoot,+ x: frame.widthPx * titlePaint.xFraction,+ y: frame.heightPx * titlePaint.yFraction,+ width: frame.widthPx * titlePaint.widthFraction,+ document: titleBuilt.document,+ typography: typography(style.leadFonts, titlePaint.sizePx, titlePaint.lineHeight, titlePaint.trackingPx),+ paints: paints(titlePaint.color),+ }),+ ],+ }));++ const rowElements: VisualElement[] = [+ box({+ id: `${program.id}-rows-${suffix}`, order: 0,+ x: frame.xPx, y: frame.yPx, width: frame.widthPx, height: frame.heightPx,+ }),+ ];+ const rowsRoot = `${program.id}-rows-${suffix}`;+ const rowTypography = typography(style.rowFonts, style.row.sizePx, style.row.lineHeight, style.row.trackingPx);+ const numberTypography = typography(style.numberFonts, style.row.sizePx, style.row.lineHeight, style.row.trackingPx);+ const rowPaints = paints(style.row.color);+ const lineHeightPx = style.row.sizePx * style.row.lineHeight;+ for (const [slot, row] of ordered.entries()) {+ const y = rowTop(style, frame.heightPx, slot);+ const x = frame.widthPx * style.row.xFraction;+ rowElements.push(flowText({+ id: `${rowsRoot}-number-${row.id}`, order: rowElements.length, parent: rowsRoot,+ x: x - style.row.numberWidthPx, y,+ width: style.row.numberWidthPx,+ document: { paragraphs: [{+ id: `${rowsRoot}-number-${row.id}-p`,+ inlines: [{ kind: "text", id: `${rowsRoot}-number-${row.id}-run`, text: `${row.rank}.` }],+ }] },+ typography: numberTypography,+ paints: rowPaints,+ }));+ const trigger = schedule.entries.find((entry) => entry.rowId === row.id)!.triggerFrame;+ const written = trigger < window.startFrame;+ const typing = trigger >= window.startFrame && trigger < window.endFrameExclusive;+ if (!written && !typing) continue;+ rowElements.push(flowText({+ id: `${rowsRoot}-label-${row.id}`, order: rowElements.length, parent: rowsRoot,+ x, y,+ width: frame.widthPx * style.row.widthFraction,+ document: rowDocument(program, row, `${rowsRoot}-label-${row.id}`),+ typography: rowTypography,+ paints: rowPaints,+ ...(typing+ ? { sequences: [typewriter(+ `${rowsRoot}-type-${row.id}`,+ graphemeCount(row.label),+ trigger - window.startFrame,+ style.typing.rowFramesPerCharacter,+ )] }+ : {}),+ }));+ }+ presents.push(present({+ id: `${program.id}:rows:${suffix}`,+ span: window,+ stacking: style.stacking.row,+ tieBreak: `${program.id}:${suffix}:rows`,+ elements: rowElements,+ }));++ for (const [slot, row] of ordered.entries()) {+ if (row.mark !== "circle") continue;+ const trigger = schedule.entries.find((entry) => entry.rowId === row.id)!.triggerFrame;+ const settled = trigger + graphemeCount(row.label) * style.typing.rowFramesPerCharacter;+ const start = Math.max(window.startFrame, settled);+ if (start >= window.endFrameExclusive) continue;+ const y = rowTop(style, frame.heightPx, slot);+ const x = frame.widthPx * style.row.xFraction;+ const width = style.row.numberWidthPx+ + graphemeCount(row.label) * style.row.sizePx * style.mark.advance+ + style.mark.padXPx * 2;+ const markRoot = `${program.id}-mark-${row.id}-${suffix}`;+ const markFrames = Math.min(style.mark.frames, window.endFrameExclusive - start);+ presents.push(present({+ id: `${program.id}:mark:${row.id}:${suffix}`,+ span: { startFrame: start, endFrameExclusive: window.endFrameExclusive },+ stacking: row.stackingOrder ?? style.stacking.mark,+ tieBreak: `${program.id}:${suffix}:mark:${row.id}`,+ elements: [+ box({+ id: markRoot, order: 0,+ x: frame.xPx, y: frame.yPx, width: frame.widthPx, height: frame.heightPx,+ }),+ {+ id: `${markRoot}-ellipse`,+ parent: markRoot,+ order: 1,+ kind: "box",+ style: [+ { name: "border", value: `${px(style.mark.strokeWidthPx)} solid ${style.mark.color}` },+ { name: "border-radius", value: "50%" },+ { name: "box-sizing", value: "border-box" },+ { name: "height", value: px(lineHeightPx + style.mark.padYPx * 2) },+ { name: "left", value: px(x - style.row.numberWidthPx - style.mark.padXPx) },+ { name: "position", value: "absolute" },+ { name: "top", value: px(y - style.mark.padYPx) },+ { name: "transform-origin", value: "50% 50%" },+ { name: "width", value: px(width) },+ ],+ animation: {+ keyframes: [+ {+ atFrame: 0,+ easing: "ease-out",+ style: [+ { name: "clip-path", value: "inset(0 100% 0 0)" },+ { name: "transform", value: `rotate(${style.mark.rotateDeg}deg)` },+ ],+ },+ {+ atFrame: markFrames,+ style: [+ { name: "clip-path", value: "inset(0 0 0 0)" },+ { name: "transform", value: `rotate(${style.mark.rotateDeg}deg)` },+ ],+ },+ ],+ },+ },+ ],+ }));+ }+ }+ assert(presents.length > 0, `Notepad list ${program.id} produced no Present.`);+ const track = sealVisualTrack({ visualIr: "hypit.visual-ir@1", id: program.id, presents });+ assertVisualTrackIdentity(track, space);+ return track;+}diff --git a/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/schedule.ts b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/schedule.tsnew file mode 100644index 00000000..72b5fb8f--- /dev/null+++ b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/schedule.ts@@ -0,0 +1,339 @@+import type { FrameSpan } from "@hypit/composition";+import { assertFontArtifactRef } from "@hypit/media";+import type { NarrativeMomentRef, NarrativeSelectionRef } from "@hypit/narrative";+import { assertProgramSpaceIdentity, programSpaceFrameCount } from "@hypit/program-space";+import type { ProgramSpace } from "@hypit/program-space";+import { canonicalize, isDigest } from "@hypit/protocol";+import type { BlobRef } from "@hypit/protocol";+import type { CompleteSemanticMap } from "@hypit/semantic-map";+import { assertSpatialFrame } from "@hypit/spatial";+import type { SpatialFrame } from "@hypit/spatial";+import { locateMomentOccurrences, locateSelectionOccurrences } from "@hypit/temporal";+import { verifyText } from "@hypit/text";+import type { Text } from "@hypit/text";++import type {+ NotepadHeader,+ NotepadMarkPaint,+ NotepadProgram,+ NotepadRowPaint,+ NotepadRowShell,+ NotepadRowSpec,+ NotepadRowSpecSet,+ NotepadSchedule,+ NotepadStyle,+ NotepadTitlePaint,+ NotepadTitleSpec,+} from "./types.js";++function assert(condition: unknown, message: string): asserts condition {+ if (!condition) throw new Error(message);+}++function identity(value: string, label: string): void {+ assert(/^[A-Za-z][A-Za-z0-9_.:#-]{0,191}$/u.test(value), `${label} is invalid.`);+}++function color(value: string, label: string): void {+ assert(value === "transparent" || /^#[0-9a-f]{3,8}$/iu.test(value),+ `${label} must be a hexadecimal color or transparent.`);+}++function finite(value: number, label: string): void {+ assert(Number.isFinite(value), `${label} must be finite.`);+}++function nonNegative(value: number, label: string): void {+ finite(value, label);+ assert(value >= 0, `${label} must be non-negative.`);+}++function positive(value: number, label: string): void {+ finite(value, label);+ assert(value > 0, `${label} must be positive.`);+}++function fraction(value: number, label: string): void {+ assert(Number.isFinite(value) && value >= 0 && value <= 1, `${label} must be a fraction between 0 and 1.`);+}++function integer(value: number, label: string, minimum = 0): void {+ assert(Number.isSafeInteger(value) && value >= minimum, `${label} must be an integer >= ${minimum}.`);+}++function stacking(value: number, label: string): void {+ assert(Number.isSafeInteger(value), `${label} must be an integer.`);+}++function frameNumber(value: number, label: string): void {+ assert(Number.isSafeInteger(value) && value >= 0, `${label} must be a non-negative frame.`);+}++function assertSpan(span: FrameSpan, label: string): void {+ frameNumber(span.startFrame, `${label}.startFrame`);+ frameNumber(span.endFrameExclusive, `${label}.endFrameExclusive`);+ assert(span.endFrameExclusive > span.startFrame, `${label} is empty.`);+}++export function assertNotepadSurface(value: BlobRef, label: string): void {+ assert(isDigest(value.digest) && Number.isSafeInteger(value.size) && value.size >= 0+ && /^image\//u.test(value.mediaType), `${label} must be an image Artifact.`);+}++export function assertNotepadHeader(value: NotepadHeader): void {+ identity(value.id, "NotepadHeader.id");+}++export function sealNotepadHeader(value: NotepadHeader): NotepadHeader {+ assertNotepadHeader(value);+ return canonicalize(value) as unknown as NotepadHeader;+}++export function assertNotepadTitleSpec(value: NotepadTitleSpec): void {+ assert(value.lead.trim().length > 0, "NotepadTitleSpec.lead is empty.");+ assert(typeof value.emphasis === "string", "NotepadTitleSpec.emphasis must be text.");+}++export function sealNotepadTitleSpec(value: NotepadTitleSpec): NotepadTitleSpec {+ assertNotepadTitleSpec(value);+ return canonicalize(value) as unknown as NotepadTitleSpec;+}++export function assertNotepadRowSpec(value: NotepadRowSpec): void {+ identity(value.id, "NotepadRowSpec.id");+ integer(value.rank, `NotepadRowSpec.${value.id}.rank`, 1);+ assert(value.label.trim().length > 0, `NotepadRowSpec.${value.id}.label is empty.`);+ assert(value.mark === "none" || value.mark === "circle", `NotepadRowSpec.${value.id}.mark is invalid.`);+ if (value.stackingOrder !== undefined) stacking(value.stackingOrder, `NotepadRowSpec.${value.id}.stackingOrder`);+}++export function assertNotepadRowShell(value: NotepadRowShell): void {+ identity(value.id, "NotepadRowShell.id");+ integer(value.rank, `NotepadRowShell.${value.id}.rank`, 1);+ assert(value.mark === "none" || value.mark === "circle", `NotepadRowShell.${value.id}.mark is invalid.`);+ if (value.stackingOrder !== undefined) stacking(value.stackingOrder, `NotepadRowShell.${value.id}.stackingOrder`);+}++export function sealNotepadRowShell(value: NotepadRowShell): NotepadRowShell {+ assertNotepadRowShell(value);+ return canonicalize(value) as unknown as NotepadRowShell;+}++export function materializeNotepadRow(shell: NotepadRowShell, content: Text): NotepadRowSpec {+ assertNotepadRowShell(shell);+ verifyText(content);+ assert(content.value.trim().length > 0, `Notepad Row ${shell.id} content is empty.`);+ const result: NotepadRowSpec = { ...shell, label: content.value };+ assertNotepadRowSpec(result);+ return canonicalize(result) as unknown as NotepadRowSpec;+}++export function createNotepadRowSpecSet(header: NotepadHeader): NotepadRowSpecSet {+ assertNotepadHeader(header);+ return { rows: [] };+}++export function assertNotepadRowSpecSet(value: NotepadRowSpecSet): void {+ const ids = new Set<string>();+ const ranks = new Set<number>();+ for (const row of value.rows) {+ assertNotepadRowSpec(row);+ assert(!ids.has(row.id), `NotepadRowSpecSet repeats ${row.id}.`);+ ids.add(row.id);+ assert(!ranks.has(row.rank), `NotepadRowSpecSet repeats rank ${row.rank}.`);+ ranks.add(row.rank);+ }+}++export function appendNotepadRowSpec(set: NotepadRowSpecSet, spec: NotepadRowSpec): NotepadRowSpecSet {+ assertNotepadRowSpecSet(set);+ assertNotepadRowSpec(spec);+ const result: NotepadRowSpecSet = { rows: [...set.rows, structuredClone(spec)] };+ assertNotepadRowSpecSet(result);+ return canonicalize(result) as unknown as NotepadRowSpecSet;+}++function assertTitlePaint(value: NotepadTitlePaint, label: string): void {+ fraction(value.xFraction, `${label}.xFraction`);+ fraction(value.yFraction, `${label}.yFraction`);+ assert(Number.isFinite(value.widthFraction) && value.widthFraction > 0 && value.widthFraction <= 1,+ `${label}.widthFraction must be within (0, 1].`);+ positive(value.sizePx, `${label}.sizePx`);+ positive(value.lineHeight, `${label}.lineHeight`);+ finite(value.trackingPx, `${label}.trackingPx`);+ color(value.color, `${label}.color`);+ nonNegative(value.underlinePx, `${label}.underlinePx`);+ if (value.shadow !== undefined) {+ finite(value.shadow.offsetX, `${label}.shadow.offsetX`);+ finite(value.shadow.offsetY, `${label}.shadow.offsetY`);+ nonNegative(value.shadow.blurPx, `${label}.shadow.blurPx`);+ color(value.shadow.color, `${label}.shadow.color`);+ }+}++function assertRowPaint(value: NotepadRowPaint, label: string): void {+ fraction(value.xFraction, `${label}.xFraction`);+ fraction(value.topFraction, `${label}.topFraction`);+ assert(Number.isFinite(value.widthFraction) && value.widthFraction > 0 && value.widthFraction <= 1,+ `${label}.widthFraction must be within (0, 1].`);+ positive(value.gapPx, `${label}.gapPx`);+ positive(value.sizePx, `${label}.sizePx`);+ positive(value.lineHeight, `${label}.lineHeight`);+ finite(value.trackingPx, `${label}.trackingPx`);+ color(value.color, `${label}.color`);+ positive(value.numberWidthPx, `${label}.numberWidthPx`);+}++function assertMarkPaint(value: NotepadMarkPaint, label: string): void {+ color(value.color, `${label}.color`);+ positive(value.strokeWidthPx, `${label}.strokeWidthPx`);+ nonNegative(value.padXPx, `${label}.padXPx`);+ nonNegative(value.padYPx, `${label}.padYPx`);+ finite(value.rotateDeg, `${label}.rotateDeg`);+ integer(value.frames, `${label}.frames`, 1);+ positive(value.advance, `${label}.advance`);+}++export function assertNotepadStyle(value: NotepadStyle): void {+ for (const [name, fonts] of [+ ["leadFonts", value.leadFonts], ["emphasisFonts", value.emphasisFonts],+ ["rowFonts", value.rowFonts], ["numberFonts", value.numberFonts],+ ] as const) {+ assert(fonts.length > 0, `NotepadStyle.${name} is empty.`);+ for (const [index, font] of fonts.entries()) assertFontArtifactRef(font, `NotepadStyle.${name}.${index}`);+ }+ assert(value.surfaceFit === "contain" || value.surfaceFit === "cover", "NotepadStyle.surfaceFit is invalid.");+ assertTitlePaint(value.title, "NotepadStyle.title");+ assertTitlePaint(value.opening, "NotepadStyle.opening");+ assertRowPaint(value.row, "NotepadStyle.row");+ assertMarkPaint(value.mark, "NotepadStyle.mark");+ integer(value.typing.titleFramesPerCharacter, "NotepadStyle.typing.titleFramesPerCharacter", 1);+ integer(value.typing.rowFramesPerCharacter, "NotepadStyle.typing.rowFramesPerCharacter", 1);+ for (const [name, order] of Object.entries(value.stacking)) {+ stacking(order, `NotepadStyle.stacking.${name}`);+ }+}++export function buildNotepadSchedule(input: {+ readonly header: NotepadHeader;+ readonly rows: NotepadRowSpecSet;+ readonly map: CompleteSemanticMap;+ readonly space: ProgramSpace;+ readonly during: NarrativeSelectionRef;+ readonly triggers: NarrativeMomentRef;+ readonly terminal: NarrativeMomentRef;+ readonly opening?: NarrativeSelectionRef;+}): NotepadSchedule {+ assertNotepadHeader(input.header);+ assertNotepadRowSpecSet(input.rows);+ assert(input.rows.rows.length > 0, "Notepad list requires at least one Row.");+ assertProgramSpaceIdentity(input.space);+ const windows = locateSelectionOccurrences(input.map, input.during, input.space);+ assert(windows.length > 0, "Notepad list Selection requires at least one occurrence.");+ const triggers = locateMomentOccurrences(input.map, input.triggers, input.space);+ assert(triggers.length === input.rows.rows.length,+ `Notepad trigger/Row cardinality differs: ${triggers.length} triggers for ${input.rows.rows.length} Rows.`);+ const terminal = locateMomentOccurrences(input.map, input.terminal, input.space);+ assert(terminal.length === 1,+ `Notepad terminal Moment requires exactly one occurrence; received ${terminal.length}.`);+ const opening = input.opening === undefined+ ? undefined+ : locateSelectionOccurrences(input.map, input.opening, input.space);+ if (opening !== undefined) {+ assert(opening.length === 1,+ `Notepad opening Selection requires exactly one occurrence; received ${opening.length}.`);+ }+ const result: NotepadSchedule = {+ id: input.header.id,+ windows: windows.map((item) => ({ startFrame: item.start.frame, endFrameExclusive: item.end.frame })),+ ...(opening === undefined+ ? {}+ : { opening: { startFrame: opening[0]!.start.frame, endFrameExclusive: opening[0]!.end.frame } }),+ terminalFrame: terminal[0]!.cue.frame,+ entries: input.rows.rows.map((row, index) => ({ rowId: row.id, triggerFrame: triggers[index]!.cue.frame })),+ };+ assertNotepadSchedule(result, input.space);+ return canonicalize(result) as unknown as NotepadSchedule;+}++export function assertNotepadSchedule(value: NotepadSchedule, space?: ProgramSpace): void {+ identity(value.id, "NotepadSchedule.id");+ assert(value.windows.length > 0, "NotepadSchedule.windows is empty.");+ let previousEnd = -1;+ for (const [index, window] of value.windows.entries()) {+ assertSpan(window, `NotepadSchedule.windows.${index}`);+ assert(window.startFrame >= previousEnd, "NotepadSchedule windows overlap or are unordered.");+ previousEnd = window.endFrameExclusive;+ }+ if (value.opening !== undefined) {+ assertSpan(value.opening, "NotepadSchedule.opening");+ assert(value.opening.endFrameExclusive <= value.windows[0]!.startFrame,+ "NotepadSchedule opening overlaps the first paper window.");+ }+ frameNumber(value.terminalFrame, "NotepadSchedule.terminalFrame");+ assert(value.terminalFrame <= value.windows.at(-1)!.endFrameExclusive,+ "NotepadSchedule terminal exceeds its last window.");+ assert(value.entries.length > 0, "NotepadSchedule.entries is empty.");+ const ids = new Set<string>();+ let previousTrigger = -1;+ for (const [index, entry] of value.entries.entries()) {+ identity(entry.rowId, `NotepadSchedule.entries.${index}.rowId`);+ assert(!ids.has(entry.rowId), `NotepadSchedule repeats ${entry.rowId}.`);+ ids.add(entry.rowId);+ frameNumber(entry.triggerFrame, `NotepadSchedule.entries.${index}.triggerFrame`);+ assert(entry.triggerFrame > previousTrigger, "NotepadSchedule trigger frames are not strictly increasing.");+ previousTrigger = entry.triggerFrame;+ assert(value.windows.some((window) => entry.triggerFrame >= window.startFrame+ && entry.triggerFrame < window.endFrameExclusive),+ `NotepadSchedule.entries.${index} triggers outside every window.`);+ }+ if (space !== undefined) {+ assertProgramSpaceIdentity(space);+ assert(value.windows.at(-1)!.endFrameExclusive <= programSpaceFrameCount(space),+ "NotepadSchedule exceeds ProgramSpace.");+ }+}++export function buildNotepadProgram(+ header: NotepadHeader,+ frame: SpatialFrame,+ surface: BlobRef,+ schedule: NotepadSchedule,+ style: NotepadStyle,+ title: NotepadTitleSpec,+ rows: NotepadRowSpecSet,+): NotepadProgram {+ assertNotepadHeader(header);+ assertSpatialFrame(frame);+ assertNotepadSurface(surface, "NotepadProgram.surface");+ assertNotepadSchedule(schedule);+ assertNotepadStyle(style);+ assertNotepadTitleSpec(title);+ assertNotepadRowSpecSet(rows);+ const result: NotepadProgram = {+ id: header.id,+ frame: structuredClone(frame),+ surface: structuredClone(surface),+ schedule: structuredClone(schedule),+ style: structuredClone(style),+ title: structuredClone(title),+ rows: structuredClone(rows.rows),+ };+ assertNotepadProgram(result);+ return canonicalize(result) as unknown as NotepadProgram;+}++export function assertNotepadProgram(value: NotepadProgram): void {+ assertSpatialFrame(value.frame);+ assertNotepadSurface(value.surface, "NotepadProgram.surface");+ assertNotepadSchedule(value.schedule);+ assertNotepadStyle(value.style);+ assertNotepadTitleSpec(value.title);+ assert(value.schedule.entries.length === value.rows.length,+ "NotepadProgram Row count differs from its Schedule.");+ for (const [index, row] of value.rows.entries()) {+ assertNotepadRowSpec(row);+ assert(value.schedule.entries[index]?.rowId === row.id,+ "NotepadProgram Row order differs from its Schedule.");+ }+}diff --git a/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/style.ts b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/style.tsnew file mode 100644index 00000000..f34b7d81--- /dev/null+++ b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/style.ts@@ -0,0 +1,144 @@+import { assertFontArtifactRef, assertFontStackRef } from "@hypit/media";+import type { FontArtifactRef, FontStackRef } from "@hypit/media";+import { canonicalize } from "@hypit/protocol";+import type { SvsRecipe } from "@hypit/svs";++import { assertNotepadStyle } from "./schedule.js";+import type { NotepadStyle } from "./types.js";++const NOTEPAD_KEYS = [+ "surface-fit",+ "title-x", "title-y", "title-width", "title-size", "title-line-height",+ "title-tracking", "title-color", "title-underline",+ "opening-x", "opening-y", "opening-width", "opening-size", "opening-line-height",+ "opening-tracking", "opening-color", "opening-underline",+ "opening-shadow-x", "opening-shadow-y", "opening-shadow-blur", "opening-shadow-color",+ "row-x", "row-top", "row-width", "row-gap", "row-size", "row-line-height",+ "row-tracking", "row-color", "row-number-width",+ "mark-color", "mark-stroke", "mark-pad-x", "mark-pad-y", "mark-rotate", "mark-frames", "mark-advance",+ "title-type-frames", "row-type-frames",+ "surface-stack", "title-stack", "row-stack", "mark-stack",+] as const;++function fail(recipe: SvsRecipe, message: string): never {+ throw new Error(`Notepad Recipe ${recipe.path} ${message}`);+}++function known(recipe: SvsRecipe): void {+ const allowed = new Set<string>(NOTEPAD_KEYS);+ const unknown = Object.keys(recipe.properties).filter((key) => !allowed.has(key));+ if (unknown.length > 0) fail(recipe, `does not accept ${unknown.join(", ")}.`);+}++function number(recipe: SvsRecipe, name: string, fallback: number): number {+ const value = recipe.properties[name];+ if (value === undefined) return fallback;+ if (typeof value !== "number" || !Number.isFinite(value)) fail(recipe, `${name} must be a finite number.`);+ return value;+}++function integer(recipe: SvsRecipe, name: string, fallback: number): number {+ const value = number(recipe, name, fallback);+ if (!Number.isSafeInteger(value)) fail(recipe, `${name} must be an integer.`);+ return value;+}++function text(recipe: SvsRecipe, name: string, fallback: string): string {+ const value = recipe.properties[name];+ if (value === undefined) return fallback;+ if (typeof value !== "string" || value.trim().length === 0) fail(recipe, `${name} must be text.`);+ return value.trim();+}++function oneOf<T extends string>(recipe: SvsRecipe, name: string, values: readonly T[], fallback: T): T {+ const value = text(recipe, name, fallback);+ if (!values.includes(value as T)) fail(recipe, `${name} must be ${values.join(" | ")}.`);+ return value as T;+}++function exactFonts(value: FontStackRef | FontArtifactRef, label: string): FontArtifactRef[] {+ if ("faces" in value) {+ assertFontStackRef(value, label);+ return [...structuredClone(value.faces)];+ }+ assertFontArtifactRef(value, label);+ return [structuredClone(value)];+}++export function decodeNotepadStyle(+ recipe: SvsRecipe,+ fonts: {+ readonly lead: FontStackRef | FontArtifactRef;+ readonly emphasis: FontStackRef | FontArtifactRef;+ readonly row: FontStackRef | FontArtifactRef;+ readonly number?: FontStackRef | FontArtifactRef;+ },+): NotepadStyle {+ known(recipe);+ const openingShadowBlur = number(recipe, "opening-shadow-blur", 10);+ const style: NotepadStyle = {+ leadFonts: exactFonts(fonts.lead, "Notepad title font"),+ emphasisFonts: exactFonts(fonts.emphasis, "Notepad emphasis font"),+ rowFonts: exactFonts(fonts.row, "Notepad row font"),+ numberFonts: exactFonts(fonts.number ?? fonts.row, "Notepad number font"),+ surfaceFit: oneOf(recipe, "surface-fit", ["contain", "cover"] as const, "cover"),+ title: {+ xFraction: number(recipe, "title-x", 0.1),+ yFraction: number(recipe, "title-y", 0.19),+ widthFraction: number(recipe, "title-width", 0.82),+ sizePx: number(recipe, "title-size", 74),+ lineHeight: number(recipe, "title-line-height", 1.16),+ trackingPx: number(recipe, "title-tracking", 0),+ color: text(recipe, "title-color", "#1c1c1c"),+ underlinePx: number(recipe, "title-underline", 0),+ },+ opening: {+ xFraction: number(recipe, "opening-x", 0.08),+ yFraction: number(recipe, "opening-y", 0.55),+ widthFraction: number(recipe, "opening-width", 0.86),+ sizePx: number(recipe, "opening-size", 74),+ lineHeight: number(recipe, "opening-line-height", 1.16),+ trackingPx: number(recipe, "opening-tracking", 0),+ color: text(recipe, "opening-color", "#ffffff"),+ underlinePx: number(recipe, "opening-underline", 0),+ shadow: {+ offsetX: number(recipe, "opening-shadow-x", 0),+ offsetY: number(recipe, "opening-shadow-y", 2),+ blurPx: openingShadowBlur,+ color: text(recipe, "opening-shadow-color", "#00000080"),+ },+ },+ row: {+ xFraction: number(recipe, "row-x", 0.21),+ topFraction: number(recipe, "row-top", 0.36),+ widthFraction: number(recipe, "row-width", 0.72),+ gapPx: number(recipe, "row-gap", 96),+ sizePx: number(recipe, "row-size", 52),+ lineHeight: number(recipe, "row-line-height", 1.2),+ trackingPx: number(recipe, "row-tracking", 0),+ color: text(recipe, "row-color", "#1c1c1c"),+ numberWidthPx: number(recipe, "row-number-width", 54),+ },+ mark: {+ color: text(recipe, "mark-color", "#1c1c1c"),+ strokeWidthPx: number(recipe, "mark-stroke", 4),+ padXPx: number(recipe, "mark-pad-x", 16),+ padYPx: number(recipe, "mark-pad-y", 8),+ rotateDeg: number(recipe, "mark-rotate", -1.5),+ frames: integer(recipe, "mark-frames", 8),+ advance: number(recipe, "mark-advance", 0.5),+ },+ typing: {+ titleFramesPerCharacter: integer(recipe, "title-type-frames", 2),+ rowFramesPerCharacter: integer(recipe, "row-type-frames", 2),+ },+ stacking: {+ surface: integer(recipe, "surface-stack", 40),+ title: integer(recipe, "title-stack", 42),+ row: integer(recipe, "row-stack", 44),+ mark: integer(recipe, "mark-stack", 46),+ },+ };+ assertNotepadStyle(style);+ return canonicalize(style) as unknown as NotepadStyle;+}diff --git a/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/surface.ts b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/surface.tsnew file mode 100644index 00000000..35c18c54--- /dev/null+++ b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/surface.ts@@ -0,0 +1,255 @@+import { readFile } from "node:fs/promises";++import { mediaTypes } from "@hypit/media";+import type { FontArtifactRef, FontStackRef } from "@hypit/media";+import { narrativeTypes } from "@hypit/narrative";+import { programSpaceTypes } from "@hypit/program-space";+import type { CanonicalValue, TypeRef } from "@hypit/protocol";+import { semanticMapTypes } from "@hypit/semantic-map";+import { spatialTypes } from "@hypit/spatial";+import { svsRecipeType } from "@hypit/svs";+import type { SvsRecipe } from "@hypit/svs";+import { textTypes } from "@hypit/text";+import type {+ MarkupAttributeValue,+ StructuredElement,+ StructuredSurfaceHandler,+ SurfaceRecordDraft,+ SurfaceResolvedReference,+} from "@hypit/markup";++import { createNotepadFragment } from "./fragment.js";+import type { NotepadFragmentRow } from "./fragment.js";+import { notepadTypes } from "./manifest.js";+import {+ assertNotepadRowSpec,+ sealNotepadHeader,+ sealNotepadRowShell,+ sealNotepadTitleSpec,+} from "./schedule.js";+import { decodeNotepadStyle } from "./style.js";+import type { NotepadRowMark, NotepadRowSpec } from "./types.js";++function sameType(left: TypeRef, right: TypeRef): boolean {+ return left.module.name === right.module.name+ && left.module.version === right.module.version+ && left.name === right.name;+}++function allowed(element: StructuredElement, names: readonly string[]): void {+ const permit = new Set(names);+ const unknown = Object.keys(element.attributes).filter((name) => !permit.has(name));+ if (unknown.length > 0) throw new Error(`${element.name} has unsupported attributes ${unknown.join(", ")}.`);+}++function empty(element: StructuredElement): void {+ if (element.children.some((child) => child.kind === "element" || child.value.trim().length > 0)) {+ throw new Error(`${element.name} must be empty.`);+ }+}++function text(element: StructuredElement, name: string): string {+ const value = element.attributes[name];+ if (typeof value !== "string" || value.trim().length === 0) throw new Error(`${element.name}.${name} must be text.`);+ return value;+}++function optionalText(element: StructuredElement, name: string): string | undefined {+ const value = element.attributes[name];+ if (value === undefined) return undefined;+ if (typeof value !== "string" || value.trim().length === 0) throw new Error(`${element.name}.${name} must be text.`);+ return value;+}++function integer(element: StructuredElement, name: string): number | undefined {+ const source = optionalText(element, name);+ if (source === undefined) return undefined;+ const value = Number(source.trim());+ if (!Number.isSafeInteger(value)) throw new Error(`${element.name}.${name} must be an integer.`);+ return value;+}++function reference(+ raw: MarkupAttributeValue | undefined,+ label: string,+ expected: readonly TypeRef[],+ resolve: (path: string) => SurfaceResolvedReference | undefined,+): SurfaceResolvedReference {+ if (typeof raw !== "object" || raw.kind !== "reference") throw new Error(`${label} must be a reference.`);+ const value = resolve(raw.path);+ if (value === undefined || !expected.some((type) => sameType(value.type, type))) {+ throw new Error(`${label} has the wrong Type.`);+ }+ return value;+}++function inline<T>(value: SurfaceResolvedReference, label: string): T {+ if (value.record?.value.kind !== "inline") throw new Error(`${label} must resolve during author compilation.`);+ return value.record.value.value as unknown as T;+}++export const decodeNotepadStyleSurface: StructuredSurfaceHandler = ({ element, resolveReference }) => {+ allowed(element, ["id", "recipe", "title-font", "emphasis-font", "row-font", "number-font"]);+ empty(element);+ const id = text(element, "id").trim();+ const recipe = reference(element.attributes.recipe, `${element.name}.recipe`, [svsRecipeType], resolveReference);+ const face = (attribute: string): FontArtifactRef | FontStackRef => inline<FontArtifactRef | FontStackRef>(+ reference(element.attributes[attribute], `${element.name}.${attribute}`,+ [mediaTypes.fontArtifact, mediaTypes.fontStack], resolveReference),+ `${element.name}.${attribute}`,+ );+ const style = decodeNotepadStyle(inline<SvsRecipe>(recipe, `${element.name}.recipe`), {+ lead: face("title-font"),+ emphasis: face("emphasis-font"),+ row: face("row-font"),+ ...(element.attributes["number-font"] === undefined ? {} : { number: face("number-font") }),+ });+ return {+ records: [{+ id, type: notepadTypes.style,+ value: { kind: "inline", value: style as unknown as CanonicalValue },+ range: element.range,+ }],+ components: [], fragments: [],+ };+};++function localName(element: StructuredElement): string {+ return element.name.slice(element.name.lastIndexOf(":") + 1);+}++function rowValue(+ element: StructuredElement,+ suffix: string,+ resolve: (path: string) => SurfaceResolvedReference | undefined,+): { readonly spec: NotepadRowSpec | Omit<NotepadRowSpec, "label">; readonly content?: SurfaceResolvedReference } {+ allowed(element, ["id", "rank", "label", "mark", "stack"]);+ empty(element);+ const id = optionalText(element, "id")?.trim() ?? `row-${suffix}`;+ const rank = integer(element, "rank");+ if (rank === undefined) throw new Error(`${element.name}.rank is required.`);+ const mark = (optionalText(element, "mark")?.trim() ?? "none") as NotepadRowMark;+ if (mark !== "none" && mark !== "circle") throw new Error(`${element.name}.mark must be none or circle.`);+ const stackingOrder = integer(element, "stack");+ const shell = { id, rank, mark, ...(stackingOrder === undefined ? {} : { stackingOrder }) };+ const raw = element.attributes.label;+ if (typeof raw === "string" && raw.trim().length > 0) {+ const spec: NotepadRowSpec = { ...shell, label: raw.trim() };+ assertNotepadRowSpec(spec);+ return { spec };+ }+ return {+ spec: sealNotepadRowShell(shell),+ content: reference(raw, `${element.name}.label`, [textTypes.text], resolve),+ };+}++export const decodeNotepadListSurface: StructuredSurfaceHandler = async ({ element, resolveReference, resolveAsset }) => {+ allowed(element, [+ "id", "map", "space", "frame", "surface", "during", "triggers", "terminal",+ "opening", "title", "title-emphasis", "style",+ ]);+ const id = text(element, "id").trim();+ const records: SurfaceRecordDraft[] = [];+ const headerId = `${id}.header`;+ records.push({+ id: headerId, type: notepadTypes.header,+ value: { kind: "inline", value: sealNotepadHeader({ id }) as unknown as CanonicalValue },+ range: element.range,+ });+ const titleId = `${id}.title`;+ records.push({+ id: titleId, type: notepadTypes.title,+ value: {+ kind: "inline",+ value: sealNotepadTitleSpec({+ lead: text(element, "title"),+ emphasis: optionalText(element, "title-emphasis") ?? "",+ }) as unknown as CanonicalValue,+ },+ range: element.range,+ });++ const map = reference(element.attributes.map, `${element.name}.map`, [semanticMapTypes.complete], resolveReference);+ const space = reference(element.attributes.space, `${element.name}.space`, [programSpaceTypes.programSpace], resolveReference);+ const frame = reference(element.attributes.frame, `${element.name}.frame`, [spatialTypes.frame], resolveReference);+ // The ruled paper is this component's own chrome, so it ships with the package+ // and is only overridden when a Source deliberately supplies another surface.+ let surfaceRef: { readonly kind: "record"; readonly id: string } | SurfaceResolvedReference["ref"];+ if (element.attributes.surface === undefined) {+ const bytes = Uint8Array.from(await readFile(new URL("../assets/paper.png", import.meta.url)));+ const resolved = await resolveAsset({+ from: "package:@hypit/local-notepad-list/paper.png",+ mediaType: "image/png",+ bytes,+ range: element.range,+ });+ const surfaceId = `${id}.surface`;+ records.push({+ id: surfaceId, type: mediaTypes.blobArtifact,+ // A blob is a StoredValue in its own right; wrapping it as an inline value+ // would hand the Producer a description of an Artifact instead of one.+ value: resolved.artifact,+ range: element.range,+ });+ surfaceRef = { kind: "record", id: surfaceId };+ } else {+ surfaceRef = reference(element.attributes.surface, `${element.name}.surface`, [mediaTypes.blobArtifact], resolveReference).ref;+ }+ const during = reference(element.attributes.during, `${element.name}.during`, [narrativeTypes.selection], resolveReference);+ const triggers = reference(element.attributes.triggers, `${element.name}.triggers`, [narrativeTypes.moment], resolveReference);+ const terminal = reference(element.attributes.terminal, `${element.name}.terminal`, [narrativeTypes.moment], resolveReference);+ const style = reference(element.attributes.style, `${element.name}.style`, [notepadTypes.style], resolveReference);+ const hasOpening = element.attributes.opening !== undefined;+ const opening = hasOpening+ ? reference(element.attributes.opening, `${element.name}.opening`, [narrativeTypes.selection], resolveReference)+ : undefined;++ const inputs: Record<string, typeof map.ref> = {+ header: { kind: "record", id: headerId },+ title: { kind: "record", id: titleId },+ map: map.ref, space: space.ref, frame: frame.ref, surface: surfaceRef,+ during: during.ref, triggers: triggers.ref, terminal: terminal.ref, style: style.ref,+ ...(opening === undefined ? {} : { opening: opening.ref }),+ };++ const rows: NotepadFragmentRow[] = [];+ const rowIds = new Set<string>();+ let index = 0;+ for (const child of element.children) {+ if (child.kind === "text") {+ if (child.value.trim().length > 0) throw new Error(`${element.name} accepts Row children only.`);+ continue;+ }+ if (localName(child) !== "Row") throw new Error(`${element.name} accepts Row children only.`);+ index += 1;+ const suffix = String(index).padStart(4, "0");+ const authored = rowValue(child, suffix, resolveReference);+ if (rowIds.has(authored.spec.id)) throw new Error(`${element.name} has duplicate Row id ${authored.spec.id}.`);+ rowIds.add(authored.spec.id);+ const specId = `${id}.row.${suffix}.spec`;+ const specName = `row-${suffix}-spec`;+ records.push({+ id: specId,+ type: authored.content === undefined ? notepadTypes.rowSpec : notepadTypes.rowShell,+ value: { kind: "inline", value: authored.spec as unknown as CanonicalValue },+ range: child.range,+ });+ inputs[specName] = { kind: "record", id: specId };+ const contentName = authored.content === undefined ? undefined : `row-${suffix}-content`;+ if (authored.content !== undefined) inputs[contentName!] = authored.content.ref;+ rows.push({ suffix, specName, ...(contentName === undefined ? {} : { contentName }) });+ }+ if (rows.length === 0) throw new Error(`${element.name} requires at least one Row.`);++ const fragment = createNotepadFragment(rows, hasOpening);+ return {+ records,+ components: [{+ id, fragment: fragment.id, inputs,+ outputs: { schedule: `${id}.schedule`, program: `${id}.program`, visual: `${id}.visual` },+ range: element.range,+ }],+ fragments: [fragment],+ };+};diff --git a/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/types.ts b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/types.tsnew file mode 100644index 00000000..1138e142--- /dev/null+++ b/examples/ranking-typewriter-reverse/packages/local-notepad-list/src/types.ts@@ -0,0 +1,140 @@+import type { FrameSpan } from "@hypit/composition";+import type { FontArtifactRef } from "@hypit/media";+import type { BlobRef } from "@hypit/protocol";+import type { SpatialFrame } from "@hypit/spatial";++/** Identity of one notepad list, sealed by the Surface before anything is scheduled. */+export type NotepadHeader = {+ readonly id: string;+};++export type NotepadRowMark = "none" | "circle";++/** One row of the list: the number it prints, the copy it writes, and its optional annotation. */+export type NotepadRowSpec = {+ readonly id: string;+ readonly rank: number;+ readonly label: string;+ readonly mark: NotepadRowMark;+ readonly stackingOrder?: number;+};++/** Structural half of a Row whose visible copy arrives on a Text graph edge. */+export type NotepadRowShell = Omit<NotepadRowSpec, "label">;++export type NotepadRowSpecSet = {+ readonly rows: readonly NotepadRowSpec[];+};++/** The title, written as one italic lead run followed by one emphasized run. */+export type NotepadTitleSpec = {+ readonly lead: string;+ readonly emphasis: string;+};++export type NotepadTitleShell = {+ readonly lead?: string;+ readonly emphasis?: string;+};++export type NotepadShadow = {+ readonly offsetX: number;+ readonly offsetY: number;+ readonly blurPx: number;+ readonly color: string;+};++/** Where and how the title is set once the paper is on screen. */+export type NotepadTitlePaint = {+ readonly xFraction: number;+ readonly yFraction: number;+ readonly widthFraction: number;+ readonly sizePx: number;+ readonly lineHeight: number;+ readonly trackingPx: number;+ readonly color: string;+ readonly underlinePx: number;+ readonly shadow?: NotepadShadow;+};++export type NotepadRowPaint = {+ readonly xFraction: number;+ readonly topFraction: number;+ readonly widthFraction: number;+ readonly gapPx: number;+ readonly sizePx: number;+ readonly lineHeight: number;+ readonly trackingPx: number;+ readonly color: string;+ readonly numberWidthPx: number;+};++export type NotepadMarkPaint = {+ readonly color: string;+ readonly strokeWidthPx: number;+ readonly padXPx: number;+ readonly padYPx: number;+ readonly rotateDeg: number;+ readonly frames: number;+ /** Mean glyph advance of the row face, as a fraction of the row size. */+ readonly advance: number;+};++export type NotepadTypingStyle = {+ readonly titleFramesPerCharacter: number;+ readonly rowFramesPerCharacter: number;+};++export type NotepadStacking = {+ readonly surface: number;+ readonly title: number;+ readonly row: number;+ readonly mark: number;+};++/**+ * One notepad list Style: the paper treatment, the two title paints, the row+ * paint, the annotation and the typing rhythm, plus the three exact faces the+ * composition sets its copy in.+ */+export type NotepadStyle = {+ readonly leadFonts: readonly FontArtifactRef[];+ readonly emphasisFonts: readonly FontArtifactRef[];+ readonly rowFonts: readonly FontArtifactRef[];+ readonly numberFonts: readonly FontArtifactRef[];+ readonly surfaceFit: "contain" | "cover";+ readonly title: NotepadTitlePaint;+ readonly opening: NotepadTitlePaint;+ readonly row: NotepadRowPaint;+ readonly mark: NotepadMarkPaint;+ readonly typing: NotepadTypingStyle;+ readonly stacking: NotepadStacking;+};++export type NotepadRowEntry = {+ readonly rowId: string;+ readonly triggerFrame: number;+};++/**+ * The resolved timing of one notepad list: every window the paper is on screen+ * for, the optional title-only opening window, the frame each row is written+ * at, and the frame the list settles on.+ */+export type NotepadSchedule = {+ readonly id: string;+ readonly windows: readonly FrameSpan[];+ readonly opening?: FrameSpan;+ readonly terminalFrame: number;+ readonly entries: readonly NotepadRowEntry[];+};++export type NotepadProgram = {+ readonly id: string;+ readonly frame: SpatialFrame;+ readonly surface: BlobRef;+ readonly schedule: NotepadSchedule;+ readonly style: NotepadStyle;+ readonly title: NotepadTitleSpec;+ readonly rows: readonly NotepadRowSpec[];+};diff --git a/examples/ranking-typewriter-reverse/packages/local-notepad-list/test/notepad-recipe.json b/examples/ranking-typewriter-reverse/packages/local-notepad-list/test/notepad-recipe.jsonnew file mode 100644index 00000000..c48db57a--- /dev/null+++ b/examples/ranking-typewriter-reverse/packages/local-notepad-list/test/notepad-recipe.json@@ -0,0 +1,42 @@+{+ "surface-fit": "cover",+ "title-x": 0.11,+ "title-y": 0.195,+ "title-width": 0.82,+ "title-size": 92,+ "title-line-height": 1.14,+ "title-color": "#1f1f1f",+ "title-underline": 0,+ "opening-x": 0.09,+ "opening-y": 0.545,+ "opening-width": 0.86,+ "opening-size": 92,+ "opening-line-height": 1.14,+ "opening-color": "#ffffff",+ "opening-underline": 5,+ "opening-shadow-x": 2,+ "opening-shadow-y": 3,+ "opening-shadow-blur": 12,+ "opening-shadow-color": "#00000099",+ "row-x": 0.315,+ "row-top": 0.366,+ "row-width": 0.66,+ "row-gap": 177,+ "row-size": 74,+ "row-line-height": 1.15,+ "row-color": "#1f1f1f",+ "row-number-width": 92,+ "mark-color": "#1f1f1f",+ "mark-stroke": 5,+ "mark-pad-x": 44,+ "mark-pad-y": 26,+ "mark-rotate": -1.5,+ "mark-frames": 9,+ "title-type-frames": 2,+ "row-type-frames": 3,+ "surface-stack": 50,+ "title-stack": 52,+ "row-stack": 54,+ "mark-stack": 56,+ "mark-advance": 0.5+}diff --git a/examples/ranking-typewriter-reverse/packages/local-notepad-list/test/render-still.ts b/examples/ranking-typewriter-reverse/packages/local-notepad-list/test/render-still.tsnew file mode 100644index 00000000..44ed201e--- /dev/null+++ b/examples/ranking-typewriter-reverse/packages/local-notepad-list/test/render-still.ts@@ -0,0 +1,209 @@+/**+ * Renders the notepad list through the local HyperFrames Runtime so the+ * composition can be looked at and compared against the reference without a+ * paid Provider and without a delivery Build.+ *+ * node --import tsx test/render-still.ts <paper.png> <state> <frame> <out.png>+ *+ * `state` is `opening` or `w1`..`w5`: which window of the list to draw. `frame`+ * counts from the first frame of that window.+ */+import { spawnSync } from "node:child_process";+import { createHash } from "node:crypto";+import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";+import { createRequire } from "node:module";+import os from "node:os";+import path from "node:path";++import { sealComposition } from "@hypit/composition";+import { decodeOpenFontStackSurface } from "@hypit/fonts-open";+import { compileHyperframesDocument, materializeHyperframesHtml } from "@hypit/hyperframes";+import type { FontStackRef } from "@hypit/media";+import { sealProgramSpace } from "@hypit/program-space";+import type { BlobRef, Digest } from "@hypit/protocol";+import { sealSpatialFrame } from "@hypit/spatial";+import type { SvsRecipe } from "@hypit/svs";++import { buildNotepadProgram, decodeNotepadStyle, renderNotepadList } from "../src/index.js";+import type { NotepadRowSpecSet, NotepadSchedule } from "../src/index.js";++const repositoryRoot = path.resolve(import.meta.dirname, "../../../../..");+const hyperframesCli = createRequire(path.join(repositoryRoot, "packages/provider-hyperframes-local/package.json"))+ .resolve("hyperframes/bin/hyperframes.mjs");++const WINDOW_FRAMES = 46;+const LEAD_FRAMES = 4;++const bytes = new Map<Digest, Uint8Array>();++function digestOf(value: Uint8Array): Digest {+ return `sha256:${createHash("sha256").update(value).digest("hex")}` as Digest;+}++async function fontStack(family: string, weight: number, style: "normal" | "italic"): Promise<FontStackRef> {+ const output = await decodeOpenFontStackSurface({+ sourceName: "render-still.svml",+ element: {+ kind: "element",+ name: "fonts:Stack",+ attributes: { id: `${family}-${weight}-${style}`, family, weight: String(weight), style },+ children: [],+ range: { start: 0, end: 1 },+ },+ resolveReference: () => undefined,+ resolveAsset(request: { readonly bytes?: Uint8Array; readonly mediaType: string }) {+ if (request.bytes === undefined) throw new Error("font asset has no bytes");+ const copy = Uint8Array.from(request.bytes);+ const artifactDigest = digestOf(copy);+ bytes.set(artifactDigest, copy);+ return { artifact: { kind: "blob", digest: artifactDigest, size: copy.byteLength, mediaType: request.mediaType } };+ },+ } as never);+ const stored = (output as { records: readonly { value: { kind: string; value: unknown } }[] }).records[0]?.value;+ if (stored?.kind !== "inline") throw new Error("font stack did not resolve");+ return stored.value as FontStackRef;+}++const recipe: SvsRecipe = {+ path: "notepad.list",+ properties: JSON.parse(+ await readFile(path.join(import.meta.dirname, "notepad-recipe.json"), "utf8"),+ ) as Record<string, string | number>,+};++const rows: NotepadRowSpecSet = {+ rows: [+ { id: "row-instagram", rank: 5, label: "Instagram", mark: "none" },+ { id: "row-courses", rank: 4, label: "AI Courses", mark: "none" },+ { id: "row-youtube", rank: 3, label: "YouTube", mark: "none" },+ { id: "row-twitter", rank: 2, label: "Twitter/X", mark: "none" },+ { id: "row-rundown", rank: 1, label: "The Rundown", mark: "circle" },+ ],+};++/**+ * The shortest schedule that still reaches the requested state: every earlier+ * window is collapsed to a few frames so only the window under inspection is+ * rendered at length.+ */+function scheduleFor(state: string): { readonly schedule: NotepadSchedule; readonly windowStart: number; readonly total: number } {+ const rowIds = rows.rows.map((row) => row.id);+ if (state === "opening") {+ const total = WINDOW_FRAMES + rowIds.length * LEAD_FRAMES;+ return {+ schedule: {+ id: "board",+ opening: { startFrame: 0, endFrameExclusive: WINDOW_FRAMES },+ windows: rowIds.map((_, index) => ({+ startFrame: WINDOW_FRAMES + index * LEAD_FRAMES,+ endFrameExclusive: WINDOW_FRAMES + (index + 1) * LEAD_FRAMES,+ })),+ terminalFrame: total,+ entries: rowIds.map((rowId, index) => ({ rowId, triggerFrame: WINDOW_FRAMES + index * LEAD_FRAMES })),+ },+ windowStart: 0,+ total,+ };+ }+ const index = Number(state.replace(/^w/u, "")) - 1;+ if (!Number.isSafeInteger(index) || index < 0 || index >= rowIds.length) {+ throw new Error(`unknown state ${state}`);+ }+ const windowStart = index * LEAD_FRAMES;+ const total = windowStart + WINDOW_FRAMES;+ return {+ schedule: {+ id: "board",+ windows: [+ ...rowIds.slice(0, index).map((_, earlier) => ({+ startFrame: earlier * LEAD_FRAMES,+ endFrameExclusive: (earlier + 1) * LEAD_FRAMES,+ })),+ { startFrame: windowStart, endFrameExclusive: total },+ ],+ terminalFrame: total,+ entries: rowIds.map((rowId, position) => ({+ rowId,+ triggerFrame: position <= index ? position * LEAD_FRAMES : windowStart + WINDOW_FRAMES - (rowIds.length - position),+ })),+ },+ windowStart,+ total,+ };+}++async function main(): Promise<void> {+ const [paperPath, state, frameArgument, outputPath] = process.argv.slice(2);+ if (paperPath === undefined || state === undefined || frameArgument === undefined || outputPath === undefined) {+ throw new Error("usage: render-still.ts <paper.png> <state> <frame> <out.png>");+ }+ const paperBytes = Uint8Array.from(await readFile(paperPath));+ const paperDigest = digestOf(paperBytes);+ bytes.set(paperDigest, paperBytes);+ const paper: BlobRef = {+ kind: "blob", digest: paperDigest, size: paperBytes.byteLength, mediaType: "image/png",+ };++ const style = decodeNotepadStyle(recipe, {+ lead: await fontStack("playfair-display", 600, "italic"),+ emphasis: await fontStack("inter", 700, "normal"),+ row: await fontStack("kalam", 400, "normal"),+ number: await fontStack("kalam", 300, "normal"),+ });++ const planned = scheduleFor(state);+ const frame = sealSpatialFrame({ xPx: 0, yPx: 0, widthPx: 1080, heightPx: 1920 });+ const program = buildNotepadProgram(+ { id: "board" }, frame, paper, planned.schedule, style,+ { lead: "Top 5 Most Popular Ways to ", emphasis: "learn AI" }, rows,+ );+ const space = sealProgramSpace({+ durationSec: planned.total / 30,+ frameRate: { numerator: 30, denominator: 1 },+ });+ const track = renderNotepadList(space, program);++ const temporary = await mkdtemp(path.join(os.tmpdir(), "notepad-still-"));+ try {+ const document = compileHyperframesDocument(sealComposition({+ id: "notepad-still",+ canvas: { width: 1080, height: 1920, clearColor: "#101014" },+ tracks: [track],+ }), space);+ const names = new Map<string, string>();+ let index = 0;+ for (const artifact of document.artifacts) {+ const value = bytes.get(artifact.digest);+ if (value === undefined) throw new Error(`unknown artifact ${artifact.digest}`);+ const name = `asset-${index++}${artifact.mediaType.startsWith("image/") ? ".png" : ".ttf"}`;+ names.set(artifact.digest, `./${name}`);+ await writeFile(path.join(temporary, name), value);+ }+ await writeFile(+ path.join(temporary, "index.html"),+ materializeHyperframesHtml(document, (artifact) => {+ const name = names.get(artifact.digest);+ if (name === undefined) throw new Error(`unmapped artifact ${artifact.digest}`);+ return name;+ }),+ );+ const frames = path.join(temporary, "frames");+ await mkdir(frames);+ const render = spawnSync(process.execPath, [+ hyperframesCli, "render", temporary,+ "--format", "png-sequence", "--output", frames,+ "--fps", "30", "--workers", "4",+ "--no-browser-gpu", "--no-best-effort", "--quiet",+ ], { encoding: "utf8", timeout: 900_000 });+ if (render.status !== 0) throw new Error(`${render.stdout}\n${render.stderr}`);+ const produced = (await readdir(frames)).filter((name) => name.endsWith(".png")).sort();+ const wanted = produced[planned.windowStart + Number(frameArgument)];+ if (wanted === undefined) throw new Error(`frame out of range; ${produced.length} rendered`);+ await copyFile(path.join(frames, wanted), outputPath);+ process.stdout.write(`${outputPath} (${produced.length} frames rendered)\n`);+ } finally {+ await rm(temporary, { recursive: true, force: true });+ }+}++await main();diff --git a/examples/ranking-typewriter-reverse/paper.svrun b/examples/ranking-typewriter-reverse/paper.svrunnew file mode 100644index 00000000..bf3459f1--- /dev/null+++ b/examples/ranking-typewriter-reverse/paper.svrun@@ -0,0 +1,9 @@+<?svml using="@hypit/run-markup@1"?>++<!-- The paper is the one picture the notepad composition sits on, so it gets its+ own narrow Target while the reconstruction loop is still tuning it. -->+<svrun version="1">+ <author source="./main.svml"/>++ <target output="paper.image"/>+</svrun>diff --git a/examples/ranking-typewriter-reverse/studio.svs b/examples/ranking-typewriter-reverse/studio.svsnew file mode 100644index 00000000..bbc537ca--- /dev/null+++ b/examples/ranking-typewriter-reverse/studio.svs@@ -0,0 +1,157 @@+<?svml using="@hypit/svs@1"?>++<sheet version="1" id="studio">+ speech.normal {+ language: en;+ pace: normal;+ min: 4;+ max: 15;+ rounding: round;+ }++ /* The reference is one locked podcast setup cut into jump cuts, so the+ performance stays continuous and the camera never moves. */+ speaker.host {+ composition-stability: strict-locked;+ camera-motion: none;+ edit-rhythm: continuous-take;+ performance: natural-explainer;+ gesture: natural;+ }++ film.vertical { background: #000000; }+ speech.visual { fit: cover; }++ /* The graph-paper list. Positions are fractions of the full 1080x1920 Frame,+ read from the sheet as it appears in the reference: the title in the upper+ fifth, five numbered slots evenly spaced below it, and the item copy set in+ an upright handwriting face beside each number. */+ notepad.list {+ surface-fit: cover;++ title-x: 0.11;+ title-y: 0.185;+ title-width: 0.82;+ title-size: 92;+ title-line-height: 1.14;+ title-color: #1f1f1f;+ title-underline: 0;++ opening-x: 0.09;+ opening-y: 0.545;+ opening-width: 0.86;+ opening-size: 92;+ opening-line-height: 1.14;+ opening-color: #ffffff;+ opening-underline: 5;+ opening-shadow-x: 2;+ opening-shadow-y: 3;+ opening-shadow-blur: 12;+ opening-shadow-color: #00000099;++ row-x: 0.305;+ row-top: 0.372;+ row-width: 0.66;+ row-gap: 177;+ row-size: 62;+ row-line-height: 1.2;+ row-color: #1f1f1f;+ row-number-width: 100;++ mark-color: #1f1f1f;+ mark-stroke: 4;+ mark-pad-x: 26;+ mark-pad-y: 14;+ mark-rotate: -1.5;+ mark-frames: 9;++ title-type-frames: 2;+ row-type-frames: 3;++ surface-stack: 50;+ title-stack: 52;+ row-stack: 54;+ mark-stack: 56;+ }++ /* Inserted pictures. The reference cuts them straight in and straight out, so+ no insert carries an entrance or an exit operator. */+ media.panel {+ stack-order: 40;+ fit: cover;+ clip: frame;+ border-width: 1;+ border-style: solid;+ border-color: #FFFFFF66;+ }++ media.card {+ stack-order: 40;+ fit: cover;+ clip: rounded;+ radius: 14;+ border-width: 2;+ border-style: solid;+ border-color: #FFFFFFCC;+ shadows: 0 10 26 0 #000000A6;+ }++ media.sheet {+ stack-order: 40;+ fit: fit-width;+ fit-constraint: free;+ content-y: 0;+ frame-y: 0;+ clip: rounded;+ radius: 12;+ border-width: 2;+ border-style: solid;+ border-color: #111111;+ frame-paint: #FFFFFF;+ }++ media.logo {+ stack-order: 42;+ fit: contain;+ }++ motion.cut {+ enter: none;+ exit: none;+ }++ /* Captions. The default is the plain white lower-third the reference uses for+ most of the programme; the boxed variant is the same type on the solid black+ capsule it switches to over the newsletter. */+ caption.plain {+ cue-min-words: 1;+ cue-max-words: 3;+ stack-order: 70;+ x: 0.5; y: 0.675; width: 0.86;+ anchor-x: center; anchor-y: center;+ size: 56;+ line-height: 1.1;+ align: center;+ fill: #FFFFFF;+ stroke-color: #000000; stroke-width: 1;+ shadow-color: #000000; shadow-opacity: 0.55;+ shadow-x: 0; shadow-y: 3; shadow-blur: 7;+ background: #00000000; border-color: #00000000; border-width: 0;+ padding: 0 0; radius: 0;+ cue-enter: fade; cue-enter-frames: 1; cue-exit: fade; cue-exit-frames: 1;+ }++ caption.boxed {+ cue-min-words: 1;+ cue-max-words: 3;+ stack-order: 70;+ x: 0.5; y: 0.675; width: 0.86;+ anchor-x: center; anchor-y: center;+ size: 56;+ line-height: 1.1;+ align: center;+ fill: #FFFFFF;+ background: #000000FF; padding: 10 18; radius: 10;+ cue-enter: fade; cue-enter-frames: 1; cue-exit: fade; cue-exit-frames: 1;+ }+</sheet>diff --git a/packages/cli/src/distribution.ts b/packages/cli/src/distribution.tsindex 6c98757d..016f46c9 100644--- a/packages/cli/src/distribution.ts+++ b/packages/cli/src/distribution.ts@@ -10,6 +10,32 @@ export type CliCompilerOptions = {readonly packageContributions: readonly NodePackageContribution[];};+/**+ * One picture asked for directly, with no Source, Build, Record or Runtime Profile.+ *+ * A component package's own chrome — a paper texture, a board, a panel — is authoring+ * input that ships inside the package, so it is never anybody's Output. Credentials are+ * the only thing this needs.+ */+export type CliPictureRequest = {+ /** Installed package specifier naming the exact model family; the Distribution defaults it. */+ readonly model?: string;+ readonly prompt: string;+ readonly aspectRatio?: string;+ readonly resolution?: string;+ /** Host directory whose node_modules contains the selected model package. */+ readonly packageRoot: string;+};++export type CliPicture = {+ /** Installed package specifier that declared the exact model. */+ readonly package: string;+ /** Exact model name, as the model package declares it. */+ readonly model: string;+ readonly mediaType: string;+ readonly bytes: Uint8Array;+};+/*** Explicit application assembly for the generic command engine.*@@ -39,4 +65,12 @@ export type CliDistribution = {}>;/** Open the Runtime Profile with this application's Runtime implementation. */openRuntimeHost(path: string, options: { readonly packageRoot: string }): Promise<NodeRuntimeHost>;+ /**+ * Generate one picture for a package asset.+ *+ * Which exact models exist is a model package's declaration and which Provider fulfils+ * them is this Distribution's choice, so both stay here. The generic engine only reads+ * the prompt, writes the file and reports where it went.+ */+ generatePicture?(request: CliPictureRequest): Promise<CliPicture>;};diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex b6842df8..ecd1f7fc 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -13,5 +13,7 @@ export type {export type {CliCompilerOptions,CliDistribution,+ CliPicture,+ CliPictureRequest,} from "./distribution.js";export type * from "./runtime-port.js";diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.tsindex 7354d306..e40c1325 100644--- a/packages/cli/src/main.ts+++ b/packages/cli/src/main.ts@@ -1,6 +1,6 @@import { randomUUID } from "node:crypto";import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";-import { readFile, stat } from "node:fs/promises";+import { mkdir, readFile, stat, writeFile } from "node:fs/promises";import type { NodeCompiledSourceClosure } from "@hypit/compiler-node";import type { NodeRuntimeHost } from "@hypit/runtime-host-node";@@ -58,6 +58,12 @@ type ParsedArgs = {readonly name: string | undefined;readonly artifact: string | undefined;readonly to: string | undefined;+ /** Prompt text, or the path of a text file holding it. */+ readonly prompt: string | undefined;+ /** Installed package specifier naming the exact model family. */+ readonly model: string | undefined;+ readonly aspectRatio: string | undefined;+ readonly resolution: string | undefined;/** Leave the declared external programs alone; build against what is running. */readonly noPrograms: boolean;readonly json: boolean;@@ -102,7 +108,8 @@ function parseArgs(argv: readonly string[]): ParsedArgs {const scoped = command === "programs" || command === "runtime" || command === "auth";const action = scoped ? tail[0] : undefined;const positional = scoped ? tail.slice(1) : tail;- const noFile = command === "builds" || command === "queue" || command === "paths";+ const noFile = command === "builds" || command === "queue" || command === "paths"+ || command === "image";const hasFile = !noFile && positional[0] !== undefined && !positional[0]!.startsWith("--");const file = hasFile ? positional[0] : undefined;const rest = noFile || !hasFile ? positional : positional.slice(1);@@ -117,6 +124,10 @@ function parseArgs(argv: readonly string[]): ParsedArgs {let name: string | undefined;let artifact: string | undefined;let to: string | undefined;+ let prompt: string | undefined;+ let model: string | undefined;+ let aspectRatio: string | undefined;+ let resolution: string | undefined;let noPrograms = false;let json = false;let color: CliColorMode = "auto";@@ -237,6 +248,34 @@ function parseArgs(argv: readonly string[]): ParsedArgs {index += 1;continue;}+ if (item === "--prompt") {+ const value = rest[index + 1];+ if (value === undefined || value.startsWith("--")) throw new Error("--prompt requires text or a text file path");+ prompt = value;+ index += 1;+ continue;+ }+ if (item === "--model") {+ const value = rest[index + 1];+ if (value === undefined || value.startsWith("--")) throw new Error("--model requires an installed package specifier");+ model = value;+ index += 1;+ continue;+ }+ if (item === "--aspect-ratio") {+ const value = rest[index + 1];+ if (value === undefined || value.startsWith("--")) throw new Error("--aspect-ratio requires a ratio the model accepts");+ aspectRatio = value;+ index += 1;+ continue;+ }+ if (item === "--resolution") {+ const value = rest[index + 1];+ if (value === undefined || value.startsWith("--")) throw new Error("--resolution requires a resolution the model accepts");+ resolution = value;+ index += 1;+ continue;+ }if (item === "--follow") {follow = true;continue;@@ -307,6 +346,10 @@ function parseArgs(argv: readonly string[]): ParsedArgs {name,artifact,to,+ prompt,+ model,+ aspectRatio,+ resolution,noPrograms,json,color,@@ -349,6 +392,10 @@ function assertCommandOptions(args: ParsedArgs): void {case "get":add("--runtime", "--name", "--record", "--output", "--artifact", "--to");break;+ case "image":+ // A package asset needs credentials and nothing else; no Runtime Profile applies.+ add("--prompt", "--to", "--model", "--aspect-ratio", "--resolution");+ break;case "cancel":add("--runtime", "--reason");break;@@ -403,12 +450,28 @@ function usage(): string {" hypit get <build-id> [--runtime profile.json] [--name source-name|--record record-id|--output logical-output-id|--artifact digest] [--to path]"," hypit cancel <build-id> [--runtime profile.json] [--reason text]"," hypit auth status|login|logout <endpoint-instance> [--runtime profile.json] [--slot name] [--from secret-file]",+ " hypit image --prompt <text|text-file> --to <path.png> [--model package] [--aspect-ratio r] [--resolution r]","","output:"," --json --verbose --color auto|always|never --no-color --debug",].join("\n");}+/**+ * A prompt is either the text itself or a file holding it. A long prompt lives in a file+ * beside the asset it describes, so it can be edited and reread; a short one does not+ * deserve a file.+ */+async function readPromptText(value: string): Promise<string> {+ const path = resolve(value);+ const isFile = await stat(path).then((item) => item.isFile(), () => false);+ const prompt = (isFile ? await readFile(path, "utf8") : value).trim();+ if (prompt.length === 0) {+ throw new Error(isFile ? `prompt file ${path} is empty` : "--prompt is empty");+ }+ return prompt;+}+function createCatalogDescriptor(options: {readonly source: string;readonly compilation: NodeCompiledSourceClosure;@@ -832,10 +895,11 @@ export async function runCli(|| args.command === "history"|| args.command === "inspect" || args.command === "get" || args.command === "cancel"|| args.command === "doctor" || args.command === "programs"- || args.command === "runtime" || args.command === "queue" || args.command === "paths";+ || args.command === "runtime" || args.command === "queue" || args.command === "paths"+ || args.command === "image";const operational = known || args.command === "auth";const fileOptional = args.command === "builds" || args.command === "history" || args.command === "queue"- || args.command === "paths"+ || args.command === "paths" || args.command === "image"|| args.command === "programs" || args.command === "runtime" || args.command === "doctor";if (!operational || (!fileOptional && args.file === undefined)) {throw new Error(usage());@@ -865,6 +929,37 @@ export async function runCli(packageRoot,});};+ if (args.command === "image") {+ if (args.prompt === undefined) throw new Error("image requires --prompt with text or a text file path");+ if (args.to === undefined) throw new Error("image requires --to with the file to write");+ if (distribution.generatePicture === undefined) {+ throw new Error("this Distribution cannot generate a picture directly");+ }+ const picture = await distribution.generatePicture({+ prompt: await readPromptText(args.prompt),+ packageRoot: await packageRootForProject(process.cwd()),+ ...(args.model === undefined ? {} : { model: args.model }),+ ...(args.aspectRatio === undefined ? {} : { aspectRatio: args.aspectRatio }),+ ...(args.resolution === undefined ? {} : { resolution: args.resolution }),+ });+ await mkdir(dirname(args.to), { recursive: true });+ await writeFile(args.to, picture.bytes);+ writeOperational({+ format: "hypit.cli-image@1",+ package: picture.package,+ model: picture.model,+ mediaType: picture.mediaType,+ size: picture.bytes.byteLength,+ path: args.to,+ }, "Picture written", "success", [+ ["Model", picture.model],+ ["Package", picture.package],+ ["Type", picture.mediaType],+ ["Bytes", String(picture.bytes.byteLength)],+ ["Path", args.to],+ ], ["This picture is authoring input; no Build, Record or Runtime Profile took part."]);+ return;+ }if (args.command === "paths") {const projectRoot = selectedRuntimeProjectRoot ?? process.cwd();const runtimePaths = args.runtime === undefineddiff --git a/packages/cli/src/output.ts b/packages/cli/src/output.tsindex a270584d..0219e4dd 100644--- a/packages/cli/src/output.ts+++ b/packages/cli/src/output.ts@@ -504,6 +504,23 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi""," hypit cancel <build-id> [--runtime <profile>] [--reason <text>]",],+ image: [+ colors.accent(colors.strong("hypit image")),+ colors.dim("Generate one picture into a file, for an asset that ships inside a package."),+ "",+ " hypit image --prompt <text|text-file> --to <path.png> [--model <package>] [--aspect-ratio <r>] [--resolution <r>]",+ "",+ " --prompt <text|file> the prompt itself, or a text file holding it",+ " --to <path> the file to write; parent directories are created",+ " --model <package> installed package declaring the exact image model",+ " --aspect-ratio <r> a ratio the selected model accepts",+ " --resolution <r> a resolution the selected model accepts",+ "",+ "A package's own chrome is authoring input, so this reads no Source and writes no",+ "Record: no .svml, .svs, .svrun, Build or Runtime Profile takes part. It needs only",+ "the credentials the selected Provider declares.",+ "Unset options take the model's own first declared value.",+ ],auth: [colors.accent(colors.strong("hypit auth")),colors.dim("Manage credentials required by one declared Endpoint instance."),@@ -543,6 +560,7 @@ export function writeCliHelp(io: CliIo, topic?: string): void {row("check <source>", "verify one self-described Author or Run source"),row("plan <run-source>", "freeze and inspect a Build plan"),row("build <run-source>", "submit a durable Build; --follow only observes"),+ row("image --prompt … --to <path>", "generate one picture file for a package asset"),"",colors.strong("Archive"),row("builds", "list known Builds"),diff --git a/packages/gemini-omni/src/activation.ts b/packages/gemini-omni/src/activation.tsindex 6a98576e..9718e397 100644--- a/packages/gemini-omni/src/activation.ts+++ b/packages/gemini-omni/src/activation.ts@@ -1,6 +1,7 @@import { createMarkupSurfaceHostFacet } from "@hypit/markup";import {geminiOmniComponent,+ geminiOmniDefinition,geminiOmniManifest,geminiOmniModuleRef,geminiOmniMarkupSurfaces,@@ -11,7 +12,7 @@ export const hypitPackage = {format: "hypit.node-package@1" as const,modules: [{ manifest: geminiOmniManifest }],components: [geminiOmniComponent],- hostFacets: [createMarkupSurfaceHostFacet({+ hostFacets: [geminiOmniDefinition.hostFacet, createMarkupSurfaceHostFacet({module: geminiOmniModuleRef,declaration: geminiOmniMarkupSurfaces.find((item) => item.name === "video")!,handler: decodeGeminiOmniVideoSurface,diff --git a/packages/gpt-image/src/activation.ts b/packages/gpt-image/src/activation.tsindex d3fce7d7..1c2b9921 100644--- a/packages/gpt-image/src/activation.ts+++ b/packages/gpt-image/src/activation.ts@@ -4,6 +4,7 @@ import {gptImageCleanManifest,gptImageCleanModuleRef,gptImageComponent,+ gptImageDefinition,gptImageManifest,gptImageMarkupSurfaces,gptImageModuleRef,@@ -22,6 +23,7 @@ export const hypitPackage = {}],components: [gptImageComponent],hostFacets: [+ gptImageDefinition.hostFacet,createMarkupSurfaceHostFacet({module: gptImageModuleRef,declaration: gptImageMarkupSurfaces.find((item) => item.name === "image")!,diff --git a/packages/gpt-image/test/surface.test.ts b/packages/gpt-image/test/surface.test.tsindex f60cc1cf..9ce5cea1 100644--- a/packages/gpt-image/test/surface.test.ts+++ b/packages/gpt-image/test/surface.test.ts@@ -2,7 +2,7 @@ import assert from "node:assert/strict";import test from "node:test";import { artifactTypes } from "@hypit/artifact";-import { parseStructuredElement } from "@hypit/markup";+import { markupSurfaceHostFacetAbi, parseStructuredElement } from "@hypit/markup";import type { StructuredSurfaceHandler, SurfaceResolvedReference } from "@hypit/markup";import { textTypes } from "@hypit/text";@@ -93,7 +93,8 @@ test("the physical package carries both independently importable Surface impleme{ name: "@hypit/gpt-image", surfaces: ["Image"] },{ name: "@hypit/gpt-image/clean", surfaces: ["Image"] },]);- assert.equal(gptImageNodePackage.hostFacets.length, 2);+ assert.equal(gptImageNodePackage.hostFacets+ .filter((facet) => facet.abi === markupSurfaceHostFacetAbi).length, 2);});test("GPT Image Surface rejects hidden inline prompts and undeclared child shapes", async () => {diff --git a/packages/grok-imagine/src/activation.ts b/packages/grok-imagine/src/activation.tsindex d6e1460a..dddbd140 100644--- a/packages/grok-imagine/src/activation.ts+++ b/packages/grok-imagine/src/activation.ts@@ -1,6 +1,7 @@import { createMarkupSurfaceHostFacet } from "@hypit/markup";import {grokImagineComponent,+ grokImagineDefinition,grokImagineManifest,grokImagineModuleRef,grokImagineMarkupSurfaces,@@ -12,6 +13,7 @@ export const hypitPackage = {modules: [{ manifest: grokImagineManifest }],components: [grokImagineComponent],hostFacets: [+ grokImagineDefinition.hostFacet,createMarkupSurfaceHostFacet({module: grokImagineModuleRef,declaration: grokImagineMarkupSurfaces.find((item) => item.name === "video")!,diff --git a/packages/mimo-tts/src/activation.ts b/packages/mimo-tts/src/activation.tsindex 7e08e54a..2e4decbd 100644--- a/packages/mimo-tts/src/activation.ts+++ b/packages/mimo-tts/src/activation.ts@@ -5,6 +5,7 @@ import {decodeMimoVoiceCloneSurface,decodeMimoVoiceDesignSurface,mimoTtsComponent,+ mimoTtsDefinition,mimoTtsManifest,mimoTtsModuleRef,mimoTtsMarkupSurfaces,@@ -15,6 +16,7 @@ export const hypitPackage = {modules: [{ manifest: mimoTtsManifest }],components: [mimoTtsComponent],hostFacets: [+ mimoTtsDefinition.hostFacet,createMarkupSurfaceHostFacet({module: mimoTtsModuleRef,declaration: mimoTtsMarkupSurfaces.find((item) => item.name === "preset")!, handler: decodeMimoPresetSurface,diff --git a/packages/mimo-tts/src/index.ts b/packages/mimo-tts/src/index.tsindex 0f9d617e..734081e0 100644--- a/packages/mimo-tts/src/index.ts+++ b/packages/mimo-tts/src/index.ts@@ -196,6 +196,11 @@ export const mimoTtsManifest = {export const mimoTtsComponent = base.component;+export const mimoTtsDefinition = {+ ...base,+ manifest: mimoTtsManifest,+};+export { createMimoTtsAudioFragment } from "./fragment.js";export {decodeMimoPresetSurface,diff --git a/packages/minimax-h3/src/activation.ts b/packages/minimax-h3/src/activation.tsindex 86eec5db..7229333a 100644--- a/packages/minimax-h3/src/activation.ts+++ b/packages/minimax-h3/src/activation.ts@@ -1,8 +1,9 @@import { createMarkupSurfaceHostFacet } from "@hypit/markup";-import { minimaxH3Component, minimaxH3Manifest, minimaxH3ModuleRef,+import { minimaxH3Component, minimaxH3Definition, minimaxH3Manifest, minimaxH3ModuleRef,minimaxH3MarkupSurfaces } from "./index.js";import { decodeMinimaxFrameVideoSurface, decodeMinimaxReferenceVideoSurface, decodeMinimaxTextVideoSurface } from "./surface.js";export const hypitPackage = { format: "hypit.node-package@1" as const, modules: [{ manifest: minimaxH3Manifest }], components: [minimaxH3Component], hostFacets: [+ minimaxH3Definition.hostFacet,createMarkupSurfaceHostFacet({ module: minimaxH3ModuleRef,declaration: minimaxH3MarkupSurfaces.find((item) => item.name === "text-video")!, handler: decodeMinimaxTextVideoSurface }),createMarkupSurfaceHostFacet({ module: minimaxH3ModuleRef,diff --git a/packages/model-kit/package.json b/packages/model-kit/package.jsonindex 386e7981..f1bae183 100644--- a/packages/model-kit/package.json+++ b/packages/model-kit/package.json@@ -12,6 +12,7 @@"@hypit/component-kit": "workspace:*","@hypit/elaborator": "workspace:*","@hypit/generation": "workspace:*",+ "@hypit/host": "workspace:*","@hypit/protocol": "workspace:*","@hypit/text": "workspace:*"}diff --git a/packages/model-kit/src/index.ts b/packages/model-kit/src/index.tsindex 236639c0..12b40cf9 100644--- a/packages/model-kit/src/index.ts+++ b/packages/model-kit/src/index.ts@@ -6,6 +6,7 @@ import type {} from "@hypit/component-kit";import { artifactDependency, artifactTypes } from "@hypit/artifact";import { sealGraphFragment } from "@hypit/elaborator";+import type { HostFacet } from "@hypit/host";import {bindGenerationMedia,bindGenerationText,@@ -101,8 +102,54 @@ export type ExactModelModule<Key extends string = string> = {readonly validators: readonly TypeValidatorFacet[];readonly producers: readonly ProducerFacet[];};+ /** Inert declaration of these exact models for Hosts that address one directly. */+ readonly hostFacet: ExactModelHostFacet;};+export const exactModelHostAbi = "hypit.exact-model-host@1";++/**+ * What one installed package can generate, named exactly, for a Host that drives a+ * single model without a Build. It carries no Provider choice and no Runtime state;+ * the Host still resolves who fulfils the Capability.+ */+export type ExactModelHostFacet = HostFacet & {+ readonly abi: typeof exactModelHostAbi;+ /** The exact model names this package declares, in declaration order. */+ readonly offers: readonly string[];+ readonly implementation: { readonly endpoints: readonly ExactModelEndpoint[] };+};++function createExactModelHostFacet(endpoints: readonly ExactModelEndpoint[]): ExactModelHostFacet {+ assert(endpoints.length > 0, "an exact model Host facet declares no endpoint");+ return {+ abi: exactModelHostAbi,+ offers: endpoints.map((item) => item.ports.model),+ implementation: { endpoints },+ };+}++/** Read every exact model declared by one selected package's Host facets. */+export function exactModelsFromHostFacets(+ facets: readonly HostFacet[],+): readonly ExactModelEndpoint[] {+ const found: ExactModelEndpoint[] = [];+ for (const facet of facets) {+ if (facet.abi !== exactModelHostAbi) continue;+ const implementation = facet.implementation as { readonly endpoints?: unknown } | null;+ const declared = implementation === null ? undefined : implementation.endpoints;+ assert(Array.isArray(declared), `${exactModelHostAbi} facet has an invalid implementation`);+ for (const item of declared as readonly unknown[]) {+ const endpoint = item as ExactModelEndpoint | null;+ assert(endpoint !== null && typeof endpoint === "object"+ && typeof endpoint.key === "string" && typeof endpoint.ports?.model === "string",+ `${exactModelHostAbi} facet declares an invalid exact model`);+ found.push(endpoint);+ }+ }+ return found;+}+export type DefineExactModelModuleOptions<Key extends string = string> = {readonly module: ModuleRef;readonly endpoints: readonly (Omit<ExactModelEndpointSpec, "key"> & { readonly key: Key })[];@@ -282,6 +329,7 @@ export function defineExactModelModule<const Key extends string>(module: { ...options.module },manifest,endpoints: endpoints as Readonly<Record<Key, ExactModelEndpoint>>,+ hostFacet: createExactModelHostFacet(Object.values(endpoints) as readonly ExactModelEndpoint[]),component: {validators: endpointData.flatMap((item) => [{type: item.requestType,diff --git a/packages/nano-banana/src/activation.ts b/packages/nano-banana/src/activation.tsindex 5024b47c..ff2c6ea4 100644--- a/packages/nano-banana/src/activation.ts+++ b/packages/nano-banana/src/activation.ts@@ -1,10 +1,11 @@import { createMarkupSurfaceHostFacet } from "@hypit/markup";import {- nanoBananaComponent, nanoBananaManifest, nanoBananaModuleRef,+ nanoBananaComponent, nanoBananaDefinition, nanoBananaManifest, nanoBananaModuleRef,nanoBananaMarkupSurfaces,} from "./index.js";import { decodeNanoBananaImageSurface, decodeNanoBananaProImageSurface } from "./surface.js";export const hypitPackage = { format: "hypit.node-package@1" as const, modules: [{ manifest: nanoBananaManifest }], components: [nanoBananaComponent], hostFacets: [+ nanoBananaDefinition.hostFacet,createMarkupSurfaceHostFacet({ module: nanoBananaModuleRef,declaration: nanoBananaMarkupSurfaces.find((item) => item.name === "image")!, handler: decodeNanoBananaImageSurface }),createMarkupSurfaceHostFacet({ module: nanoBananaModuleRef,diff --git a/packages/seedance/src/activation.ts b/packages/seedance/src/activation.tsindex cba3e77b..c4bda476 100644--- a/packages/seedance/src/activation.ts+++ b/packages/seedance/src/activation.ts@@ -5,6 +5,7 @@ import {decodeSeedanceReferenceVideoSurface,decodeSeedanceTextVideoSurface,seedanceComponent,+ seedanceDefinition,seedanceManifest,seedanceModuleRef,seedanceMarkupSurfaces,@@ -15,6 +16,7 @@ export const hypitPackage = {modules: [{ manifest: seedanceManifest }],components: [seedanceComponent],hostFacets: [+ seedanceDefinition.hostFacet,createMarkupSurfaceHostFacet({module: seedanceModuleRef,declaration: seedanceMarkupSurfaces.find((item) => item.name === "text-video")!,diff --git a/packages/seedream/src/activation.ts b/packages/seedream/src/activation.tsindex 8440480c..2ccbedad 100644--- a/packages/seedream/src/activation.ts+++ b/packages/seedream/src/activation.ts@@ -1,8 +1,9 @@import { createMarkupSurfaceHostFacet } from "@hypit/markup";-import { seedreamComponent, seedreamManifest, seedreamModuleRef,+import { seedreamComponent, seedreamDefinition, seedreamManifest, seedreamModuleRef,seedreamMarkupSurfaces } from "./index.js";import { decodeSeedreamReferenceImageSurface, decodeSeedreamTextImageSurface } from "./surface.js";export const hypitPackage = { format: "hypit.node-package@1" as const, modules: [{ manifest: seedreamManifest }], components: [seedreamComponent], hostFacets: [+ seedreamDefinition.hostFacet,createMarkupSurfaceHostFacet({ module: seedreamModuleRef,declaration: seedreamMarkupSurfaces.find((item) => item.name === "text-image")!, handler: decodeSeedreamTextImageSurface }),createMarkupSurfaceHostFacet({ module: seedreamModuleRef,diff --git a/packages/video-cli/package.json b/packages/video-cli/package.jsonindex 865afa04..b9a319ea 100644--- a/packages/video-cli/package.json+++ b/packages/video-cli/package.json@@ -10,8 +10,15 @@"dependencies": {"@hypit/cli": "workspace:*","@hypit/compiler-markup-node": "workspace:*",+ "@hypit/credential-store-env": "workspace:*",+ "@hypit/driver-node": "workspace:*",+ "@hypit/endpoint-kit": "workspace:*",+ "@hypit/generation": "workspace:*","@hypit/markup": "workspace:*",+ "@hypit/model-kit": "workspace:*","@hypit/package-loader-node": "workspace:*",+ "@hypit/protocol": "workspace:*",+ "@hypit/provider-kie": "workspace:*","@hypit/runtime-local": "workspace:*","@hypit/workspace-fs-node": "workspace:*"}diff --git a/packages/video-cli/src/distribution.ts b/packages/video-cli/src/distribution.tsindex 1865271b..710c4dfa 100644--- a/packages/video-cli/src/distribution.ts+++ b/packages/video-cli/src/distribution.ts@@ -17,6 +17,10 @@ export const videoCliDistribution: CliDistribution = {const { discoverVideoSourcePackages } = await import("./package-selection.js");return await discoverVideoSourcePackages(path, options);},+ generatePicture: async (request) => {+ const { generateVideoCliPicture } = await import("./picture.js");+ return await generateVideoCliPicture(request);+ },openRuntimeHost: async (path, options) => await openLocalRuntimeHost(path, {packageRoot: options.packageRoot,workerLaunch: {diff --git a/packages/video-cli/src/picture.ts b/packages/video-cli/src/picture.tsnew file mode 100644index 00000000..606ae920--- /dev/null+++ b/packages/video-cli/src/picture.ts@@ -0,0 +1,174 @@+import type { CliPicture, CliPictureRequest } from "@hypit/cli";+import { EnvironmentCredentialStore } from "@hypit/credential-store-env";+import { EndpointRegistry, MemoryArtifactStore } from "@hypit/driver-node";+import type { EndpointRegistration } from "@hypit/driver-node";+import type { EndpointOutcome } from "@hypit/endpoint-kit";+import { sealGenerationPortRequest, verifyGeneratedImageSet } from "@hypit/generation";+import type { GenerationPort, GenerationPortValue } from "@hypit/generation";+import { exactModelsFromHostFacets } from "@hypit/model-kit";+import type { ExactModelEndpoint } from "@hypit/model-kit";+import { loadNodePackageSelection } from "@hypit/package-loader-node";+import type { BlobRef, CanonicalValue, Need } from "@hypit/protocol";+import { createKieProvider } from "@hypit/provider-kie";++/**+ * The exact model family this Distribution reaches for when the author names none.+ * It is a Host default, not a Core preference: `--model` replaces it outright.+ */+const defaultPictureModel = "@hypit/nano-banana";++/** Options this command exposes, mapped onto the port names models declare for them. */+const optionPorts = {+ aspectRatio: "--aspect-ratio",+ resolution: "--resolution",+} as const;++function assert(condition: unknown, message: string): asserts condition {+ if (!condition) throw new Error(message);+}++/**+ * Read the exact image models one installed package declares. The package loader owns+ * which physical bytes answer to the specifier; this only reads the inert declaration.+ */+async function selectImageModel(+ specifier: string,+ packageRoot: string,+): Promise<ExactModelEndpoint> {+ const loaded = await loadNodePackageSelection([specifier], packageRoot);+ const selected = loaded.find((item) => item.specifier === specifier);+ assert(selected !== undefined, `installed package ${specifier} contributed nothing`);+ const declared = exactModelsFromHostFacets(selected.contribution.hostFacets ?? []);+ const images = declared.filter((item) => item.ports.result === "image");+ const [endpoint] = images;+ assert(endpoint !== undefined, declared.length === 0+ ? `${specifier} declares no exact model`+ : `${specifier} declares no exact image model; it offers ${declared.map((item) => item.ports.model).join(", ")}`);+ return endpoint;+}++/**+ * Fill every port the model requires. An option the author gave wins; everything else+ * takes the model's own first declared value, so the cheapest, most neutral rendering+ * is what an unqualified request buys.+ */+function portValue(+ port: GenerationPort,+ request: CliPictureRequest,+ model: string,+): GenerationPortValue | undefined {+ if (port.name === "prompt") return request.prompt;+ const supplied = port.name === "aspectRatio" ? request.aspectRatio+ : port.name === "resolution" ? request.resolution+ : undefined;+ if (supplied !== undefined) return supplied;+ if (port.minItems === 0) return undefined;+ const kind = port.value;+ if (kind.kind === "enum") return kind.values[0]!;+ if (kind.kind === "boolean") return true;+ if (kind.kind === "number") return kind.minimum ?? 1;+ throw new Error(`${model} requires ${port.name}, which hypit image cannot supply`);+}++function sealPictureRequest(endpoint: ExactModelEndpoint, request: CliPictureRequest): CanonicalValue {+ const table = endpoint.ports;+ for (const [name, option] of Object.entries(optionPorts)) {+ if (request[name as keyof typeof optionPorts] === undefined) continue;+ assert(table.ports.some((port) => port.name === name),+ `${table.model} has no ${name}; remove ${option}`);+ }+ const ports = Object.fromEntries(table.ports.flatMap((port) => {+ const value = portValue(port, request, table.model);+ return value === undefined ? [] : [[port.name, [value]] as const];+ }));+ return sealGenerationPortRequest(table, ports) as unknown as CanonicalValue;+}++/**+ * Reveal only the secrets this exact Endpoint registration declares. A missing one names+ * the environment variable to set rather than the Provider's internals.+ */+async function resolveCredentials(+ registration: EndpointRegistration,+): Promise<Readonly<Record<string, { readonly secret: string }>>> {+ const store = new EnvironmentCredentialStore();+ const resolved: Record<string, { readonly secret: string }> = {};+ for (const [slot, ref] of Object.entries(registration.credentials ?? {})) {+ const value = await store.resolve(ref);+ assert(value !== undefined, ref.store === "env"+ ? `credential ${slot} is unavailable; set ${ref.key} in the environment`+ : `credential ${slot} lives in CredentialStore ${ref.store}, which hypit image cannot open`);+ resolved[slot] = value;+ }+ return resolved;+}++function delay(milliseconds: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, milliseconds));+}++/** Read the single picture out of the completed generation, then out of the Store. */+async function readPicture(+ outcome: Extract<EndpointOutcome, { readonly status: "completed" }>,+ artifacts: MemoryArtifactStore,+): Promise<{ readonly bytes: Uint8Array; readonly mediaType: string }> {+ const value = outcome.result.value;+ assert(value.kind === "inline", "the model returned no inline image set");+ verifyGeneratedImageSet(value.value);+ const [image] = (value.value as unknown as { readonly images: readonly BlobRef[] }).images;+ assert(image !== undefined, "the model returned no picture");+ const bytes = await artifacts.get(image.digest);+ assert(bytes !== undefined, `generated Artifact ${image.digest} was not stored`);+ return { bytes, mediaType: image.mediaType };+}++/**+ * Generate one picture with no Core graph.+ *+ * A package asset is authoring input, so nothing here is durable: the Need, the+ * ArtifactStore and the Provider all live for the length of this one call, and no+ * Build, Record or Runtime Profile observes any of it.+ */+export async function generateVideoCliPicture(request: CliPictureRequest): Promise<CliPicture> {+ const specifier = request.model ?? defaultPictureModel;+ const model = await selectImageModel(specifier, request.packageRoot);+ const need: Need = {+ id: "need:hypit-image",+ capability: model.capability,+ returns: model.returns,+ constraints: sealPictureRequest(model, request),+ result: "record:hypit-image",+ };+ const registry = new EndpointRegistry();+ await createKieProvider({}).install(registry);+ const resolution = registry.resolve(need);+ assert(resolution.status === "resolved",+ `no Provider in this Distribution fulfils ${model.ports.model}`);+ const registration = resolution.registration;+ assert(registration.kind === "asynchronous",+ `${model.ports.model} is fulfilled by an Endpoint hypit image cannot drive`);+ const artifacts = new MemoryArtifactStore();+ const common = {+ command: { kind: "fulfill-need" as const, id: "command:hypit-image", need },+ need,+ artifacts,+ credentials: await resolveCredentials(registration),+ operation: "operation:hypit-image",+ };+ let outcome = await registration.endpoint.start(common);+ while (outcome.status === "pending") {+ const waitMs = outcome.wakeAt === undefined ? 0 : outcome.wakeAt - Date.now();+ if (waitMs > 0) await delay(waitMs);+ outcome = await registration.endpoint.poll({ ...common, handle: outcome.handle });+ }+ assert(outcome.status === "completed", outcome.status === "failed"+ ? `${model.ports.model} failed: ${outcome.failure.code} — ${outcome.failure.message}`+ : `${model.ports.model} returned no picture`);+ const picture = await readPicture(outcome, artifacts);+ return {+ package: specifier,+ model: model.ports.model,+ mediaType: picture.mediaType,+ bytes: picture.bytes,+ };+}diff --git a/packages/video-cli/test/cli.test.ts b/packages/video-cli/test/cli.test.tsindex d9d101f3..328bd64f 100644--- a/packages/video-cli/test/cli.test.ts+++ b/packages/video-cli/test/cli.test.ts@@ -1,6 +1,6 @@import assert from "node:assert/strict";import { createHash } from "node:crypto";-import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import test from "node:test";@@ -60,6 +60,78 @@ test("provider-free example plans from installed Source packages", async () => {assert.equal(plan.goals.length, 1);});+/**+ * The command a package author uses for the package's own chrome. Every wire call is+ * answered locally: this test spends nothing and reaches no network.+ */+test("image writes one picture file with no Source, Build, Record or Runtime Profile", async () => {+ const root = await mkdtemp(join(tmpdir(), "hypit-cli-image-"));+ const pictureBytes = Uint8Array.from([137, 80, 78, 71, 13, 10, 26, 10]);+ const calls: string[] = [];+ const requests: Record<string, unknown>[] = [];+ const realFetch = globalThis.fetch;+ const realKey = process.env.KIE_API_KEY;+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ calls.push(url);+ if (url.endsWith("/api/v1/jobs/createTask")) {+ assert.equal((init?.headers as Record<string, string>).authorization, "Bearer test-image-key");+ requests.push(JSON.parse(String(init?.body)) as Record<string, unknown>);+ return Response.json({ code: 200, msg: "success", data: { taskId: "task_image_test" } });+ }+ if (url.includes("/api/v1/jobs/recordInfo")) {+ return Response.json({ code: 200, data: {+ taskId: "task_image_test", model: "nano-banana-2", state: "success",+ resultJson: JSON.stringify({ resultUrls: ["https://tempfile.aiquickdraw.com/paper.png"] }),+ } });+ }+ if (url.endsWith("/api/v1/common/download-url")) {+ return Response.json({ code: 200, data: "https://download.kie.test/paper.png" });+ }+ if (url === "https://download.kie.test/paper.png") {+ return new Response(pictureBytes, { status: 200, headers: { "content-type": "image/png" } });+ }+ throw new Error(`Unexpected URL ${url}`);+ }) as typeof globalThis.fetch;+ process.env.KIE_API_KEY = "test-image-key";+ try {+ const promptFile = join(root, "paper.txt");+ await writeFile(promptFile, "A sheet of warm cream laid paper, even lighting, no text.\n", "utf8");+ const destination = join(root, "assets", "paper.png");+ let output = "";+ await runCli([+ "image", "--prompt", promptFile, "--to", destination, "--aspect-ratio", "1:1",+ ], { write: (text) => { output += text; } });+ const machine = JSON.parse(output) as {+ readonly package: string; readonly model: string;+ readonly mediaType: string; readonly size: number; readonly path: string;+ };+ assert.equal(machine.package, "@hypit/nano-banana");+ assert.equal(machine.model, "nano-banana-2");+ assert.equal(machine.mediaType, "image/png");+ assert.equal(machine.size, pictureBytes.byteLength);+ assert.equal(machine.path, destination);+ assert.deepEqual(Uint8Array.from(await readFile(destination)), pictureBytes);+ // The author gave one option; every other port took the model's own first value.+ assert.deepEqual(requests, [{+ model: "nano-banana-2",+ input: {+ prompt: "A sheet of warm cream laid paper, even lighting, no text.",+ image_input: [],+ aspect_ratio: "1:1",+ resolution: "1K",+ output_format: "png",+ },+ }]);+ assert.equal(calls.filter((item) => item.endsWith("/api/v1/jobs/createTask")).length, 1);+ } finally {+ globalThis.fetch = realFetch;+ if (realKey === undefined) delete process.env.KIE_API_KEY;+ else process.env.KIE_API_KEY = realKey;+ await rm(root, { recursive: true, force: true });+ }+});+test("materializeRecord copies an archived Artifact without rerunning a Build", async () => {const root = await mkdtemp(join(tmpdir(), "hypit-cli-get-"));try {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 095e83fe..3694f0e5 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1613,6 +1613,9 @@ importers:'@hypit/generation':specifier: workspace:*version: link:../generation+ '@hypit/host':+ specifier: workspace:*+ version: link:../host'@hypit/protocol':specifier: workspace:*version: link:../protocol@@ -2900,12 +2903,33 @@ importers:'@hypit/compiler-markup-node':specifier: workspace:*version: link:../compiler-markup-node+ '@hypit/credential-store-env':+ specifier: workspace:*+ version: link:../credential-store-env+ '@hypit/driver-node':+ specifier: workspace:*+ version: link:../driver-node+ '@hypit/endpoint-kit':+ specifier: workspace:*+ version: link:../endpoint-kit+ '@hypit/generation':+ specifier: workspace:*+ version: link:../generation'@hypit/markup':specifier: workspace:*version: link:../markup+ '@hypit/model-kit':+ specifier: workspace:*+ version: link:../model-kit'@hypit/package-loader-node':specifier: workspace:*version: link:../package-loader-node+ '@hypit/protocol':+ specifier: workspace:*+ version: link:../protocol+ '@hypit/provider-kie':+ specifier: workspace:*+ version: link:../provider-kie'@hypit/runtime-local':specifier: workspace:*version: link:../runtime-local