@sundownreel/mcp 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -2
- package/brand.json +29 -0
- package/chunks/chunk-ONI7QK5B.mjs +63 -0
- package/chunks/chunk-YUE6XWVB.mjs +2 -0
- package/dsl/index.mjs +2 -0
- package/dsl/semantic.mjs +5 -0
- package/dsl/types.ts +240 -0
- package/engine/fonts/ArchivoBlack.ttf +0 -0
- package/engine/fonts/Caveat-Bold.ttf +0 -0
- package/engine-geo/data-manifest.json +460 -0
- package/engine-remotion/public/music/README.md +6 -0
- package/engine-remotion/public/music/bed-curious.mp3 +0 -0
- package/engine-remotion/public/music/bed-explainer.mp3 +0 -0
- package/engine-remotion/public/music/bed-reflective.mp3 +0 -0
- package/engine-remotion/public/music/bed-tense.mp3 +0 -0
- package/engine-remotion/public/music/bed-upbeat.mp3 +0 -0
- package/engine-remotion/public/music/music-index.json +52 -0
- package/engine-remotion/public/sfx/README.md +6 -0
- package/engine-remotion/public/sfx/alarm-buzz.mp3 +0 -0
- package/engine-remotion/public/sfx/beep-happy.mp3 +0 -0
- package/engine-remotion/public/sfx/boing-small.mp3 +0 -0
- package/engine-remotion/public/sfx/cash-register.mp3 +0 -0
- package/engine-remotion/public/sfx/chart-draw.mp3 +0 -0
- package/engine-remotion/public/sfx/click-key.mp3 +0 -0
- package/engine-remotion/public/sfx/click-sharp.mp3 +0 -0
- package/engine-remotion/public/sfx/click-switch.mp3 +0 -0
- package/engine-remotion/public/sfx/cloth-swish.mp3 +0 -0
- package/engine-remotion/public/sfx/counter-tick.mp3 +0 -0
- package/engine-remotion/public/sfx/ding.mp3 +0 -0
- package/engine-remotion/public/sfx/error-beep.mp3 +0 -0
- package/engine-remotion/public/sfx/glass-ping.mp3 +0 -0
- package/engine-remotion/public/sfx/glass-tick.mp3 +0 -0
- package/engine-remotion/public/sfx/impact-light.mp3 +0 -0
- package/engine-remotion/public/sfx/impact-punch.mp3 +0 -0
- package/engine-remotion/public/sfx/impact-soft.mp3 +0 -0
- package/engine-remotion/public/sfx/impact-thud.mp3 +0 -0
- package/engine-remotion/public/sfx/impact-tin.mp3 +0 -0
- package/engine-remotion/public/sfx/impact-wood.mp3 +0 -0
- package/engine-remotion/public/sfx/office-ambience-1.mp3 +0 -0
- package/engine-remotion/public/sfx/paper-feed.mp3 +0 -0
- package/engine-remotion/public/sfx/paper-rustle.mp3 +0 -0
- package/engine-remotion/public/sfx/paper-slide.mp3 +0 -0
- package/engine-remotion/public/sfx/paper-tear.mp3 +0 -0
- package/engine-remotion/public/sfx/pencil-scratch.mp3 +0 -0
- package/engine-remotion/public/sfx/pop-drop.mp3 +0 -0
- package/engine-remotion/public/sfx/pop-pluck.mp3 +0 -0
- package/engine-remotion/public/sfx/pop.mp3 +0 -0
- package/engine-remotion/public/sfx/printer-chatter.mp3 +0 -0
- package/engine-remotion/public/sfx/receipt-tick.mp3 +0 -0
- package/engine-remotion/public/sfx/room-tone.mp3 +0 -0
- package/engine-remotion/public/sfx/sfx-index.json +322 -0
- package/engine-remotion/public/sfx/slide-whoosh.mp3 +0 -0
- package/engine-remotion/public/sfx/stamp-thud.mp3 +0 -0
- package/engine-remotion/public/sfx/stinger-8bit.mp3 +0 -0
- package/engine-remotion/public/sfx/stinger-hit.mp3 +0 -0
- package/engine-remotion/public/sfx/stinger-pizzi.mp3 +0 -0
- package/engine-remotion/public/sfx/stinger-sax.mp3 +0 -0
- package/engine-remotion/public/sfx/stinger-steel.mp3 +0 -0
- package/engine-remotion/public/sfx/sweat-drop.mp3 +0 -0
- package/engine-remotion/public/sfx/swipe.mp3 +0 -0
- package/engine-remotion/public/sfx/tick-crisp.mp3 +0 -0
- package/engine-remotion/public/sfx/tick-soft.mp3 +0 -0
- package/engine-remotion/public/sfx/type-click.mp3 +0 -0
- package/engine-remotion/public/sfx/typewriter-soft.mp3 +0 -0
- package/engine-remotion/public/sfx/ui-confirm.mp3 +0 -0
- package/engine-remotion/public/sfx/wheel-roll.mp3 +0 -0
- package/engine-remotion/public/sfx/whoosh-rise.mp3 +0 -0
- package/engine-remotion/public/sfx/whoosh-ui-rise.mp3 +0 -0
- package/engine-remotion/public/sfx/whoosh.mp3 +0 -0
- package/library/music/bed.wav +0 -0
- package/library/sfx/thud.wav +0 -0
- package/library/sfx/tick.wav +0 -0
- package/library/sfx/whoosh.wav +0 -0
- package/package.json +38 -4
- package/pipeline/scripts/master_audio.sh +12 -0
- package/prompts/engine-engineer.md +26 -0
- package/prompts/fact-checker.md +22 -0
- package/prompts/idea-scout.md +21 -0
- package/prompts/library-artist.md +15 -0
- package/prompts/qa.md +20 -0
- package/prompts/researcher.md +22 -0
- package/prompts/shot-dsl-writer.md +63 -0
- package/prompts/style-shot-writer.md +46 -0
- package/registry/styles.mjs +89 -0
- package/render/fonts/Anton-Regular.ttf +0 -0
- package/render/fonts/ArchivoBlack.ttf +0 -0
- package/render/fonts/Caveat-Bold.ttf +0 -0
- package/render/fonts/Caveat.ttf +0 -0
- package/render/fonts/Cinzel-Black.ttf +0 -0
- package/render/fonts/Cinzel-SemiBold.ttf +0 -0
- package/render/fonts/CormorantGaramond-MediumItalic.ttf +0 -0
- package/render/fonts/CourierPrime-Regular.ttf +0 -0
- package/render/fonts/IBMPlexMono-SemiBold.ttf +0 -0
- package/render/fonts/IBMPlexSerif-SemiBold.ttf +0 -0
- package/render/fonts/Kalam-Bold.ttf +0 -0
- package/render/fonts/KaushanScript-Regular.ttf +0 -0
- package/render/fonts/LibreBaskerville-Bold.ttf +0 -0
- package/render/fonts/LibreBaskerville-Italic.ttf +0 -0
- package/render/fonts/PlayfairDisplay-Bold.ttf +0 -0
- package/render/fonts/PlayfairDisplay-Regular.ttf +0 -0
- package/render/fonts/README.md +15 -0
- package/render/fonts/ZillaSlab-Bold-Lining.ttf +0 -0
- package/render/fonts/licenses/Anton-OFL.txt +93 -0
- package/render/fonts/licenses/ArchivoBlack-OFL.txt +93 -0
- package/render/fonts/licenses/Caveat-OFL.txt +93 -0
- package/render/fonts/licenses/Cinzel-OFL.txt +93 -0
- package/render/fonts/licenses/CormorantGaramond-OFL.txt +93 -0
- package/render/fonts/licenses/CourierPrime-OFL.txt +93 -0
- package/render/fonts/licenses/IBMPlexMono-OFL.txt +93 -0
- package/render/fonts/licenses/IBMPlexSerif-OFL.txt +93 -0
- package/render/fonts/licenses/Kalam-OFL.txt +93 -0
- package/render/fonts/licenses/KaushanScript-OFL.txt +95 -0
- package/render/fonts/licenses/LibreBaskerville-OFL.txt +93 -0
- package/render/fonts/licenses/PlayfairDisplay-OFL.txt +93 -0
- package/render/fonts/licenses/ZillaSlab-OFL.txt +93 -0
- package/render/render.mjs +59539 -0
- package/render3d/data/footprints/README.md +27 -0
- package/render3d/data/footprints/test-district.geojson +1 -0
- package/render3d/fonts/ArchivoBlack.ttf +0 -0
- package/render3d/fonts/IBMPlexMono-400.ttf +0 -0
- package/render3d/fonts/IBMPlexMono-600.ttf +0 -0
- package/render3d/fonts/Inter-400.ttf +0 -0
- package/render3d/fonts/Inter-600.ttf +0 -0
- package/render3d/fonts/Inter-800.ttf +0 -0
- package/render3d/fonts/licenses/ArchivoBlack-OFL.txt +93 -0
- package/render3d/fonts/licenses/BlockfolkCaps-OFL.txt +96 -0
- package/render3d/fonts/licenses/IBMPlexMono-OFL.txt +93 -0
- package/render3d/fonts/licenses/Inter-OFL.txt +93 -0
- package/render3d/render.mjs +41191 -0
- package/render3d/runtime.js +4532 -0
- package/rendergeo/fonts/Anton-Regular.ttf +0 -0
- package/rendergeo/fonts/ArchivoBlack.ttf +0 -0
- package/rendergeo/fonts/BarlowCondensed-Bold.ttf +0 -0
- package/rendergeo/fonts/BarlowCondensed-SemiBold.ttf +0 -0
- package/rendergeo/fonts/Caveat-Bold.ttf +0 -0
- package/rendergeo/fonts/Caveat.ttf +0 -0
- package/rendergeo/fonts/Cinzel-Black.ttf +0 -0
- package/rendergeo/fonts/Cinzel-SemiBold.ttf +0 -0
- package/rendergeo/fonts/CormorantGaramond-Medium.ttf +0 -0
- package/rendergeo/fonts/CormorantGaramond-MediumItalic.ttf +0 -0
- package/rendergeo/fonts/CormorantGaramond-SemiBold.ttf +0 -0
- package/rendergeo/fonts/CourierPrime-Regular.ttf +0 -0
- package/rendergeo/fonts/IBMPlexMono-Medium.ttf +0 -0
- package/rendergeo/fonts/IBMPlexMono-Regular.ttf +0 -0
- package/rendergeo/fonts/IBMPlexMono-SemiBold.ttf +0 -0
- package/rendergeo/fonts/IBMPlexSansCondensed-Medium.ttf +0 -0
- package/rendergeo/fonts/IBMPlexSansCondensed-SemiBold.ttf +0 -0
- package/rendergeo/fonts/IBMPlexSerif-SemiBold.ttf +0 -0
- package/rendergeo/fonts/Kalam-Bold.ttf +0 -0
- package/rendergeo/fonts/KaushanScript-Regular.ttf +0 -0
- package/rendergeo/fonts/LibreBaskerville-Bold.ttf +0 -0
- package/rendergeo/fonts/LibreBaskerville-Italic.ttf +0 -0
- package/rendergeo/fonts/OldStandard-Bold.ttf +0 -0
- package/rendergeo/fonts/OldStandard-Italic.ttf +0 -0
- package/rendergeo/fonts/OldStandard-Regular.ttf +0 -0
- package/rendergeo/fonts/PlayfairDisplay-Bold.ttf +0 -0
- package/rendergeo/fonts/PlayfairDisplay-Regular.ttf +0 -0
- package/rendergeo/fonts/ZillaSlab-Bold-Lining.ttf +0 -0
- package/rendergeo/render-geo.mjs +45063 -0
- package/server.js +293 -0
- package/studio-cli/bin/sundownreel-gate.mjs +205 -0
- package/studio-cli/src/gate.mjs +704 -0
- package/styles/README.md +32 -0
- package/styles/broadsheet/STYLE.md +5 -0
- package/styles/broadsheet/style.json +11 -0
- package/styles/cartoon/STYLE.md +37 -0
- package/styles/cartoon/style.json +12 -0
- package/styles/chalkline/STYLE.md +30 -0
- package/styles/chalkline/style.json +11 -0
- package/thumbnails/dist/make.mjs +62995 -0
- package/vendor/gsap.min.js +11 -0
package/server.js
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {createRequire as __sdrCreateRequire} from 'node:module'; const require = __sdrCreateRequire(import.meta.url);
|
|
3
|
+
var oE=Object.create;var _d=Object.defineProperty;var iE=Object.getOwnPropertyDescriptor;var aE=Object.getOwnPropertyNames;var cE=Object.getPrototypeOf,lE=Object.prototype.hasOwnProperty;var v=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var j=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},Sd=(t,e)=>{for(var r in e)_d(t,r,{get:e[r],enumerable:!0})},dE=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of aE(e))!lE.call(t,s)&&s!==r&&_d(t,s,{get:()=>e[s],enumerable:!(n=iE(e,s))||n.enumerable});return t};var Vm=(t,e,r)=>(r=t!=null?oE(cE(t)):{},dE(e||!t||!t.__esModule?_d(r,"default",{value:t,enumerable:!0}):r,t));import{existsSync as xd,mkdirSync as uE,statSync as pE}from"node:fs";import kd from"node:os";import Dt from"node:path";import{fileURLToPath as zm}from"node:url";function $d(){let t=Qi("SUNDOWNREEL_STUDIO");if(t)return{path:t,source:"SUNDOWNREEL_STUDIO"};let e=Qi("REELFORGE_HOME");if(e)return{path:e,source:"REELFORGE_HOME"};let r=Dt.join(kd.homedir(),"SundownReel"),n=Dt.join(kd.homedir(),"ReelForge");return!xd(r)&&hE(n)?{path:n,source:"legacy-default"}:{path:r,source:"default"}}function _t(){return $d().path}function Ed(){let t=Qi("SUNDOWNREEL_HOME");return t?{path:t,source:"SUNDOWNREEL_HOME"}:{path:Dt.join(kd.homedir(),".sundownreel"),source:"default"}}function ea(){return Ed().path}function Rd(){let t=ea();return uE(t,{recursive:!0}),t}function st(){return Rd()}function Po(){return Qi("SUNDOWNREEL_ENV_FILE")??Dt.join(_t(),".env")}function J(){let t=zm(new URL(".",import.meta.url));return xd(Dt.join(t,"server.js"))&&xd(Dt.join(t,"brand.json"))?Dt.resolve(t):null}function Id(t,e){let r=J();return r?Dt.join(r,t):zm(new URL(e,import.meta.url))}function jd(){return process.env.SUNDOWNREEL_LIBRARY?Dt.resolve(process.env.SUNDOWNREEL_LIBRARY):Id("library","../library")}function Hm(){return Id("styles","../styles")}function Se(){return Dt.resolve(Id(".","../.."))}var Qi,hE,Bm,pe=v(()=>{"use strict";Qi=t=>{let e=process.env[t]?.trim();return e?Dt.resolve(e):null},hE=t=>{try{return pE(t).isDirectory()}catch{return!1}};Bm=["Studio home (episodes in videos/, prompts/, .env): SUNDOWNREEL_STUDIO > REELFORGE_HOME (legacy) > ~/SundownReel > ~/ReelForge (legacy, used only when ~/SundownReel is missing and ~/ReelForge exists).","App state home (Chalkline projects, jobs, licence cache, cache/, gate approval keys in keys/): SUNDOWNREEL_HOME > ~/.sundownreel.","User env file: SUNDOWNREEL_ENV_FILE > <studio home>/.env. Read once at server start: allow-listed names only, never overrides a variable already set in the server's environment, refused unless it is a regular file with mode 600 (not a symlink).","Neither home can be set from the .env file. The gate approval public key is <app state home>/keys/gate-ed25519.pub (made by `sundownreel-gate key`)."]});import{lstatSync as fE,readFileSync as mE}from"node:fs";function yE(t){let e=new Map,r=[],n=[];return t.replace(/^/,"").split(/\r?\n/).forEach((o,i)=>{let a=i+1,c=o.trim();if(!c||c.startsWith("#"))return;c.startsWith("export ")&&(c=c.slice(7).trimStart());let l=c.indexOf("=");if(l<=0){r.push(`line ${a}: not KEY=VALUE (ignored)`);return}let d=c.slice(0,l).trim();if(!gE.test(d)){r.push(`line ${a}: invalid variable name (use A-Z, 0-9, _; ignored)`);return}let p=bE(c.slice(l+1).trim());if(p===null){r.push(`line ${a}: ${d} has an unterminated or malformed quoted value (ignored)`);return}e.has(d)&&n.push(d),e.set(d,p)}),{entries:e,warnings:r,duplicates:n}}function bE(t){if(!t)return"";let e=t[0];if(e==="'"||e==='"'){let n="";for(let s=1;s<t.length;s++){let o=t[s];if(o===e){let i=t.slice(s+1).trim();return i===""||i.startsWith("#")?n:null}if(e==='"'&&o==="\\"&&s+1<t.length){let i=t[++s];n+=i==="n"?`
|
|
4
|
+
`:i==="t"?" ":i==="r"?"\r":i==='"'||i==="\\"?i:`\\${i}`;continue}n+=o}return null}let r=t.search(/\s#/);return(r>=0?t.slice(0,r):t).trim()}function Jm(t){let e={path:t,exists:!1,usable:!1,mode:null,problem:null,names:[]},r;try{r=fE(t)}catch{return{state:e,parsed:null}}if(e.exists=!0,e.mode=(r.mode&511).toString(8).padStart(3,"0"),r.isSymbolicLink())return e.problem=`${t} is a symlink; refused. Replace it with a regular file (mode 600).`,{state:e,parsed:null};if(!r.isFile())return e.problem=`${t} is not a regular file; refused.`,{state:e,parsed:null};if(process.platform!=="win32"){let o=typeof process.getuid=="function"?process.getuid():null;if(o!==null&&r.uid!==o)return e.problem=`${t} belongs to another user; refused. Recreate it as your user with mode 600.`,{state:e,parsed:null};if(r.mode&63)return e.problem=`${t} is readable by other users (mode ${e.mode}); refused. Fix: chmod 600 "${t}", then restart the MCP server.`,{state:e,parsed:null}}if(r.size>64*1024)return e.problem=`${t} is larger than 64 KB; refused (it should hold a few KEY=VALUE lines).`,{state:e,parsed:null};let n;try{n=mE(t,"utf8")}catch(o){return e.problem=`${t} could not be read (${o.code??"error"}).`,{state:e,parsed:null}}let s=yE(n);return e.usable=!0,e.names=[...s.entries.keys()],{state:e,parsed:s}}function Wm(t=Po()){let{state:e,parsed:r}=Jm(t);return{...e,warnings:r?.warnings??[]}}function Km(t=Po()){let e={file:null,loaded:[],ignored:[],warnings:[]},{state:r,parsed:n}=Jm(t);if(!r.exists)return e;if(!n)return e.warnings.push(r.problem??`${t} was not loaded.`),e;e.file=t,e.warnings.push(...n.warnings.map(o=>`${t} ${o}`));for(let o of new Set(n.duplicates))e.ignored.push({name:o,reason:"duplicate"}),e.warnings.push(`${t}: ${o} is defined more than once; the last line wins.`);for(let[o,i]of n.entries){if(!Object.prototype.hasOwnProperty.call(Pd,o)){e.ignored.push({name:o,reason:"not-allowed"});continue}let a=process.env[o],c=ta.has(o)&&ta.get(o)===a;if(a!==void 0&&!c){e.ignored.push({name:o,reason:"already-set"});continue}process.env[o]=i,ta.set(o,i),e.loaded.push(o)}let s=e.ignored.filter(o=>o.reason==="not-allowed").map(o=>o.name);return s.length&&e.warnings.push(`${t}: not loaded (not on the allow list): ${s.join(", ")}.`),e}function Zm(){return[...ta].filter(([t,e])=>process.env[t]===e).map(([t])=>t)}var Pd,gE,ta,Od=v(()=>{"use strict";pe();Pd={ELEVENLABS_API_KEY:"vo_align word timing (ElevenLabs forced alignment); sundownreel-init stores it here",SUNDOWNREEL_LICENSE_KEY:"internal fallback licence key (license.ts); customers connect with sundownreel_connect instead. A secret better kept in a mode-600 file than in the Claude config",SUNDOWNREEL_LICENSE_API:"override of the licence/connect API (license.ts); defaults to https://api.sundownreel.com. For dev or staging only: answers must still be signed by a baked-in key, and a device token saved for another API is ignored",SUNDOWNREEL_ELEVENLABS_API_KEY:"Chalkline-profile ElevenLabs voice (voice.ts)",SUNDOWNREEL_ELEVENLABS_VOICE_ID:"Chalkline-profile ElevenLabs voice id (voice.ts)",SUNDOWNREEL_TTS:"Chalkline-profile voice engine preference (voice.ts)",PIPER_BIN:"local Piper TTS binary (voice.ts)",PIPER_MODEL:"local Piper TTS voice model (voice.ts)",SUNDOWNREEL_KOKORO:"enable local Kokoro TTS (voice.ts)",SUNDOWNREEL_KOKORO_VOICE:"Kokoro voice name (voice.ts)",FFMPEG_PATH:"ffmpeg location for doctor and the render backends' env (renderer.ts passes it through)",REELFORGE_RENDER_CLI:"2D render backend CLI override (renderer.ts BACKENDS resvg-2d)",REELFORGE_RENDER_CLI_3D:"3D render backend CLI override (renderer.ts BACKENDS engine-3d)",REELFORGE_RENDER_CLI_GEO:"map render backend CLI override (renderer.ts BACKENDS engine-geo)",RF3D_CHROME:"Chrome/Chromium binary for the 3D backend (engine-3d findChrome; passed through by renderer.ts)",REELFORGE_STYLES_MODULE:"built style registry .mjs (styles/registry.ts)",REELFORGE_PYTHON:"Python with the pipeline deps when the bundled venv is not used (cartoon/pyrun.ts)",REELFORGE_PIPELINE:"pipeline/ folder when it is not next to this install (cartoon/pyrun.ts)",SUNDOWNREEL_THUMBNAILS_CLI:"thumbnails CLI override (default thumbnails/dist/make.mjs; doctor checks it)",SUNDOWNREEL_CHROME:"Chrome for the Chalkline HyperFrames renderer (render.ts)"},gE=/^[A-Z][A-Z0-9_]*$/;ta=new Map});var K,Td,P,sr,Oo=v(()=>{(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},t.getValidEnumValues=s=>{let o=t.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},t.find=(s,o)=>{for(let i of s)if(o(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(K||(K={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Td||(Td={}));P=K.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),sr=t=>{switch(typeof t){case"undefined":return P.undefined;case"string":return P.string;case"number":return Number.isNaN(t)?P.nan:P.number;case"boolean":return P.boolean;case"function":return P.function;case"bigint":return P.bigint;case"symbol":return P.symbol;case"object":return Array.isArray(t)?P.array:t===null?P.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?P.promise:typeof Map<"u"&&t instanceof Map?P.map:typeof Set<"u"&&t instanceof Set?P.set:typeof Date<"u"&&t instanceof Date?P.date:P.object;default:return P.unknown}}});var _,wE,ot,ra=v(()=>{Oo();_=K.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),wE=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),ot=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,K.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];r[o]=r[o]||[],r[o].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};ot.create=t=>new ot(t)});var vE,kr,Nd=v(()=>{ra();Oo();vE=(t,e)=>{let r;switch(t.code){case _.invalid_type:t.received===P.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case _.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,K.jsonStringifyReplacer)}`;break;case _.unrecognized_keys:r=`Unrecognized key(s) in object: ${K.joinValues(t.keys,", ")}`;break;case _.invalid_union:r="Invalid input";break;case _.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${K.joinValues(t.options)}`;break;case _.invalid_enum_value:r=`Invalid enum value. Expected ${K.joinValues(t.options)}, received '${t.received}'`;break;case _.invalid_arguments:r="Invalid function arguments";break;case _.invalid_return_type:r="Invalid function return type";break;case _.invalid_date:r="Invalid date";break;case _.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:K.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case _.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case _.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case _.custom:r="Invalid input";break;case _.invalid_intersection_types:r="Intersection results could not be merged";break;case _.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case _.not_finite:r="Number must be finite";break;default:r=e.defaultError,K.assertNever(t)}return{message:r}},kr=vE});function _E(t){Ym=t}function _s(){return Ym}var Ym,na=v(()=>{Nd();Ym=kr});function R(t,e){let r=_s(),n=To({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===kr?void 0:kr].filter(s=>!!s)});t.common.issues.push(n)}var To,SE,Fe,D,xn,Ue,sa,oa,Hr,Ss,Ad=v(()=>{na();Nd();To=t=>{let{data:e,path:r,errorMaps:n,issueData:s}=t,o=[...r,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:e,defaultError:a}).message;return{...s,path:o,message:a}},SE=[];Fe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let s of r){if(s.status==="aborted")return D;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r){let o=await s.key,i=await s.value;n.push({key:o,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return D;o.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[o.value]=i.value)}return{status:e.value,value:n}}},D=Object.freeze({status:"aborted"}),xn=t=>({status:"dirty",value:t}),Ue=t=>({status:"valid",value:t}),sa=t=>t.status==="aborted",oa=t=>t.status==="dirty",Hr=t=>t.status==="valid",Ss=t=>typeof Promise<"u"&&t instanceof Promise});var Xm=v(()=>{});var O,Qm=v(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(O||(O={}))});function G(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:s}}function ng(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function FE(t){return new RegExp(`^${ng(t)}$`)}function sg(t){let e=`${rg}T${ng(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function qE(t,e){return!!((e==="v4"||!e)&&TE.test(t)||(e==="v6"||!e)&&AE.test(t))}function GE(t,e){if(!IE.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function UE(t,e){return!!((e==="v4"||!e)&&NE.test(t)||(e==="v6"||!e)&&CE.test(t))}function VE(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function xs(t){if(t instanceof it){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=St.create(xs(n))}return new it({...t._def,shape:()=>e})}else return t instanceof Rr?new Rr({...t._def,type:xs(t.element)}):t instanceof St?St.create(xs(t.unwrap())):t instanceof ir?ir.create(xs(t.unwrap())):t instanceof or?or.create(t.items.map(e=>xs(e))):t}function Ld(t,e){let r=sr(t),n=sr(e);if(t===e)return{valid:!0,data:t};if(r===P.object&&n===P.object){let s=K.objectKeys(e),o=K.objectKeys(t).filter(a=>s.indexOf(a)!==-1),i={...t,...e};for(let a of o){let c=Ld(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===P.array&&n===P.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let o=0;o<t.length;o++){let i=t[o],a=e[o],c=Ld(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===P.date&&n===P.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function og(t,e){return new An({values:t,typeName:x.ZodEnum,...G(e)})}function tg(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function ig(t,e={},r){return t?Jr.create().superRefine((n,s)=>{let o=t(n);if(o instanceof Promise)return o.then(i=>{if(!i){let a=tg(e,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=tg(e,n),a=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:a})}}):Jr.create()}var xt,eg,U,xE,kE,$E,EE,RE,IE,jE,PE,OE,Cd,TE,NE,AE,CE,LE,DE,rg,ME,Br,kn,$n,En,Rn,ks,In,jn,Jr,Er,Mt,$s,Rr,it,Pn,$r,ia,On,or,aa,Es,Rs,ca,Tn,Nn,An,Cn,Wr,kt,St,ir,Ln,Dn,Is,zE,No,Ao,Mn,HE,x,BE,ag,cg,JE,WE,lg,KE,ZE,YE,XE,QE,eR,tR,rR,nR,sR,oR,iR,aR,cR,lR,dR,uR,pR,hR,fR,mR,gR,yR,bR,wR,vR,_R,SR,xR,kR,$R,ER,RR,IR,dg=v(()=>{ra();na();Qm();Ad();Oo();xt=class{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},eg=(t,e)=>{if(Hr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new ot(t.common.issues);return this._error=r,this._error}}};U=class{get description(){return this._def.description}_getType(e){return sr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:sr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Fe,ctx:{common:e.parent.common,data:e.data,parsedType:sr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Ss(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:sr(e)},s=this._parseSync({data:e,path:n.path,parent:n});return eg(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:sr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Hr(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Hr(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:sr(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(Ss(s)?s:Promise.resolve(s));return eg(n,o)}refine(e,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,o)=>{let i=e(s),a=()=>o.addIssue({code:_.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new kt({schema:this,typeName:x.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return St.create(this,this._def)}nullable(){return ir.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Rr.create(this)}promise(){return Wr.create(this,this._def)}or(e){return Pn.create([this,e],this._def)}and(e){return On.create(this,e,this._def)}transform(e){return new kt({...G(this._def),schema:this,typeName:x.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Ln({...G(this._def),innerType:this,defaultValue:r,typeName:x.ZodDefault})}brand(){return new No({typeName:x.ZodBranded,type:this,...G(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Dn({...G(this._def),innerType:this,catchValue:r,typeName:x.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Ao.create(this,e)}readonly(){return Mn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},xE=/^c[^\s-]{8,}$/i,kE=/^[0-9a-z]+$/,$E=/^[0-9A-HJKMNP-TV-Z]{26}$/i,EE=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,RE=/^[a-z0-9_-]{21}$/i,IE=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,jE=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,PE=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,OE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",TE=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,NE=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,AE=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,CE=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,LE=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,DE=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,rg="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ME=new RegExp(`^${rg}$`);Br=class t extends U{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==P.string){let o=this._getOrReturnCtx(e);return R(o,{code:_.invalid_type,expected:P.string,received:o.parsedType}),D}let n=new Fe,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),R(s,{code:_.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),R(s,{code:_.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let i=e.data.length>o.value,a=e.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(e,s),i?R(s,{code:_.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&R(s,{code:_.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")PE.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"email",code:_.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Cd||(Cd=new RegExp(OE,"u")),Cd.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"emoji",code:_.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")EE.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"uuid",code:_.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")RE.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"nanoid",code:_.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")xE.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"cuid",code:_.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")kE.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"cuid2",code:_.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")$E.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"ulid",code:_.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),R(s,{validation:"url",code:_.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"regex",code:_.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),R(s,{code:_.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),R(s,{code:_.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),R(s,{code:_.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?sg(o).test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{code:_.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?ME.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{code:_.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?FE(o).test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{code:_.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?jE.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"duration",code:_.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?qE(e.data,o.version)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"ip",code:_.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?GE(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"jwt",code:_.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?UE(e.data,o.version)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"cidr",code:_.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?LE.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"base64",code:_.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?DE.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"base64url",code:_.invalid_string,message:o.message}),n.dirty()):K.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:_.invalid_string,...O.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...O.errToObj(e)})}url(e){return this._addCheck({kind:"url",...O.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...O.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...O.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...O.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...O.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...O.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...O.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...O.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...O.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...O.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...O.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...O.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...O.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...O.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...O.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...O.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...O.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...O.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...O.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...O.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...O.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...O.errToObj(r)})}nonempty(e){return this.min(1,O.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Br.create=t=>new Br({checks:[],typeName:x.ZodString,coerce:t?.coerce??!1,...G(t)});kn=class t extends U{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==P.number){let o=this._getOrReturnCtx(e);return R(o,{code:_.invalid_type,expected:P.number,received:o.parsedType}),D}let n,s=new Fe;for(let o of this._def.checks)o.kind==="int"?K.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{code:_.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),R(n,{code:_.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),R(n,{code:_.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?VE(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),R(n,{code:_.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{code:_.not_finite,message:o.message}),s.dirty()):K.assertNever(o);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,O.toString(r))}gt(e,r){return this.setLimit("min",e,!1,O.toString(r))}lte(e,r){return this.setLimit("max",e,!0,O.toString(r))}lt(e,r){return this.setLimit("max",e,!1,O.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:O.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:O.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:O.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:O.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&K.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};kn.create=t=>new kn({checks:[],typeName:x.ZodNumber,coerce:t?.coerce||!1,...G(t)});$n=class t extends U{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==P.bigint)return this._getInvalidInput(e);let n,s=new Fe;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),R(n,{code:_.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),R(n,{code:_.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),R(n,{code:_.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):K.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return R(r,{code:_.invalid_type,expected:P.bigint,received:r.parsedType}),D}gte(e,r){return this.setLimit("min",e,!0,O.toString(r))}gt(e,r){return this.setLimit("min",e,!1,O.toString(r))}lte(e,r){return this.setLimit("max",e,!0,O.toString(r))}lt(e,r){return this.setLimit("max",e,!1,O.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:O.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:O.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};$n.create=t=>new $n({checks:[],typeName:x.ZodBigInt,coerce:t?.coerce??!1,...G(t)});En=class extends U{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==P.boolean){let n=this._getOrReturnCtx(e);return R(n,{code:_.invalid_type,expected:P.boolean,received:n.parsedType}),D}return Ue(e.data)}};En.create=t=>new En({typeName:x.ZodBoolean,coerce:t?.coerce||!1,...G(t)});Rn=class t extends U{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==P.date){let o=this._getOrReturnCtx(e);return R(o,{code:_.invalid_type,expected:P.date,received:o.parsedType}),D}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return R(o,{code:_.invalid_date}),D}let n=new Fe,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),R(s,{code:_.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),R(s,{code:_.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):K.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:O.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:O.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Rn.create=t=>new Rn({checks:[],coerce:t?.coerce||!1,typeName:x.ZodDate,...G(t)});ks=class extends U{_parse(e){if(this._getType(e)!==P.symbol){let n=this._getOrReturnCtx(e);return R(n,{code:_.invalid_type,expected:P.symbol,received:n.parsedType}),D}return Ue(e.data)}};ks.create=t=>new ks({typeName:x.ZodSymbol,...G(t)});In=class extends U{_parse(e){if(this._getType(e)!==P.undefined){let n=this._getOrReturnCtx(e);return R(n,{code:_.invalid_type,expected:P.undefined,received:n.parsedType}),D}return Ue(e.data)}};In.create=t=>new In({typeName:x.ZodUndefined,...G(t)});jn=class extends U{_parse(e){if(this._getType(e)!==P.null){let n=this._getOrReturnCtx(e);return R(n,{code:_.invalid_type,expected:P.null,received:n.parsedType}),D}return Ue(e.data)}};jn.create=t=>new jn({typeName:x.ZodNull,...G(t)});Jr=class extends U{constructor(){super(...arguments),this._any=!0}_parse(e){return Ue(e.data)}};Jr.create=t=>new Jr({typeName:x.ZodAny,...G(t)});Er=class extends U{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ue(e.data)}};Er.create=t=>new Er({typeName:x.ZodUnknown,...G(t)});Mt=class extends U{_parse(e){let r=this._getOrReturnCtx(e);return R(r,{code:_.invalid_type,expected:P.never,received:r.parsedType}),D}};Mt.create=t=>new Mt({typeName:x.ZodNever,...G(t)});$s=class extends U{_parse(e){if(this._getType(e)!==P.undefined){let n=this._getOrReturnCtx(e);return R(n,{code:_.invalid_type,expected:P.void,received:n.parsedType}),D}return Ue(e.data)}};$s.create=t=>new $s({typeName:x.ZodVoid,...G(t)});Rr=class t extends U{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==P.array)return R(r,{code:_.invalid_type,expected:P.array,received:r.parsedType}),D;if(s.exactLength!==null){let i=r.data.length>s.exactLength.value,a=r.data.length<s.exactLength.value;(i||a)&&(R(r,{code:i?_.too_big:_.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(R(r,{code:_.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(R(r,{code:_.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>s.type._parseAsync(new xt(r,i,r.path,a)))).then(i=>Fe.mergeArray(n,i));let o=[...r.data].map((i,a)=>s.type._parseSync(new xt(r,i,r.path,a)));return Fe.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:O.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:O.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:O.toString(r)}})}nonempty(e){return this.min(1,e)}};Rr.create=(t,e)=>new Rr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:x.ZodArray,...G(e)});it=class t extends U{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=K.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==P.object){let l=this._getOrReturnCtx(e);return R(l,{code:_.invalid_type,expected:P.object,received:l.parsedType}),D}let{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Mt&&this._def.unknownKeys==="strip"))for(let l in s.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let d=o[l],p=s.data[l];c.push({key:{status:"valid",value:l},value:d._parse(new xt(s,p,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof Mt){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")a.length>0&&(R(s,{code:_.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let d of a){let p=s.data[d];c.push({key:{status:"valid",value:d},value:l._parse(new xt(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of c){let p=await d.key,f=await d.value;l.push({key:p,value:f,alwaysSet:d.alwaysSet})}return l}).then(l=>Fe.mergeObjectSync(n,l)):Fe.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return O.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:O.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:x.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of K.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of K.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return xs(this)}partial(e){let r={};for(let n of K.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of K.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof St;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return og(K.objectKeys(this.shape))}};it.create=(t,e)=>new it({shape:()=>t,unknownKeys:"strip",catchall:Mt.create(),typeName:x.ZodObject,...G(e)});it.strictCreate=(t,e)=>new it({shape:()=>t,unknownKeys:"strict",catchall:Mt.create(),typeName:x.ZodObject,...G(e)});it.lazycreate=(t,e)=>new it({shape:t,unknownKeys:"strip",catchall:Mt.create(),typeName:x.ZodObject,...G(e)});Pn=class extends U{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new ot(a.ctx.common.issues));return R(r,{code:_.invalid_union,unionErrors:i}),D}if(r.common.async)return Promise.all(n.map(async o=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new ot(c));return R(r,{code:_.invalid_union,unionErrors:a}),D}}get options(){return this._def.options}};Pn.create=(t,e)=>new Pn({options:t,typeName:x.ZodUnion,...G(e)});$r=t=>t instanceof Tn?$r(t.schema):t instanceof kt?$r(t.innerType()):t instanceof Nn?[t.value]:t instanceof An?t.options:t instanceof Cn?K.objectValues(t.enum):t instanceof Ln?$r(t._def.innerType):t instanceof In?[void 0]:t instanceof jn?[null]:t instanceof St?[void 0,...$r(t.unwrap())]:t instanceof ir?[null,...$r(t.unwrap())]:t instanceof No||t instanceof Mn?$r(t.unwrap()):t instanceof Dn?$r(t._def.innerType):[],ia=class t extends U{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==P.object)return R(r,{code:_.invalid_type,expected:P.object,received:r.parsedType}),D;let n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(R(r,{code:_.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),D)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let s=new Map;for(let o of r){let i=$r(o.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,o)}}return new t({typeName:x.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...G(n)})}};On=class extends U{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(o,i)=>{if(sa(o)||sa(i))return D;let a=Ld(o.value,i.value);return a.valid?((oa(o)||oa(i))&&r.dirty(),{status:r.value,value:a.data}):(R(n,{code:_.invalid_intersection_types}),D)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};On.create=(t,e,r)=>new On({left:t,right:e,typeName:x.ZodIntersection,...G(r)});or=class t extends U{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.array)return R(n,{code:_.invalid_type,expected:P.array,received:n.parsedType}),D;if(n.data.length<this._def.items.length)return R(n,{code:_.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),D;!this._def.rest&&n.data.length>this._def.items.length&&(R(n,{code:_.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new xt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(o).then(i=>Fe.mergeArray(r,i)):Fe.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};or.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new or({items:t,typeName:x.ZodTuple,rest:null,...G(e)})};aa=class t extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.object)return R(n,{code:_.invalid_type,expected:P.object,received:n.parsedType}),D;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in n.data)s.push({key:o._parse(new xt(n,a,n.path,a)),value:i._parse(new xt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Fe.mergeObjectAsync(r,s):Fe.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof U?new t({keyType:e,valueType:r,typeName:x.ZodRecord,...G(n)}):new t({keyType:Br.create(),valueType:e,typeName:x.ZodRecord,...G(r)})}},Es=class extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.map)return R(n,{code:_.invalid_type,expected:P.map,received:n.parsedType}),D;let s=this._def.keyType,o=this._def.valueType,i=[...n.data.entries()].map(([a,c],l)=>({key:s._parse(new xt(n,a,n.path,[l,"key"])),value:o._parse(new xt(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,d=await c.value;if(l.status==="aborted"||d.status==="aborted")return D;(l.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(l.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,d=c.value;if(l.status==="aborted"||d.status==="aborted")return D;(l.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(l.value,d.value)}return{status:r.value,value:a}}}};Es.create=(t,e,r)=>new Es({valueType:e,keyType:t,typeName:x.ZodMap,...G(r)});Rs=class t extends U{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.set)return R(n,{code:_.invalid_type,expected:P.set,received:n.parsedType}),D;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(R(n,{code:_.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(R(n,{code:_.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let o=this._def.valueType;function i(c){let l=new Set;for(let d of c){if(d.status==="aborted")return D;d.status==="dirty"&&r.dirty(),l.add(d.value)}return{status:r.value,value:l}}let a=[...n.data.values()].map((c,l)=>o._parse(new xt(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:O.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:O.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Rs.create=(t,e)=>new Rs({valueType:t,minSize:null,maxSize:null,typeName:x.ZodSet,...G(e)});ca=class t extends U{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==P.function)return R(r,{code:_.invalid_type,expected:P.function,received:r.parsedType}),D;function n(a,c){return To({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,_s(),kr].filter(l=>!!l),issueData:{code:_.invalid_arguments,argumentsError:c}})}function s(a,c){return To({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,_s(),kr].filter(l=>!!l),issueData:{code:_.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Wr){let a=this;return Ue(async function(...c){let l=new ot([]),d=await a._def.args.parseAsync(c,o).catch(h=>{throw l.addIssue(n(c,h)),l}),p=await Reflect.apply(i,this,d);return await a._def.returns._def.type.parseAsync(p,o).catch(h=>{throw l.addIssue(s(p,h)),l})})}else{let a=this;return Ue(function(...c){let l=a._def.args.safeParse(c,o);if(!l.success)throw new ot([n(c,l.error)]);let d=Reflect.apply(i,this,l.data),p=a._def.returns.safeParse(d,o);if(!p.success)throw new ot([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:or.create(e).rest(Er.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||or.create([]).rest(Er.create()),returns:r||Er.create(),typeName:x.ZodFunction,...G(n)})}},Tn=class extends U{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Tn.create=(t,e)=>new Tn({getter:t,typeName:x.ZodLazy,...G(e)});Nn=class extends U{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return R(r,{received:r.data,code:_.invalid_literal,expected:this._def.value}),D}return{status:"valid",value:e.data}}get value(){return this._def.value}};Nn.create=(t,e)=>new Nn({value:t,typeName:x.ZodLiteral,...G(e)});An=class t extends U{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return R(r,{expected:K.joinValues(n),received:r.parsedType,code:_.invalid_type}),D}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return R(r,{received:r.data,code:_.invalid_enum_value,options:n}),D}return Ue(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};An.create=og;Cn=class extends U{_parse(e){let r=K.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==P.string&&n.parsedType!==P.number){let s=K.objectValues(r);return R(n,{expected:K.joinValues(s),received:n.parsedType,code:_.invalid_type}),D}if(this._cache||(this._cache=new Set(K.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=K.objectValues(r);return R(n,{received:n.data,code:_.invalid_enum_value,options:s}),D}return Ue(e.data)}get enum(){return this._def.values}};Cn.create=(t,e)=>new Cn({values:t,typeName:x.ZodNativeEnum,...G(e)});Wr=class extends U{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==P.promise&&r.common.async===!1)return R(r,{code:_.invalid_type,expected:P.promise,received:r.parsedType}),D;let n=r.parsedType===P.promise?r.data:Promise.resolve(r.data);return Ue(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Wr.create=(t,e)=>new Wr({type:t,typeName:x.ZodPromise,...G(e)});kt=class extends U{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===x.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:i=>{R(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(n.data,o);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return D;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?D:c.status==="dirty"?xn(c.value):r.value==="dirty"?xn(c.value):c});{if(r.value==="aborted")return D;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?D:a.status==="dirty"?xn(a.value):r.value==="dirty"?xn(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?D:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?D:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Hr(i))return D;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Hr(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:r.value,value:a})):D);K.assertNever(s)}};kt.create=(t,e,r)=>new kt({schema:t,typeName:x.ZodEffects,effect:e,...G(r)});kt.createWithPreprocess=(t,e,r)=>new kt({schema:e,effect:{type:"preprocess",transform:t},typeName:x.ZodEffects,...G(r)});St=class extends U{_parse(e){return this._getType(e)===P.undefined?Ue(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};St.create=(t,e)=>new St({innerType:t,typeName:x.ZodOptional,...G(e)});ir=class extends U{_parse(e){return this._getType(e)===P.null?Ue(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ir.create=(t,e)=>new ir({innerType:t,typeName:x.ZodNullable,...G(e)});Ln=class extends U{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===P.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Ln.create=(t,e)=>new Ln({innerType:t,typeName:x.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...G(e)});Dn=class extends U{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ss(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ot(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ot(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Dn.create=(t,e)=>new Dn({innerType:t,typeName:x.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...G(e)});Is=class extends U{_parse(e){if(this._getType(e)!==P.nan){let n=this._getOrReturnCtx(e);return R(n,{code:_.invalid_type,expected:P.nan,received:n.parsedType}),D}return{status:"valid",value:e.data}}};Is.create=t=>new Is({typeName:x.ZodNaN,...G(t)});zE=Symbol("zod_brand"),No=class extends U{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Ao=class t extends U{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?D:o.status==="dirty"?(r.dirty(),xn(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?D:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:x.ZodPipeline})}},Mn=class extends U{_parse(e){let r=this._def.innerType._parse(e),n=s=>(Hr(s)&&(s.value=Object.freeze(s.value)),s);return Ss(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};Mn.create=(t,e)=>new Mn({innerType:t,typeName:x.ZodReadonly,...G(e)});HE={object:it.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(x||(x={}));BE=(t,e={message:`Input not instance of ${t.name}`})=>ig(r=>r instanceof t,e),ag=Br.create,cg=kn.create,JE=Is.create,WE=$n.create,lg=En.create,KE=Rn.create,ZE=ks.create,YE=In.create,XE=jn.create,QE=Jr.create,eR=Er.create,tR=Mt.create,rR=$s.create,nR=Rr.create,sR=it.create,oR=it.strictCreate,iR=Pn.create,aR=ia.create,cR=On.create,lR=or.create,dR=aa.create,uR=Es.create,pR=Rs.create,hR=ca.create,fR=Tn.create,mR=Nn.create,gR=An.create,yR=Cn.create,bR=Wr.create,wR=kt.create,vR=St.create,_R=ir.create,SR=kt.createWithPreprocess,xR=Ao.create,kR=()=>ag().optional(),$R=()=>cg().optional(),ER=()=>lg().optional(),RR={string:(t=>Br.create({...t,coerce:!0})),number:(t=>kn.create({...t,coerce:!0})),boolean:(t=>En.create({...t,coerce:!0})),bigint:(t=>$n.create({...t,coerce:!0})),date:(t=>Rn.create({...t,coerce:!0}))},IR=D});var u={};Sd(u,{BRAND:()=>zE,DIRTY:()=>xn,EMPTY_PATH:()=>SE,INVALID:()=>D,NEVER:()=>IR,OK:()=>Ue,ParseStatus:()=>Fe,Schema:()=>U,ZodAny:()=>Jr,ZodArray:()=>Rr,ZodBigInt:()=>$n,ZodBoolean:()=>En,ZodBranded:()=>No,ZodCatch:()=>Dn,ZodDate:()=>Rn,ZodDefault:()=>Ln,ZodDiscriminatedUnion:()=>ia,ZodEffects:()=>kt,ZodEnum:()=>An,ZodError:()=>ot,ZodFirstPartyTypeKind:()=>x,ZodFunction:()=>ca,ZodIntersection:()=>On,ZodIssueCode:()=>_,ZodLazy:()=>Tn,ZodLiteral:()=>Nn,ZodMap:()=>Es,ZodNaN:()=>Is,ZodNativeEnum:()=>Cn,ZodNever:()=>Mt,ZodNull:()=>jn,ZodNullable:()=>ir,ZodNumber:()=>kn,ZodObject:()=>it,ZodOptional:()=>St,ZodParsedType:()=>P,ZodPipeline:()=>Ao,ZodPromise:()=>Wr,ZodReadonly:()=>Mn,ZodRecord:()=>aa,ZodSchema:()=>U,ZodSet:()=>Rs,ZodString:()=>Br,ZodSymbol:()=>ks,ZodTransformer:()=>kt,ZodTuple:()=>or,ZodType:()=>U,ZodUndefined:()=>In,ZodUnion:()=>Pn,ZodUnknown:()=>Er,ZodVoid:()=>$s,addIssueToContext:()=>R,any:()=>QE,array:()=>nR,bigint:()=>WE,boolean:()=>lg,coerce:()=>RR,custom:()=>ig,date:()=>KE,datetimeRegex:()=>sg,defaultErrorMap:()=>kr,discriminatedUnion:()=>aR,effect:()=>wR,enum:()=>gR,function:()=>hR,getErrorMap:()=>_s,getParsedType:()=>sr,instanceof:()=>BE,intersection:()=>cR,isAborted:()=>sa,isAsync:()=>Ss,isDirty:()=>oa,isValid:()=>Hr,late:()=>HE,lazy:()=>fR,literal:()=>mR,makeIssue:()=>To,map:()=>uR,nan:()=>JE,nativeEnum:()=>yR,never:()=>tR,null:()=>XE,nullable:()=>_R,number:()=>cg,object:()=>sR,objectUtil:()=>Td,oboolean:()=>ER,onumber:()=>$R,optional:()=>vR,ostring:()=>kR,pipeline:()=>xR,preprocess:()=>SR,promise:()=>bR,quotelessJson:()=>wE,record:()=>dR,set:()=>pR,setErrorMap:()=>_E,strictObject:()=>oR,string:()=>ag,symbol:()=>ZE,transformer:()=>wR,tuple:()=>lR,undefined:()=>YE,union:()=>iR,unknown:()=>eR,util:()=>K,void:()=>rR});var la=v(()=>{na();Ad();Xm();Oo();dg();ra()});var Ft=v(()=>{la();la()});function jg(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Pg(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Dd,ug,da,Kr,pg,hg,jR,ar,at,Co,cr,$t,ua,fg,mg,gg,yg,bg,Md,he,wg,vg,_g,pa,PR,ha,OR,Lo,Do,Sg,TR,NR,Fd,AR,CR,qd,fa,LR,DR,ma,MR,ga,ya,xg,kg,Gd,$g,Eg,FR,ba,qR,wa,GR,Ud,UR,va,VR,zR,HR,BR,JR,WR,KR,ZR,YR,XR,_a,QR,eI,Sa,Vd,zd,Hd,tI,rI,Rg,nI,sI,oI,iI,aI,xa,cI,Ig,Mq,lI,ka,dI,Mo,uI,Bd,pI,hI,fI,mI,gI,yI,bI,Jd,wI,vI,_I,SI,xI,kI,$I,EI,RI,II,jI,PI,OI,TI,Wd,NI,AI,CI,$a,LI,DI,MI,Kd,FI,Fq,qq,Gq,Uq,Vq,zq,fe,Fo=v(()=>{Ft();Dd="2025-06-18",ug=[Dd,"2025-03-26","2024-11-05","2024-10-07"],da="2.0",Kr=u.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),pg=u.union([u.string(),u.number().int()]),hg=u.string(),jR=u.object({progressToken:pg.optional()}).passthrough(),ar=u.object({_meta:jR.optional()}),at=u.object({method:u.string(),params:ar.passthrough().optional()}),Co=u.object({_meta:u.record(u.string(),u.unknown()).optional()}),cr=u.object({method:u.string(),params:Co.passthrough().optional()}),$t=u.object({_meta:u.record(u.string(),u.unknown()).optional()}).passthrough(),ua=u.union([u.string(),u.number().int()]),fg=u.object({jsonrpc:u.literal(da),id:ua}).merge(at).strict(),mg=t=>fg.safeParse(t).success,gg=u.object({jsonrpc:u.literal(da)}).merge(cr).strict(),yg=t=>gg.safeParse(t).success,bg=u.object({jsonrpc:u.literal(da),id:ua,result:$t}).strict(),Md=t=>bg.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"})(he||(he={}));wg=u.object({jsonrpc:u.literal(da),id:ua,error:u.object({code:u.number().int(),message:u.string(),data:u.optional(u.unknown())})}).strict(),vg=t=>wg.safeParse(t).success,_g=u.union([fg,gg,bg,wg]),pa=$t.strict(),PR=Co.extend({requestId:ua,reason:u.string().optional()}),ha=cr.extend({method:u.literal("notifications/cancelled"),params:PR}),OR=u.object({src:u.string(),mimeType:u.string().optional(),sizes:u.array(u.string()).optional()}),Lo=u.object({icons:u.array(OR).optional()}),Do=u.object({name:u.string(),title:u.string().optional()}),Sg=Do.extend({version:u.string(),websiteUrl:u.string().optional()}).merge(Lo),TR=u.object({experimental:u.record(u.string(),Kr).optional(),sampling:Kr.optional(),elicitation:u.intersection(u.object({applyDefaults:u.boolean().optional()}).optional(),u.record(u.string(),u.unknown()).optional()),roots:u.object({listChanged:u.boolean().optional()}).optional()}),NR=ar.extend({protocolVersion:u.string(),capabilities:TR,clientInfo:Sg}),Fd=at.extend({method:u.literal("initialize"),params:NR}),AR=u.object({experimental:u.record(u.string(),Kr).optional(),logging:Kr.optional(),completions:Kr.optional(),prompts:u.optional(u.object({listChanged:u.optional(u.boolean())})),resources:u.object({subscribe:u.boolean().optional(),listChanged:u.boolean().optional()}).optional(),tools:u.object({listChanged:u.boolean().optional()}).optional()}),CR=$t.extend({protocolVersion:u.string(),capabilities:AR,serverInfo:Sg,instructions:u.string().optional()}),qd=cr.extend({method:u.literal("notifications/initialized")}),fa=at.extend({method:u.literal("ping")}),LR=u.object({progress:u.number(),total:u.optional(u.number()),message:u.optional(u.string())}),DR=Co.merge(LR).extend({progressToken:pg}),ma=cr.extend({method:u.literal("notifications/progress"),params:DR}),MR=ar.extend({cursor:hg.optional()}),ga=at.extend({params:MR.optional()}),ya=$t.extend({nextCursor:u.optional(hg)}),xg=u.object({uri:u.string(),mimeType:u.optional(u.string()),_meta:u.record(u.string(),u.unknown()).optional()}),kg=xg.extend({text:u.string()}),Gd=u.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),$g=xg.extend({blob:Gd}),Eg=Do.extend({uri:u.string(),description:u.optional(u.string()),mimeType:u.optional(u.string()),_meta:u.optional(u.object({}).passthrough())}).merge(Lo),FR=Do.extend({uriTemplate:u.string(),description:u.optional(u.string()),mimeType:u.optional(u.string()),_meta:u.optional(u.object({}).passthrough())}).merge(Lo),ba=ga.extend({method:u.literal("resources/list")}),qR=ya.extend({resources:u.array(Eg)}),wa=ga.extend({method:u.literal("resources/templates/list")}),GR=ya.extend({resourceTemplates:u.array(FR)}),Ud=ar.extend({uri:u.string()}),UR=Ud,va=at.extend({method:u.literal("resources/read"),params:UR}),VR=$t.extend({contents:u.array(u.union([kg,$g]))}),zR=cr.extend({method:u.literal("notifications/resources/list_changed")}),HR=Ud,BR=at.extend({method:u.literal("resources/subscribe"),params:HR}),JR=Ud,WR=at.extend({method:u.literal("resources/unsubscribe"),params:JR}),KR=Co.extend({uri:u.string()}),ZR=cr.extend({method:u.literal("notifications/resources/updated"),params:KR}),YR=u.object({name:u.string(),description:u.optional(u.string()),required:u.optional(u.boolean())}),XR=Do.extend({description:u.optional(u.string()),arguments:u.optional(u.array(YR)),_meta:u.optional(u.object({}).passthrough())}).merge(Lo),_a=ga.extend({method:u.literal("prompts/list")}),QR=ya.extend({prompts:u.array(XR)}),eI=ar.extend({name:u.string(),arguments:u.record(u.string(),u.string()).optional()}),Sa=at.extend({method:u.literal("prompts/get"),params:eI}),Vd=u.object({type:u.literal("text"),text:u.string(),_meta:u.record(u.string(),u.unknown()).optional()}),zd=u.object({type:u.literal("image"),data:Gd,mimeType:u.string(),_meta:u.record(u.string(),u.unknown()).optional()}),Hd=u.object({type:u.literal("audio"),data:Gd,mimeType:u.string(),_meta:u.record(u.string(),u.unknown()).optional()}),tI=u.object({type:u.literal("resource"),resource:u.union([kg,$g]),_meta:u.record(u.string(),u.unknown()).optional()}),rI=Eg.extend({type:u.literal("resource_link")}),Rg=u.union([Vd,zd,Hd,rI,tI]),nI=u.object({role:u.enum(["user","assistant"]),content:Rg}),sI=$t.extend({description:u.optional(u.string()),messages:u.array(nI)}),oI=cr.extend({method:u.literal("notifications/prompts/list_changed")}),iI=u.object({title:u.string().optional(),readOnlyHint:u.boolean().optional(),destructiveHint:u.boolean().optional(),idempotentHint:u.boolean().optional(),openWorldHint:u.boolean().optional()}),aI=Do.extend({description:u.string().optional(),inputSchema:u.object({type:u.literal("object"),properties:u.record(u.string(),Kr).optional(),required:u.optional(u.array(u.string()))}),outputSchema:u.object({type:u.literal("object"),properties:u.record(u.string(),Kr).optional(),required:u.optional(u.array(u.string())),additionalProperties:u.optional(u.boolean())}).optional(),annotations:u.optional(iI),_meta:u.record(u.string(),u.unknown()).optional()}).merge(Lo),xa=ga.extend({method:u.literal("tools/list")}),cI=ya.extend({tools:u.array(aI)}),Ig=$t.extend({content:u.array(Rg).default([]),structuredContent:u.record(u.string(),u.unknown()).optional(),isError:u.optional(u.boolean())}),Mq=Ig.or($t.extend({toolResult:u.unknown()})),lI=ar.extend({name:u.string(),arguments:u.optional(u.record(u.string(),u.unknown()))}),ka=at.extend({method:u.literal("tools/call"),params:lI}),dI=cr.extend({method:u.literal("notifications/tools/list_changed")}),Mo=u.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),uI=ar.extend({level:Mo}),Bd=at.extend({method:u.literal("logging/setLevel"),params:uI}),pI=Co.extend({level:Mo,logger:u.string().optional(),data:u.unknown()}),hI=cr.extend({method:u.literal("notifications/message"),params:pI}),fI=u.object({name:u.string().optional()}),mI=u.object({hints:u.optional(u.array(fI)),costPriority:u.optional(u.number().min(0).max(1)),speedPriority:u.optional(u.number().min(0).max(1)),intelligencePriority:u.optional(u.number().min(0).max(1))}),gI=u.object({role:u.enum(["user","assistant"]),content:u.union([Vd,zd,Hd])}),yI=ar.extend({messages:u.array(gI),modelPreferences:mI.optional(),systemPrompt:u.string().optional(),includeContext:u.enum(["none","thisServer","allServers"]).optional(),temperature:u.number().optional(),maxTokens:u.number().int(),stopSequences:u.array(u.string()).optional(),metadata:Kr.optional()}),bI=at.extend({method:u.literal("sampling/createMessage"),params:yI}),Jd=$t.extend({model:u.string(),stopReason:u.optional(u.enum(["endTurn","stopSequence","maxTokens"]).or(u.string())),role:u.enum(["user","assistant"]),content:u.discriminatedUnion("type",[Vd,zd,Hd])}),wI=u.object({type:u.literal("boolean"),title:u.string().optional(),description:u.string().optional(),default:u.boolean().optional()}),vI=u.object({type:u.literal("string"),title:u.string().optional(),description:u.string().optional(),minLength:u.number().optional(),maxLength:u.number().optional(),format:u.enum(["email","uri","date","date-time"]).optional(),default:u.string().optional()}),_I=u.object({type:u.enum(["number","integer"]),title:u.string().optional(),description:u.string().optional(),minimum:u.number().optional(),maximum:u.number().optional(),default:u.number().optional()}),SI=u.object({type:u.literal("string"),title:u.string().optional(),description:u.string().optional(),enum:u.array(u.string()),default:u.string().optional()}),xI=u.object({type:u.literal("string"),title:u.string().optional(),description:u.string().optional(),oneOf:u.array(u.object({const:u.string(),title:u.string()})),default:u.string().optional()}),kI=u.object({type:u.literal("string"),title:u.string().optional(),description:u.string().optional(),enum:u.array(u.string()),enumNames:u.array(u.string()).optional(),default:u.string().optional()}),$I=u.union([SI,xI]),EI=u.object({type:u.literal("array"),title:u.string().optional(),description:u.string().optional(),minItems:u.number().optional(),maxItems:u.number().optional(),items:u.object({type:u.literal("string"),enum:u.array(u.string())}),default:u.array(u.string()).optional()}),RI=u.object({type:u.literal("array"),title:u.string().optional(),description:u.string().optional(),minItems:u.number().optional(),maxItems:u.number().optional(),items:u.object({anyOf:u.array(u.object({const:u.string(),title:u.string()}))}),default:u.array(u.string()).optional()}),II=u.union([EI,RI]),jI=u.union([kI,$I,II]),PI=u.union([jI,wI,vI,_I]),OI=ar.extend({message:u.string(),requestedSchema:u.object({type:u.literal("object"),properties:u.record(u.string(),PI),required:u.array(u.string()).optional()})}),TI=at.extend({method:u.literal("elicitation/create"),params:OI}),Wd=$t.extend({action:u.enum(["accept","decline","cancel"]),content:u.record(u.union([u.string(),u.number(),u.boolean(),u.array(u.string())])).optional()}),NI=u.object({type:u.literal("ref/resource"),uri:u.string()}),AI=u.object({type:u.literal("ref/prompt"),name:u.string()}),CI=ar.extend({ref:u.union([AI,NI]),argument:u.object({name:u.string(),value:u.string()}),context:u.object({arguments:u.record(u.string(),u.string()).optional()}).optional()}),$a=at.extend({method:u.literal("completion/complete"),params:CI});LI=$t.extend({completion:u.object({values:u.array(u.string()).max(100),total:u.optional(u.number().int()),hasMore:u.optional(u.boolean())}).passthrough()}),DI=u.object({uri:u.string().startsWith("file://"),name:u.string().optional(),_meta:u.record(u.string(),u.unknown()).optional()}),MI=at.extend({method:u.literal("roots/list")}),Kd=$t.extend({roots:u.array(DI)}),FI=cr.extend({method:u.literal("notifications/roots/list_changed")}),Fq=u.union([fa,Fd,$a,Bd,Sa,_a,ba,wa,va,BR,WR,ka,xa]),qq=u.union([ha,ma,qd,FI]),Gq=u.union([pa,Jd,Wd,Kd]),Uq=u.union([fa,bI,TI,MI]),Vq=u.union([ha,ma,hI,ZR,zR,dI,oI]),zq=u.union([pa,CR,LI,sI,QR,qR,GR,VR,Ig,cI]),fe=class extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}}});function qI(t){return _g.parse(JSON.parse(t))}function Og(t){return JSON.stringify(t)+`
|
|
5
|
+
`}var Ea,Tg=v(()=>{Fo();Ea=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
6
|
+
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),qI(r)}clear(){this._buffer=void 0}}});var Ag={};Sd(Ag,{StdioServerTransport:()=>Zd});import Ng from"node:process";var Zd,Cg=v(()=>{Tg();Zd=class{constructor(e=Ng.stdin,r=Ng.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Ea,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{var s;(s=this.onerror)===null||s===void 0||s.call(this,n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var e,r;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(r=this.onerror)===null||r===void 0||r.call(this,n)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)===null||e===void 0||e.call(this)}send(e){return new Promise(r=>{let n=Og(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});function Lg(t,e){t==="doctor"?qt.doctorRan=!0:t==="ideas_generate"?qt.slatePending=!0:(t==="ideas_save"||t==="episode_create")&&(qt.slatePending=!1);let r=typeof e?.episodeId=="string"?e.episodeId:null,n=typeof e?.styleId=="string"?e.styleId:null;t==="get_style_guide"&&n&&qt.seen.add(`guide:${n}`),r&&qt.seen.add(`${t}:${r}`)}function Dg(t,e){qt.seen.delete(`${t}:${e}`)}function Yd(t,e){return qt.briefed.get(t)===e?!1:(qt.briefed.set(t,e),!0)}var qt,Ra,Mg,Ia,qo=v(()=>{"use strict";qt={doctorRan:!1,slatePending:!1,briefed:new Map,seen:new Set};Ra=(t,e)=>qt.seen.has(`${t==="get_style_guide"?"guide":t}:${e}`);Mg=()=>qt.doctorRan,Ia=()=>qt.slatePending});function Fg(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function qg(t,e){let r={...t};for(let n in e){let s=n,o=e[s];if(o===void 0)continue;let i=r[s];Fg(i)&&Fg(o)?r[s]={...i,...o}:r[s]=o}return r}var GI,ja,Gg=v(()=>{Fo();GI=6e4,ja=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(ha,r=>{let n=this._requestHandlerAbortControllers.get(r.params.requestId);n?.abort(r.params.reason)}),this.setNotificationHandler(ma,r=>{this._onprogress(r)}),this.setRequestHandler(fa,r=>({}))}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new fe(he.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,n,s;this._transport=e;let o=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{o?.(),this._onclose()};let i=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=c=>{i?.(c),this._onerror(c)};let a=(s=this._transport)===null||s===void 0?void 0:s.onmessage;this._transport.onmessage=(c,l)=>{a?.(c,l),Md(c)||vg(c)?this._onresponse(c):mg(c)?this._onrequest(c,l):yg(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let n=new fe(he.ConnectionClosed,"Connection closed");for(let s of r.values())s(n)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;let n=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(s=>this._onerror(new Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,r){var n,s;let o=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,i=this._transport;if(o===void 0){i?.send({jsonrpc:"2.0",id:e.id,error:{code:he.MethodNotFound,message:"Method not found"}}).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let c={signal:a.signal,sessionId:i?.sessionId,_meta:(s=e.params)===null||s===void 0?void 0:s._meta,sendNotification:l=>this.notification(l,{relatedRequestId:e.id}),sendRequest:(l,d,p)=>this.request(l,d,{...p,relatedRequestId:e.id}),authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo};Promise.resolve().then(()=>o(e,c)).then(l=>{if(!a.signal.aborted)return i?.send({result:l,jsonrpc:"2.0",id:e.id})},l=>{var d;if(!a.signal.aborted)return i?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:he.InternalError,message:(d=l.message)!==null&&d!==void 0?d:"Internal error"}})}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){i(c);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),Md(e))n(e);else{let s=new fe(e.error.code,e.error.message,e.error.data);n(s)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}=n??{};return new Promise((a,c)=>{var l,d,p,f,h,m;if(!this._transport){c(new Error("Not connected"));return}((l=this._options)===null||l===void 0?void 0:l.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(d=n?.signal)===null||d===void 0||d.throwIfAborted();let g=this._requestMessageId++,y={...e,jsonrpc:"2.0",id:g};n?.onprogress&&(this._progressHandlers.set(g,n.onprogress),y.params={...e.params,_meta:{...((p=e.params)===null||p===void 0?void 0:p._meta)||{},progressToken:g}});let w=k=>{var I;this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),(I=this._transport)===null||I===void 0||I.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:g,reason:String(k)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(C=>this._onerror(new Error(`Failed to send cancellation: ${C}`))),c(k)};this._responseHandlers.set(g,k=>{var I;if(!(!((I=n?.signal)===null||I===void 0)&&I.aborted)){if(k instanceof Error)return c(k);try{let C=r.parse(k.result);a(C)}catch(C){c(C)}}}),(f=n?.signal)===null||f===void 0||f.addEventListener("abort",()=>{var k;w((k=n?.signal)===null||k===void 0?void 0:k.reason)});let S=(h=n?.timeout)!==null&&h!==void 0?h:GI,$=()=>w(new fe(he.RequestTimeout,"Request timed out",{timeout:S}));this._setupTimeout(g,S,n?.maxTotalTimeout,$,(m=n?.resetTimeoutOnProgress)!==null&&m!==void 0?m:!1),this._transport.send(y,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(k=>{this._cleanupTimeout(g),c(k)})})}async notification(e,r){var n,s;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((s=(n=this._options)===null||n===void 0?void 0:n.debouncedNotificationMethods)!==null&&s!==void 0?s:[]).includes(e.method)&&!e.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var c;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let l={...e,jsonrpc:"2.0"};(c=this._transport)===null||c===void 0||c.send(l,r).catch(d=>this._onerror(d))});return}let a={...e,jsonrpc:"2.0"};await this._transport.send(a,r)}setRequestHandler(e,r){let n=e.shape.method.value;this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>Promise.resolve(r(e.parse(s),o)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,n=>Promise.resolve(r(e.parse(n))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}});var Vo=j(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.regexpCode=te.getEsmExportName=te.getProperty=te.safeStringify=te.stringify=te.strConcat=te.addCodeArg=te.str=te._=te.nil=te._Code=te.Name=te.IDENTIFIER=te._CodeOrName=void 0;var Go=class{};te._CodeOrName=Go;te.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Fn=class extends Go{constructor(e){if(super(),!te.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};te.Name=Fn;var Et=class extends Go{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Fn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};te._Code=Et;te.nil=new Et("");function Ug(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Qd(r,e[n]),r.push(t[++n]);return new Et(r)}te._=Ug;var Xd=new Et("+");function Vg(t,...e){let r=[Uo(t[0])],n=0;for(;n<e.length;)r.push(Xd),Qd(r,e[n]),r.push(Xd,Uo(t[++n]));return UI(r),new Et(r)}te.str=Vg;function Qd(t,e){e instanceof Et?t.push(...e._items):e instanceof Fn?t.push(e):t.push(HI(e))}te.addCodeArg=Qd;function UI(t){let e=1;for(;e<t.length-1;){if(t[e]===Xd){let r=VI(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function VI(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Fn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Fn))return`"${t}${e.slice(1)}`}function zI(t,e){return e.emptyStr()?t:t.emptyStr()?e:Vg`${t}${e}`}te.strConcat=zI;function HI(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Uo(Array.isArray(t)?t.join(","):t)}function BI(t){return new Et(Uo(t))}te.stringify=BI;function Uo(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}te.safeStringify=Uo;function JI(t){return typeof t=="string"&&te.IDENTIFIER.test(t)?new Et(`.${t}`):Ug`[${t}]`}te.getProperty=JI;function WI(t){if(typeof t=="string"&&te.IDENTIFIER.test(t))return new Et(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}te.getEsmExportName=WI;function KI(t){return new Et(t.toString())}te.regexpCode=KI});var ru=j(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.ValueScope=lt.ValueScopeName=lt.Scope=lt.varKinds=lt.UsedValueState=void 0;var ct=Vo(),eu=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Pa;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Pa||(lt.UsedValueState=Pa={}));lt.varKinds={const:new ct.Name("const"),let:new ct.Name("let"),var:new ct.Name("var")};var Oa=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof ct.Name?e:this.name(e)}name(e){return new ct.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};lt.Scope=Oa;var Ta=class extends ct.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,ct._)`.${new ct.Name(r)}[${n}]`}};lt.ValueScopeName=Ta;var ZI=(0,ct._)`\n`,tu=class extends Oa{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?ZI:ct.nil}}get(){return this._scope}name(e){return new Ta(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let s=this.toName(e),{prefix:o}=s,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let d=a.get(i);if(d)return d}else a=this._values[o]=new Map;a.set(i,s);let c=this._scope[o]||(this._scope[o]=[]),l=c.length;return c[l]=r.ref,s.setValue(r,{property:o,itemIndex:l}),s}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,ct._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},r,n)}_reduceValues(e,r,n={},s){let o=ct.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,Pa.Started);let d=r(l);if(d){let p=this.opts.es5?lt.varKinds.var:lt.varKinds.const;o=(0,ct._)`${o}${p} ${l} = ${d};${this.opts._n}`}else if(d=s?.(l))o=(0,ct._)`${o}${d}${this.opts._n}`;else throw new eu(l);c.set(l,Pa.Completed)})}return o}};lt.ValueScope=tu});var z=j(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.or=B.and=B.not=B.CodeGen=B.operators=B.varKinds=B.ValueScopeName=B.ValueScope=B.Scope=B.Name=B.regexpCode=B.stringify=B.getProperty=B.nil=B.strConcat=B.str=B._=void 0;var Y=Vo(),Gt=ru(),Zr=Vo();Object.defineProperty(B,"_",{enumerable:!0,get:function(){return Zr._}});Object.defineProperty(B,"str",{enumerable:!0,get:function(){return Zr.str}});Object.defineProperty(B,"strConcat",{enumerable:!0,get:function(){return Zr.strConcat}});Object.defineProperty(B,"nil",{enumerable:!0,get:function(){return Zr.nil}});Object.defineProperty(B,"getProperty",{enumerable:!0,get:function(){return Zr.getProperty}});Object.defineProperty(B,"stringify",{enumerable:!0,get:function(){return Zr.stringify}});Object.defineProperty(B,"regexpCode",{enumerable:!0,get:function(){return Zr.regexpCode}});Object.defineProperty(B,"Name",{enumerable:!0,get:function(){return Zr.Name}});var La=ru();Object.defineProperty(B,"Scope",{enumerable:!0,get:function(){return La.Scope}});Object.defineProperty(B,"ValueScope",{enumerable:!0,get:function(){return La.ValueScope}});Object.defineProperty(B,"ValueScopeName",{enumerable:!0,get:function(){return La.ValueScopeName}});Object.defineProperty(B,"varKinds",{enumerable:!0,get:function(){return La.varKinds}});B.operators={GT:new Y._Code(">"),GTE:new Y._Code(">="),LT:new Y._Code("<"),LTE:new Y._Code("<="),EQ:new Y._Code("==="),NEQ:new Y._Code("!=="),NOT:new Y._Code("!"),OR:new Y._Code("||"),AND:new Y._Code("&&"),ADD:new Y._Code("+")};var Ir=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},nu=class extends Ir{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Gt.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Ps(this.rhs,e,r)),this}get names(){return this.rhs instanceof Y._CodeOrName?this.rhs.names:{}}},Na=class extends Ir{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof Y.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Ps(this.rhs,e,r),this}get names(){let e=this.lhs instanceof Y.Name?{}:{...this.lhs.names};return Ca(e,this.rhs)}},su=class extends Na{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},ou=class extends Ir{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},iu=class extends Ir{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},au=class extends Ir{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},cu=class extends Ir{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Ps(this.code,e,r),this}get names(){return this.code instanceof Y._CodeOrName?this.code.names:{}}},zo=class extends Ir{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,s=n.length;for(;s--;){let o=n[s];o.optimizeNames(e,r)||(YI(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Un(e,r.names),{})}},jr=class extends zo{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},lu=class extends zo{},js=class extends jr{};js.kind="else";var qn=class t extends jr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new js(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(zg(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Ps(this.condition,e,r),this}get names(){let e=super.names;return Ca(e,this.condition),this.else&&Un(e,this.else.names),e}};qn.kind="if";var Gn=class extends jr{};Gn.kind="for";var du=class extends Gn{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Ps(this.iteration,e,r),this}get names(){return Un(super.names,this.iteration.names)}},uu=class extends Gn{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?Gt.varKinds.var:this.varKind,{name:n,from:s,to:o}=this;return`for(${r} ${n}=${s}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=Ca(super.names,this.from);return Ca(e,this.to)}},Aa=class extends Gn{constructor(e,r,n,s){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Ps(this.iterable,e,r),this}get names(){return Un(super.names,this.iterable.names)}},Ho=class extends jr{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Ho.kind="func";var Bo=class extends zo{render(e){return"return "+super.render(e)}};Bo.kind="return";var pu=class extends jr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,s;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(s=this.finally)===null||s===void 0||s.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Un(e,this.catch.names),this.finally&&Un(e,this.finally.names),e}},Jo=class extends jr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Jo.kind="catch";var Wo=class extends jr{render(e){return"finally"+super.render(e)}};Wo.kind="finally";var hu=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
7
|
+
`:""},this._extScope=e,this._scope=new Gt.Scope({parent:e}),this._nodes=[new lu]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,s){let o=this._scope.toName(r);return n!==void 0&&s&&(this._constants[o.str]=n),this._leafNode(new nu(e,o,n)),o}const(e,r,n){return this._def(Gt.varKinds.const,e,r,n)}let(e,r,n){return this._def(Gt.varKinds.let,e,r,n)}var(e,r,n){return this._def(Gt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Na(e,r,n))}add(e,r){return this._leafNode(new su(e,B.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==Y.nil&&this._leafNode(new cu(e)),this}object(...e){let r=["{"];for(let[n,s]of e)r.length>1&&r.push(","),r.push(n),(n!==s||this.opts.es5)&&(r.push(":"),(0,Y.addCodeArg)(r,s));return r.push("}"),new Y._Code(r)}if(e,r,n){if(this._blockNode(new qn(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new qn(e))}else(){return this._elseNode(new js)}endIf(){return this._endBlockNode(qn,js)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new du(e),r)}forRange(e,r,n,s,o=this.opts.es5?Gt.varKinds.var:Gt.varKinds.let){let i=this._scope.toName(e);return this._for(new uu(o,i,r,n),()=>s(i))}forOf(e,r,n,s=Gt.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof Y.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Y._)`${i}.length`,a=>{this.var(o,(0,Y._)`${i}[${a}]`),n(o)})}return this._for(new Aa("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?Gt.varKinds.var:Gt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,Y._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new Aa("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(Gn)}label(e){return this._leafNode(new ou(e))}break(e){return this._leafNode(new iu(e))}return(e){let r=new Bo;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Bo)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new pu;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new Jo(o),r(o)}return n&&(this._currNode=s.finally=new Wo,this.code(n)),this._endBlockNode(Jo,Wo)}throw(e){return this._leafNode(new au(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=Y.nil,n,s){return this._blockNode(new Ho(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Ho)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof qn))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};B.CodeGen=hu;function Un(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ca(t,e){return e instanceof Y._CodeOrName?Un(t,e.names):t}function Ps(t,e,r){if(t instanceof Y.Name)return n(t);if(!s(t))return t;return new Y._Code(t._items.reduce((o,i)=>(i instanceof Y.Name&&(i=n(i)),i instanceof Y._Code?o.push(...i._items):o.push(i),o),[]));function n(o){let i=r[o.str];return i===void 0||e[o.str]!==1?o:(delete e[o.str],i)}function s(o){return o instanceof Y._Code&&o._items.some(i=>i instanceof Y.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function YI(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function zg(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,Y._)`!${fu(t)}`}B.not=zg;var XI=Hg(B.operators.AND);function QI(...t){return t.reduce(XI)}B.and=QI;var e1=Hg(B.operators.OR);function t1(...t){return t.reduce(e1)}B.or=t1;function Hg(t){return(e,r)=>e===Y.nil?r:r===Y.nil?e:(0,Y._)`${fu(e)} ${t} ${fu(r)}`}function fu(t){return t instanceof Y.Name?t:(0,Y._)`(${t})`}});var Q=j(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.checkStrictMode=W.getErrorPath=W.Type=W.useFunc=W.setEvaluated=W.evaluatedPropsToName=W.mergeEvaluated=W.eachItem=W.unescapeJsonPointer=W.escapeJsonPointer=W.escapeFragment=W.unescapeFragment=W.schemaRefOrVal=W.schemaHasRulesButRef=W.schemaHasRules=W.checkUnknownRules=W.alwaysValidSchema=W.toHash=void 0;var de=z(),r1=Vo();function n1(t){let e={};for(let r of t)e[r]=!0;return e}W.toHash=n1;function s1(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Wg(t,e),!Kg(e,t.self.RULES.all))}W.alwaysValidSchema=s1;function Wg(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let o in e)s[o]||Xg(t,`unknown keyword: "${o}"`)}W.checkUnknownRules=Wg;function Kg(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}W.schemaHasRules=Kg;function o1(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}W.schemaHasRulesButRef=o1;function i1({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,de._)`${r}`}return(0,de._)`${t}${e}${(0,de.getProperty)(n)}`}W.schemaRefOrVal=i1;function a1(t){return Zg(decodeURIComponent(t))}W.unescapeFragment=a1;function c1(t){return encodeURIComponent(gu(t))}W.escapeFragment=c1;function gu(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}W.escapeJsonPointer=gu;function Zg(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}W.unescapeJsonPointer=Zg;function l1(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}W.eachItem=l1;function Bg({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,a)=>{let c=i===void 0?o:i instanceof de.Name?(o instanceof de.Name?t(s,o,i):e(s,o,i),i):o instanceof de.Name?(e(s,i,o),o):r(o,i);return a===de.Name&&!(c instanceof de.Name)?n(s,c):c}}W.mergeEvaluated={props:Bg({mergeNames:(t,e,r)=>t.if((0,de._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,de._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,de._)`${r} || {}`).code((0,de._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,de._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,de._)`${r} || {}`),yu(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Yg}),items:Bg({mergeNames:(t,e,r)=>t.if((0,de._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,de._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,de._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,de._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Yg(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,de._)`{}`);return e!==void 0&&yu(t,r,e),r}W.evaluatedPropsToName=Yg;function yu(t,e,r){Object.keys(r).forEach(n=>t.assign((0,de._)`${e}${(0,de.getProperty)(n)}`,!0))}W.setEvaluated=yu;var Jg={};function d1(t,e){return t.scopeValue("func",{ref:e,code:Jg[e.code]||(Jg[e.code]=new r1._Code(e.code))})}W.useFunc=d1;var mu;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(mu||(W.Type=mu={}));function u1(t,e,r){if(t instanceof de.Name){let n=e===mu.Num;return r?n?(0,de._)`"[" + ${t} + "]"`:(0,de._)`"['" + ${t} + "']"`:n?(0,de._)`"/" + ${t}`:(0,de._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,de.getProperty)(t).toString():"/"+gu(t)}W.getErrorPath=u1;function Xg(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}W.checkStrictMode=Xg});var Pr=j(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});var Ve=z(),p1={data:new Ve.Name("data"),valCxt:new Ve.Name("valCxt"),instancePath:new Ve.Name("instancePath"),parentData:new Ve.Name("parentData"),parentDataProperty:new Ve.Name("parentDataProperty"),rootData:new Ve.Name("rootData"),dynamicAnchors:new Ve.Name("dynamicAnchors"),vErrors:new Ve.Name("vErrors"),errors:new Ve.Name("errors"),this:new Ve.Name("this"),self:new Ve.Name("self"),scope:new Ve.Name("scope"),json:new Ve.Name("json"),jsonPos:new Ve.Name("jsonPos"),jsonLen:new Ve.Name("jsonLen"),jsonPart:new Ve.Name("jsonPart")};bu.default=p1});var Ko=j(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.extendErrors=ze.resetErrorsCount=ze.reportExtraError=ze.reportError=ze.keyword$DataError=ze.keywordError=void 0;var ee=z(),Da=Q(),Ke=Pr();ze.keywordError={message:({keyword:t})=>(0,ee.str)`must pass "${t}" keyword validation`};ze.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ee.str)`"${t}" keyword must be ${e} ($data)`:(0,ee.str)`"${t}" keyword is invalid ($data)`};function h1(t,e=ze.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,c=ty(t,e,r);n??(i||a)?Qg(o,c):ey(s,(0,ee._)`[${c}]`)}ze.reportError=h1;function f1(t,e=ze.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=ty(t,e,r);Qg(s,a),o||i||ey(n,Ke.default.vErrors)}ze.reportExtraError=f1;function m1(t,e){t.assign(Ke.default.errors,e),t.if((0,ee._)`${Ke.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ee._)`${Ke.default.vErrors}.length`,e),()=>t.assign(Ke.default.vErrors,null)))}ze.resetErrorsCount=m1;function g1({gen:t,keyword:e,schemaValue:r,data:n,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,Ke.default.errors,a=>{t.const(i,(0,ee._)`${Ke.default.vErrors}[${a}]`),t.if((0,ee._)`${i}.instancePath === undefined`,()=>t.assign((0,ee._)`${i}.instancePath`,(0,ee.strConcat)(Ke.default.instancePath,o.errorPath))),t.assign((0,ee._)`${i}.schemaPath`,(0,ee.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,ee._)`${i}.schema`,r),t.assign((0,ee._)`${i}.data`,n))})}ze.extendErrors=g1;function Qg(t,e){let r=t.const("err",e);t.if((0,ee._)`${Ke.default.vErrors} === null`,()=>t.assign(Ke.default.vErrors,(0,ee._)`[${r}]`),(0,ee._)`${Ke.default.vErrors}.push(${r})`),t.code((0,ee._)`${Ke.default.errors}++`)}function ey(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,ee._)`new ${t.ValidationError}(${e})`):(r.assign((0,ee._)`${n}.errors`,e),r.return(!1))}var Vn={keyword:new ee.Name("keyword"),schemaPath:new ee.Name("schemaPath"),params:new ee.Name("params"),propertyName:new ee.Name("propertyName"),message:new ee.Name("message"),schema:new ee.Name("schema"),parentSchema:new ee.Name("parentSchema")};function ty(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ee._)`{}`:y1(t,e,r)}function y1(t,e,r={}){let{gen:n,it:s}=t,o=[b1(s,r),w1(t,r)];return v1(t,e,o),n.object(...o)}function b1({errorPath:t},{instancePath:e}){let r=e?(0,ee.str)`${t}${(0,Da.getErrorPath)(e,Da.Type.Str)}`:t;return[Ke.default.instancePath,(0,ee.strConcat)(Ke.default.instancePath,r)]}function w1({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,ee.str)`${e}/${t}`;return r&&(s=(0,ee.str)`${s}${(0,Da.getErrorPath)(r,Da.Type.Str)}`),[Vn.schemaPath,s]}function v1(t,{params:e,message:r},n){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:c,propertyName:l,topSchemaRef:d,schemaPath:p}=a;n.push([Vn.keyword,s],[Vn.params,typeof e=="function"?e(t):e||(0,ee._)`{}`]),c.messages&&n.push([Vn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Vn.schema,i],[Vn.parentSchema,(0,ee._)`${d}${p}`],[Ke.default.data,o]),l&&n.push([Vn.propertyName,l])}});var ny=j(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});Os.boolOrEmptySchema=Os.topBoolOrEmptySchema=void 0;var _1=Ko(),S1=z(),x1=Pr(),k1={message:"boolean schema is false"};function $1(t){let{gen:e,schema:r,validateName:n}=t;r===!1?ry(t,!1):typeof r=="object"&&r.$async===!0?e.return(x1.default.data):(e.assign((0,S1._)`${n}.errors`,null),e.return(!0))}Os.topBoolOrEmptySchema=$1;function E1(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),ry(t)):r.var(e,!0)}Os.boolOrEmptySchema=E1;function ry(t,e){let{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,_1.reportError)(s,k1,void 0,e)}});var wu=j(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});Ts.getRules=Ts.isJSONType=void 0;var R1=["string","number","integer","boolean","null","object","array"],I1=new Set(R1);function j1(t){return typeof t=="string"&&I1.has(t)}Ts.isJSONType=j1;function P1(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Ts.getRules=P1});var vu=j(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.shouldUseRule=Yr.shouldUseGroup=Yr.schemaHasRulesForType=void 0;function O1({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&sy(t,n)}Yr.schemaHasRulesForType=O1;function sy(t,e){return e.rules.some(r=>oy(t,r))}Yr.shouldUseGroup=sy;function oy(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Yr.shouldUseRule=oy});var Zo=j(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.reportTypeError=He.checkDataTypes=He.checkDataType=He.coerceAndCheckDataType=He.getJSONTypes=He.getSchemaTypes=He.DataType=void 0;var T1=wu(),N1=vu(),A1=Ko(),V=z(),iy=Q(),Ns;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Ns||(He.DataType=Ns={}));function C1(t){let e=ay(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}He.getSchemaTypes=C1;function ay(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(T1.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}He.getJSONTypes=ay;function L1(t,e){let{gen:r,data:n,opts:s}=t,o=D1(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,N1.schemaHasRulesForType)(t,e[0]));if(i){let a=Su(e,n,s.strictNumbers,Ns.Wrong);r.if(a,()=>{o.length?M1(t,e,o):xu(t)})}return i}He.coerceAndCheckDataType=L1;var cy=new Set(["string","number","integer","boolean","null"]);function D1(t,e){return e?t.filter(r=>cy.has(r)||e==="array"&&r==="array"):[]}function M1(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,V._)`typeof ${s}`),a=n.let("coerced",(0,V._)`undefined`);o.coerceTypes==="array"&&n.if((0,V._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,V._)`${s}[0]`).assign(i,(0,V._)`typeof ${s}`).if(Su(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,V._)`${a} !== undefined`);for(let l of r)(cy.has(l)||l==="array"&&o.coerceTypes==="array")&&c(l);n.else(),xu(t),n.endIf(),n.if((0,V._)`${a} !== undefined`,()=>{n.assign(s,a),F1(t,a)});function c(l){switch(l){case"string":n.elseIf((0,V._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,V._)`"" + ${s}`).elseIf((0,V._)`${s} === null`).assign(a,(0,V._)`""`);return;case"number":n.elseIf((0,V._)`${i} == "boolean" || ${s} === null
|
|
8
|
+
|| (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,V._)`+${s}`);return;case"integer":n.elseIf((0,V._)`${i} === "boolean" || ${s} === null
|
|
9
|
+
|| (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,V._)`+${s}`);return;case"boolean":n.elseIf((0,V._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,V._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":n.elseIf((0,V._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(a,null);return;case"array":n.elseIf((0,V._)`${i} === "string" || ${i} === "number"
|
|
10
|
+
|| ${i} === "boolean" || ${s} === null`).assign(a,(0,V._)`[${s}]`)}}}function F1({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,V._)`${e} !== undefined`,()=>t.assign((0,V._)`${e}[${r}]`,n))}function _u(t,e,r,n=Ns.Correct){let s=n===Ns.Correct?V.operators.EQ:V.operators.NEQ,o;switch(t){case"null":return(0,V._)`${e} ${s} null`;case"array":o=(0,V._)`Array.isArray(${e})`;break;case"object":o=(0,V._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,V._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,V._)`typeof ${e} ${s} ${t}`}return n===Ns.Correct?o:(0,V.not)(o);function i(a=V.nil){return(0,V.and)((0,V._)`typeof ${e} == "number"`,a,r?(0,V._)`isFinite(${e})`:V.nil)}}He.checkDataType=_u;function Su(t,e,r,n){if(t.length===1)return _u(t[0],e,r,n);let s,o=(0,iy.toHash)(t);if(o.array&&o.object){let i=(0,V._)`typeof ${e} != "object"`;s=o.null?i:(0,V._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=V.nil;o.number&&delete o.integer;for(let i in o)s=(0,V.and)(s,_u(i,e,r,n));return s}He.checkDataTypes=Su;var q1={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,V._)`{type: ${t}}`:(0,V._)`{type: ${e}}`};function xu(t){let e=G1(t);(0,A1.reportError)(e,q1)}He.reportTypeError=xu;function G1(t){let{gen:e,data:r,schema:n}=t,s=(0,iy.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var dy=j(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.assignDefaults=void 0;var As=z(),U1=Q();function V1(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)ly(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>ly(t,o,s.default))}Ma.assignDefaults=V1;function ly(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,As._)`${o}${(0,As.getProperty)(e)}`;if(s){(0,U1.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,As._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,As._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,As._)`${a} = ${(0,As.stringify)(r)}`)}});var Rt=j(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.validateUnion=ce.validateArray=ce.usePattern=ce.callValidateCode=ce.schemaProperties=ce.allSchemaProperties=ce.noPropertyInData=ce.propertyInData=ce.isOwnProperty=ce.hasPropFunc=ce.reportMissingProp=ce.checkMissingProp=ce.checkReportMissingProp=void 0;var ge=z(),ku=Q(),Xr=Pr(),z1=Q();function H1(t,e){let{gen:r,data:n,it:s}=t;r.if(Eu(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}ce.checkReportMissingProp=H1;function B1({gen:t,data:e,it:{opts:r}},n,s){return(0,ge.or)(...n.map(o=>(0,ge.and)(Eu(t,e,o,r.ownProperties),(0,ge._)`${s} = ${o}`)))}ce.checkMissingProp=B1;function J1(t,e){t.setParams({missingProperty:e},!0),t.error()}ce.reportMissingProp=J1;function uy(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}ce.hasPropFunc=uy;function $u(t,e,r){return(0,ge._)`${uy(t)}.call(${e}, ${r})`}ce.isOwnProperty=$u;function W1(t,e,r,n){let s=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${s} && ${$u(t,e,r)}`:s}ce.propertyInData=W1;function Eu(t,e,r,n){let s=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(s,(0,ge.not)($u(t,e,r))):s}ce.noPropertyInData=Eu;function py(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ce.allSchemaProperties=py;function K1(t,e){return py(e).filter(r=>!(0,ku.alwaysValidSchema)(t,e[r]))}ce.schemaProperties=K1;function Z1({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},a,c,l){let d=l?(0,ge._)`${t}, ${e}, ${n}${s}`:e,p=[[Xr.default.instancePath,(0,ge.strConcat)(Xr.default.instancePath,o)],[Xr.default.parentData,i.parentData],[Xr.default.parentDataProperty,i.parentDataProperty],[Xr.default.rootData,Xr.default.rootData]];i.opts.dynamicRef&&p.push([Xr.default.dynamicAnchors,Xr.default.dynamicAnchors]);let f=(0,ge._)`${d}, ${r.object(...p)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${f})`:(0,ge._)`${a}(${f})`}ce.callValidateCode=Z1;var Y1=(0,ge._)`new RegExp`;function X1({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,ge._)`${s.code==="new RegExp"?Y1:(0,z1.useFunc)(t,s)}(${r}, ${n})`})}ce.usePattern=X1;function Q1(t){let{gen:e,data:r,keyword:n,it:s}=t,o=e.name("valid");if(s.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(o,!0),i(()=>e.break()),o;function i(a){let c=e.const("len",(0,ge._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:ku.Type.Num},o),e.if((0,ge.not)(o),a)})}}ce.validateArray=Q1;function ej(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,ku.alwaysValidSchema)(s,c))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,l)=>{let d=t.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(i,(0,ge._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,ge.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ce.validateUnion=ej});var my=j(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.validateKeywordUsage=lr.validSchemaType=lr.funcKeywordCode=lr.macroKeywordCode=void 0;var Ze=z(),zn=Pr(),tj=Rt(),rj=Ko();function nj(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),c=fy(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:Ze.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}lr.macroKeywordCode=nj;function sj(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:c}=t;ij(c,e);let l=!a&&e.compile?e.compile.call(c.self,o,i,c):e.validate,d=fy(n,s,l),p=n.let("valid");t.block$data(p,f),t.ok((r=e.valid)!==null&&r!==void 0?r:p);function f(){if(e.errors===!1)g(),e.modifying&&hy(t),y(()=>t.error());else{let w=e.async?h():m();e.modifying&&hy(t),y(()=>oj(t,w))}}function h(){let w=n.let("ruleErrs",null);return n.try(()=>g((0,Ze._)`await `),S=>n.assign(p,!1).if((0,Ze._)`${S} instanceof ${c.ValidationError}`,()=>n.assign(w,(0,Ze._)`${S}.errors`),()=>n.throw(S))),w}function m(){let w=(0,Ze._)`${d}.errors`;return n.assign(w,null),g(Ze.nil),w}function g(w=e.async?(0,Ze._)`await `:Ze.nil){let S=c.opts.passContext?zn.default.this:zn.default.self,$=!("compile"in e&&!a||e.schema===!1);n.assign(p,(0,Ze._)`${w}${(0,tj.callValidateCode)(t,d,S,$)}`,e.modifying)}function y(w){var S;n.if((0,Ze.not)((S=e.valid)!==null&&S!==void 0?S:p),w)}}lr.funcKeywordCode=sj;function hy(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ze._)`${n.parentData}[${n.parentDataProperty}]`))}function oj(t,e){let{gen:r}=t;r.if((0,Ze._)`Array.isArray(${e})`,()=>{r.assign(zn.default.vErrors,(0,Ze._)`${zn.default.vErrors} === null ? ${e} : ${zn.default.vErrors}.concat(${e})`).assign(zn.default.errors,(0,Ze._)`${zn.default.vErrors}.length`),(0,rj.extendErrors)(t)},()=>t.error())}function ij({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function fy(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ze.stringify)(r)})}function aj(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}lr.validSchemaType=aj;function cj({schema:t,opts:e,self:r,errSchemaPath:n},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");let i=s.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[o])){let c=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}lr.validateKeywordUsage=cj});var yy=j(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.extendSubschemaMode=Qr.extendSubschemaData=Qr.getSubschema=void 0;var dr=z(),gy=Q();function lj(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:o,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,dr._)`${t.schemaPath}${(0,dr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,dr._)`${t.schemaPath}${(0,dr.getProperty)(e)}${(0,dr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,gy.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||o===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}Qr.getSubschema=lj;function dj(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:o,propertyName:i}){if(s!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:l,dataPathArr:d,opts:p}=e,f=a.let("data",(0,dr._)`${e.data}${(0,dr.getProperty)(r)}`,!0);c(f),t.errorPath=(0,dr.str)`${l}${(0,gy.getErrorPath)(r,n,p.jsPropertySyntax)}`,t.parentDataProperty=(0,dr._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(s!==void 0){let l=s instanceof dr.Name?s:a.let("data",s,!0);c(l),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);function c(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}Qr.extendSubschemaData=dj;function uj(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:o}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}Qr.extendSubschemaMode=uj});var Ru=j((h4,by)=>{"use strict";by.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,s,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var i=o[s];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var vy=j((f4,wy)=>{"use strict";var en=wy.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};Fa(e,n,s,t,"",t)};en.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};en.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};en.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};en.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Fa(t,e,r,n,s,o,i,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,o,i,a,c,l);for(var d in n){var p=n[d];if(Array.isArray(p)){if(d in en.arrayKeywords)for(var f=0;f<p.length;f++)Fa(t,e,r,p[f],s+"/"+d+"/"+f,o,s,d,n,f)}else if(d in en.propsKeywords){if(p&&typeof p=="object")for(var h in p)Fa(t,e,r,p[h],s+"/"+d+"/"+pj(h),o,s,d,n,h)}else(d in en.keywords||t.allKeys&&!(d in en.skipKeywords))&&Fa(t,e,r,p,s+"/"+d,o,s,d,n)}r(n,s,o,i,a,c,l)}}function pj(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Yo=j(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.getSchemaRefs=dt.resolveUrl=dt.normalizeId=dt._getFullPath=dt.getFullPath=dt.inlineRef=void 0;var hj=Q(),fj=Ru(),mj=vy(),gj=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function yj(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Iu(t):e?_y(t)<=e:!1}dt.inlineRef=yj;var bj=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Iu(t){for(let e in t){if(bj.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Iu)||typeof r=="object"&&Iu(r))return!0}return!1}function _y(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!gj.has(r)&&(typeof t[r]=="object"&&(0,hj.eachItem)(t[r],n=>e+=_y(n)),e===1/0))return 1/0}return e}function Sy(t,e="",r){r!==!1&&(e=Cs(e));let n=t.parse(e);return xy(t,n)}dt.getFullPath=Sy;function xy(t,e){return t.serialize(e).split("#")[0]+"#"}dt._getFullPath=xy;var wj=/#\/?$/;function Cs(t){return t?t.replace(wj,""):""}dt.normalizeId=Cs;function vj(t,e,r){return r=Cs(r),t.resolve(e,r)}dt.resolveUrl=vj;var _j=/^[a-z_][-a-z0-9._]*$/i;function Sj(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=Cs(t[r]||e),o={"":s},i=Sy(n,s,!1),a={},c=new Set;return mj(t,{allKeys:!0},(p,f,h,m)=>{if(m===void 0)return;let g=i+f,y=o[m];typeof p[r]=="string"&&(y=w.call(this,p[r])),S.call(this,p.$anchor),S.call(this,p.$dynamicAnchor),o[f]=y;function w($){let k=this.opts.uriResolver.resolve;if($=Cs(y?k(y,$):$),c.has($))throw d($);c.add($);let I=this.refs[$];return typeof I=="string"&&(I=this.refs[I]),typeof I=="object"?l(p,I.schema,$):$!==Cs(g)&&($[0]==="#"?(l(p,a[$],$),a[$]=p):this.refs[$]=g),$}function S($){if(typeof $=="string"){if(!_j.test($))throw new Error(`invalid anchor "${$}"`);w.call(this,`#${$}`)}}}),a;function l(p,f,h){if(f!==void 0&&!fj(p,f))throw d(h)}function d(p){return new Error(`reference "${p}" resolves to more than one schema`)}}dt.getSchemaRefs=Sj});var ei=j(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.getData=tn.KeywordCxt=tn.validateFunctionCode=void 0;var Iy=ny(),ky=Zo(),Pu=vu(),qa=Zo(),xj=dy(),Qo=my(),ju=yy(),T=z(),q=Pr(),kj=Yo(),Or=Q(),Xo=Ko();function $j(t){if(Oy(t)&&(Ty(t),Py(t))){Ij(t);return}jy(t,()=>(0,Iy.topBoolOrEmptySchema)(t))}tn.validateFunctionCode=$j;function jy({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,T._)`${q.default.data}, ${q.default.valCxt}`,n.$async,()=>{t.code((0,T._)`"use strict"; ${$y(r,s)}`),Rj(t,s),t.code(o)}):t.func(e,(0,T._)`${q.default.data}, ${Ej(s)}`,n.$async,()=>t.code($y(r,s)).code(o))}function Ej(t){return(0,T._)`{${q.default.instancePath}="", ${q.default.parentData}, ${q.default.parentDataProperty}, ${q.default.rootData}=${q.default.data}${t.dynamicRef?(0,T._)`, ${q.default.dynamicAnchors}={}`:T.nil}}={}`}function Rj(t,e){t.if(q.default.valCxt,()=>{t.var(q.default.instancePath,(0,T._)`${q.default.valCxt}.${q.default.instancePath}`),t.var(q.default.parentData,(0,T._)`${q.default.valCxt}.${q.default.parentData}`),t.var(q.default.parentDataProperty,(0,T._)`${q.default.valCxt}.${q.default.parentDataProperty}`),t.var(q.default.rootData,(0,T._)`${q.default.valCxt}.${q.default.rootData}`),e.dynamicRef&&t.var(q.default.dynamicAnchors,(0,T._)`${q.default.valCxt}.${q.default.dynamicAnchors}`)},()=>{t.var(q.default.instancePath,(0,T._)`""`),t.var(q.default.parentData,(0,T._)`undefined`),t.var(q.default.parentDataProperty,(0,T._)`undefined`),t.var(q.default.rootData,q.default.data),e.dynamicRef&&t.var(q.default.dynamicAnchors,(0,T._)`{}`)})}function Ij(t){let{schema:e,opts:r,gen:n}=t;jy(t,()=>{r.$comment&&e.$comment&&Ay(t),Nj(t),n.let(q.default.vErrors,null),n.let(q.default.errors,0),r.unevaluated&&jj(t),Ny(t),Lj(t)})}function jj(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,T._)`${r}.evaluated`),e.if((0,T._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,T._)`${t.evaluated}.props`,(0,T._)`undefined`)),e.if((0,T._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,T._)`${t.evaluated}.items`,(0,T._)`undefined`))}function $y(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,T._)`/*# sourceURL=${r} */`:T.nil}function Pj(t,e){if(Oy(t)&&(Ty(t),Py(t))){Oj(t,e);return}(0,Iy.boolOrEmptySchema)(t,e)}function Py({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Oy(t){return typeof t.schema!="boolean"}function Oj(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&Ay(t),Aj(t),Cj(t);let o=n.const("_errs",q.default.errors);Ny(t,o),n.var(e,(0,T._)`${o} === ${q.default.errors}`)}function Ty(t){(0,Or.checkUnknownRules)(t),Tj(t)}function Ny(t,e){if(t.opts.jtd)return Ey(t,[],!1,e);let r=(0,ky.getSchemaTypes)(t.schema),n=(0,ky.coerceAndCheckDataType)(t,r);Ey(t,r,!n,e)}function Tj(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Or.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Nj(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Or.checkStrictMode)(t,"default is ignored in the schema root")}function Aj(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,kj.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Cj(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Ay({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,T._)`${q.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,T.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,T._)`${q.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function Lj(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,T._)`${q.default.errors} === 0`,()=>e.return(q.default.data),()=>e.throw((0,T._)`new ${s}(${q.default.vErrors})`)):(e.assign((0,T._)`${n}.errors`,q.default.vErrors),o.unevaluated&&Dj(t),e.return((0,T._)`${q.default.errors} === 0`))}function Dj({gen:t,evaluated:e,props:r,items:n}){r instanceof T.Name&&t.assign((0,T._)`${e}.props`,r),n instanceof T.Name&&t.assign((0,T._)`${e}.items`,n)}function Ey(t,e,r,n){let{gen:s,schema:o,data:i,allErrors:a,opts:c,self:l}=t,{RULES:d}=l;if(o.$ref&&(c.ignoreKeywordsWithRef||!(0,Or.schemaHasRulesButRef)(o,d))){s.block(()=>Ly(t,"$ref",d.all.$ref.definition));return}c.jtd||Mj(t,e),s.block(()=>{for(let f of d.rules)p(f);p(d.post)});function p(f){(0,Pu.shouldUseGroup)(o,f)&&(f.type?(s.if((0,qa.checkDataType)(f.type,i,c.strictNumbers)),Ry(t,f),e.length===1&&e[0]===f.type&&r&&(s.else(),(0,qa.reportTypeError)(t)),s.endIf()):Ry(t,f),a||s.if((0,T._)`${q.default.errors} === ${n||0}`))}}function Ry(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,xj.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,Pu.shouldUseRule)(n,o)&&Ly(t,o.keyword,o.definition,e.type)})}function Mj(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Fj(t,e),t.opts.allowUnionTypes||qj(t,e),Gj(t,t.dataTypes))}function Fj(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Cy(t.dataTypes,r)||Ou(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),Vj(t,e)}}function qj(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Ou(t,"use allowUnionTypes to allow union type keyword")}function Gj(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,Pu.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>Uj(e,i))&&Ou(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function Uj(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Cy(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Vj(t,e){let r=[];for(let n of t.dataTypes)Cy(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Ou(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Or.checkStrictMode)(t,e,t.opts.strictTypes)}var Ga=class{constructor(e,r,n){if((0,Qo.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Or.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Dy(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Qo.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",q.default.errors))}result(e,r,n){this.failResult((0,T.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,T.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,T._)`${r} !== undefined && (${(0,T.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Xo.reportExtraError:Xo.reportError)(this,this.def.error,r)}$dataError(){(0,Xo.reportError)(this,this.def.$dataError||Xo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Xo.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=T.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=T.nil,r=T.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,T.or)((0,T._)`${s} === undefined`,r)),e!==T.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==T.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,T.or)(i(),a());function i(){if(n.length){if(!(r instanceof T.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,T._)`${(0,qa.checkDataTypes)(c,r,o.opts.strictNumbers,qa.DataType.Wrong)}`}return T.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,T._)`!${c}(${r})`}return T.nil}}subschema(e,r){let n=(0,ju.getSubschema)(this.it,e);(0,ju.extendSubschemaData)(n,this.it,e),(0,ju.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return Pj(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Or.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Or.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,T.Name)),!0}};tn.KeywordCxt=Ga;function Ly(t,e,r,n){let s=new Ga(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,Qo.funcKeywordCode)(s,r):"macro"in r?(0,Qo.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,Qo.funcKeywordCode)(s,r)}var zj=/^\/(?:[^~]|~0|~1)*$/,Hj=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Dy(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return q.default.rootData;if(t[0]==="/"){if(!zj.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=q.default.rootData}else{let l=Hj.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+l[1];if(s=l[2],s==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(o=r[e-d],!s)return o}let i=o,a=s.split("/");for(let l of a)l&&(o=(0,T._)`${o}${(0,T.getProperty)((0,Or.unescapeJsonPointer)(l))}`,i=(0,T._)`${i} && ${o}`);return i;function c(l,d){return`Cannot access ${l} ${d} levels up, current level is ${e}`}}tn.getData=Dy});var Ua=j(Nu=>{"use strict";Object.defineProperty(Nu,"__esModule",{value:!0});var Tu=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Nu.default=Tu});var ti=j(Lu=>{"use strict";Object.defineProperty(Lu,"__esModule",{value:!0});var Au=Yo(),Cu=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Au.resolveUrl)(e,r,n),this.missingSchema=(0,Au.normalizeId)((0,Au.getFullPath)(e,this.missingRef))}};Lu.default=Cu});var za=j(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.resolveSchema=It.getCompilingSchema=It.resolveRef=It.compileSchema=It.SchemaEnv=void 0;var Ut=z(),Bj=Ua(),Hn=Pr(),Vt=Yo(),My=Q(),Jj=ei(),Ls=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Vt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};It.SchemaEnv=Ls;function Mu(t){let e=Fy.call(this,t);if(e)return e;let r=(0,Vt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new Ut.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:Bj.default,code:(0,Ut._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Hn.default.data,parentData:Hn.default.parentData,parentDataProperty:Hn.default.parentDataProperty,dataNames:[Hn.default.data],dataPathArr:[Ut.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Ut.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Ut.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ut._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,Jj.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();d=`${i.scopeRefs(Hn.default.scope)}return ${p}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let h=new Function(`${Hn.default.self}`,`${Hn.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=t.schema,h.schemaEnv=t,t.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:c,validateCode:p,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:g}=l;h.evaluated={props:m instanceof Ut.Name?void 0:m,items:g instanceof Ut.Name?void 0:g,dynamicProps:m instanceof Ut.Name,dynamicItems:g instanceof Ut.Name},h.source&&(h.source.evaluated=(0,Ut.stringify)(h.evaluated))}return t.validate=h,t}catch(p){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),p}finally{this._compilations.delete(t)}}It.compileSchema=Mu;function Wj(t,e,r){var n;r=(0,Vt.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=Yj.call(this,t,r);if(o===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(o=new Ls({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=Kj.call(this,o)}It.resolveRef=Wj;function Kj(t){return(0,Vt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Mu.call(this,t)}function Fy(t){for(let e of this._compilations)if(Zj(e,t))return e}It.getCompilingSchema=Fy;function Zj(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Yj(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Va.call(this,t,e)}function Va(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Vt._getFullPath)(this.opts.uriResolver,r),s=(0,Vt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return Du.call(this,r,t);let o=(0,Vt.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=Va.call(this,t,i);return typeof a?.schema!="object"?void 0:Du.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Mu.call(this,i),o===(0,Vt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(s=(0,Vt.resolveUrl)(this.opts.uriResolver,s,l)),new Ls({schema:a,schemaId:c,root:t,baseId:s})}return Du.call(this,r,i)}}It.resolveSchema=Va;var Xj=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Du(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,My.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!Xj.has(a)&&l&&(e=(0,Vt.resolveUrl)(this.opts.uriResolver,e,l))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,My.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Vt.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=Va.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new Ls({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var qy=j((v4,Qj)=>{Qj.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var zu=j((_4,Wy)=>{"use strict";var eP=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),qu=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),tP=RegExp.prototype.test.bind(/^\d*$/u),Bn=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Gu=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Uy=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Uu=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),rP=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),ut=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)ut[e]="%"+t[e>>4]+t[e&15]}function Be(t){return t<2048?ut[192|t>>6]+ut[128|t&63]:t<65536?ut[224|t>>12]+ut[128|t>>6&63]+ut[128|t&63]:ut[240|t>>18]+ut[128|t>>12&63]+ut[128|t>>6&63]+ut[128|t&63]}function nP(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var sP=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),oP=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),iP=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),aP=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function cP(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!iP(t[e])){if(t[e]==="%"&&e+2<t.length&&Bn(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function Gy(t){let e=-1,r=0,n=-1,s=0;for(let a=0;a<t.length;a++)t[a]==="0"?(n===-1&&(n=a),s++,s>r&&(r=s,e=n)):(n=-1,s=0);if(r<2)return t.join(":");let o=t.slice(0,e).join(":"),i=t.slice(e+r).join(":");return o+"::"+i}function lP(t){let e=t.indexOf("::");if(e!==-1&&t.indexOf("::",e+1)!==-1)return;let r=e===-1?t.split(":"):t.slice(0,e).split(":"),n=e===-1?[]:t.slice(e+2).split(":");e!==-1&&(r.length===1&&r[0]===""&&(r.length=0),n.length===1&&n[0]===""&&(n.length=0));let s=r.concat(n),o=0;for(let a=0;a<s.length;a++){let c=s[a];if(c==="")return;if(c.indexOf(".")!==-1){if(a!==s.length-1||e!==-1&&n.length===0||!qu(c))return;o+=2;continue}if(!sP(c))return;s[a]=parseInt(c,16).toString(16),o++}if(e===-1)return o!==8?void 0:Gy(s);if(o>=8)return;let i=s.slice(0,r.length);for(let a=o;a<8;a++)i.push("0");for(let a=r.length;a<s.length;a++)i.push(s[a]);return Gy(i)}function Fu(t){let e=t[0]==="["&&t[t.length-1]==="]";if((t[0]==="["||t[t.length-1]==="]")&&!e)return{host:t,isIPV6:!1,error:!0};let n=e?t.slice(1,-1):t;if(e&&oP(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(dP(n,":")<2)return{host:t,isIPV6:!1,error:e};let s="",o=n.indexOf("%");if(o!==-1){let a=n.slice(o,o+3).toLowerCase()==="%25"?3:1;if(s=n.slice(o+a),!cP(s))return{host:t,isIPV6:!1,error:!0};n=n.slice(0,o)}let i=lP(n);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(s?"%"+s:""),escapedHost:i+(s?"%25"+s:""),isIPV6:!0}}function dP(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function Vy(t){let e=t,r=[],n=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(s===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(s===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function uP(t){if(t===""||t[0]==="/")return Vy(t);let e=t.split("/"),r=e.length-1,n=[],s=!1;for(let o=0;o<=r;o++){let i=e[o];i==="."||i===".."?(i===".."&&(n.length!==0&&n[n.length-1]!==".."?n.pop():n.push("..")),s=o===r):n.push(i)}return s&&n[n.length-1]!==".."&&n.push(""),(n.length===0||n[0]===""||n[0].includes(":"))&&n.unshift("."),n.join("/")}var pP={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},hP=/[@/?#:]/g,fP=/[@/?#]/g;function zy(t,e){let r=e?fP:hP;return r.lastIndex=0,t.replace(r,n=>pP[n])}function Hy(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let s=t.slice(n+1,n+3);if(Bn(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));e&&Gu(i)?r+=i:r+="%"+o,n+=2;continue}}r+=t[n]}return r}function mP(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="%"&&r+2<t.length){let s=t.slice(r+1,r+3);if(Bn(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));i!=="."&&Gu(i)?e+=i:e+="%"+o,r+=2;continue}}if(Uy(n))e+=n;else{let s=t.charCodeAt(r);if(s<128)e+=Jy(s)?n:ut[s];else if(s<55296||s>57343)e+=Be(s);else if(s<=56319&&r+1<t.length){let o=t.charCodeAt(r+1);o>=56320&&o<=57343?(e+=Be(65536+(s-55296<<10)+(o-56320)),r++):e+=Be(65533)}else e+=Be(65533)}}return e}function gP(t,e=!1){let r="",n=e&&t[0]!=="/";for(let s=0;s<t.length;s++){let o=t[s];if(o==="%"&&s+2<t.length){let i=t.slice(s+1,s+3);if(Bn(i)){r+="%"+i.toUpperCase(),s+=2;continue}}if(o==="/"&&(n=!1),Uy(o)&&(o!==":"||!n))r+=o;else{let i=t.charCodeAt(s);if(i<128)r+=ut[i];else if(i<55296||i>57343)r+=Be(i);else if(i<=56319&&s+1<t.length){let a=t.charCodeAt(s+1);a>=56320&&a<=57343?(r+=Be(65536+(i-55296<<10)+(a-56320)),s++):r+=Be(65533)}else r+=Be(65533)}}return r}function Vu(t,e){let r="";for(let n=0;n<t.length;n++){let s=t[n];if(s==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(Bn(o)){r+="%"+o.toUpperCase(),n+=2;continue}}if(e(s))r+=s;else{let o=t.charCodeAt(n);if(o<128)r+=ut[o];else if(o<55296||o>57343)r+=Be(o);else if(o<=56319&&n+1<t.length){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(r+=Be(65536+(o-55296<<10)+(i-56320)),n++):r+=Be(65533)}else r+=Be(65533)}}return r}function By(t){return Vu(t,rP)}function yP(t){return Vu(t,Uu)}function bP(t){return Vu(t,Uu)}function Jy(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===42||t===43||t===45||t===46||t===47||t===64||t===95}function wP(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="%"&&r+2<t.length){let s=t.slice(r+1,r+3);if(Bn(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));Gu(i)?e+=i:e+="%"+o,r+=2;continue}}if(Uu(n))e+=n;else{let s=t.charCodeAt(r);if(s<128)e+=Jy(s)?n:ut[s];else if(s<55296||s>57343)e+=Be(s);else if(s<=56319&&r+1<t.length){let o=t.charCodeAt(r+1);o>=56320&&o<=57343?(e+=Be(65536+(s-55296<<10)+(o-56320)),r++):e+=Be(65533)}else e+=Be(65533)}}return e}function vP(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(Bn(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function _P(t){let e=[];if(t.userinfo!==void 0&&(e.push(By(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!qu(r)){let n=Fu(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=Hy(r,!0),n=Fu(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=zy(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!tP(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}Wy.exports={nonSimpleDomain:aP,recomposeAuthority:_P,reescapeHostDelimiters:zy,normalizePercentEncoding:Hy,normalizePathEncoding:mP,serializePathEncoding:gP,normalizeQueryFragmentEncoding:wP,encodeUserinfo:By,encodeQuery:yP,encodeFragment:bP,escapePreservingEscapes:vP,removeDotSegments:Vy,removeDotSegmentsRelative:uP,isIPv4:qu,isUUID:eP,normalizeIPv6:Fu,stringArrayToHexStripped:nP}});var Qy=j((S4,Xy)=>{"use strict";var{isUUID:SP}=zu(),xP=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,kP=["http","https","ws","wss","urn","urn:uuid"];function $P(t){return kP.indexOf(t)!==-1}function Hu(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Ky(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Zy(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function EP(t){return t.secure=Hu(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function RP(t){if((t.port===(Hu(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let e=t.resourceName.indexOf("?"),r=e===-1?t.resourceName:t.resourceName.slice(0,e);t.path=r&&r!=="/"?r:void 0,t.query=e===-1?void 0:t.resourceName.slice(e+1),t.resourceName=void 0}return t.fragment=void 0,t}function IP(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(xP);if(r&&r[0]===t.path){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let s=`${n}:${e.nid||t.nid}`,o=Bu(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function jP(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),s=`${r}:${e.nid||n}`,o=Bu(s);o&&(t=o.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function PP(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!SP(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function OP(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Yy={scheme:"http",domainHost:!0,parse:Ky,serialize:Zy},TP={scheme:"https",domainHost:Yy.domainHost,parse:Ky,serialize:Zy},Ha={scheme:"ws",domainHost:!0,parse:EP,serialize:RP},NP={scheme:"wss",domainHost:Ha.domainHost,parse:Ha.parse,serialize:Ha.serialize},AP={scheme:"urn",parse:IP,serialize:jP,skipNormalize:!0},CP={scheme:"urn:uuid",parse:PP,serialize:OP,skipNormalize:!0},Ba={http:Yy,https:TP,ws:Ha,wss:NP,urn:AP,"urn:uuid":CP};Object.setPrototypeOf(Ba,null);function Bu(t){return t&&(Ba[t]||Ba[t.toLowerCase()])||void 0}Xy.exports={wsIsSecure:Hu,SCHEMES:Ba,isValidSchemeName:$P,getSchemeHandler:Bu}});var fb=j((x4,Ya)=>{"use strict";var{normalizeIPv6:sb,removeDotSegments:ni,removeDotSegmentsRelative:ob,recomposeAuthority:LP,normalizePercentEncoding:Ju,normalizePathEncoding:DP,serializePathEncoding:eb,normalizeQueryFragmentEncoding:tb,encodeQuery:MP,encodeFragment:FP,reescapeHostDelimiters:qP,isIPv4:ib,nonSimpleDomain:GP}=zu(),{SCHEMES:ab,getSchemeHandler:Wu}=Qy(),cb=/^[A-Za-z][A-Za-z0-9+.-]*$/u,lb="URI scheme is malformed.",Ja="URI host is malformed.",UP=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function rb(t){let e=String(t);if(!cb.test(e))throw new TypeError(lb);return e}function VP(t,e){return typeof t=="string"?t=XP(t,e):typeof t=="object"&&(t=Ka(Jn(t,e),e)),t}function zP(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:s,malformedAuthorityOrPort:o,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:l}=Wa(t,n),{parsed:d,malformedAuthorityOrPort:p,malformedPercentEncoding:f,malformedSchemeSpecific:h,malformedHost:m,malformedScheme:g}=Wa(e,n);if(o||p||i||f||a||h||c||m||l||g)throw new Error(s.error||d.error||"URI is malformed.");let y=db(s,d,n,!0),w=Wu(r&&r.scheme||y.scheme),S=y.host,$=S!==void 0&&S!==""&&(ib(S)||sb(S).isIPV6);if(pb(y,r||{},w,$))throw new Error(Ja);ub(y,r||{},w,$);let k=S&&S.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(S);if(y.error&&!k)throw new Error(y.error);return n.skipEscape=!0,Jn(y,n)}function db(t,e,r,n){let s={};if(n||(t=Ka(Jn(t,r),r),e=Ka(Jn(e,r),r)),r=r||{},!r.tolerant&&e.scheme)s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=ni(e.path||""),s.query=e.query;else{if(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=ni(e.path||""),s.query=e.query;else{if(!e.path)s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query;else{if(e.path[0]==="/")s.path=ni(e.path);else{let o=t.userinfo!==void 0||t.host!==void 0||t.port!==void 0;o&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=t.scheme===void 0&&!o&&s.path[0]!=="/"?ob(s.path):ni(s.path)}s.query=e.query}s.userinfo=t.userinfo,s.host=t.host,s.port=t.port}s.scheme=t.scheme}return s.fragment=e.fragment,s}function HP(t,e,r){let n=nb(t,r),s=nb(e,r);return n!==void 0&&s!==void 0&&n===s}function Jn(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),s=[];r.scheme&&(r.scheme=rb(r.scheme));let o=Wu(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n);let i=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,a=(r.scheme===void 0||n.reference==="suffix")&&!i,c=!n.skipEscape&&a;r.path!==void 0&&(n.skipEscape?r.path=Ju(r.path):r.path=eb(r.path,c)),n.reference!=="suffix"&&r.scheme&&(r.scheme=rb(r.scheme),s.push(r.scheme,":"));let l=LP(r);if(l!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(l),r.path&&r.path[0]!=="/"&&s.push("/")),r.path!==void 0){let d=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(d=a&&d[0]!=="/"?ob(d):ni(d)),a&&(d=eb(d,!0)),l===void 0&&d[0]==="/"&&d[1]==="/"&&(d="/%2F"+d.slice(2)),s.push(d)}return r.query!==void 0&&s.push("?",MP(r.query)),r.fragment!==void 0&&s.push("#",FP(r.fragment)),s.join("")}var BP=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,JP=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,WP=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function KP(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function ri(t){if(t===void 0)return!1;let e=t.indexOf("%");for(;e!==-1;){if(e+2>=t.length||!/^[\da-f]{2}$/iu.test(t.slice(e+1,e+3)))return!0;e=t.indexOf("%",e+3)}return!1}function Za(t){return t[0]==="["&&t[t.length-1]==="]"}function ZP(t){let e=t[4];return ri(t[3])||e!==void 0&&!Za(e)&&ri(e)||ri(t[6])||ri(t[7])||ri(t[8])}function ub(t,e,r,n){if(pb(t,e,r,n))return t.error=t.error||Ja,!0;if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!Za(t.host)&&(e.domainHost||r&&r.domainHost)&&n===!1&&GP(t.host)){let s;try{s=new URL("http://"+t.host)}catch(o){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+o,!0}if(!YP(s))return t.error=t.error||Ja,!0;t.host=s.hostname}return!1}function pb(t,e,r,n){return!!(t.host&&n===!1&&!Za(t.host)&&(e.domainHost||r&&r.domainHost)&&UP.test(t.host))}function YP(t){return t.username===""&&t.password===""&&t.port===""&&t.pathname==="/"&&t.search===""&&t.hash===""&&t.hostname!==""}function Wa(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},s=!1,o=!1,i=!1,a=!1,c=!1,l=!1,d=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let p=t.match(JP);p!==null&&p[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",s=!0);let f=t.match(WP);if(f!==null){let m=f[1],g=m.replace(/[\t\n\r]/g,"");g.length>=2&&(g.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",s=!0):m.length!==g.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",s=!0))}let h=t.match(BP);if(h){n.scheme=h[1],n.userinfo=h[3],n.host=h[4],n.port=parseInt(h[5],10),n.path=h[6]||"",n.query=h[7],n.fragment=h[8],n.scheme!==void 0&&(cb.test(n.scheme)?n.scheme=n.scheme.toLowerCase():(n.error=n.error||lb,l=!0)),o=ZP(h),o&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=h[5]);let m=KP(n,h);if(m!==void 0&&(n.error=n.error||m,s=!0),n.host)if(ib(n.host)===!1){let w=Za(n.host),S=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,$=sb(n.host);d=$.isIPV6||$.isIPVFuture===!0,c=S&&(!w||$.error===!0),n.host=d?$.host:$.host.toLowerCase(),c&&(n.error=n.error||Ja,s=!0)}else d=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let g=Wu(r.scheme||n.scheme);if(c||(a=ub(n,r,g,d)),t.indexOf("%")!==-1&&n.host!==void 0&&!c){let y=d?n.host:Ju(n.host,!0);d||(y=Ju(y.toLowerCase())),n.host=d||r.scheme!=="null"?qP(y,d):y}(!g||g&&!g.skipNormalize)&&(n.path&&(n.path=DP(n.path)),n.query&&(n.query=tb(n.query)),n.fragment&&(n.fragment=tb(n.fragment))),g&&g.parse&&(g.parse(n,r),g===ab.urn&&n.nid===void 0&&(i=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:s,malformedPercentEncoding:o,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:l}}function Ka(t,e){return Wa(t,e).parsed}function XP(t,e){return hb(t,e).normalized}function hb(t,e){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:i,malformedScheme:a}=Wa(t,e);return{normalized:n||s||o||i||a?t:Jn(r,e),malformedAuthorityOrPort:n,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:i,malformedScheme:a}}function nb(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:Jn(t,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:s,malformedPercentEncoding:o,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=hb(r,e);return s||o||i||a||c?void 0:n}var Ku={SCHEMES:ab,normalize:VP,resolve:zP,resolveComponent:db,equal:HP,serialize:Jn,parse:Ka};Ya.exports=Ku;Ya.exports.default=Ku;Ya.exports.fastUri=Ku});var gb=j(Zu=>{"use strict";Object.defineProperty(Zu,"__esModule",{value:!0});var mb=fb();mb.code='require("ajv/dist/runtime/uri").default';Zu.default=mb});var kb=j(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.CodeGen=qe.Name=qe.nil=qe.stringify=qe.str=qe._=qe.KeywordCxt=void 0;var QP=ei();Object.defineProperty(qe,"KeywordCxt",{enumerable:!0,get:function(){return QP.KeywordCxt}});var Ds=z();Object.defineProperty(qe,"_",{enumerable:!0,get:function(){return Ds._}});Object.defineProperty(qe,"str",{enumerable:!0,get:function(){return Ds.str}});Object.defineProperty(qe,"stringify",{enumerable:!0,get:function(){return Ds.stringify}});Object.defineProperty(qe,"nil",{enumerable:!0,get:function(){return Ds.nil}});Object.defineProperty(qe,"Name",{enumerable:!0,get:function(){return Ds.Name}});Object.defineProperty(qe,"CodeGen",{enumerable:!0,get:function(){return Ds.CodeGen}});var eO=Ua(),_b=ti(),tO=wu(),si=za(),rO=z(),oi=Yo(),Xa=Zo(),Xu=Q(),yb=qy(),nO=gb(),Sb=(t,e)=>new RegExp(t,e);Sb.code="new RegExp";var sO=["removeAdditional","useDefaults","coerceTypes"],oO=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),iO={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},aO={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},bb=200;function cO(t){var e,r,n,s,o,i,a,c,l,d,p,f,h,m,g,y,w,S,$,k,I,C,ne,xe,ue;let b=t.strict,H=(e=t.code)===null||e===void 0?void 0:e.optimize,se=H===!0||H===void 0?1:H||0,wt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Sb,_n=(s=t.uriResolver)!==null&&s!==void 0?s:nO.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:b)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:b)!==null&&c!==void 0?c:!0,strictTypes:(d=(l=t.strictTypes)!==null&&l!==void 0?l:b)!==null&&d!==void 0?d:"log",strictTuples:(f=(p=t.strictTuples)!==null&&p!==void 0?p:b)!==null&&f!==void 0?f:"log",strictRequired:(m=(h=t.strictRequired)!==null&&h!==void 0?h:b)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:se,regExp:wt}:{optimize:se,regExp:wt},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:bb,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:bb,meta:(w=t.meta)!==null&&w!==void 0?w:!0,messages:(S=t.messages)!==null&&S!==void 0?S:!0,inlineRefs:($=t.inlineRefs)!==null&&$!==void 0?$:!0,schemaId:(k=t.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(I=t.addUsedSchema)!==null&&I!==void 0?I:!0,validateSchema:(C=t.validateSchema)!==null&&C!==void 0?C:!0,validateFormats:(ne=t.validateFormats)!==null&&ne!==void 0?ne:!0,unicodeRegExp:(xe=t.unicodeRegExp)!==null&&xe!==void 0?xe:!0,int32range:(ue=t.int32range)!==null&&ue!==void 0?ue:!0,uriResolver:_n}}var ii=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...cO(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new rO.ValueScope({scope:{},prefixes:oO,es5:r,lines:n}),this.logger=fO(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,tO.getRules)(),wb.call(this,iO,e,"NOT SUPPORTED"),wb.call(this,aO,e,"DEPRECATED","warn"),this._metaOpts=pO.call(this),e.formats&&dO.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&uO.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),lO.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=yb;n==="id"&&(s={...yb},s.id=s.$id,delete s.$id),r&&e&&this.addMetaSchema(s,s[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let s=n(r);return"$async"in n||(this.errors=n.errors),s}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return s.call(this,e,r);async function s(d,p){await o.call(this,d.$schema);let f=this._addSchema(d,p);return f.validate||i.call(this,f)}async function o(d){d&&!this.getSchema(d)&&await s.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(p){if(!(p instanceof _b.default))throw p;return a.call(this,p),await c.call(this,p.missingSchema),i.call(this,d)}}function a({missingSchema:d,missingRef:p}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${p} cannot be resolved`)}async function c(d){let p=await l.call(this,d);this.refs[d]||await o.call(this,p.$schema),this.refs[d]||this.addSchema(p,d,r)}async function l(d){let p=this._loading[d];if(p)return p;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,s);return this}let o;if(typeof e=="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw new Error(`schema ${i} must be string`)}return r=(0,oi.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,s,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let s=this.validate(n,e);if(!s&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return s}getSchema(e){let r;for(;typeof(r=vb.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new si.SchemaEnv({schema:{},schemaId:n});if(r=si.resolveSchema.call(this,s,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=vb.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,oi.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(gO.call(this,n,r),!r)return(0,Xu.eachItem)(n,o=>Yu.call(this,o)),this;bO.call(this,r);let s={...r,type:(0,Xa.getJSONTypes)(r.type),schemaType:(0,Xa.getJSONTypes)(r.schemaType)};return(0,Xu.eachItem)(n,s.type.length===0?o=>Yu.call(this,o,s):o=>s.type.forEach(i=>Yu.call(this,o,s,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let s=n.rules.findIndex(o=>o.keyword===e);s>=0&&n.rules.splice(s,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,o)=>s+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of r){let o=s.split("/").slice(1),i=e;for(let a of o)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,d=i[a];l&&d&&(i[a]=xb(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let s=e[n];(!r||r.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,r,n,s=this.opts.validateSchema,o=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,oi.normalizeId)(i||n);let l=oi.getSchemaRefs.call(this,e,n);return c=new si.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),s&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):si.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{si.compileSchema.call(this,e)}finally{this.opts=r}}};ii.ValidationError=eO.default;ii.MissingRefError=_b.default;qe.default=ii;function wb(t,e,r,n="error"){for(let s in t){let o=s;o in e&&this.logger[n](`${r}: option ${s}. ${t[o]}`)}}function vb(t){return t=(0,oi.normalizeId)(t),this.schemas[t]||this.refs[t]}function lO(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function dO(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function uO(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function pO(){let t={...this.opts};for(let e of sO)delete t[e];return t}var hO={log(){},warn(){},error(){}};function fO(t){if(t===!1)return hO;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var mO=/^[a-z_$][a-z0-9_$:-]*$/i;function gO(t,e){let{RULES:r}=this;if((0,Xu.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!mO.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Yu(t,e,r){var n;let s=e?.post;if(r&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Xa.getJSONTypes)(e.type),schemaType:(0,Xa.getJSONTypes)(e.schemaType)}};e.before?yO.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function yO(t,e,r){let n=t.rules.findIndex(s=>s.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function bO(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=xb(e)),t.validateSchema=this.compile(e,!0))}var wO={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function xb(t){return{anyOf:[t,wO]}}});var $b=j(Qu=>{"use strict";Object.defineProperty(Qu,"__esModule",{value:!0});var vO={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Qu.default=vO});var jb=j(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.callRef=Wn.getValidate=void 0;var _O=ti(),Eb=Rt(),pt=z(),Ms=Pr(),Rb=za(),Qa=Q(),SO={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:c}=n,{root:l}=o;if((r==="#"||r==="#/")&&s===l.baseId)return p();let d=Rb.resolveRef.call(c,l,s,r);if(d===void 0)throw new _O.default(n.opts.uriResolver,s,r);if(d instanceof Rb.SchemaEnv)return f(d);return h(d);function p(){if(o===l)return ec(t,i,o,o.$async);let m=e.scopeValue("root",{ref:l});return ec(t,(0,pt._)`${m}.validate`,l,l.$async)}function f(m){let g=Ib(t,m);ec(t,g,m,m.$async)}function h(m){let g=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,pt.stringify)(m)}:{ref:m}),y=e.name("valid"),w=t.subschema({schema:m,dataTypes:[],schemaPath:pt.nil,topSchemaRef:g,errSchemaPath:r},y);t.mergeEvaluated(w),t.ok(y)}}};function Ib(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,pt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Wn.getValidate=Ib;function ec(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:c}=o,l=c.passContext?Ms.default.this:pt.nil;n?d():p();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=s.let("valid");s.try(()=>{s.code((0,pt._)`await ${(0,Eb.callValidateCode)(t,e,l)}`),h(e),i||s.assign(m,!0)},g=>{s.if((0,pt._)`!(${g} instanceof ${o.ValidationError})`,()=>s.throw(g)),f(g),i||s.assign(m,!1)}),t.ok(m)}function p(){t.result((0,Eb.callValidateCode)(t,e,l),()=>h(e),()=>f(e))}function f(m){let g=(0,pt._)`${m}.errors`;s.assign(Ms.default.vErrors,(0,pt._)`${Ms.default.vErrors} === null ? ${g} : ${Ms.default.vErrors}.concat(${g})`),s.assign(Ms.default.errors,(0,pt._)`${Ms.default.vErrors}.length`)}function h(m){var g;if(!o.opts.unevaluated)return;let y=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(o.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(o.props=Qa.mergeEvaluated.props(s,y.props,o.props));else{let w=s.var("props",(0,pt._)`${m}.evaluated.props`);o.props=Qa.mergeEvaluated.props(s,w,o.props,pt.Name)}if(o.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(o.items=Qa.mergeEvaluated.items(s,y.items,o.items));else{let w=s.var("items",(0,pt._)`${m}.evaluated.items`);o.items=Qa.mergeEvaluated.items(s,w,o.items,pt.Name)}}}Wn.callRef=ec;Wn.default=SO});var Pb=j(ep=>{"use strict";Object.defineProperty(ep,"__esModule",{value:!0});var xO=$b(),kO=jb(),$O=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",xO.default,kO.default];ep.default=$O});var Ob=j(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});var tc=z(),rn=tc.operators,rc={maximum:{okStr:"<=",ok:rn.LTE,fail:rn.GT},minimum:{okStr:">=",ok:rn.GTE,fail:rn.LT},exclusiveMaximum:{okStr:"<",ok:rn.LT,fail:rn.GTE},exclusiveMinimum:{okStr:">",ok:rn.GT,fail:rn.LTE}},EO={message:({keyword:t,schemaCode:e})=>(0,tc.str)`must be ${rc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,tc._)`{comparison: ${rc[t].okStr}, limit: ${e}}`},RO={keyword:Object.keys(rc),type:"number",schemaType:"number",$data:!0,error:EO,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,tc._)`${r} ${rc[e].fail} ${n} || isNaN(${r})`)}};tp.default=RO});var Tb=j(rp=>{"use strict";Object.defineProperty(rp,"__esModule",{value:!0});var ai=z(),IO={message:({schemaCode:t})=>(0,ai.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ai._)`{multipleOf: ${t}}`},jO={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:IO,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,ai._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,ai._)`${i} !== parseInt(${i})`;t.fail$data((0,ai._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};rp.default=jO});var Ab=j(np=>{"use strict";Object.defineProperty(np,"__esModule",{value:!0});function Nb(t){let e=t.length,r=0,n=0,s;for(;n<e;)r++,s=t.charCodeAt(n++),s>=55296&&s<=56319&&n<e&&(s=t.charCodeAt(n),(s&64512)===56320&&n++);return r}np.default=Nb;Nb.code='require("ajv/dist/runtime/ucs2length").default'});var Cb=j(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});var Kn=z(),PO=Q(),OO=Ab(),TO={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Kn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Kn._)`{limit: ${t}}`},NO={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:TO,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?Kn.operators.GT:Kn.operators.LT,i=s.opts.unicode===!1?(0,Kn._)`${r}.length`:(0,Kn._)`${(0,PO.useFunc)(t.gen,OO.default)}(${r})`;t.fail$data((0,Kn._)`${i} ${o} ${n}`)}};sp.default=NO});var Lb=j(op=>{"use strict";Object.defineProperty(op,"__esModule",{value:!0});var AO=Rt(),CO=Q(),Fs=z(),LO={message:({schemaCode:t})=>(0,Fs.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Fs._)`{pattern: ${t}}`},DO={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:LO,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,l=c.code==="new RegExp"?(0,Fs._)`new RegExp`:(0,CO.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,Fs._)`${l}(${o}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,Fs._)`!${d}`)}else{let c=(0,AO.usePattern)(t,s);t.fail$data((0,Fs._)`!${c}.test(${r})`)}}};op.default=DO});var Db=j(ip=>{"use strict";Object.defineProperty(ip,"__esModule",{value:!0});var ci=z(),MO={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,ci.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,ci._)`{limit: ${t}}`},FO={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:MO,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?ci.operators.GT:ci.operators.LT;t.fail$data((0,ci._)`Object.keys(${r}).length ${s} ${n}`)}};ip.default=FO});var Mb=j(ap=>{"use strict";Object.defineProperty(ap,"__esModule",{value:!0});var li=Rt(),di=z(),qO=Q(),GO={message:({params:{missingProperty:t}})=>(0,di.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,di._)`{missingProperty: ${t}}`},UO={keyword:"required",type:"object",schemaType:"array",$data:!0,error:GO,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:o,it:i}=t,{opts:a}=i;if(!o&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?l():d(),a.strictRequired){let h=t.parentSchema.properties,{definedProperties:m}=t.it;for(let g of r)if(h?.[g]===void 0&&!m.has(g)){let y=i.schemaEnv.baseId+i.errSchemaPath,w=`required property "${g}" is not defined at "${y}" (strictRequired)`;(0,qO.checkStrictMode)(i,w,i.opts.strictRequired)}}function l(){if(c||o)t.block$data(di.nil,p);else for(let h of r)(0,li.checkReportMissingProp)(t,h)}function d(){let h=e.let("missing");if(c||o){let m=e.let("valid",!0);t.block$data(m,()=>f(h,m)),t.ok(m)}else e.if((0,li.checkMissingProp)(t,r,h)),(0,li.reportMissingProp)(t,h),e.else()}function p(){e.forOf("prop",n,h=>{t.setParams({missingProperty:h}),e.if((0,li.noPropertyInData)(e,s,h,a.ownProperties),()=>t.error())})}function f(h,m){t.setParams({missingProperty:h}),e.forOf(h,n,()=>{e.assign(m,(0,li.propertyInData)(e,s,h,a.ownProperties)),e.if((0,di.not)(m),()=>{t.error(),e.break()})},di.nil)}}};ap.default=UO});var Fb=j(cp=>{"use strict";Object.defineProperty(cp,"__esModule",{value:!0});var ui=z(),VO={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,ui.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,ui._)`{limit: ${t}}`},zO={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:VO,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?ui.operators.GT:ui.operators.LT;t.fail$data((0,ui._)`${r}.length ${s} ${n}`)}};cp.default=zO});var nc=j(lp=>{"use strict";Object.defineProperty(lp,"__esModule",{value:!0});var qb=Ru();qb.code='require("ajv/dist/runtime/equal").default';lp.default=qb});var Gb=j(up=>{"use strict";Object.defineProperty(up,"__esModule",{value:!0});var dp=Zo(),Ge=z(),HO=Q(),BO=nc(),JO={message:({params:{i:t,j:e}})=>(0,Ge.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ge._)`{i: ${t}, j: ${e}}`},WO={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:JO,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:o,schemaCode:i,it:a}=t;if(!n&&!s)return;let c=e.let("valid"),l=o.items?(0,dp.getSchemaTypes)(o.items):[];t.block$data(c,d,(0,Ge._)`${i} === false`),t.ok(c);function d(){let m=e.let("i",(0,Ge._)`${r}.length`),g=e.let("j");t.setParams({i:m,j:g}),e.assign(c,!0),e.if((0,Ge._)`${m} > 1`,()=>(p()?f:h)(m,g))}function p(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function f(m,g){let y=e.name("item"),w=(0,dp.checkDataTypes)(l,y,a.opts.strictNumbers,dp.DataType.Wrong),S=e.const("indices",(0,Ge._)`{}`);e.for((0,Ge._)`;${m}--;`,()=>{e.let(y,(0,Ge._)`${r}[${m}]`),e.if(w,(0,Ge._)`continue`),l.length>1&&e.if((0,Ge._)`typeof ${y} == "string"`,(0,Ge._)`${y} += "_"`),e.if((0,Ge._)`typeof ${S}[${y}] == "number"`,()=>{e.assign(g,(0,Ge._)`${S}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Ge._)`${S}[${y}] = ${m}`)})}function h(m,g){let y=(0,HO.useFunc)(e,BO.default),w=e.name("outer");e.label(w).for((0,Ge._)`;${m}--;`,()=>e.for((0,Ge._)`${g} = ${m}; ${g}--;`,()=>e.if((0,Ge._)`${y}(${r}[${m}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(w)})))}}};up.default=WO});var Ub=j(hp=>{"use strict";Object.defineProperty(hp,"__esModule",{value:!0});var pp=z(),KO=Q(),ZO=nc(),YO={message:"must be equal to constant",params:({schemaCode:t})=>(0,pp._)`{allowedValue: ${t}}`},XO={keyword:"const",$data:!0,error:YO,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,pp._)`!${(0,KO.useFunc)(e,ZO.default)}(${r}, ${s})`):t.fail((0,pp._)`${o} !== ${r}`)}};hp.default=XO});var Vb=j(fp=>{"use strict";Object.defineProperty(fp,"__esModule",{value:!0});var pi=z(),QO=Q(),eT=nc(),tT={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,pi._)`{allowedValues: ${t}}`},rT={keyword:"enum",schemaType:"array",$data:!0,error:tT,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=i.opts.loopEnum,c,l=()=>c??(c=(0,QO.useFunc)(e,eT.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,p);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let h=e.const("vSchema",o);d=(0,pi.or)(...s.map((m,g)=>f(h,g)))}t.pass(d);function p(){e.assign(d,!1),e.forOf("v",o,h=>e.if((0,pi._)`${l()}(${r}, ${h})`,()=>e.assign(d,!0).break()))}function f(h,m){let g=s[m];return typeof g=="object"&&g!==null?(0,pi._)`${l()}(${r}, ${h}[${m}])`:(0,pi._)`${r} === ${g}`}}};fp.default=rT});var zb=j(mp=>{"use strict";Object.defineProperty(mp,"__esModule",{value:!0});var nT=Ob(),sT=Tb(),oT=Cb(),iT=Lb(),aT=Db(),cT=Mb(),lT=Fb(),dT=Gb(),uT=Ub(),pT=Vb(),hT=[nT.default,sT.default,oT.default,iT.default,aT.default,cT.default,lT.default,dT.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},uT.default,pT.default];mp.default=hT});var yp=j(hi=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});hi.validateAdditionalItems=void 0;var Zn=z(),gp=Q(),fT={message:({params:{len:t}})=>(0,Zn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Zn._)`{limit: ${t}}`},mT={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:fT,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,gp.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Hb(t,n)}};function Hb(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,Zn._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Zn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,gp.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,Zn._)`${a} <= ${e.length}`);r.if((0,Zn.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,d=>{t.subschema({keyword:o,dataProp:d,dataPropType:gp.Type.Num},l),i.allErrors||r.if((0,Zn.not)(l),()=>r.break())})}}hi.validateAdditionalItems=Hb;hi.default=mT});var bp=j(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.validateTuple=void 0;var Bb=z(),sc=Q(),gT=Rt(),yT={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Jb(t,"additionalItems",e);r.items=!0,!(0,sc.alwaysValidSchema)(r,e)&&t.ok((0,gT.validateArray)(t))}};function Jb(t,e,r=t.schema){let{gen:n,parentSchema:s,data:o,keyword:i,it:a}=t;d(s),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=sc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,Bb._)`${o}.length`);r.forEach((p,f)=>{(0,sc.alwaysValidSchema)(a,p)||(n.if((0,Bb._)`${l} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function d(p){let{opts:f,errSchemaPath:h}=a,m=r.length,g=m===p.minItems&&(m===p.maxItems||p[e]===!1);if(f.strictTuples&&!g){let y=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${h}"`;(0,sc.checkStrictMode)(a,y,f.strictTuples)}}}fi.validateTuple=Jb;fi.default=yT});var Wb=j(wp=>{"use strict";Object.defineProperty(wp,"__esModule",{value:!0});var bT=bp(),wT={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,bT.validateTuple)(t,"items")};wp.default=wT});var Zb=j(vp=>{"use strict";Object.defineProperty(vp,"__esModule",{value:!0});var Kb=z(),vT=Q(),_T=Rt(),ST=yp(),xT={message:({params:{len:t}})=>(0,Kb.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Kb._)`{limit: ${t}}`},kT={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:xT,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,vT.alwaysValidSchema)(n,e)&&(s?(0,ST.validateAdditionalItems)(t,s):t.ok((0,_T.validateArray)(t)))}};vp.default=kT});var Yb=j(_p=>{"use strict";Object.defineProperty(_p,"__esModule",{value:!0});var jt=z(),oc=Q(),$T={message:({params:{min:t,max:e}})=>e===void 0?(0,jt.str)`must contain at least ${t} valid item(s)`:(0,jt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,jt._)`{minContains: ${t}}`:(0,jt._)`{minContains: ${t}, maxContains: ${e}}`},ET={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:$T,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t,i,a,{minContains:c,maxContains:l}=n;o.opts.next?(i=c===void 0?1:c,a=l):i=1;let d=e.const("len",(0,jt._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,oc.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,oc.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,oc.alwaysValidSchema)(o,r)){let g=(0,jt._)`${d} >= ${i}`;a!==void 0&&(g=(0,jt._)`${g} && ${d} <= ${a}`),t.pass(g);return}o.items=!0;let p=e.name("valid");a===void 0&&i===1?h(p,()=>e.if(p,()=>e.break())):i===0?(e.let(p,!0),a!==void 0&&e.if((0,jt._)`${s}.length > 0`,f)):(e.let(p,!1),f()),t.result(p,()=>t.reset());function f(){let g=e.name("_valid"),y=e.let("count",0);h(g,()=>e.if(g,()=>m(y)))}function h(g,y){e.forRange("i",0,d,w=>{t.subschema({keyword:"contains",dataProp:w,dataPropType:oc.Type.Num,compositeRule:!0},g),y()})}function m(g){e.code((0,jt._)`${g}++`),a===void 0?e.if((0,jt._)`${g} >= ${i}`,()=>e.assign(p,!0).break()):(e.if((0,jt._)`${g} > ${a}`,()=>e.assign(p,!1).break()),i===1?e.assign(p,!0):e.if((0,jt._)`${g} >= ${i}`,()=>e.assign(p,!0)))}}};_p.default=ET});var ew=j(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.validateSchemaDeps=ur.validatePropertyDeps=ur.error=void 0;var Sp=z(),RT=Q(),mi=Rt();ur.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Sp.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Sp._)`{property: ${t},
|
|
11
|
+
missingProperty: ${n},
|
|
12
|
+
depsCount: ${e},
|
|
13
|
+
deps: ${r}}`};var IT={keyword:"dependencies",type:"object",schemaType:"object",error:ur.error,code(t){let[e,r]=jT(t);Xb(t,e),Qb(t,r)}};function jT({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function Xb(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,mi.propertyInData)(r,n,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?r.if(c,()=>{for(let l of a)(0,mi.checkReportMissingProp)(t,l)}):(r.if((0,Sp._)`${c} && (${(0,mi.checkMissingProp)(t,a,o)})`),(0,mi.reportMissingProp)(t,o),r.else())}}ur.validatePropertyDeps=Xb;function Qb(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,RT.alwaysValidSchema)(o,e[a])||(r.if((0,mi.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let c=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}ur.validateSchemaDeps=Qb;ur.default=IT});var rw=j(xp=>{"use strict";Object.defineProperty(xp,"__esModule",{value:!0});var tw=z(),PT=Q(),OT={message:"property name must be valid",params:({params:t})=>(0,tw._)`{propertyName: ${t.propertyName}}`},TT={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:OT,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,PT.alwaysValidSchema)(s,r))return;let o=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,tw.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};xp.default=TT});var $p=j(kp=>{"use strict";Object.defineProperty(kp,"__esModule",{value:!0});var ic=Rt(),zt=z(),NT=Pr(),ac=Q(),AT={message:"must NOT have additional properties",params:({params:t})=>(0,zt._)`{additionalProperty: ${t.additionalProperty}}`},CT={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:AT,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:o,it:i}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,ac.alwaysValidSchema)(i,r))return;let l=(0,ic.allSchemaProperties)(n.properties),d=(0,ic.allSchemaProperties)(n.patternProperties);p(),t.ok((0,zt._)`${o} === ${NT.default.errors}`);function p(){e.forIn("key",s,y=>{!l.length&&!d.length?m(y):e.if(f(y),()=>m(y))})}function f(y){let w;if(l.length>8){let S=(0,ac.schemaRefOrVal)(i,n.properties,"properties");w=(0,ic.isOwnProperty)(e,S,y)}else l.length?w=(0,zt.or)(...l.map(S=>(0,zt._)`${y} === ${S}`)):w=zt.nil;return d.length&&(w=(0,zt.or)(w,...d.map(S=>(0,zt._)`${(0,ic.usePattern)(t,S)}.test(${y})`))),(0,zt.not)(w)}function h(y){e.code((0,zt._)`delete ${s}[${y}]`)}function m(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,ac.alwaysValidSchema)(i,r)){let w=e.name("valid");c.removeAdditional==="failing"?(g(y,w,!1),e.if((0,zt.not)(w),()=>{t.reset(),h(y)})):(g(y,w),a||e.if((0,zt.not)(w),()=>e.break()))}}function g(y,w,S){let $={keyword:"additionalProperties",dataProp:y,dataPropType:ac.Type.Str};S===!1&&Object.assign($,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema($,w)}}};kp.default=CT});var ow=j(Rp=>{"use strict";Object.defineProperty(Rp,"__esModule",{value:!0});var LT=ei(),nw=Rt(),Ep=Q(),sw=$p(),DT={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&sw.default.code(new LT.KeywordCxt(o,sw.default,"additionalProperties"));let i=(0,nw.allSchemaProperties)(r);for(let p of i)o.definedProperties.add(p);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Ep.mergeEvaluated.props(e,(0,Ep.toHash)(i),o.props));let a=i.filter(p=>!(0,Ep.alwaysValidSchema)(o,r[p]));if(a.length===0)return;let c=e.name("valid");for(let p of a)l(p)?d(p):(e.if((0,nw.propertyInData)(e,s,p,o.opts.ownProperties)),d(p),o.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(p),t.ok(c);function l(p){return o.opts.useDefaults&&!o.compositeRule&&r[p].default!==void 0}function d(p){t.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};Rp.default=DT});var lw=j(Ip=>{"use strict";Object.defineProperty(Ip,"__esModule",{value:!0});var iw=Rt(),cc=z(),aw=Q(),cw=Q(),MT={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:o}=t,{opts:i}=o,a=(0,iw.allSchemaProperties)(r),c=a.filter(g=>(0,aw.alwaysValidSchema)(o,r[g]));if(a.length===0||c.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let l=i.strictSchema&&!i.allowMatchingProperties&&s.properties,d=e.name("valid");o.props!==!0&&!(o.props instanceof cc.Name)&&(o.props=(0,cw.evaluatedPropsToName)(e,o.props));let{props:p}=o;f();function f(){for(let g of a)l&&h(g),o.allErrors?m(g):(e.var(d,!0),m(g),e.if(d))}function h(g){for(let y in l)new RegExp(g).test(y)&&(0,aw.checkStrictMode)(o,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function m(g){e.forIn("key",n,y=>{e.if((0,cc._)`${(0,iw.usePattern)(t,g)}.test(${y})`,()=>{let w=c.includes(g);w||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:cw.Type.Str},d),o.opts.unevaluated&&p!==!0?e.assign((0,cc._)`${p}[${y}]`,!0):!w&&!o.allErrors&&e.if((0,cc.not)(d),()=>e.break())})})}}};Ip.default=MT});var dw=j(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});var FT=Q(),qT={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,FT.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};jp.default=qT});var uw=j(Pp=>{"use strict";Object.defineProperty(Pp,"__esModule",{value:!0});var GT=Rt(),UT={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:GT.validateUnion,error:{message:"must match a schema in anyOf"}};Pp.default=UT});var pw=j(Op=>{"use strict";Object.defineProperty(Op,"__esModule",{value:!0});var lc=z(),VT=Q(),zT={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,lc._)`{passingSchemas: ${t.passing}}`},HT={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:zT,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let o=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(l),t.result(i,()=>t.reset(),()=>t.error(!0));function l(){o.forEach((d,p)=>{let f;(0,VT.alwaysValidSchema)(s,d)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&e.if((0,lc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,lc._)`[${a}, ${p}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,p),f&&t.mergeEvaluated(f,lc.Name)})})}}};Op.default=HT});var hw=j(Tp=>{"use strict";Object.defineProperty(Tp,"__esModule",{value:!0});var BT=Q(),JT={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let s=e.name("valid");r.forEach((o,i)=>{if((0,BT.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};Tp.default=JT});var gw=j(Np=>{"use strict";Object.defineProperty(Np,"__esModule",{value:!0});var dc=z(),mw=Q(),WT={message:({params:t})=>(0,dc.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,dc._)`{failingKeyword: ${t.ifClause}}`},KT={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:WT,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,mw.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=fw(n,"then"),o=fw(n,"else");if(!s&&!o)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),s&&o){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(a,l("then",d),l("else",d))}else s?e.if(a,l("then")):e.if((0,dc.not)(a),l("else"));t.pass(i,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(d)}function l(d,p){return()=>{let f=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(f,i),p?e.assign(p,(0,dc._)`${d}`):t.setParams({ifClause:d})}}}};function fw(t,e){let r=t.schema[e];return r!==void 0&&!(0,mw.alwaysValidSchema)(t,r)}Np.default=KT});var yw=j(Ap=>{"use strict";Object.defineProperty(Ap,"__esModule",{value:!0});var ZT=Q(),YT={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,ZT.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Ap.default=YT});var bw=j(Cp=>{"use strict";Object.defineProperty(Cp,"__esModule",{value:!0});var XT=yp(),QT=Wb(),eN=bp(),tN=Zb(),rN=Yb(),nN=ew(),sN=rw(),oN=$p(),iN=ow(),aN=lw(),cN=dw(),lN=uw(),dN=pw(),uN=hw(),pN=gw(),hN=yw();function fN(t=!1){let e=[cN.default,lN.default,dN.default,uN.default,pN.default,hN.default,sN.default,oN.default,nN.default,iN.default,aN.default];return t?e.push(QT.default,tN.default):e.push(XT.default,eN.default),e.push(rN.default),e}Cp.default=fN});var ww=j(Lp=>{"use strict";Object.defineProperty(Lp,"__esModule",{value:!0});var ke=z(),mN={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},gN={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:mN,code(t,e){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:d,self:p}=a;if(!c.validateFormats)return;s?f():h();function f(){let m=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),g=r.const("fDef",(0,ke._)`${m}[${i}]`),y=r.let("fType"),w=r.let("format");r.if((0,ke._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(y,(0,ke._)`${g}.type || "string"`).assign(w,(0,ke._)`${g}.validate`),()=>r.assign(y,(0,ke._)`"string"`).assign(w,g)),t.fail$data((0,ke.or)(S(),$()));function S(){return c.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${w}`}function $(){let k=d.$async?(0,ke._)`(${g}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,ke._)`${w}(${n})`,I=(0,ke._)`(typeof ${w} == "function" ? ${k} : ${w}.test(${n}))`;return(0,ke._)`${w} && ${w} !== true && ${y} === ${e} && !${I}`}}function h(){let m=p.formats[o];if(!m){S();return}if(m===!0)return;let[g,y,w]=$(m);g===e&&t.pass(k());function S(){if(c.strictSchema===!1){p.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${o}" ignored in schema at path "${l}"`}}function $(I){let C=I instanceof RegExp?(0,ke.regexpCode)(I):c.code.formats?(0,ke._)`${c.code.formats}${(0,ke.getProperty)(o)}`:void 0,ne=r.scopeValue("formats",{key:o,ref:I,code:C});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,ke._)`${ne}.validate`]:["string",I,ne]}function k(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!d.$async)throw new Error("async format in sync schema");return(0,ke._)`await ${w}(${n})`}return typeof y=="function"?(0,ke._)`${w}(${n})`:(0,ke._)`${w}.test(${n})`}}}};Lp.default=gN});var vw=j(Dp=>{"use strict";Object.defineProperty(Dp,"__esModule",{value:!0});var yN=ww(),bN=[yN.default];Dp.default=bN});var _w=j(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.contentVocabulary=qs.metadataVocabulary=void 0;qs.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];qs.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var xw=j(Mp=>{"use strict";Object.defineProperty(Mp,"__esModule",{value:!0});var wN=Pb(),vN=zb(),_N=bw(),SN=vw(),Sw=_w(),xN=[wN.default,vN.default,(0,_N.default)(),SN.default,Sw.metadataVocabulary,Sw.contentVocabulary];Mp.default=xN});var $w=j(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.DiscrError=void 0;var kw;(function(t){t.Tag="tag",t.Mapping="mapping"})(kw||(uc.DiscrError=kw={}))});var Rw=j(qp=>{"use strict";Object.defineProperty(qp,"__esModule",{value:!0});var Gs=z(),Fp=$w(),Ew=za(),kN=ti(),$N=Q(),EN={message:({params:{discrError:t,tagName:e}})=>t===Fp.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Gs._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},RN={keyword:"discriminator",type:"object",schemaType:"object",error:EN,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Gs._)`${r}${(0,Gs.getProperty)(a)}`);e.if((0,Gs._)`typeof ${l} == "string"`,()=>d(),()=>t.error(!1,{discrError:Fp.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function d(){let h=f();e.if(!1);for(let m in h)e.elseIf((0,Gs._)`${l} === ${m}`),e.assign(c,p(h[m]));e.else(),t.error(!1,{discrError:Fp.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function p(h){let m=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:h},m);return t.mergeEvaluated(g,Gs.Name),m}function f(){var h;let m={},g=w(s),y=!0;for(let k=0;k<i.length;k++){let I=i[k];if(I?.$ref&&!(0,$N.schemaHasRulesButRef)(I,o.self.RULES)){let ne=I.$ref;if(I=Ew.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,ne),I instanceof Ew.SchemaEnv&&(I=I.schema),I===void 0)throw new kN.default(o.opts.uriResolver,o.baseId,ne)}let C=(h=I?.properties)===null||h===void 0?void 0:h[a];if(typeof C!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(g||w(I)),S(C,k)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return m;function w({required:k}){return Array.isArray(k)&&k.includes(a)}function S(k,I){if(k.const)$(k.const,I);else if(k.enum)for(let C of k.enum)$(C,I);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function $(k,I){if(typeof k!="string"||k in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[k]=I}}}};qp.default=RN});var Iw=j((uG,IN)=>{IN.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Up=j((ye,Gp)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var jN=kb(),PN=xw(),ON=Rw(),jw=Iw(),TN=["/properties"],pc="http://json-schema.org/draft-07/schema",Us=class extends jN.default{_addVocabularies(){super._addVocabularies(),PN.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(ON.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(jw,TN):jw;this.addMetaSchema(e,pc,!1),this.refs["http://json-schema.org/schema"]=pc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(pc)?pc:void 0)}};ye.Ajv=Us;Gp.exports=ye=Us;Gp.exports.Ajv=Us;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Us;var NN=ei();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return NN.KeywordCxt}});var Vs=z();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return Vs._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return Vs.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return Vs.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return Vs.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return Vs.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return Vs.CodeGen}});var AN=Ua();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return AN.default}});var CN=ti();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return CN.default}})});var Dw=j(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.formatNames=hr.fastFormats=hr.fullFormats=void 0;function pr(t,e){return{validate:t,compare:e}}hr.fullFormats={date:pr(Nw,Bp),time:pr(zp(!0),Jp),"date-time":pr(Pw(!0),Cw),"iso-time":pr(zp(),Aw),"iso-date-time":pr(Pw(),Lw),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:GN,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:WN,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:UN,int32:{type:"number",validate:HN},int64:{type:"number",validate:BN},float:{type:"number",validate:Tw},double:{type:"number",validate:Tw},password:!0,binary:!0};hr.fastFormats={...hr.fullFormats,date:pr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Bp),time:pr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Jp),"date-time":pr(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Cw),"iso-time":pr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Aw),"iso-date-time":pr(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Lw),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};hr.formatNames=Object.keys(hr.fullFormats);function LN(t){return t%4===0&&(t%100!==0||t%400===0)}var DN=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,MN=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Nw(t){let e=DN.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n===2&&LN(r)?29:MN[n])}function Bp(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Vp=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function zp(t){return function(r){let n=Vp.exec(r);if(!n)return!1;let s=+n[1],o=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,l=+(n[6]||0),d=+(n[7]||0);if(l>23||d>59||t&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let p=o-d*c,f=s-l*c-(p<0?1:0);return(f===23||f===-1)&&(p===59||p===-1)&&i<61}}function Jp(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function Aw(t,e){if(!(t&&e))return;let r=Vp.exec(t),n=Vp.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var Hp=/t|\s/i;function Pw(t){let e=zp(t);return function(n){let s=n.split(Hp);return s.length===2&&Nw(s[0])&&e(s[1])}}function Cw(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Lw(t,e){if(!(t&&e))return;let[r,n]=t.split(Hp),[s,o]=e.split(Hp),i=Bp(r,s);if(i!==void 0)return i||Jp(n,o)}var FN=/\/|:/,qN=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function GN(t){return FN.test(t)&&qN.test(t)}var Ow=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function UN(t){return Ow.lastIndex=0,Ow.test(t)}var VN=-(2**31),zN=2**31-1;function HN(t){return Number.isInteger(t)&&t<=zN&&t>=VN}function BN(t){return Number.isInteger(t)}function Tw(){return!0}var JN=/[^\\]\\Z/;function WN(t){if(JN.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Mw=j(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.formatLimitDefinition=void 0;var KN=Up(),Ht=z(),nn=Ht.operators,hc={formatMaximum:{okStr:"<=",ok:nn.LTE,fail:nn.GT},formatMinimum:{okStr:">=",ok:nn.GTE,fail:nn.LT},formatExclusiveMaximum:{okStr:"<",ok:nn.LT,fail:nn.GTE},formatExclusiveMinimum:{okStr:">",ok:nn.GT,fail:nn.LTE}},ZN={message:({keyword:t,schemaCode:e})=>(0,Ht.str)`should be ${hc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ht._)`{comparison: ${hc[t].okStr}, limit: ${e}}`};zs.formatLimitDefinition={keyword:Object.keys(hc),type:"string",schemaType:"string",$data:!0,error:ZN,code(t){let{gen:e,data:r,schemaCode:n,keyword:s,it:o}=t,{opts:i,self:a}=o;if(!i.validateFormats)return;let c=new KN.KeywordCxt(o,a.RULES.all.format.definition,"format");c.$data?l():d();function l(){let f=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),h=e.const("fmt",(0,Ht._)`${f}[${c.schemaCode}]`);t.fail$data((0,Ht.or)((0,Ht._)`typeof ${h} != "object"`,(0,Ht._)`${h} instanceof RegExp`,(0,Ht._)`typeof ${h}.compare != "function"`,p(h)))}function d(){let f=c.schema,h=a.formats[f];if(!h||h===!0)return;if(typeof h!="object"||h instanceof RegExp||typeof h.compare!="function")throw new Error(`"${s}": format "${f}" does not define "compare" function`);let m=e.scopeValue("formats",{key:f,ref:h,code:i.code.formats?(0,Ht._)`${i.code.formats}${(0,Ht.getProperty)(f)}`:void 0});t.fail$data(p(m))}function p(f){return(0,Ht._)`${f}.compare(${r}, ${n}) ${hc[s].fail} 0`}},dependencies:["format"]};var YN=t=>(t.addKeyword(zs.formatLimitDefinition),t);zs.default=YN});var Uw=j((gi,Gw)=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});var Hs=Dw(),XN=Mw(),Wp=z(),Fw=new Wp.Name("fullFormats"),QN=new Wp.Name("fastFormats"),Kp=(t,e={keywords:!0})=>{if(Array.isArray(e))return qw(t,e,Hs.fullFormats,Fw),t;let[r,n]=e.mode==="fast"?[Hs.fastFormats,QN]:[Hs.fullFormats,Fw],s=e.formats||Hs.formatNames;return qw(t,s,r,n),e.keywords&&(0,XN.default)(t),t};Kp.get=(t,e="full")=>{let n=(e==="fast"?Hs.fastFormats:Hs.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function qw(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,Wp._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Gw.exports=gi=Kp;Object.defineProperty(gi,"__esModule",{value:!0});gi.default=Kp});function eA(){let t=new Vw.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,zw.default)(t),t}var Vw,zw,fc,Hw=v(()=>{Vw=Vm(Up(),1),zw=Vm(Uw(),1);fc=class{constructor(e){this._ajv=e??eA()}getValidator(e){var r;let n="$id"in e&&typeof e.$id=="string"?(r=this._ajv.getSchema(e.$id))!==null&&r!==void 0?r:this._ajv.compile(e):this._ajv.compile(e);return s=>n(s)?{valid:!0,data:s,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}}});var mc,Bw=v(()=>{Gg();Fo();Hw();mc=class extends ja{constructor(e,r){var n,s;super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Mo.options.map((o,i)=>[o,i])),this.isMessageIgnored=(o,i)=>{let a=this._loggingLevels.get(i);return a?this.LOG_LEVEL_SEVERITY.get(o)<this.LOG_LEVEL_SEVERITY.get(a):!1},this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._instructions=r?.instructions,this._jsonSchemaValidator=(s=r?.jsonSchemaValidator)!==null&&s!==void 0?s:new fc,this.setRequestHandler(Fd,o=>this._oninitialize(o)),this.setNotificationHandler(qd,()=>{var o;return(o=this.oninitialized)===null||o===void 0?void 0:o.call(this)}),this._capabilities.logging&&this.setRequestHandler(Bd,async(o,i)=>{var a;let c=i.sessionId||((a=i.requestInfo)===null||a===void 0?void 0:a.headers["mcp-session-id"])||void 0,{level:l}=o.params,d=Mo.safeParse(l);return d.success&&this._loggingLevels.set(c,d.data),{}})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=qg(this._capabilities,e)}assertCapabilityForMethod(e){var r,n,s;switch(e){case"sampling/createMessage":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!(!((n=this._clientCapabilities)===null||n===void 0)&&n.elicitation))throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!(!((s=this._clientCapabilities)===null||s===void 0)&&s.roots))throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"ping":case"initialize":break}}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:ug.includes(r)?r:Dd,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},pa)}async createMessage(e,r){return this.request({method:"sampling/createMessage",params:e},Jd,r)}async elicitInput(e,r){let n=await this.request({method:"elicitation/create",params:e},Wd,r);if(n.action==="accept"&&n.content&&e.requestedSchema)try{let o=this._jsonSchemaValidator.getValidator(e.requestedSchema)(n.content);if(!o.valid)throw new fe(he.InvalidParams,`Elicitation response content does not match requested schema: ${o.errorMessage}`)}catch(s){throw s instanceof fe?s:new fe(he.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return n}async listRoots(e,r){return this.request({method:"roots/list",params:e},Kd,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});var Ww,Jw,Kw,gc=v(()=>{Ww=Symbol("Let zodToJsonSchema decide on which parser to use"),Jw={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Kw=t=>typeof t=="string"?{...Jw,name:t}:{...Jw,...t}});var Zw,Zp=v(()=>{gc();Zw=t=>{let e=Kw(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function Yp(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function X(t,e,r,n,s){t[e]=r,Yp(t,e,n,s)}var sn=v(()=>{});var yc,bc=v(()=>{yc=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});var wc=v(()=>{la()});function ve(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?yc(e,t.currentPath):e.join("/")}}var Pt=v(()=>{bc()});function Yw(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==x.ZodAny&&(r.items=F(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&X(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&X(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(X(r,"minItems",t.exactLength.value,t.exactLength.message,e),X(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Xp=v(()=>{wc();sn();Ie()});function Xw(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?X(r,"minimum",n.value,n.message,e):X(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),X(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?X(r,"maximum",n.value,n.message,e):X(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),X(r,"maximum",n.value,n.message,e));break;case"multipleOf":X(r,"multipleOf",n.value,n.message,e);break}return r}var Qp=v(()=>{sn()});function Qw(){return{type:"boolean"}}var eh=v(()=>{});function vc(t,e){return F(t.type._def,e)}var _c=v(()=>{Ie()});var ev,th=v(()=>{Ie();ev=(t,e)=>F(t.innerType._def,e)});function rh(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>rh(t,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return tA(t,e)}}var tA,nh=v(()=>{sn();tA=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":X(r,"minimum",n.value,n.message,e);break;case"max":X(r,"maximum",n.value,n.message,e);break}return r}});function tv(t,e){return{...F(t.innerType._def,e),default:t.defaultValue()}}var sh=v(()=>{Ie()});function rv(t,e){return e.effectStrategy==="input"?F(t.schema._def,e):ve(e)}var oh=v(()=>{Ie();Pt()});function nv(t){return{type:"string",enum:Array.from(t.values)}}var ih=v(()=>{});function sv(t,e){let r=[F(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),F(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return r.forEach(o=>{if(rA(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...c}=o;i=c}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}var rA,ah=v(()=>{Ie();rA=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function ov(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var ch=v(()=>{});function Sc(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":X(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":X(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Jt(r,"email",n.message,e);break;case"format:idn-email":Jt(r,"idn-email",n.message,e);break;case"pattern:zod":Ye(r,Bt.email,n.message,e);break}break;case"url":Jt(r,"uri",n.message,e);break;case"uuid":Jt(r,"uuid",n.message,e);break;case"regex":Ye(r,n.regex,n.message,e);break;case"cuid":Ye(r,Bt.cuid,n.message,e);break;case"cuid2":Ye(r,Bt.cuid2,n.message,e);break;case"startsWith":Ye(r,RegExp(`^${dh(n.value,e)}`),n.message,e);break;case"endsWith":Ye(r,RegExp(`${dh(n.value,e)}$`),n.message,e);break;case"datetime":Jt(r,"date-time",n.message,e);break;case"date":Jt(r,"date",n.message,e);break;case"time":Jt(r,"time",n.message,e);break;case"duration":Jt(r,"duration",n.message,e);break;case"length":X(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),X(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ye(r,RegExp(dh(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Jt(r,"ipv4",n.message,e),n.version!=="v4"&&Jt(r,"ipv6",n.message,e);break}case"base64url":Ye(r,Bt.base64url,n.message,e);break;case"jwt":Ye(r,Bt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ye(r,Bt.ipv4Cidr,n.message,e),n.version!=="v4"&&Ye(r,Bt.ipv6Cidr,n.message,e);break}case"emoji":Ye(r,Bt.emoji(),n.message,e);break;case"ulid":{Ye(r,Bt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Jt(r,"binary",n.message,e);break}case"contentEncoding:base64":{X(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ye(r,Bt.base64,n.message,e);break}}break}case"nanoid":Ye(r,Bt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function dh(t,e){return e.patternStrategy==="escape"?sA(t):t}function sA(t){let e="";for(let r=0;r<t.length;r++)nA.has(t[r])||(e+="\\"),e+=t[r];return e}function Jt(t,e,r,n){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):X(t,"format",e,r,n)}function Ye(t,e,r,n){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:iv(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):X(t,"pattern",iv(e,n),r,n)}function iv(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,s="",o=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(o){s+=n[c],o=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(s+=n[c],a=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){s+=`(^|(?<=[\r
|
|
14
|
+
]))`;continue}else if(n[c]==="$"){s+=`($|(?=[\r
|
|
15
|
+
]))`;continue}}if(r.s&&n[c]==="."){s+=i?`${n[c]}\r
|
|
16
|
+
`:`[${n[c]}\r
|
|
17
|
+
]`;continue}s+=n[c],n[c]==="\\"?o=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}var lh,Bt,nA,xc=v(()=>{sn();Bt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(lh===void 0&&(lh=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),lh),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};nA=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function kc(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===x.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??ve(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===x.ZodString&&t.keyType._def.checks?.length){let{type:n,...s}=Sc(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===x.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===x.ZodBranded&&t.keyType._def.type._def.typeName===x.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...s}=vc(t.keyType._def,e);return{...r,propertyNames:s}}}return r}var $c=v(()=>{wc();Ie();xc();_c();Pt()});function av(t,e){if(e.mapStrategy==="record")return kc(t,e);let r=F(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ve(e),n=F(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ve(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var uh=v(()=>{Ie();$c();Pt()});function cv(t){let e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}var ph=v(()=>{});function lv(t){return t.target==="openAi"?void 0:{not:ve({...t,currentPath:[...t.currentPath,"not"]})}}var hh=v(()=>{Pt()});function dv(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var fh=v(()=>{});function pv(t,e){if(e.target==="openApi3")return uv(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in yi&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=yi[o._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((s,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];default:return s}},[]);if(n.length===r.length){let s=n.filter((o,i,a)=>a.indexOf(o)===i);return{type:s.length>1?s:s[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return uv(t,e)}var yi,uv,Ec=v(()=>{Ie();yi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};uv=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>F(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function hv(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:yi[t.innerType._def.typeName],nullable:!0}:{type:[yi[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=F(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=F(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var mh=v(()=>{Ie();Ec()});function fv(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Yp(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?X(r,"minimum",n.value,n.message,e):X(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),X(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?X(r,"maximum",n.value,n.message,e):X(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),X(r,"maximum",n.value,n.message,e));break;case"multipleOf":X(r,"multipleOf",n.value,n.message,e);break}return r}var gh=v(()=>{sn()});function mv(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},s=[],o=t.shape();for(let a in o){let c=o[a];if(c===void 0||c._def===void 0)continue;let l=iA(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let d=F(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});d!==void 0&&(n.properties[a]=d,l||s.push(a))}s.length&&(n.required=s);let i=oA(t,e);return i!==void 0&&(n.additionalProperties=i),n}function oA(t,e){if(t.catchall._def.typeName!=="ZodNever")return F(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function iA(t){try{return t.isOptional()}catch{return!0}}var yh=v(()=>{Ie()});var gv,bh=v(()=>{Ie();Pt();gv=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return F(t.innerType._def,e);let r=F(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ve(e)},r]}:ve(e)}});var yv,wh=v(()=>{Ie();yv=(t,e)=>{if(e.pipeStrategy==="input")return F(t.in._def,e);if(e.pipeStrategy==="output")return F(t.out._def,e);let r=F(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=F(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}}});function bv(t,e){return F(t.type._def,e)}var vh=v(()=>{Ie()});function wv(t,e){let n={type:"array",uniqueItems:!0,items:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&X(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&X(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var _h=v(()=>{sn();Ie()});function vv(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>F(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:F(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>F(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Sh=v(()=>{Ie()});function _v(t){return{not:ve(t)}}var xh=v(()=>{Pt()});function Sv(t){return ve(t)}var kh=v(()=>{Pt()});var xv,$h=v(()=>{Ie();xv=(t,e)=>F(t.innerType._def,e)});var kv,Eh=v(()=>{wc();Pt();Xp();Qp();eh();_c();th();nh();sh();oh();ih();ah();ch();uh();ph();hh();fh();mh();gh();yh();bh();wh();vh();$c();_h();xc();Sh();xh();Ec();kh();$h();kv=(t,e,r)=>{switch(e){case x.ZodString:return Sc(t,r);case x.ZodNumber:return fv(t,r);case x.ZodObject:return mv(t,r);case x.ZodBigInt:return Xw(t,r);case x.ZodBoolean:return Qw();case x.ZodDate:return rh(t,r);case x.ZodUndefined:return _v(r);case x.ZodNull:return dv(r);case x.ZodArray:return Yw(t,r);case x.ZodUnion:case x.ZodDiscriminatedUnion:return pv(t,r);case x.ZodIntersection:return sv(t,r);case x.ZodTuple:return vv(t,r);case x.ZodRecord:return kc(t,r);case x.ZodLiteral:return ov(t,r);case x.ZodEnum:return nv(t);case x.ZodNativeEnum:return cv(t);case x.ZodNullable:return hv(t,r);case x.ZodOptional:return gv(t,r);case x.ZodMap:return av(t,r);case x.ZodSet:return wv(t,r);case x.ZodLazy:return()=>t.getter()._def;case x.ZodPromise:return bv(t,r);case x.ZodNaN:case x.ZodNever:return lv(r);case x.ZodEffects:return rv(t,r);case x.ZodAny:return ve(r);case x.ZodUnknown:return Sv(r);case x.ZodDefault:return tv(t,r);case x.ZodBranded:return vc(t,r);case x.ZodReadonly:return xv(t,r);case x.ZodCatch:return ev(t,r);case x.ZodPipeline:return yv(t,r);case x.ZodFunction:case x.ZodVoid:case x.ZodSymbol:return;default:return(n=>{})(e)}}});function F(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Ww)return a}if(n&&!r){let a=aA(n,e);if(a!==void 0)return a}let s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);let o=kv(t,t.typeName,e),i=typeof o=="function"?F(o(),e):o;if(i&&cA(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var aA,cA,Ie=v(()=>{gc();Eh();bc();Pt();aA=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:yc(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),ve(e)):e.$refStrategy==="seen"?ve(e):void 0}},cA=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var $v=v(()=>{});var Rc,Rh=v(()=>{Ie();Zp();Pt();Rc=(t,e)=>{let r=Zw(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,d])=>({...c,[l]:F(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??ve(r)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=F(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??ve(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=s===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:o}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var Ev=v(()=>{gc();Zp();sn();bc();Ie();$v();Pt();Xp();Qp();eh();_c();th();nh();sh();oh();ih();ah();ch();uh();ph();hh();fh();mh();gh();yh();bh();wh();vh();$h();$c();_h();xc();Sh();xh();Ec();kh();Eh();Rh();Rh()});function lA(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,a)=>{var c,l;let{message:d}=t;return i.code==="invalid_enum_value"?{message:d??a.defaultError}:typeof a.data>"u"?{message:(c=d??n)!==null&&c!==void 0?c:a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:(l=d??r)!==null&&l!==void 0?l:a.defaultError}},description:s}}var Ih,Bs,Rv=v(()=>{Ft();(function(t){t.Completable="McpCompletable"})(Ih||(Ih={}));Bs=class extends U{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}};Bs.create=(t,e)=>new Bs({type:t,typeName:Ih.Completable,complete:e.complete,...lA(e)})});var Iv=v(()=>{});function uA(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!dA.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,o)=>o.indexOf(n)===s);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function pA(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function jh(t){let e=uA(t);return pA(t,e.warnings),e.isValid}var dA,jv=v(()=>{dA=/^[A-Za-z0-9._-]{1,128}$/});function Ph(t){return typeof t!="object"||t===null?!1:Object.keys(t).length===0||Object.values(t).some(fA)}function fA(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Pv(t){if(t)return Ph(t)?u.object(t):t}function mA(t){return Object.entries(t.shape).map(([e,r])=>({name:e,description:r.description,required:!r.isOptional()}))}function Ov(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var jc,hA,Ic,Tv=v(()=>{Bw();Ev();Ft();Fo();Rv();Iv();jv();jc=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new mc(e,r)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(xa.shape.method.value),this.server.assertCanSetRequestHandler(ka.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(xa,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:r.inputSchema?Rc(r.inputSchema,{strictUnions:!0,pipeStrategy:"input"}):hA,annotations:r.annotations,_meta:r._meta};return r.outputSchema&&(n.outputSchema=Rc(r.outputSchema,{strictUnions:!0,pipeStrategy:"output"})),n})})),this.server.setRequestHandler(ka,async(e,r)=>{let n=this._registeredTools[e.params.name],s;try{if(!n)throw new fe(he.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new fe(he.InvalidParams,`Tool ${e.params.name} disabled`);if(n.inputSchema){let o=n.callback,i=await n.inputSchema.safeParseAsync(e.params.arguments);if(!i.success)throw new fe(he.InvalidParams,`Input validation error: Invalid arguments for tool ${e.params.name}: ${i.error.message}`);let a=i.data;s=await Promise.resolve(o(a,r))}else{let o=n.callback;s=await Promise.resolve(o(r))}if(n.outputSchema&&!s.isError){if(!s.structuredContent)throw new fe(he.InvalidParams,`Output validation error: Tool ${e.params.name} has an output schema but no structured content was provided`);let o=await n.outputSchema.safeParseAsync(s.structuredContent);if(!o.success)throw new fe(he.InvalidParams,`Output validation error: Invalid structured content for tool ${e.params.name}: ${o.error.message}`)}}catch(o){return this.createToolError(o instanceof Error?o.message:String(o))}return s}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler($a.shape.method.value),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler($a,async e=>{switch(e.params.ref.type){case"ref/prompt":return jg(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Pg(e),this.handleResourceCompletion(e,e.params.ref);default:throw new fe(he.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new fe(he.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new fe(he.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Ic;let s=n.argsSchema.shape[e.params.argument.name];if(!(s instanceof Bs))return Ic;let i=await s._def.complete(e.params.argument.value,e.params.context);return Ov(i)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return Ic;throw new fe(he.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return Ic;let o=await s(e.params.argument.value,e.params.context);return Ov(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(ba.shape.method.value),this.server.assertCanSetRequestHandler(wa.shape.method.value),this.server.assertCanSetRequestHandler(va.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ba,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),s=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(r);for(let a of i.resources)s.push({...o.metadata,...a})}return{resources:[...n,...s]}}),this.server.setRequestHandler(wa,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(va,async(e,r)=>{let n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new fe(he.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,r)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(n.toString());if(i)return o.readCallback(n,i,r)}throw new fe(he.InvalidParams,`Resource ${n} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(_a.shape.method.value),this.server.assertCanSetRequestHandler(Sa.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(_a,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?mA(r.argsSchema):void 0}))})),this.server.setRequestHandler(Sa,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new fe(he.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new fe(he.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let s=await n.argsSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new fe(he.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${s.error.message}`);let o=s.data,i=n.callback;return await Promise.resolve(i(o,r))}else{let s=n.callback;return await Promise.resolve(s(r))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,r,...n){let s;typeof n[0]=="object"&&(s=n.shift());let o=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,s){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,n,s,o){let i={name:e,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,s,o){let i={resourceTemplate:n,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredResourceTemplates[e],a.name&&(this._registeredResourceTemplates[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.template<"u"&&(i.resourceTemplate=a.template),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResourceTemplates[e]=i,i}_createRegisteredPrompt(e,r,n,s,o){let i={title:r,description:n,argsSchema:s===void 0?void 0:u.object(s),callback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=u.object(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,i}_createRegisteredTool(e,r,n,s,o,i,a,c){jh(e);let l={title:r,description:n,inputSchema:Pv(s),outputSchema:Pv(o),annotations:i,_meta:a,callback:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&jh(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=u.object(d.paramsSchema)),typeof d.callback<"u"&&(l.callback=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,s,o,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];Ph(c)?(s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Ph(r[0])&&(i=r.shift())):typeof c=="object"&&c!==null&&(i=r.shift())}let a=r[0];return this._createRegisteredTool(e,void 0,n,s,o,i,void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:s,description:o,inputSchema:i,outputSchema:a,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,s,o,i,a,c,l,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let s;r.length>1&&(s=r.shift());let o=r[0],i=this._createRegisteredPrompt(e,void 0,n,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:s,description:o,argsSchema:i}=r,a=this._createRegisteredPrompt(e,s,o,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},hA={type:"object",properties:{}};Ic={completion:{values:[],hasMore:!1}}});import{readFileSync as gA}from"node:fs";import Nv from"node:path";function Js(){let t=process.env.SUNDOWNREEL_BRAND_FILE,e=Nv.join(Se(),"brand.json"),r=t&&t.length>0?Nv.resolve(t):e;return JSON.parse(gA(r,"utf8"))}var Pc=v(()=>{"use strict";pe()});import{mkdirSync as Ah,readFileSync as yA,writeFileSync as Mv,existsSync as Ch,readdirSync as Fv,renameSync as bA}from"node:fs";import{createRequire as wA}from"node:module";import ht from"node:path";function Tc(t){return Ch(t)?JSON.parse(yA(t,"utf8")):null}function qv(t,e){Ah(ht.dirname(t),{recursive:!0}),Mv(t,JSON.stringify(e,null,2))}function Ks(t){let e=new Uint8Array(4);crypto.getRandomValues(e);let r=[...e].map(n=>n.toString(16).padStart(2,"0")).join("");return`${t}_${r}`}function vA(t){if(!/^p_[a-f0-9]{8}$/.test(t))throw new Error("Unknown project.")}function Tr(t){return vA(t),ht.join(st(),"projects",t)}function Ot(t){return t.updatedAt=new Date().toISOString(),qv(ht.join(Tr(t.id),"project.json"),t),t}function $e(t){let e=Tc(ht.join(Tr(t),"project.json"));if(!e)throw new Error("Unknown project.");return e}function Nc(){let t=ht.join(st(),"projects");return Ch(t)?Fv(t).map(e=>Tc(ht.join(t,e,"project.json"))).filter(e=>!!e).sort((e,r)=>r.createdAt.localeCompare(e.createdAt)):[]}function Uv(){return new Date().toISOString()}function Av(t){if(t!=null)try{return JSON.parse(t)}catch{return t}}function Oh(t){let e={id:t.id,type:t.type,status:t.status,progress:t.progress,message:t.message,createdAt:t.created_at,updatedAt:t.updated_at,attempts:t.attempts};return t.project_id&&(e.projectId=t.project_id),t.episode_id&&(e.episodeId=t.episode_id),t.error&&(e.error=t.error),t.result!==null&&(e.result=Av(t.result)),t.args!==null&&(e.args=Av(t.args)),t.lane&&(e.lane=t.lane),e.leaseOwner=t.lease_owner,e.leaseUntil=t.lease_until,e}function Cv(t,e){return e==null?null:_A.has(t)?JSON.stringify(e):typeof e=="number"||typeof e=="string"?e:String(e)}function Vv(){return ht.join(st(),"jobs")}function Nh(t){return ht.join(Vv(),`${t}.json`)}function Lh(t){try{return Tc(t)}catch{return null}}function zv(t,e){return(!e.episodeId||t.episodeId===e.episodeId)&&(!e.projectId||t.projectId===e.projectId)&&(!e.type||t.type===e.type)&&(!e.status?.length||e.status.includes(t.status))}function bi(){let t=Vv();return Ch(t)?Fv(t).filter(e=>SA.test(e)).map(e=>Lh(ht.join(t,e))).filter(e=>!!e).sort((e,r)=>r.createdAt.localeCompare(e.createdAt)):[]}function Bv(t){Hv.push(t)}function xA(t){let e=wA(import.meta.url),{DatabaseSync:r}=e("node:sqlite");return Ah(ht.dirname(t),{recursive:!0}),new Th(new r(t))}function Yn(){let t=ht.join(st(),"jobs.db"),e=process.env.SUNDOWNREEL_JOBS_STORE==="json",r=`${e?"json":"auto"}:${t}`,n=Lv.get(r);if(n)return n;if(e)n=new Oc;else try{n=xA(t)}catch(s){Dv||(Dv=!0,console.error(`Sundown Reel: the durable job store (node:sqlite at ${t}) is unavailable (${s instanceof Error?s.message:String(s)}); falling back to JSON job files. Jobs still persist; leases and cancel across processes are best effort. Use Node 22.13+ (24 recommended).`)),n=new Oc}Lv.set(r,n);for(let s of Hv)s(n.kind);return n}function Jv(t){return Xn.includes(t.status)?{...t,note:`Recorded by an older Sundown Reel server. If it no longer updates, that server stopped: re-run the tool that started it (${t.type}).`}:t}function Wv(t){kA=t}function fr(t,e,r){return Yn().update(t,{...e,updatedAt:Uv()},r)}function Zs(t){let e=Yn(),r=e.get(t);if(r)return r;if(e.kind==="sqlite"){let n=Lh(Nh(t));return n?Jv(n):null}return null}function on(t){let{leaseOwner:e,leaseUntil:r,args:n,...s}=t;return s}function Kv(t){if(!/^job_[a-f0-9]{8}$/.test(t))throw new Error("Unknown job.");let e=Zs(t);if(!e)throw new Error("Unknown job.");return on(e)}function Dh(t={}){let e=Yn(),r=e.list(t);if(e.kind==="json")return r;let{limit:n,...s}=t,o=new Set(r.map(c=>c.id)),i=bi().filter(c=>!o.has(c.id)).map(Jv).filter(c=>zv(c,s));if(!i.length)return r;let a=[...r,...i].sort((c,l)=>l.createdAt.localeCompare(c.createdAt));return n?a.slice(0,n):a}function Mh(){let t=new Date().toISOString().slice(0,7),e=ht.join(st(),"usage.json"),r=Tc(e);return!r||r.month!==t?{month:t,count:0}:r}function Zv(){let t=Mh();return t.count+=1,qv(ht.join(st(),"usage.json"),t),t}var Xn,Gv,Ws,_A,Th,SA,Oc,Lv,Dv,Hv,kA,wi,Ys=v(()=>{"use strict";pe();Xn=["queued","running"],Gv=new Set(["args","attempts","lane","leaseOwner","leaseUntil"]);Ws={type:"type",status:"status",progress:"progress",message:"message",projectId:"project_id",episodeId:"episode_id",args:"args",result:"result",error:"error",attempts:"attempts",lane:"lane",leaseOwner:"lease_owner",leaseUntil:"lease_until",createdAt:"created_at",updatedAt:"updated_at"},_A=new Set(["args","result"]);Th=class{constructor(e){this.db=e;e.exec("PRAGMA busy_timeout = 5000");try{e.exec("PRAGMA journal_mode = WAL")}catch{}e.exec(`CREATE TABLE IF NOT EXISTS jobs (
|
|
18
|
+
id TEXT PRIMARY KEY,
|
|
19
|
+
type TEXT NOT NULL,
|
|
20
|
+
status TEXT NOT NULL,
|
|
21
|
+
progress REAL NOT NULL DEFAULT 0,
|
|
22
|
+
message TEXT NOT NULL DEFAULT '',
|
|
23
|
+
project_id TEXT,
|
|
24
|
+
episode_id TEXT,
|
|
25
|
+
args TEXT,
|
|
26
|
+
result TEXT,
|
|
27
|
+
error TEXT,
|
|
28
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
29
|
+
lane TEXT,
|
|
30
|
+
lease_owner TEXT,
|
|
31
|
+
lease_until INTEGER,
|
|
32
|
+
created_at TEXT NOT NULL,
|
|
33
|
+
updated_at TEXT NOT NULL
|
|
34
|
+
);
|
|
35
|
+
CREATE INDEX IF NOT EXISTS jobs_episode ON jobs(episode_id);
|
|
36
|
+
CREATE INDEX IF NOT EXISTS jobs_status ON jobs(status);`)}db;kind="sqlite";get(e){let r=this.db.prepare("SELECT * FROM jobs WHERE id = ?").get(e);return r?Oh(r):null}list(e){let r=[],n=[];e.episodeId&&(r.push("episode_id = ?"),n.push(e.episodeId)),e.projectId&&(r.push("project_id = ?"),n.push(e.projectId)),e.type&&(r.push("type = ?"),n.push(e.type)),e.status?.length&&(r.push(`status IN (${e.status.map(()=>"?").join(",")})`),n.push(...e.status));let s=e.limit?` LIMIT ${Math.max(1,Math.floor(e.limit))}`:"",o=`SELECT * FROM jobs${r.length?` WHERE ${r.join(" AND ")}`:""} ORDER BY created_at DESC, rowid DESC${s}`;return this.db.prepare(o).all(...n).map(Oh)}upsert(e){let r=e,n=Object.keys(Ws).filter(a=>!Gv.has(a)||r[a]!==void 0),s=["id",...n.map(a=>Ws[a])],o=[e.id,...n.map(a=>Cv(a,r[a]))],i=n.filter(a=>a!=="createdAt").map(a=>`${Ws[a]} = excluded.${Ws[a]}`);this.db.prepare(`INSERT INTO jobs (${s.join(",")}) VALUES (${s.map(()=>"?").join(",")}) ON CONFLICT(id) DO UPDATE SET ${i.join(", ")}`).run(...o)}update(e,r,n={}){let s=r,o=Object.keys(s).filter(l=>Ws[l]&&s[l]!==void 0);if(!o.length)return!1;let i=o.map(l=>Cv(l,s[l])),a=["id = ?"];i.push(e),n.status?.length&&(a.push(`status IN (${n.status.map(()=>"?").join(",")})`),i.push(...n.status)),n.owner&&(a.push("lease_owner = ?"),i.push(n.owner));let c=this.db.prepare(`UPDATE jobs SET ${o.map(l=>`${Ws[l]} = ?`).join(", ")} WHERE ${a.join(" AND ")}`).run(...i);return Number(c.changes)>0}activeNotOwnedBy(e){return this.db.prepare("SELECT * FROM jobs WHERE status IN ('queued','running') AND (lease_owner IS NULL OR lease_owner != ?)").all(e).map(Oh)}idsOwnedBy(e,r){return this.db.prepare(`SELECT id FROM jobs WHERE lease_owner = ? AND status IN (${r.map(()=>"?").join(",")})`).all(e,...r).map(s=>s.id)}renew(e,r){this.db.prepare("UPDATE jobs SET lease_until = ? WHERE lease_owner = ? AND status IN ('queued','running')").run(r,e)}close(){this.db.close()}},SA=/^job_[a-f0-9]{8}\.json$/;Oc=class{kind="json";write(e){let r=Nh(e.id);Ah(ht.dirname(r),{recursive:!0});let n=`${r}.tmp-${process.pid}`;Mv(n,JSON.stringify(e,null,2)),bA(n,r)}get(e){return Lh(Nh(e))}list(e){let r=bi().filter(n=>zv(n,e));return e.limit?r.slice(0,e.limit):r}upsert(e){let r=this.get(e.id),n={...e};if(r){n.createdAt=r.createdAt??e.createdAt;let s=n;for(let o of Gv)s[o]===void 0&&(s[o]=r[o])}this.write(n)}update(e,r,n={}){let s=this.get(e);if(!s||n.status?.length&&!n.status.includes(s.status)||n.owner&&s.leaseOwner!==n.owner)return!1;let o={...s};for(let[i,a]of Object.entries(r))a!==void 0&&(o[i]=a);return this.write(o),!0}activeNotOwnedBy(e){return bi().filter(r=>Xn.includes(r.status)&&r.leaseOwner!==e)}idsOwnedBy(e,r){return bi().filter(n=>n.leaseOwner===e&&r.includes(n.status)).map(n=>n.id)}renew(e,r){for(let n of bi())n.leaseOwner===e&&Xn.includes(n.status)&&this.write({...n,leaseUntil:r})}close(){}},Lv=new Map,Dv=!1,Hv=[];kA=null;wi={activeNotOwnedBy:t=>Yn().activeNotOwnedBy(t),idsOwnedBy:(t,e)=>Yn().idsOwnedBy(t,e),renew:(t,e)=>Yn().renew(t,e),insert:t=>Yn().upsert({...t,updatedAt:Uv()})}});import{AsyncLocalStorage as $A}from"node:async_hooks";import EA from"node:diagnostics_channel";import{randomBytes as RA}from"node:crypto";function jA(t){if(!t)return!0;let[e,r]=t.split(":"),n=Number(e);if(!Number.isInteger(n)||n<=0)return!0;if(n===process.pid)return r!==Yv;try{return process.kill(n,0),!1}catch(s){return s.code==="ESRCH"}}function Gh(t){return/render|animatic|final|preview|export|assemble/i.test(t)&&!/thumb|still|review|qa/i.test(t)?"heavy":"light"}function e_(t){if(t.exitCode!==null||t.signalCode!==null)return;try{t.kill("SIGTERM")}catch{}setTimeout(()=>{if(t.exitCode===null&&t.signalCode===null)try{t.kill("SIGKILL")}catch{}},3e3).unref()}function PA(){try{wi.renew(Qn(),Date.now()+Qs());let t=new Set(wi.idsOwnedBy(Qn(),["cancelled"]));for(let e of t){let r=es.get(e);r&&!r.controller.signal.aborted&&o_(r,"Cancelled.")}}catch(t){console.error(`Sundown Reel jobs: heartbeat failed: ${t instanceof Error?t.message:String(t)}`)}}function OA(){Xs||(Xs=setInterval(()=>{PA(),!es.size&&Xs&&(clearInterval(Xs),Xs=null)},Math.max(20,Math.floor(Qs()/3))),Xs.unref())}function eo(t){return{cartoon_animatic:"render_animatic",cartoon_final:"render_final",cartoon_vo_align:"vo_align",cartoon_qa:"qa_run",thumbnail_make:"thumbnail_make",review_shots:"review_shots",render_shot:"render_shot",render_preview:"render_preview",assemble_export:"assemble_export",geodata_install:"geodata_install",browser_install:"browser_install"}[t]??null}function TA(t){let e=eo(t.type),r=t.episodeId?` {episodeId: "${t.episodeId}"}`:t.projectId?` {projectId: "${t.projectId}"}`:"";return"Interrupted: the Sundown Reel server process running this job stopped (restart, crash or sleep) before it finished; nothing is running it now. "+(e?`Re-run ${e}${r} to start it again.`:`Re-run the tool that started it (${t.type}).`)}function r_(){t_=Date.now();let t=Date.now(),e=Qn(),r=[];for(let n of wi.activeNotOwnedBy(e)){if(!(n.leaseUntil===null||n.leaseUntil===void 0||n.leaseUntil<t)&&!jA(n.leaseOwner))continue;let o=TA(n);fr(n.id,{status:"interrupted",message:o,error:o},{status:Xn,...n.leaseOwner?{owner:n.leaseOwner}:{}})&&r.push(on({...n,status:"interrupted",message:o,error:o}))}for(let n of Xv.keys())NA(n);return r}function Uh(){Date.now()-t_>2e3&&r_()}function NA(t){let e=Xv.get(t);if(e)for(let r of Dh({type:t,status:["interrupted"]})){let n=r.attempts??1;if(n>IA||!fr(r.id,{status:"queued",message:`Resumed after a server restart (attempt ${n+1}).`,error:"",attempts:n+1,leaseOwner:Qn(),leaseUntil:Date.now()+Qs()},{status:["interrupted"]}))continue;let o=Zs(r.id);o&&n_(o,(i,a)=>e(o.args,i,a))}}function n_(t,e){let r=t.lane??Gh(t.type),n={id:t.id,job:t,work:e,controller:new AbortController,children:new Set};es.set(t.id,n),qh[r].queue.push(n),OA(),s_(r)}function s_(t){let e=qh[t];if(e.running)return;let r=e.queue.shift();r&&(e.running=r,AA(r).finally(()=>{e.running=null,es.delete(r.id),s_(t)}))}function o_(t,e){if(!t.controller.signal.aborted){t.job.status="cancelled",t.job.message=e,t.controller.abort(new Error(e));for(let r of t.children)e_(r)}}async function AA(t){let e=Qn();if(!fr(t.id,{status:"running",message:"Running.",leaseOwner:e,leaseUntil:Date.now()+Qs(),attempts:Math.max(1,t.job.attempts??0)},{status:["queued"]})||t.controller.signal.aborted)return;t.job.status="running",t.job.message="Running.";let n=new Promise(i=>t.controller.signal.addEventListener("abort",()=>i("aborted"),{once:!0})),s={jobId:t.id,signal:t.controller.signal},o=Qv.run(t,()=>Promise.resolve().then(()=>t.work(t.job,s)));o.catch(()=>{});try{let i=await Promise.race([o.then(a=>({value:a})),n]);if(i==="aborted"){fr(t.id,{status:"cancelled",message:t.job.message||"Cancelled."},{status:["running","cancelled"]});return}t.job.result=i.value,t.job.status="succeeded",t.job.progress=100,t.job.message="Finished.",fr(t.id,{status:"succeeded",progress:100,message:"Finished.",result:i.value??null},{status:["running"],owner:e})}catch(i){if(t.controller.signal.aborted){fr(t.id,{status:"cancelled",message:t.job.message||"Cancelled."},{status:["running","cancelled"]});return}let a=i instanceof Error?i.message:String(i);t.job.status="failed",t.job.error=a,t.job.message=a,fr(t.id,{status:"failed",error:a,message:a},{status:["running"],owner:e})}}function ft(t,e,r,n={}){let s=new Date().toISOString(),o=n.lane??Gh(t),i={id:Ks("job"),type:t,status:"queued",progress:0,message:"Queued.",...e?{projectId:e}:{},...n.episodeId?{episodeId:n.episodeId}:{},...n.args!==void 0?{args:n.args}:{},lane:o,attempts:0,leaseOwner:Qn(),leaseUntil:Date.now()+Qs(),createdAt:s,updatedAt:s};return wi.insert(i),n_(i,r),on(i)}function Xe(t,e,r){if(!es.get(t.id)?.controller.signal.aborted){t.progress=Math.max(0,Math.min(99,Math.round(e))),t.message=r;try{fr(t.id,{progress:t.progress,message:r},{status:["running","queued"]})}catch(s){console.error(`Sundown Reel jobs: progress write failed: ${s instanceof Error?s.message:String(s)}`)}}}function ts(t={}){return Uh(),Dh(t).map(on)}function i_(t){Uh();let e=Zs(t);return e?on(e):null}function a_(t){if(!/^job_[a-f0-9]{8}$/.test(t))throw new Error(`Unknown job "${t}". Job ids look like job_1a2b3c4d (job_list shows them).`);Uh();let e=Zs(t);if(!e)throw new Error(`Unknown job "${t}". Call job_list to see the jobs on this machine.`);if(!Xn.includes(e.status))return{jobId:t,cancelled:!1,status:e.status,note:`Nothing to cancel: the job is already ${e.status}.`,job:on(e)};let r="Cancelled by job_cancel.",n=fr(t,{status:"cancelled",message:r},{status:Xn}),s=es.get(t);if(s){let a=qh[s.job.lane??Gh(s.job.type)],c=a.queue.indexOf(s);c>=0&&(a.queue.splice(c,1),es.delete(t)),o_(s,r)}let o=Zs(t)??{...e,status:"cancelled",message:r},i=n?s?e.status==="running"?"Stopped: its signal was aborted and its child processes were sent SIGTERM.":"Removed from the queue before it started.":"Marked cancelled; the server process that runs it stops it within a few seconds.":`The job finished (${o.status}) before it could be cancelled.`;return{jobId:t,cancelled:n,status:o.status,note:i,job:on(o)}}var IA,Qs,Yv,Qn,qh,es,Xv,Qv,Xs,t_,Fh,mr=v(()=>{"use strict";Ys();IA=2,Qs=()=>Math.max(50,Number(process.env.SUNDOWNREEL_JOB_LEASE_MS??3e4)),Yv=RA(4).toString("hex"),Qn=()=>`${process.pid}:${Yv}`;Wv(()=>({owner:Qn(),until:Date.now()+Qs()}));qh={heavy:{queue:[],running:null},light:{queue:[],running:null}},es=new Map,Xv=new Map,Qv=new $A;EA.subscribe("child_process",t=>{let e=Qv.getStore(),r=t.process;!e||!r||(e.children.add(r),r.once("exit",()=>e.children.delete(r)),e.controller.signal.aborted&&e_(r))});Xs=null;t_=0;Fh=!1;Bv(()=>{if(!Fh){Fh=!0;try{r_()}catch(t){console.error(`Sundown Reel jobs: recovery failed: ${t instanceof Error?t.message:String(t)}`)}finally{Fh=!1}}})});function Ac(t){return to(t).rows}function to(t){let e=t.charCodeAt(0)===65279?t.slice(1):t,r=[],n=[],s="",o=!1;for(let l=0;l<e.length;l++){let d=e[l];o?d==='"'&&e[l+1]==='"'?(s+='"',l++):d==='"'?o=!1:s+=d:d==='"'?o=!0:d===","?(n.push(s),s=""):d===`
|
|
37
|
+
`||d==="\r"?(d==="\r"&&e[l+1]===`
|
|
38
|
+
`&&l++,n.push(s),r.push(n),n=[],s=""):s+=d}(s||n.length)&&(n.push(s),r.push(n));let[i,...a]=r.filter(l=>l.some(d=>d.trim()));if(!i)return{header:[],rows:[]};let c=i.map(l=>l.trim());return{header:c,rows:a.map(l=>Object.fromEntries(c.map((d,p)=>[d,(l[p]??"").trim()])))}}function c_(t){return/[",\r\n]/.test(t)||/^\s|\s$/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function Vh(t,e){let r=[t.map(c_).join(",")];for(let n of e)r.push(t.map(s=>c_(n[s]??"")).join(","));return`${r.join(`
|
|
39
|
+
`)}
|
|
40
|
+
`}var vi=v(()=>{"use strict"});import{existsSync as GU,readFileSync as l_,statSync as CA}from"node:fs";import d_ from"node:path";function p_(t,e,r){return{dry_run:!0,method:"POST",url:u_,headers:{"xi-api-key":"***REDACTED***"},content_type:"multipart/form-data",files:{file:{filename:d_.basename(t),size_bytes:CA(t).size}},data:{text:e},out:r}}async function h_(t,e,r){let n=new FormData;n.append("file",new Blob([l_(t)]),d_.basename(t)),n.append("text",e);let s=await(DA??fetch)(u_,{method:"POST",headers:{"xi-api-key":r},body:n,signal:AbortSignal.timeout(6e5)});if(!s.ok){let a=(await s.text().catch(()=>"")).slice(0,300);throw new Error(`ElevenLabs forced alignment failed: HTTP ${s.status}${a?` ${a}`:""}`)}let o=await s.json(),i=(o.words??[]).filter(a=>(a.text??"").trim()).map(a=>({text:a.text,start:Cc(a.start),end:Cc(a.end)}));if(!i.length)throw new Error(`no words returned: ${JSON.stringify(o).slice(0,300)}`);return{loss:o.loss??null,words:i}}function f_(t){try{let e=l_(t);if(e.length<44||e.toString("ascii",0,4)!=="RIFF"||e.toString("ascii",8,12)!=="WAVE")return null;let r=0;for(let n=12;n+8<=e.length;){let s=e.toString("ascii",n,n+4),o=e.readUInt32LE(n+4);if(s==="fmt "&&(r=e.readUInt32LE(n+16)),s==="data"&&r>0)return Math.min(o,e.length-n-8)/r;n+=8+o+o%2}}catch{}return null}function m_(t,e){let r=t.split(/\s+/).filter(Boolean),n=e&&e>0&&r.length?e/r.length:1/LA;return{loss:null,estimated:!0,words:r.map((o,i)=>({text:o,start:Cc(i*n),end:Cc((i+1)*n)}))}}var u_,LA,DA,Cc,zh,g_=v(()=>{"use strict";u_="https://api.elevenlabs.io/v1/forced-alignment",LA=2.6,DA=null,Cc=t=>Math.round(t*1e3)/1e3;zh='No ELEVENLABS_API_KEY is configured, so 06-vo/words.json holds ESTIMATED word timing (flagged "estimated": true), not a real alignment: shots, chapters and captions may drift from the recording. Add the key to the Claude config env and run vo_align again for exact timing.'});import{existsSync as Hh,mkdirSync as MA,readFileSync as v_,statSync as FA,writeFileSync as y_}from"node:fs";import gr from"node:path";function GA(t){let e=Lc(t);return(Array.isArray(e)?e:e.words??[]).map(n=>({w:String(n.w??n.text??""),s:Number(n.s??n.start)}))}function UA(t,e,r){let n=e?" The thumbnail was created with AI image tools.":"";return r?`Animated with our own code-based cartoon engine. Script researched and drafted with AI assistance and reviewed by a human; voice: ${t||"Jacob's own voice"}.${n}`:`Animated with code-rendered graphics by Sundown Reel. Script researched and drafted with AI assistance and reviewed by a human.${t?` Voice: ${t}.`:""}${n}`}function __(t,e={}){let r=Lc(gr.join(t,"04-script/meta.json")),n=GA(gr.join(t,"06-vo/words.json")),s=n.map(g=>b_(g.w)),o=g=>{let y=g.split(/\s+/).map(b_).filter(Boolean);for(let w=0;w<s.length;w++)if(y.every((S,$)=>s[w+$]===S))return n[w].s;throw new Error(`chapter anchor not found: ${g}`)},i=[{t:"0:00",title:r.chapters[0].title},...r.chapters.slice(1).map(g=>({t:qA(o(g.anchor)),title:g.title}))],a=Ac(v_(gr.join(t,"03-research/facts.csv"),"utf8")),c=gr.join(t,"10-credits.json"),l=Hh(c)?Lc(c):{},d=w_(gr.join(t,"08-package"))&&!w_(gr.join(t,"12-package"))?"08-package":"12-package",p=["12-package","08-package"].some(g=>{let y=gr.join(t,g,"thumb-log.json");return Hh(y)&&(Lc(y)??[]).some(w=>w.status==="saved")}),f=UA(l.narration?.voice_disclosure,p,!!e.operator),h=[r.hook_line,"","Chapters:",...i.map(g=>`${g.t} ${g.title}`),"","Sources (every number on screen):"];for(let g of a)g.status==="verified"&&h.push(`[${g.id}] ${g.claim} \u2014 ${g.source_name}, ${g.source_date}: ${g.url}`);h.push("","This video is educational entertainment, not financial advice. Scenarios are hypothetical unless a source is cited.",f,"",`Music & SFX: ${(l.audio??["(fill in licenses)"]).join("; ")}`);let m=`${h.join(`
|
|
41
|
+
`)}
|
|
42
|
+
`;return MA(gr.join(t,d),{recursive:!0}),y_(gr.join(t,d,"meta.json"),JSON.stringify({title:r.title??null,disclosure:f,chapters:i},null,1)),y_(gr.join(t,d,"description.md"),m),{pkg:d,description:m,chapters:i,disclosure:f}}var b_,qA,Lc,w_,S_=v(()=>{"use strict";vi();b_=t=>t.toLowerCase().replace(/[^a-z0-9$%]+/g,""),qA=t=>`${Math.floor(t/60)}:${String(Math.floor(t%60)).padStart(2,"0")}`,Lc=t=>JSON.parse(v_(t,"utf8")),w_=t=>Hh(t)&&FA(t).isDirectory()});import{existsSync as VA,statSync as zA}from"node:fs";import x_ from"node:path";function HA(t){for(let e of(process.env.PATH??"").split(x_.delimiter)){if(!e)continue;let r=x_.join(e,process.platform==="win32"?`${t}.cmd`:t);try{if(VA(r)&&zA(r).isFile())return!0}catch{}}return!1}function yr(){return J()&&!HA("sundownreel-gate")?"npx -p @sundownreel/mcp sundownreel-gate":"sundownreel-gate"}var _i=v(()=>{"use strict";pe()});import{existsSync as k_,statSync as BA}from"node:fs";import Si from"node:path";function Wt(){return Si.join(_t(),"videos")}function Bh(t){if(!JA.test(t)||t.includes(".."))throw new Error(`Invalid episode id "${t}". Use the folder name under videos/ (call episode_list).`)}function N(t){Bh(t);let e=Wt(),r=Si.join(e,t);if(Si.relative(e,r).startsWith(".."))throw new Error(`Invalid episode id "${t}".`);if(!k_(r)||!BA(r).isDirectory())throw new Error(`Unknown episode "${t}" under ${e}. Call episode_list.`);return r}function rs(){let t=Si.join(_t(),"prompts");return k_(t)?t:Si.join(Se(),"prompts")}var JA,Pe=v(()=>{"use strict";pe();JA=/^[A-Za-z0-9_][A-Za-z0-9._-]{0,119}$/});import{spawn as WA}from"node:child_process";import{existsSync as Mc}from"node:fs";import Nr from"node:path";function ro(){return!J()||Mc(Nr.join(an(),"scripts","qa.py"))}function an(){if(process.env.REELFORGE_PIPELINE)return Nr.resolve(process.env.REELFORGE_PIPELINE);let t=Nr.join(_t(),"pipeline");return Mc(Nr.join(t,"scripts"))?t:Nr.join(Se(),"pipeline")}function Jh(){if(process.env.REELFORGE_PYTHON)return process.env.REELFORGE_PYTHON;let t=Nr.join(an(),".venv","bin","python");return Mc(t)?t:"python3"}function KA(t){let e=["PATH","HOME","TMPDIR","LANG","LC_ALL","REELFORGE_HOME","SUNDOWNREEL_STUDIO"],r={PYTHONDONTWRITEBYTECODE:"1",PYTHONIOENCODING:"utf-8"};for(let n of e)process.env[n]&&(r[n]=process.env[n]);return{...r,...t}}function Wh(t,e,r){let n=Nr.join(an(),"scripts",t);if(!Mc(n))return Promise.reject(new Dc(`Pipeline not installed: ${n} is missing. Set REELFORGE_PIPELINE to the reel-forge pipeline/ folder.`));let s=Jh(),o=[Nr.basename(s),`pipeline/scripts/${t}`,...e].join(" ");return new Promise((i,a)=>{let c=WA(s,["-I",n,...e],{cwd:r.cwd??Nr.dirname(an()),env:KA(r.env??{}),stdio:["ignore","pipe","pipe"]}),l="",d="",p=(h,m)=>h.length>2e5?h:h+m,f=setTimeout(()=>c.kill("SIGKILL"),r.timeoutMs);c.stdout.on("data",h=>l=p(l,h.toString())),c.stderr.on("data",h=>d=p(d,h.toString())),c.on("error",h=>{clearTimeout(f),a(new Dc(`Could not start ${s}: ${h.message}. Set REELFORGE_PYTHON.`))}),c.on("close",(h,m)=>{clearTimeout(f),i({code:h??(m?137:1),stdout:l,stderr:d,command:o})})})}var xi,Dc,Fc,no=v(()=>{"use strict";pe();Pe();xi="QA was skipped: the automated QA pipeline (Python) is not part of the npm package. Review the final, the package text and the thumbnail yourself before Gate 4.",Dc=class extends Error{};Fc=(t,e=12)=>t.trim().split(/\r?\n/).slice(-e).join(`
|
|
43
|
+
`)});import{existsSync as ZA,readFileSync as YA}from"node:fs";import XA from"node:path";function $_(t){let e=XA.join(t,"episode.json");if(!ZA(e))return null;try{let r=JSON.parse(YA(e,"utf8"));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function Ee(t){let e=$_(t)?.style;return typeof e=="string"&&e.trim()?e.trim():rC}function Kh(t){return oe(t)?eC:QA}function br(t){let e=$_(t)?.gateProfile,r=e==="quick"||e==="strict"?e:null,n=r??Kh(Ee(t));return{profile:n,source:r?"episode.json":"default",...nC[n]}}function E_(t){let e=r=>t.required.includes(r)?"required":"optional";return{gate1:e(1),gate2:e(2),gate3:e(3),gate4:e(4)}}var QA,eC,tC,rC,oe,nC,wr=v(()=>{"use strict";QA="quick",eC="strict",tC=new Set(["cutout","cartoon","paper-puppet","paper-cutout","puppet-explainer","ledger-cartoon"]),rC="cutout",oe=t=>tC.has(t.replace(/@\d+$/,"")),nC={strict:{required:[1,2,3,4],optional:[],describe:"All four gates: topic, script + facts, animatic, package."},quick:{required:[2,4],optional:[1,3],describe:"Quick film: script + facts (Gate 2) and package (Gate 4) are required; topic (Gate 1) and animatic (Gate 3) are optional. Approve with --skip-earlier to record a skipped optional gate."}}});function ki(t){let e=sC(t);return qc[e]?e:Zh[e]??null}function so(t,e=[]){for(let r of[t,...e]){let n=ki(r);if(n)return n}return t}var qc,Zh,R_,sC,Gc=v(()=>{"use strict";qc={"ledger-cartoon":{name:"Ledger Cartoon",catalogTier:"operator"},gridpaper:{name:"Gridpaper",catalogTier:"standard"},shadowbox:{name:"Shadowbox",catalogTier:"standard"},"evidence-lamp":{name:"Evidence Lamp",catalogTier:"max"},"kraft-dossier":{name:"Kraft Dossier",catalogTier:"max"},stickfolk:{name:"Stickfolk",catalogTier:"max"},"terra-relief":{name:"Terra Relief",catalogTier:"max"},"docket-3d":{name:"Docket 3D",catalogTier:"max"},"orbit-survey":{name:"Orbit Survey",catalogTier:"max"},"stagelit-stick":{name:"Stagelit Stick",catalogTier:"standard"},"gilded-noir":{name:"Gilded Noir",catalogTier:"max"},"plinth-city":{name:"Plinth City",catalogTier:"standard"},"exploded-view":{name:"Exploded View",catalogTier:"standard"},frontline:{name:"Front Line",catalogTier:"standard"},"static-rules":{name:"Static Rules",catalogTier:"max"},"glyph-story":{name:"Glyph Story",catalogTier:"standard"},"desk-chronicle":{name:"Desk Chronicle",catalogTier:"standard"},blockfolk:{name:"Blockfolk",catalogTier:"max"},fieldbook:{name:"Fieldbook",catalogTier:"standard"},"block-print":{name:"Block Print",catalogTier:"max"},"period-canvas":{name:"Period Canvas",catalogTier:"max"},"brush-scroll":{name:"Brush Scroll",catalogTier:"max"},"diecut-saga":{name:"Die-Cut Saga",catalogTier:"standard"},"shockring-duel":{name:"Shockring Duel",catalogTier:"none"}},Zh={cutout:"ledger-cartoon","paper-cutout":"ledger-cartoon","puppet-explainer":"ledger-cartoon",cartoon:"ledger-cartoon","paper-puppet":"ledger-cartoon",pictogram:"glyph-story","painted-atlas":"terra-relief","relief-atlas":"terra-relief","orbit-analyst":"orbit-survey","field-journal":"fieldbook","ink-wash":"brush-scroll",plaster:"plinth-city",whitemodel:"plinth-city",exploded:"exploded-view",teardown:"exploded-view",doc3d:"docket-3d",stickstage:"stagelit-stick",stickset:"stagelit-stick","night-front":"frontline","front-line":"frontline","gilded-deco":"gilded-noir","dread-ink":"static-rules","toybox-history":"desk-chronicle",woodblock:"block-print","chalk-board":"gridpaper","folded-paper":"shadowbox","street-whatif":"stickfolk"},R_="ledger-cartoon",sC=t=>t.trim().replace(/@\d+$/,"")});import{createHash as oC}from"node:crypto";import{existsSync as Ar,mkdirSync as iC,readdirSync as sf,readFileSync as aC,renameSync as cC,rmSync as lC,statSync as of}from"node:fs";import{createRequire as Vc}from"node:module";import _e from"node:path";import{pathToFileURL as dC}from"node:url";function I_(t,e){let r=t,n=uC.filter(s=>typeof r?.[s]!="function");if(n.length)throw new oo(`${e} is not a style registry (missing ${n.join(", ")}).`);return r}async function rf(t){try{return Vc(import.meta.url)(t)}catch(e){try{return await import(dC(t).href)}catch{throw e}}}function pC(){let t;try{t=Vc(import.meta.url).resolve("@reelforge/styles/package.json")}catch{return null}let e=JSON.parse(aC(t,"utf8")),r=e.exports?.["."]??e.exports,n=typeof r=="string"?[r]:r&&typeof r=="object"?["node","import","default"].map(s=>r[s]).filter(s=>typeof s=="string"):[];for(let s of[...n,e.main].filter(o=>typeof o=="string")){if(!/\.(mjs|js)$/.test(s))continue;let o=_e.resolve(_e.dirname(t),s);if(Ar(o))return o}return null}function nf(t,e){if(Ar(t))for(let r of sf(t)){if(r==="node_modules"||r.startsWith("."))continue;let n=_e.join(t,r);of(n).isDirectory()?nf(n,e):/\.(ts|tsx|json)$/.test(r)&&e.push(n)}}function hC(t){let e=[];nf(_e.join(t,"styles","src"),e),nf(_e.join(t,"dsl","src"),e);for(let n of["styles/package.json","dsl/package.json"])Ar(_e.join(t,n))&&e.push(_e.join(t,n));let r=oC("sha256");for(let n of e.sort()){let s=of(n);r.update(`${_e.relative(t,n)}:${s.size}:${Math.floor(s.mtimeMs)}
|
|
44
|
+
`)}return r.digest("hex").slice(0,16)}async function fC(t){let e=_e.join(t,"styles","src","index.ts");if(!Ar(e))return null;let r;try{r=Vc(_e.join(t,"styles","package.json")).resolve("esbuild")}catch{try{r=Vc(import.meta.url).resolve("esbuild")}catch{return null}}let n=_e.join(st(),"cache");iC(n,{recursive:!0});let s=_e.join(n,`styles-${hC(t)}.mjs`);if(Ar(s))return s;let o=await rf(r),i=typeof o.build=="function"?o:o.default,a=`${s}.tmp-${process.pid}.mjs`;await i.build({entryPoints:[e],bundle:!0,platform:"node",format:"esm",outfile:a,logLevel:"silent"}),cC(a,s);for(let c of sf(n))/^styles-[0-9a-f]{16}\.mjs$/.test(c)&&_e.join(n,c)!==s&&lC(_e.join(n,c),{force:!0});return s}async function mC(){let t=[],e=process.env.REELFORGE_STYLES_MODULE?.trim();if(e){let c=_e.resolve(e);if(!Ar(c))throw new oo(`REELFORGE_STYLES_MODULE=${e} does not exist. ${Xh}`);try{return{mod:I_(await rf(c),c),source:c}}catch(l){throw new oo(`REELFORGE_STYLES_MODULE=${e} could not be loaded: ${Uc(l)}. ${Xh}`)}}let r=async(c,l)=>{if(!c)return null;t.push(l);try{return{mod:I_(await rf(c),c),source:c}}catch(d){return t[t.length-1]=`${l} (${Uc(d)})`,null}},n=Se(),s=Yh?null:["index.mjs","index.js"].map(c=>_e.join(n,"styles","dist",c)).find(c=>Ar(c))??null,o=J(),i=o&&Ar(_e.join(o,"registry","styles.mjs"))?_e.join(o,"registry","styles.mjs"):null,a=await r(Yh?null:i,"bundled registry")??await r(Yh?null:pC(),"@reelforge/styles")??await r(s,"styles/dist")??await(async()=>{try{return await r(await fC(n),"styles/src via esbuild")}catch(c){return t.push(`styles/src via esbuild (${Uc(c)})`),null}})();if(a)return a;throw new oo(`The style registry (@reelforge/styles) is not available in this install${t.length?` (tried: ${t.join("; ")})`:""}. ${Xh}`)}async function Zt(){if(tf)return tf;$i??=mC();try{return(await $i).mod}catch(t){throw $i=null,t}}async function Ei(){if(tf)return{source:"injected"};try{return await Zt(),{source:$i?(await $i).source:null}}catch(t){return{source:null,error:Uc(t)}}}async function Tt(){try{return await Zt()}catch{return null}}function j_(t,e){let r=t.findStyle(e);if(r)return r;let n=ki(e);if(!n)return;let s=t.findStyle(n);if(s)return s;let o=t.listStyles({}).find(i=>so(i.id,i.aliases??[])===n);return o?t.findStyle(o.id):void 0}async function vr(t){let e=P_(t);if(Hc[e])return Hc[e];let r=await Zt(),n=j_(r,e);if(!n){let s=r.listStyles({}).filter(o=>Ae()||!oe(o.id)).map(o=>so(o.id,o.aliases??[]));throw new zc(`Unknown style "${t}". Known styles: ${s.join(", ")}. Call list_styles.`)}return n.id}async function Ne(t){let e=P_(t);if(Hc[e])return Hc[e];if(oe(e))return e;let r=await Tt();return(r?j_(r,e)?.id:void 0)??e}async function Yt(t){let e=await Ne(t),n=(await Tt())?.findStyle(e);return so(e,n?.aliases??[])}async function O_(){let t=await Tt();return t?[...new Set(t.listStyles({}).flatMap(e=>[e.id,...e.aliases??[]]))]:null}async function cn(t){let e=await vr(t),n=(await Zt()).findStyle(e);if(!n)throw new zc(`Unknown style "${t}". Call list_styles.`);let s=so(n.id,n.aliases??[]);return Kt({id:n.id,canonicalId:s,canonicalName:qc[s]?.name??n.name,name:n.name,family:n.family,renderer:n.renderer,status:n.status,tier:n.tier,operatorOnly:oe(n.id),...n.pacing?{pacing:n.pacing}:{}})}function T_(t,e=[]){let r=Se(),s=[...[...new Set([t,...e])].flatMap(i=>[_e.join(r,"styles","demo","stills",i),_e.join(r,"library","golden","styles",i),_e.join(r,"library","golden","3d",i),_e.join(r,"library","golden","geo",i)]),...t==="cutout"?[_e.join(r,"library","golden","thumbnails")]:[]],o=[];for(let i of s)if(!(!Ar(i)||!of(i).isDirectory()))for(let a of sf(i).sort())/\.(png|jpe?g|webp)$/i.test(a)&&o.length<4&&o.push(_e.join(i,a));return o}function af(t){let e=so(t.id,t.aliases??[]),r=qc[e],n=[...new Set([t.id,...t.aliases??[]])].filter(s=>s!==e);return{...t,id:e,name:r?.name??t.name,registryId:t.id,aliases:n,catalogTier:r?.catalogTier??null}}async function io(t={},e={}){let r=await Zt(),n=e.includeOperator??Ae();return Kt(r.listStyles({...t})).filter(s=>n||!oe(s.id)).map(s=>{let o=af(s);return{...o,samples:T_(s.id,[o.id]),operatorOnly:oe(s.id),renderable:s.status==="ready"}})}async function cf(t){let e=await vr(t),r=await Zt(),n=Kt(r.styleGuide(e)),s=af({...n,id:String(n.id??e),name:String(n.name??e),aliases:n.aliases??[]});return{...s,samples:T_(e,[s.id]),operatorOnly:oe(e)}}async function lf(t){let e=await cf(t),r=Array.isArray(e.kinds)?e.kinds.map(n=>({id:n.id,describe:n.describe,beats:n.beats,example:n.example})):[];return{id:e.id,name:e.name,registryId:e.registryId,status:e.status,renderer:e.renderer,promptGuide:e.promptGuide,pacing:e.pacing,kinds:r,lookJsonSchema:e.lookJsonSchema,library:e.library,vocabulary:e.vocabulary}}async function N_(t,e,r=[],n={}){let s=await vr(t),o=await Zt();return Kt(o.planShots(s,Kt(e),Kt(r),Kt(n)))}async function A_(t,e,r={}){let n=await vr(e),s=await Zt();return Kt(s.restyle(Kt(t),n,r))}async function C_(t){let e=await Zt();return Kt(e.validateStyles(Kt(t))).map(n=>n.level==="error"&&n.path==="style"&&/\bis planned\b/.test(n.msg)?{...n,level:"warn",msg:`${n.msg}: you can plan and write it now; it renders when its renderer ships`}:n)}async function L_(){let e=(await Tt())?.autoSfx;if(e)return(r,n)=>{try{return e(r,n)??[]}catch{return[]}}}async function D_(t){let e=await Tt();return e?e.listStyles({readyOnly:!0}).filter(r=>Ae()||!oe(r.id)).filter(r=>!t||r.tier!=="max"||t.styles==="all").map(r=>{let n=af(r);return`${n.name} (${n.id})`}):[]}async function M_(t,e){let r=await Ne(t);if(oe(r))return;let n=await cn(r);if(n.tier==="max"&&e.styles!=="all"){let s=await D_(e);throw new Qh(`The ${n.canonicalName} style (${n.canonicalId}) needs the Max plan; this licence (${e.tier}) covers standard styles only.`+(s.length?` Ready styles on your plan: ${s.join(", ")}.`:"")+" Upgrade to Max, or pick another style with list_styles.")}}async function df(t){let e=await Ne(t);if(oe(e))return await Tt()?cn(e):null;let r=await cn(e);if(r.status!=="ready"){let n=await D_();throw new ef(`The renderer for ${r.canonicalName} (${r.canonicalId}, ${r.renderer}) isn't built yet; plan and write now, render when it ships`+(n.length?`, or pick a ready style: ${n.join(", ")} (project_set_style).`:"."))}return r}var oo,zc,Qh,ef,tf,$i,Yh,uC,Xh,Uc,Kt,Hc,P_,ln=v(()=>{"use strict";Xt();wr();pe();Gc();oo=class extends Error{},zc=class extends Error{},Qh=class extends Error{},ef=class extends Error{},tf=null,$i=null,Yh=!1,uC=["listStyles","styleGuide","findStyle","planShots","restyle","validateStyles"];Xh="Build the registry (npm run build -w @reelforge/styles \u2192 styles/dist/index.mjs), or set REELFORGE_STYLES_MODULE to a built registry .mjs; in the monorepo the dev fallback needs esbuild (npm install at the repo root).",Uc=t=>t instanceof Error?t.message:String(t);Kt=t=>JSON.parse(JSON.stringify(t)),Hc={cartoon:"cutout","paper-puppet":"cutout","paper-cutout":"cutout","puppet-explainer":"cutout",[R_]:"cutout"};P_=t=>t.trim().replace(/@\d+$/,"")});import{existsSync as q_,lstatSync as gC,mkdirSync as yC,readdirSync as F_,readlinkSync as bC,rmSync as wC,symlinkSync as vC}from"node:fs";import Qt from"node:path";function G_(t){let e=ki(t)??t;return _C.has(e)?"geodata":SC.has(e)?"browser":null}function ns(){let t=r=>q_(Qt.join(r,"data","geo","naturalearth")),e=process.env.SUNDOWNREEL_GEODATA?.trim();for(let r of[e?Qt.resolve(e):null,pf(),J()])if(r&&t(r))return r;return null}function U_(){let t=ns();if(!t)return null;let e=Qt.join(Rd(),"geo-repo"),r=Qt.join(e,"data");yC(Qt.join(e,"engine-geo","cache"),{recursive:!0});let n=Qt.join(t,"data"),s=null;try{s=gC(r).isSymbolicLink()?bC(r):""}catch{}return s!==n&&(s!==null&&wC(r,{recursive:!0,force:!0}),vC(n,r,"dir")),e}function dn(){let t=Qt.join(Bc(),"chrome-headless-shell"),e=process.platform==="win32"?"chrome-headless-shell.exe":"chrome-headless-shell";try{for(let r of F_(t).sort().reverse())for(let n of F_(Qt.join(t,r))){let s=Qt.join(t,r,n,e);if(q_(s))return s}}catch{}return null}var _C,SC,uf,Ri,pf,Bc,un=v(()=>{"use strict";pe();Gc();_C=new Set(["terra-relief","frontline","orbit-survey","fieldbook"]),SC=new Set(["stagelit-stick","plinth-city","exploded-view","docket-3d","blockfolk"]),uf={geodata:"geodata_install",browser:"browser_install"};Ri=class extends Error{constructor(r,n){super(`${r==="geodata"?"The map styles need the open geodata":"The 3D styles need a headless Chrome"} (${n}), and it is not downloaded yet. Call ${uf[r]} and poll job_status, then retry.`);this.kind=r}kind},pf=()=>Qt.join(ea(),"geodata"),Bc=()=>Qt.join(ea(),"browsers")});import{spawn as xC}from"node:child_process";import{existsSync as ao,readFileSync as kC}from"node:fs";import{createRequire as $C}from"node:module";import pn from"node:path";import{fileURLToPath as EC}from"node:url";function IC(t){try{return $C(import.meta.url).resolve(`${t}/package.json`)}catch{let e=pn.dirname(EC(import.meta.url));for(;;){let r=pn.join(e,"node_modules",...t.split("/"),"package.json");if(ao(r))return r;let n=pn.dirname(e);if(n===e)return null;e=n}}}function mf(t="resvg-2d"){let e=os[t],r=process.env[e.env];if(r){if(!ao(r))throw new ss(`Renderer not installed: ${e.env}=${r} does not exist.`);return pn.resolve(r)}let n=J();if(n){let c=pn.join(n,V_[t].dir,V_[t].file);if(ao(c))return c}let s=IC(e.pkg);if(!s)throw new ss(`Renderer not installed: ${e.pkg} (CLI "${e.bin}") is not in this install. ${e.missingHint}`);let o=JSON.parse(kC(s,"utf8")),i=typeof o.bin=="string"?o.bin:o.bin?.[e.bin];if(!i)throw new ss(`Renderer not installed: ${e.pkg} has no "${e.bin}" CLI. ${e.missingHint} Its lead must add a "${e.bin}" bin that speaks the reelforge-render contract (still / animatic / final on a Shot DSL episode), or point ${e.env} at one.`);let a=pn.resolve(pn.dirname(s),i);if(!ao(a))throw new ss(`Renderer not installed: ${e.pkg} is present but its CLI ${i} is not built. Build it with "npm run build -w ${e.pkg}", then retry.`);return a}function gf(){let t=["PATH","HOME","TMPDIR","LANG","LC_ALL","REELFORGE_HOME","SUNDOWNREEL_STUDIO","FFMPEG_PATH","RF3D_CHROME","RF3D_GL"],e={};for(let r of t)process.env[r]&&(e[r]=process.env[r]);return e}function jC(t,e,r,n){return new Promise((s,o)=>{let i=xC(process.execPath,[t,...e],{env:gf(),stdio:["ignore","pipe","pipe"]}),a="",c="",l=setTimeout(()=>i.kill("SIGKILL"),r);i.stdout.on("data",d=>{let p=d.toString();if(a+=p,n)for(let f of p.split(/\r?\n/))f.trim()&&n(f)}),i.stderr.on("data",d=>c+=d.toString()),i.on("error",d=>{clearTimeout(l),o(d)}),i.on("close",(d,p)=>{if(clearTimeout(l),d===0)return s({stdout:a,stderr:c});let f=c.trim().split(/\r?\n/).slice(-8).join(`
|
|
45
|
+
`)||a.trim().split(/\r?\n/).slice(-4).join(`
|
|
46
|
+
`);o(new Error(`${pn.basename(t)} ${e[0]} failed (${p??`exit ${d}`}): ${f}`))})})}function PC(t,e){if(e[0]==="--version")return[];if(t==="engine-geo"&&!e.includes("--data")){let r=U_();if(!r)throw new Ri("geodata","~116 MB of Natural Earth, terrain and imagery");return["--data",r]}if(t==="engine-3d"&&!e.includes("--chrome")&&!process.env.RF3D_CHROME&&!process.env.CHROME_PATH&&!Ii()){let r=dn();if(!r)throw new Ri("browser","no Chrome, Chromium or Edge found on this machine");return["--chrome",r]}return[]}function z_(t){return OC.get(t)??(t==="resvg-2d"?new ff:new Jc(t))}async function yf(t){let e=await Ne(t);if(oe(e))return{styleId:e,family:"resvg-2d",renderer:z_("resvg-2d")};let r=await cn(e);if(!RC(r.renderer))throw new ss(`Renderer not installed: style ${r.id} wants renderer "${r.renderer}", which this MCP does not know (known: ${Wc.join(", ")}).`);return{styleId:r.id,family:r.renderer,renderer:z_(r.renderer)}}var ss,hf,Wc,os,RC,V_,Jc,ff,OC,bf=v(()=>{"use strict";ln();pe();Kc();un();wr();ss=class extends Error{},hf=class extends Error{},Wc=["resvg-2d","engine-3d","engine-geo"],os={"resvg-2d":{family:"resvg-2d",pkg:"@reelforge/engine-resvg",bin:"reelforge-render",env:"REELFORGE_RENDER_CLI",missingHint:"The 2D styles render only with the headless SVG\u2192resvg backend."},"engine-3d":{family:"engine-3d",pkg:"@reelforge/engine-3d",bin:"reelforge-render-3d",env:"REELFORGE_RENDER_CLI_3D",contractMismatch:/usage: render\.mjs/i,missingHint:"The 3D styles render with the engine-3d backend (three.js in headless Chrome)."},"engine-geo":{family:"engine-geo",pkg:"@reelforge/engine-geo",bin:"reelforge-render-geo",env:"REELFORGE_RENDER_CLI_GEO",missingHint:"The map styles render with the engine-geo backend (build it: npm run build -w @reelforge/engine-geo). It needs the open geodata bundle in data/geo (see data/geo/README.md) or --data DIR.",contractMismatch:/usage: render-geo/i}},RC=t=>Wc.includes(t);V_={"resvg-2d":{dir:"render",file:"render.mjs"},"engine-3d":{dir:"render3d",file:"render.mjs"},"engine-geo":{dir:"rendergeo",file:"render-geo.mjs"}};Jc=class{constructor(e){this.family=e;this.id=os[e].pkg}family;id;async exec(e,r,n){let s=mf(this.family);J()&&(e=[...e,...PC(this.family,e)]);try{return await jC(s,e,r,n)}catch(o){let i=os[this.family],a=o instanceof Error?o.message:String(o);throw e[0]!=="--version"&&i.contractMismatch?.test(a)?new hf(`${i.pkg} (${i.bin}) does not accept a Shot DSL episode through the reelforge-render contract yet: ${a}
|
|
47
|
+
Its lead must accept the validated Shot DSL episode (still / animatic / final, same flags as reelforge-render) or provide a converter from the Shot DSL to its own document.`):o}}async version(){let{stdout:e}=await this.exec(["--version"],3e4);return e.trim()||"unknown"}async still(e){let r=await this.version(),n=["still","--shots",e.shots,"--shot",e.shotId,"--t",String(e.t),"--scale",String(e.scale),"--out",e.out];e.frame!==void 0&&this.family!=="resvg-2d"&&n.push("--frame",String(e.frame)),e.publicDir&&n.push("--public",e.publicDir),e.words&&n.push("--words",e.words);let{stderr:s}=await this.exec(n,18e4);if(!ao(e.out))throw new Error(`${os[this.family].bin} still exited 0 but wrote no file at ${e.out}.`);return{path:e.out,renderer:this.id,version:r,log:s.trim()||void 0}}async animatic(e,r){let n=await this.version(),s=["animatic","--shots",e.shots,"--compiled",e.compiled,"--height",String(e.height),"--out",e.out];return e.vo&&s.push("--vo",e.vo),e.words&&s.push("--words",e.words),e.publicDir&&s.push("--public",e.publicDir),this.runVideo(n,s,e.out,r)}async final(e,r){let n=await this.version(),s=[e.shots,e.out,"--compiled",e.compiled,"--json-progress"];return e.vo&&s.push("--vo",e.vo),e.words&&s.push("--words",e.words),e.publicDir&&s.push("--public",e.publicDir),this.runVideo(n,s,e.out,r)}async runVideo(e,r,n,s){let o=(r[0]==="animatic"?6:24)*36e5,{stderr:i}=await this.exec(r,o,a=>{try{let c=JSON.parse(a);typeof c.progress=="number"&&s?.(c.progress,c.message??"Rendering.")}catch{}});if(!ao(n))throw new Error(`${os[this.family].bin} exited 0 but wrote no file at ${n}.`);return{path:n,renderer:this.id,version:e,log:i.trim()||void 0}}},ff=class extends Jc{constructor(){super("resvg-2d")}},OC=new Map});var H_,B_=v(()=>{"use strict";H_=["MCowBQYDK2VwAyEAu37RVAB3WbLulESoEAW6o45xKwLUzrEVbq027Em8ik4="]});import{createHash as TC,createPublicKey as NC,verify as AC}from"node:crypto";import{existsSync as CC,readFileSync as LC,renameSync as DC,writeFileSync as MC}from"node:fs";import FC from"node:path";function co(){return(process.env.SUNDOWNREEL_LICENSE_API?.trim()||qC).replace(/\/$/,"")}function VC(t){let e=J_.get(t);if(!e){try{e=NC({key:Buffer.from(t,"base64"),format:"der",type:"spki"})}catch{return null}J_.set(t,e)}return e}function K_(t){return(UC??[...H_]).map(r=>({key:r,dev:!1}))}function Z_(t){return TC("sha256").update(t).digest("hex")}function Y_(t,e,r,n){if(typeof t!="string")return null;let s=t.split(".");if(s.length!==3||s[0]!==GC)return null;let o=Buffer.from(`${s[0]}.${s[1]}`),i=Buffer.from(s[2],"base64url");for(let a of K_(r)){let c=VC(a.key);if(!c)continue;let l=!1;try{l=AC(null,o,c,i)}catch{l=!1}if(!l)continue;let d;try{d=JSON.parse(Buffer.from(s[1],"base64url").toString("utf8"))}catch{return null}return d.v!==1||d.kh!==Z_(e)||typeof d.exp!="number"||d.exp<=n||a.dev&&d.active&&(d.tier!=="standard"||d.entitlements?.styles!=="standard")?null:{claims:d,devKey:a.dev,token:t}}return null}function Zc(){return FC.join(st(),"license-cache.json")}function wf(t,e,r){if(!CC(Zc()))return null;try{let n=JSON.parse(LC(Zc(),"utf8"));return Y_(n.token,t,e,r)}catch{return null}}function zC(t,e,r,n){let s=wf(e,r,n);if(s){let i=s.claims.active===t.claims.active&&s.claims.tier===t.claims.tier,a=s.claims.exp-s.claims.iat,c=s.claims.exp-n;if(i&&c>a/2)return}let o=`${Zc()}.tmp-${process.pid}`;MC(o,JSON.stringify({token:t.token})),DC(o,Zc())}function X_(t,e){return e&&t.claims.status==="disconnected"?(t0(e),new Nt(HC)):new Nt(t.claims.status==="revoked"?JC:BC)}function Q_(t,e){let r=t.claims.entitlements;if(!r)throw new Nt("The licence token carries no entitlements.");return{...r,graceHours:e,...t.devKey?{dev:!0}:{}}}function WC(){let t=Number(process.env.SUNDOWNREEL_LICENSE_MEMO_SEC??"300");return Number.isFinite(t)&&t>=0?t*1e3:3e5}async function Cr(t){let e=is(),r=process.env.SUNDOWNREEL_LICENSE_KEY?.trim(),n=e??r;if(!n)throw new Nt("This machine isn't connected yet. Run sundownreel_connect and approve it in your browser.");let s=n,o=co();if(!/^https?:\/\//.test(o))throw new Nt(`SUNDOWNREEL_LICENSE_API must be an http(s) URL (got "${o}").`);if(!K_(o).length)throw new Nt("This build has no licence public key, so it cannot verify any licence. Install a release build of Sundown Reel.");let i=t?.fetchImpl??fetch,a=t?.now??Date.now(),c=Js(),l=`${Z_(s)}|${o}`,d=W_.get(l);if(d&&d.until>a)return d.entitlements;let p;try{let m=await i(`${o}/v1/license/validate`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e?{device_token:e}:{key:s}),signal:AbortSignal.timeout(8e3)});if(p=await m.json(),!m.ok&&p.active!==!1)throw new Error(`License API returned ${m.status}`)}catch{return KC(s,o,a,c.graceHours,e)}let f=Y_(p.token,s,o,a);if(!f){let m=wf(s,o,a);if(m)return e0(m,c.graceHours,e);throw new Nt("The license server's answer is not signed by Sundown Reel, so it was ignored. Check SUNDOWNREEL_LICENSE_API.")}if(zC(f,s,o,a),!f.claims.active)throw X_(f,e);let h=Q_(f,c.graceHours);return W_.set(l,{entitlements:h,until:a+WC()}),h}function e0(t,e,r){if(!t.claims.active)throw X_(t,r);return Q_(t,e)}function KC(t,e,r,n,s){let o=wf(t,e,r);if(o)return e0(o,n,s);throw new Nt("License server unreachable and no valid offline grace cache. Check SUNDOWNREEL_LICENSE_API.")}var Nt,qC,GC,UC,J_,HC,BC,JC,W_,lo=v(()=>{"use strict";Pc();Yc();B_();pe();Nt=class extends Error{},qC="https://api.sundownreel.com";GC="srl1",UC=null,J_=new Map;HC="This machine was disconnected from your Sundown Reel account. Run sundownreel_connect to connect it again.",BC="subscription inactive: your Sundown Reel plan isn't active. Open your dashboard (https://sundownreel.com/account) to renew.",JC="subscription inactive: your Sundown Reel plan is on hold. Contact hello@sundownreel.com.";W_=new Map});import{spawn as ZC}from"node:child_process";import{chmodSync as YC,existsSync as XC,readFileSync as QC,renameSync as e2,rmSync as t2,writeFileSync as r2}from"node:fs";import n2 from"node:os";import s2 from"node:path";function vf(){return s2.join(st(),"device.json")}function is(){let t=vf();if(!XC(t))return null;try{let e=JSON.parse(QC(t,"utf8"));return typeof e.device_token!="string"||!e.device_token||e.api!==co()?null:e.device_token}catch{return null}}function o2(t){let e=vf(),r=`${e}.tmp-${process.pid}`;r2(r,JSON.stringify({device_token:t,api:co(),connected_at:new Date().toISOString()},null,2),{mode:384}),YC(r,384),e2(r,e)}function t0(t){if(is()===t)try{t2(vf(),{force:!0})}catch{}}async function i2(t){try{let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start",'""',t]]:["xdg-open",[t]],n=ZC(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}async function c2(t){let e=t?.fetchImpl??fetch,r=co(),n=await e(`${r}/v1/device/start`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:n2.hostname(),platform:process.platform}),signal:AbortSignal.timeout(1e4)});if(!n.ok)throw new Error(`Could not start the connection (the Sundown Reel server answered ${n.status}). Try again in a minute.`);let s=await n.json();if(!s.device_code||!s.user_code)throw new Error("The Sundown Reel server's answer was not understood. Try again in a minute.");let o=s.verification_uri_complete||s.verification_uri,i=(s.interval??5)*1e3,a=Date.now()+(s.expires_in??600)*1e3,c=!1,l={userCode:s.user_code,url:o,poll:Promise.resolve("expired"),cancel:()=>{c=!0}},d=(async()=>{for(;!c&&Date.now()<a&&(await a2(i),!(c||Date.now()>=a));)try{let p=await e(`${r}/v1/device/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_code:s.device_code}),signal:AbortSignal.timeout(1e4)}),f=await p.json().catch(()=>({}));if(p.ok&&typeof f.device_token=="string"){if(c)break;try{o2(f.device_token)}catch(h){let m=h instanceof Error?h.message:String(h);return l.error=`Connected, but couldn't save the connection on this computer: ${m}. Check that ${st()} is writable, then run sundownreel_connect again.`,process.stderr.write(`sundownreel_connect: ${l.error}
|
|
48
|
+
`),"error"}return"connected"}if(f.error==="access_denied")return"denied";if(f.error==="expired_token")return"expired";f.error==="slow_down"&&(i+=5e3)}catch{}return"expired"})();return(t?.openUrl??i2)(o).catch(()=>{}),l.poll=d,l}function r0(t){return[`Open ${t.url} and approve this machine. Check that the page shows the code ${t.userCode}.`,"The browser was opened for you if this computer allows it. This connects automatically once you approve; there is nothing to paste.","Run sundownreel_connect again to see this message, or call it with reconnect: true to start over."].join(`
|
|
49
|
+
`)}async function n0(t,e){let r=!!t?.reconnect,n=co();if(ji&&!r){let i=ji;return ji=null,i}if(ji=null,_r&&_r.api===n&&!r)return r0(_r);if(!r&&is())return"This machine is already connected to your Sundown Reel account. Call sundownreel_connect with reconnect: true to connect it again.";_r?.cancel(),_r=null;let s=await c2(e),o={...s,api:n};return _r=o,s.poll.then(i=>{_r===o&&(_r=null),i==="error"&&s.error&&(ji=s.error)},()=>{_r===o&&(_r=null)}),r0(s)}var a2,_r,ji,Yc=v(()=>{"use strict";lo();pe();a2=t=>new Promise(e=>{setTimeout(e,t).unref?.()});_r=null,ji=null});import{spawn as l2}from"node:child_process";import{accessSync as c0,constants as l0,existsSync as mt,readdirSync as s0,statSync as $f,statfsSync as d2}from"node:fs";import{createRequire as u2}from"node:module";import d0 from"node:os";import me from"node:path";function kf(t){try{return $f(t).isFile()?(process.platform!=="win32"&&c0(t,l0.X_OK),!0):!1}catch{return!1}}function Pi(t){for(let e of(process.env.PATH??"").split(me.delimiter)){if(!e)continue;let r=me.join(e,el(t));if(kf(r))return r}return null}function h2(t,e,r){return new Promise(n=>{let s="",o=!1,i=d=>{o||(o=!0,clearTimeout(c),n(d))},a;try{a=l2(t,e,{stdio:["ignore","pipe","pipe"],env:{PATH:process.env.PATH??"",HOME:d0.homedir()}})}catch(d){n({ok:!1,firstLine:tl(d)});return}let c=setTimeout(()=>{a.kill("SIGKILL"),i({ok:!1,firstLine:`timed out after ${r} ms`})},r),l=d=>{s.length<4096&&(s+=d.toString())};a.stdout?.on("data",l),a.stderr?.on("data",l),a.on("error",d=>i({ok:!1,firstLine:tl(d)})),a.on("close",d=>i({ok:d===0,firstLine:s.trim().split(/\r?\n/)[0]??""}))})}function Qc(t){let e=me.resolve(t);for(;!mt(e)&&me.dirname(e)!==e;)e=me.dirname(e);return e}function f2(t){try{let e=d2(Qc(t));return e.bavail*e.bsize}catch{return null}}function a0(t){try{return c0(t,l0.W_OK),!0}catch{return!1}}function Ii(t=Se()){let e=process.env.RF3D_CHROME||process.env.CHROME_PATH;if(e&&mt(e))return e;let r=[];process.platform==="darwin"&&r.push("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"),process.platform==="linux"&&r.push("/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium","/usr/bin/chromium-browser"),process.platform==="win32"&&r.push("C:/Program Files/Google/Chrome/Application/chrome.exe","C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe");let n=r.find(o=>mt(o));if(n)return n;let s=[me.join(t,"node_modules/.remotion/chrome-headless-shell"),me.join(d0.homedir(),".cache/puppeteer/chrome-headless-shell")];for(let o of s)if(mt(o))try{for(let i of s0(o).sort().reverse()){let a=me.join(o,i);for(let c of mt(a)?s0(a):[]){let l=me.join(a,c,el("chrome-headless-shell"));if(mt(l))return l}}}catch{}return null}function m2(){let t=process.env.FFMPEG_PATH?.trim();if(t){let e=me.resolve(t),r=null;try{r=$f(e).isDirectory()?me.join(e,el("ffmpeg")):e}catch{return{ffmpeg:null,ffprobe:null,via:"FFMPEG_PATH",problem:`FFMPEG_PATH=${t} does not exist`}}if(!kf(r))return{ffmpeg:null,ffprobe:null,via:"FFMPEG_PATH",problem:`FFMPEG_PATH: no executable ffmpeg at ${r}`};let n=me.join(me.dirname(r),el("ffprobe"));return{ffmpeg:r,ffprobe:kf(n)?n:Pi("ffprobe"),via:"FFMPEG_PATH"}}return{ffmpeg:Pi("ffmpeg"),ffprobe:Pi("ffprobe"),via:"PATH"}}function g2(){let t=J();if(t&&mt(me.join(t,"dsl","index.mjs")))return me.join(t,"dsl","index.mjs");try{let r=u2(import.meta.url).resolve("@reelforge/dsl");if(/\.(m?js)$/.test(r)&&mt(r))return r}catch{}let e=me.join(Se(),"dsl","dist","index.js");return mt(e)?e:null}function y2(t,e,r){return new Promise(n=>{let s=setTimeout(()=>n(r),e);t.then(o=>{clearTimeout(s),n(o)},()=>{clearTimeout(s),n(r)})})}async function u0(t={},e={}){let r=Date.now(),n=e.probe??h2,s=[],o=E=>(s.push(E),E),i=Se(),a=$d(),c=Ed(),l=Po(),d=m2(),p=Jh(),f=!!process.env.REELFORGE_PYTHON,h=!f&&p!=="python3",m=d.ffmpeg?n(d.ffmpeg,["-version"],Sf):Promise.resolve(null),g=d.ffprobe?n(d.ffprobe,["-version"],Sf):Promise.resolve(null),y=h||f?n(p,["--version"],Sf):Promise.resolve(null),w=y2((e.styles??Ei)(),i0,{source:null,error:`the style registry did not load within ${i0} ms (it may be bundling for the first time; run doctor again)`}),S=v2(t,e),$=e.nodeVersion??process.versions.node,k=Number($.split(".")[0]);o(k>=_f?{id:"node",status:"ok",detail:`node ${$}`}:{id:"node",status:"fail",detail:`node ${$} (needs ${_f}+)`,fix:`Install Node ${_f} or newer (https://nodejs.org or \`brew install node\`), point the Claude config "command" at it, restart Claude.`});{let[E,Z]=await Promise.all([m,g]),ae="Install ffmpeg (macOS: `brew install ffmpeg`; Debian/Ubuntu: `sudo apt install ffmpeg`) so ffmpeg and ffprobe are on the MCP server's PATH, or set FFMPEG_PATH to the ffmpeg binary; restart the MCP server.";if(d.problem)o({id:"ffmpeg",status:"fail",detail:d.problem,fix:`Fix or unset FFMPEG_PATH. ${ae}`});else if(!d.ffmpeg||!E?.ok)o({id:"ffmpeg",status:"fail",detail:d.ffmpeg?`ffmpeg at ${d.ffmpeg} does not run (${E?.firstLine??"?"})`:"ffmpeg not found on PATH",fix:ae});else if(!d.ffprobe||!Z?.ok)o({id:"ffmpeg",status:"fail",detail:`ffmpeg ${xf(E.firstLine)} found but ffprobe ${d.ffprobe?"does not run":"is missing"}`,fix:ae});else{let vt=`ffmpeg ${xf(E.firstLine)} + ffprobe ${xf(Z.firstLine)} (${d.via}: ${me.dirname(d.ffmpeg)})`,we=d.via==="FFMPEG_PATH"?Pi("ffmpeg"):d.ffmpeg;o(we?{id:"ffmpeg",status:"ok",detail:vt}:{id:"ffmpeg",status:"warn",detail:`${vt}; but no ffmpeg on PATH, and the render backends and the Python pipeline call \`ffmpeg\` from PATH`,fix:`Add ${me.dirname(d.ffmpeg)} to PATH in the MCP server's env (Claude config "env"), then restart the MCP server.`})}}for(let[E,Z,ae,vt]of[["studio-home",a,"episodes (videos/), prompts/, .env","sundownreel-init (or episode_create)"],["state-home",c,"Chalkline projects, jobs, licence cache, gate keys","the MCP server on first use"]]){let we=mt(Z.path),le=`${Z.path} (${Z.source==="default"?"default":Z.source==="legacy-default"?"legacy default":`from ${Z.source}`}; ${ae})`;if(we&&!$f(Z.path).isDirectory())o({id:E,status:"fail",detail:`${le} is not a folder`,fix:`Move that file away or point ${E==="studio-home"?"SUNDOWNREEL_STUDIO (or REELFORGE_HOME)":"SUNDOWNREEL_HOME"} at a folder.`});else if(we)o(a0(Z.path)?{id:E,status:"ok",detail:`${le} writable`}:{id:E,status:"fail",detail:`${le} is not writable`,fix:`Give your user write access (chmod u+w "${Z.path}") or point ${E==="studio-home"?"SUNDOWNREEL_STUDIO (or REELFORGE_HOME)":"SUNDOWNREEL_HOME"} at a writable folder.`});else{let zr=Qc(Z.path);a0(zr)?E==="studio-home"&&J()?o({id:E,status:"ok",detail:`${le} does not exist yet; episode_create creates it on first use`}):o(E==="studio-home"?{id:E,status:"warn",detail:`${le} does not exist yet`,fix:`Run \`sundownreel-init\` in your terminal (creates ${Z.path}/videos and the Claude config entry), or episode_create will create it.`}:{id:E,status:"ok",detail:`${le} will be created by ${vt}`}):o({id:E,status:"fail",detail:`${le} does not exist and ${zr} is not writable`,fix:`Create it yourself (mkdir -p "${Z.path}") or point ${E==="studio-home"?"SUNDOWNREEL_STUDIO (or REELFORGE_HOME)":"SUNDOWNREEL_HOME"} at a writable folder.`})}}a.source==="legacy-default"&&o({id:"studio-home-legacy",status:"warn",detail:`Using the old studio folder ${a.path} because ~/SundownReel does not exist.`,fix:`Optional: rename it to ~/SundownReel (mv "${a.path}" "${me.join(me.dirname(a.path),"SundownReel")}"), then restart the MCP server. Nothing else changes.`});{let E=(e.freeBytes??f2)(a.path);if(E==null)o({id:"disk",status:"warn",detail:"free space unknown",fix:`Check free space with \`df -h "${Qc(a.path)}"\`; keep at least ${Xc} GB free for renders.`});else{let Z=p2(E),ae=`${Z.toFixed(1)} GB free at ${Qc(a.path)}`;Z<o0?o({id:"disk",status:"fail",detail:`${ae} (renders refuse under ${o0} GB)`,fix:`Free at least ${Xc} GB: delete old renders (videos/*/09-renders, 10-final) or move the studio (SUNDOWNREEL_STUDIO) to a bigger disk.`}):Z<Xc?o({id:"disk",status:"warn",detail:`${ae} (tight: a final render plus audio can take several GB)`,fix:`Free space to at least ${Xc} GB (old renders under videos/*/09-renders and 10-final are safe to delete once uploaded).`}):o({id:"disk",status:"ok",detail:ae})}}{let E=Wm(l),Z=Object.keys(Pd),ae=Zm(),vt=Z.filter(le=>process.env[le]!==void 0&&process.env[le]!==""),we={file:l,mode:E.mode,inFile:E.names.filter(le=>Z.includes(le)),notAllowed:E.names.filter(le=>!Z.includes(le)),fromFile:ae,fromServerEnv:vt.filter(le=>!ae.includes(le))};if(!E.exists&&J())o({id:"env-file",status:"ok",detail:"no env file (optional): put keys such as ELEVENLABS_API_KEY in the Claude config env, e.g. `claude mcp add sundownreel -e ELEVENLABS_API_KEY=... -- npx -y @sundownreel/mcp`",data:we});else if(!E.exists)o({id:"env-file",status:"warn",detail:`no ${l} (optional; keys can also live in the Claude config "env")`,fix:"Run `sundownreel-init` in your terminal: it stores keys (ElevenLabs, licence) in that file with mode 600.",data:we});else if(!E.usable)o({id:"env-file",status:"fail",detail:E.problem??`${l} is not usable`,fix:E.problem?.includes("chmod")?`chmod 600 "${l}", then restart the MCP server.`:`Replace ${l} with a regular file you own, mode 600, then restart the MCP server.`,data:we});else{let le=we.inFile.filter(sE=>process.env[sE]===void 0),zr=[`${l} (mode ${E.mode})`,we.inFile.length?`sets ${we.inFile.join(", ")}`:"sets no allow-listed names"];we.notAllowed.length&&zr.push(`ignored (not allow-listed): ${we.notAllowed.join(", ")}`),E.warnings.length&&zr.push(`${E.warnings.length} malformed line(s): ${E.warnings.join("; ")}`),le.length?o({id:"env-file",status:"warn",detail:`${zr.join("; ")}; not loaded yet: ${le.join(", ")}`,fix:"Restart the MCP server (quit and reopen Claude) so it reads the .env file at start.",data:we}):E.warnings.length?o({id:"env-file",status:"warn",detail:zr.join("; "),fix:`Fix the listed lines in ${l} (KEY=VALUE, one per line), then restart the MCP server.`,data:we}):o({id:"env-file",status:"ok",detail:zr.join("; "),data:we})}}let I=Oi();I.enabled?o({id:"operator",status:"ok",detail:"operator machine: every style usable, no licence call"}):process.env.SUNDOWNREEL_OPERATOR==="1"?o({id:"operator",status:"warn",detail:`operator mode requested but off: ${I.reason}`,fix:"On the operator machine, run `sundownreel-gate key` in your own terminal, then restart the MCP server."}):o({id:"operator",status:"ok",detail:"customer mode (styles unlocked by the licence tier)"}),o(await S);let C=me.join(i,w2),ne=Pi("sundownreel-gate"),xe=ne?"sundownreel-gate key":J()?`${yr()} key`:`node "${C}" key`;{let E=hn();o(E?{id:"gate-key",status:"ok",detail:`approval key ${E.keyId} at ${as()}`}:{id:"gate-key",status:"warn",detail:`no gate approval public key at ${as()}: nobody can approve gates on this machine yet (Gate 2 and Gate 4 are required for every episode)`,fix:`The human runs \`${xe}\` in their own terminal (not through Claude: it refuses agent shells). Then call doctor again.`}),o(mt(C)||ne?{id:"gate-cli",status:"ok",detail:ne?`sundownreel-gate on PATH (${ne})`:`sundownreel-gate at ${C} (not on PATH: the human types \`${J()?yr():`node "${C}"`} \u2026\`)`}:{id:"gate-cli",status:"fail",detail:"the sundownreel-gate approval CLI (studio-cli) is not in this install",fix:"Reinstall Sundown Reel (the studio-cli/ folder ships with it) or run `npm link -w @sundownreel/studio-cli` in the install folder."})}let ue={};for(let E of Wc){let Z=`renderer-${E}`,ae=os[E],vt;try{let we=mf(E);if(vt={id:Z,status:"ok",detail:`${ae.bin} at ${we}`},E==="engine-3d"){let le=(e.findChrome??(()=>Ii(i)??(J()?dn():null)))();vt=le?{id:Z,status:"ok",detail:`${ae.bin} at ${we}; Chrome at ${le}`}:{id:Z,status:"warn",detail:`${ae.bin} at ${we}, but no Chrome/Chromium found: the 3D styles (stagelit-stick, plinth-city, exploded-view, docket-3d, blockfolk) cannot render until one is installed`,fix:J()?"Call browser_install (a background job that downloads chrome-headless-shell once, ~100 MB, into the app state home) and poll job_status; or install Google Chrome, or set RF3D_CHROME to a Chrome/Chromium binary in the Claude config env.":"Install Google Chrome, or set RF3D_CHROME to a Chrome/Chromium binary (in the .env or the Claude config env), then restart the MCP server."}}if(E==="engine-geo"&&J()){let le=ns();vt=le?{id:Z,status:"ok",detail:`${ae.bin} at ${we}; geodata at ${me.join(le,"data","geo")}`}:{id:Z,status:"warn",detail:`${ae.bin} at ${we}, but the open geodata is not downloaded yet: the map styles (frontline, terra-relief, orbit-survey, fieldbook) cannot render until it is`,fix:"Call geodata_install (a background job that downloads ~116 MB once into the app state home, verified against published checksums) and poll job_status; or point SUNDOWNREEL_GEODATA at a folder that contains data/geo."}}}catch(we){let le=E==="resvg-2d"?`Build the headless renderer: \`npm run build -w ${ae.pkg}\` in the Sundown Reel install (or set ${ae.env} to the ${ae.bin} CLI).`:E==="engine-3d"?`Build it: \`npm run build -w ${ae.pkg}\` (or set ${ae.env}). Only the 3D styles need it.`:`Not shipped yet: only the map styles need it (or set ${ae.env} to a ${ae.bin} CLI). Pick another style meanwhile.`;vt={id:Z,status:E==="resvg-2d"?"fail":"warn",detail:tl(we),fix:le}}ue[E]=vt}o(ue["resvg-2d"]);let b=g2();o(b?{id:"dsl",status:"ok",detail:`@reelforge/dsl built (${b})`}:{id:"dsl",status:"fail",detail:"@reelforge/dsl is not built to JavaScript (dist/index.js missing)",fix:"Build it: `npm run build -w @reelforge/dsl` in the Sundown Reel install, then call doctor again."});{let E=await w;o(E.source?{id:"styles",status:"ok",detail:`style registry loaded (${E.source})`}:{id:"styles",status:"fail",detail:`style registry not loadable: ${E.error??"unknown error"}`,fix:"Build it: `npm run build -w @reelforge/styles` (styles/dist/index.mjs), or set REELFORGE_STYLES_MODULE to a built registry .mjs."})}{let E=await y,Z=me.join(an(),".venv","bin","python"),ae="Set up the Python pipeline: `python3.12 -m venv pipeline/.venv && pipeline/.venv/bin/pip install -r pipeline/requirements.txt` in the Sundown Reel install (or set REELFORGE_PYTHON to a Python with numpy, opencv, PIL, scipy).";J()&&!h&&!f?o({id:"python",status:"warn",detail:"no Python pipeline in the npm package: qa_run, shotplan_make, package_make and vo_align need the full Sundown Reel install (renders and final audio mastering do not)"}):!h&&!f?o({id:"python",status:"fail",detail:`no pipeline venv (${Z} missing): qa_run, shotplan_make and package_make need it`,fix:ae}):E?.ok?o({id:"python",status:"ok",detail:`${E.firstLine} (${f?"REELFORGE_PYTHON":p})`}):o({id:"python",status:"fail",detail:`${p} does not run (${E?.firstLine??"?"})`,fix:ae})}{let E=process.env.SUNDOWNREEL_THUMBNAILS_CLI?.trim(),Z=E?me.resolve(E):me.join(i,"thumbnails","dist","make.mjs");o(mt(Z)?{id:"thumbnails",status:"ok",detail:`thumbnails CLI at ${Z}`}:{id:"thumbnails",status:"warn",detail:`${E?`SUNDOWNREEL_THUMBNAILS_CLI=${E}`:"thumbnails/dist/make.mjs"} not found: thumbnail_make cannot run`,fix:E?"Fix or unset SUNDOWNREEL_THUMBNAILS_CLI.":"Build it: `node thumbnails/build.mjs` in the Sundown Reel install."})}o(ue["engine-3d"]),o(ue["engine-geo"]),o(process.env.ELEVENLABS_API_KEY?.trim()?{id:"elevenlabs",status:"ok",detail:"ELEVENLABS_API_KEY is set (vo_align can call forced alignment when the human allows the spend)"}:J()?{id:"elevenlabs",status:"ok",detail:"no ELEVENLABS_API_KEY (optional): vo_align writes estimated word timing (shots may drift from the recording)",fix:"For exact alignment add your own key to the Claude config env: `claude mcp add sundownreel -e ELEVENLABS_API_KEY=... -- npx -y @sundownreel/mcp`, then restart."}:{id:"elevenlabs",status:"warn",detail:"no ELEVENLABS_API_KEY (optional): vo_align writes estimated word timing from the script instead (shots and captions may drift from the recording; an existing real alignment is kept)",fix:"For exact alignment: run `sundownreel-init` and paste your ElevenLabs key (stored in the studio .env, mode 600), then restart the MCP server."});let H=E=>s.find(Z=>Z.id===E),se=E=>H(E)?.status!=="fail",wt=E=>H(E)?.status==="ok",_n=se("studio-home")&&se("state-home")&&se("licence")&&se("node"),xr={episodes:_n,render:_n&&wt("renderer-resvg-2d")&&se("ffmpeg")&&wt("dsl")&&wt("styles")&&se("disk"),voAlign:wt("python")&&se("ffmpeg"),qa:wt("python")&&se("ffmpeg"),thumbnails:wt("thumbnails")&&se("node")},Xi=s.filter(E=>E.status==="fail"),Sn=s.filter(E=>E.status==="warn"),vd=Xi[0]??(H("gate-key")?.status==="warn"?H("gate-key"):void 0),nE=vd?.fix?`${vd.id}: ${vd.fix}`:"call next_step";return{summary:Xi.length===0?`Setup OK${Sn.length?` with ${Sn.length} warning(s) (${Sn.map(E=>E.id).join(", ")})`:""}: ${s.length-Sn.length}/${s.length} checks pass.`:`${Xi.length} problem(s) to fix (${Xi.map(E=>E.id).join(", ")})${Sn.length?`, ${Sn.length} warning(s) (${Sn.map(E=>E.id).join(", ")})`:""}.`,ready:xr,checks:s,homes:{studio:{path:a.path,source:a.source,exists:mt(a.path),holds:"episodes (videos/<id>/), prompts/, .env"},state:{path:c.path,source:c.source,exists:mt(c.path),holds:"Chalkline projects/, jobs/, license-cache.json, cache/, keys/ (gate approval keys)"},envFile:l,gateKey:as(),rules:Bm},next:nE,ms:Date.now()-r}}async function v2(t,e){let r="licence",n=Oi().enabled,s=is()??process.env.SUNDOWNREEL_LICENSE_KEY?.trim(),o="Call sundownreel_connect and approve this machine in the browser page it opens, then call doctor again.";if(n&&!s)return{id:r,status:"ok",detail:"operator machine: no licence needed"};if(!s)return{id:r,status:"fail",detail:"this machine is not connected yet (run sundownreel_connect)",fix:o};let i=!!t.online;try{let a=await Cr({fetchImpl:i?e.fetchImpl:b2});return{id:r,status:"ok",detail:`licence active: tier ${a.tier}, styles ${a.styles}${i?" (validated online)":" (signed cache, checked offline)"}${a.dev?", dev key":""}`}}catch(a){let c=tl(a);return!i&&/unreachable and no valid offline grace cache/i.test(c)?{id:r,status:n?"ok":"warn",detail:`${is()?"this machine is connected":"a licence key is configured"} but the licence is not verified on this machine yet (no valid signed cache)`,fix:"Call doctor {online: true} to validate the licence with the licence server once (any licensed tool does the same)."}:/inactive/i.test(c)?{id:r,status:n?"warn":"fail",detail:`licence: ${c}`,fix:"Renew the plan from your dashboard (https://sundownreel.com/account), then call doctor {online: true}."}:/was disconnected/i.test(c)?{id:r,status:n?"warn":"fail",detail:`licence: ${c}`,fix:o}:{id:r,status:n?"warn":"fail",detail:`licence: ${c}`,fix:i?"Check your network (and SUNDOWNREEL_LICENSE_API if you set it), or run sundownreel_connect again, then call doctor {online: true}.":o}}}var _f,Xc,o0,Sf,i0,el,p2,tl,xf,b2,w2,Kc=v(()=>{"use strict";_i();er();Xt();no();bf();Od();Yc();lo();un();pe();ln();_f=22,Xc=5,o0=1.5,Sf=1500,i0=1500,el=t=>process.platform==="win32"?`${t}.exe`:t,p2=t=>t/1024**3,tl=t=>t instanceof Error?t.message:String(t);xf=t=>/version\s+(\S+)/i.exec(t)?.[1]??t.slice(0,60);b2=(async()=>{throw new Error("doctor runs offline")}),w2=me.join("studio-cli","bin","sundownreel-gate.mjs")});function p0(t){return J()?t==="geodata"?ns()===null:!(process.env.RF3D_CHROME||process.env.CHROME_PATH||(Ii()??dn())):!1}var h0=v(()=>{"use strict";Kc();pe();un()});function _2(t){return/^[A-Za-z0-9_./:@%+=,-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function Qe(t,e,r,n=!1){let s=`${yr()} ${r} ${_2(t)} --gate ${e}`;return r==="approve"?n?`${s} --skip-earlier`:s:`${s} --note "${r==="reject"?"why it is rejected":"what to change"}"`}function nl(t,e){return t.gates.filter(r=>r.gate<e&&r.state==="none"&&t.profile.optional.includes(r.gate)).map(r=>r.gate)}function Ce(t,e){return Qe(t.dir,e,"approve",nl(t,e).length>0)}function Ef(t,e){return[{stage:`gate${e}`,actor:"human",command:Qe(t,e,"send-back"),why:"Send it back with notes: the agent redoes the stage."},{stage:`gate${e}`,actor:"human",command:Qe(t,e,"reject"),why:"Reject it (the episode stops here unless the human restarts the stage)."}]}function Rf(t,e){let r=t.gates[e-1]?.readingSheet,n=r?[`Reading sheet: ${r}`]:[];switch(e){case 1:return[...n,"The human reads 01-topic/gate1.md (topic, promise, title directions)."];case 2:return[...n,"The human reads 04-script/script.md + script_vo.txt and the fact table (facts_get), and confirms the hypothetical flag in episode.json.","No disputed fact; scenario facts only in a hypothetical episode.","Every fact the script or shots use is verified/computed (scenario only if hypothetical) and checked by a session other than its researcher (decision #13)."];case 3:return[...n,`The human watches the animatic${t.files.animatic?` (${t.files.animatic.rel})`:""} and notes changes by shot id.`];default:return[...n,`The human reviews 12-package (description, chapters, sources, disclosure, thumbnail) and the final${t.files.final?` (${t.files.final.rel})`:""}; show it with package_get.`]}}function If(t){let e=[];t.files.shots&&t.files.validated&&!t.files.compiledFresh&&e.push({problem:"shots.json changed after the last successful shots_compile.",fix:`shots_compile {episodeId: "${t.id}"}`});for(let r of t.gates){if(r.state!=="stale")continue;let n=[r.changedPins?.length?`${r.changedPins.join(", ")} changed after approval`:"",r.staleReason??""].filter(Boolean).join("; ");e.push({problem:`Gate ${r.gate} (${r.name}) is stale: ${n||"an earlier gate is not approved"}.`,fix:`Undo the change, or the human re-reviews and re-approves: ${Ce(t,r.gate)}`})}return e}function jf(t){let e=[],r=t.facts;r&&(r.disputed.length&&e.push({problem:`Disputed facts ${r.disputed.join(", ")}: never on screen, and Gate 2 can't be approved while they exist.`,fix:"Replace each with a better-sourced row (facts_upsert, then factcheck_record by a different session) or drop the claim from the script (script_save)."}),(r.unverified.length||r.noStatus.length)&&e.push({problem:`Facts not checked yet: ${[...r.unverified,...r.noStatus].join(", ")} (never on screen).`,fix:"factcheck_record from a session that is not the researcher (factcheck_plan, read only, lists what to check)."}),r.scenario.length&&!t.hypothetical&&e.push({problem:`Scenario facts ${r.scenario.join(", ")} in an episode not flagged hypothetical: Gate 2 refuses this.`,fix:"Ask the human whether the episode is hypothetical (they set it in episode.json); otherwise replace those numbers with verified or computed ones."}),r.noOnScreen.length&&e.push({problem:`${r.noOnScreen.length} fact(s) without an on_screen string: ${r.noOnScreen.slice(0,12).join(", ")}${r.noOnScreen.length>12?", \u2026":""}.`,fix:'facts_upsert the exact on-screen text (e.g. "$1.2T") for every fact you will show.'})),t.keyInstalled||e.push({problem:"No gate approval key on this machine: no gate can read as approved.",fix:`The human runs \`${yr()} key\` once in their own terminal on this machine, then decides gates with the same command.`});for(let n of t.gates)n.ignoredRecords&&e.push({problem:`Gate ${n.gate}: ${n.ignoredRecords} gate record(s) ignored (not signed by sundownreel-gate on this machine).`,fix:`Only signed records count. The human decides the gate with ${Qe(t.dir,n.gate,"approve")} (gate_status lists the ignored lines).`});for(let n of t.jobs)n.abandoned&&e.push({problem:`Job ${n.jobId} (${n.type}) is still "${n.status}" but has not updated for ${x2(n.updatedAt)} min; the server that ran it probably stopped.`,fix:"Run that step again (next_step names the tool); jobs don't survive a server restart."});for(let n of t.interrupted)e.push({problem:`Job ${n.jobId} (${n.type}) was interrupted: ${n.message}`,fix:n.rerun?`${n.rerun} {episodeId: "${t.id}"} starts it again (next_step names it when it is the next step).`:"Re-run the tool that started it."});return t.diskFreeGb!==null&&t.diskFreeGb<t.minFreeGb&&e.push({problem:`Only ${t.diskFreeGb.toFixed(2)} GB free on the disk holding the episode; renders need ${t.minFreeGb} GB.`,fix:"Free disk space (delete old 08-render/<run> folders you no longer need), then retry."}),e}function k2(t){return[...jf(t),...If(t)]}function Ti(t){let e=r=>t.required.includes(r)?"required":"optional";return{...t,gates:{gate1:e(1),gate2:e(2),gate3:e(3),gate4:e(4)}}}function uo(t){let e=k2(t),r=[],n=o=>{let{optionalGates:i,...a}=o,c=i??r;return{episodeId:t.id,...a,step:o.step??m0[o.stage]??0,checklist:o.checklist??rl[o.stage]??[],...c.length?{optionalGates:c}:{},blockers:[...o.blockers??[],...e],profile:Ti(t.profile),style:t.style}},s=t.jobs.filter(o=>!o.abandoned);if(s.length){let o=s[0];return n({stage:"wait",actor:"wait",tool:"job_status",args:{jobId:o.jobId},why:`A ${o.type} job is ${o.status} (${o.progress}%: ${o.message}); poll it until it succeeds or fails.`,then:{stage:"next",actor:"agent",tool:"next_step",args:{episodeId:t.id},why:"Ask for the next step once the job is done."},checklist:["job_status says succeeded (or failed: read its error, fix, re-run)."]})}for(let o of S2){if(typeof o=="number"){let a=E2(t,o,r);if(a)return n(a);continue}let i=$2(t,o);if(i)return n(i)}return n({stage:"done",actor:"human",why:"Gate 4 is approved: the human uploads the final and the package by hand (no tool uploads, publishes or schedules)."})}function g0(t,e){let r=t.id,n=t.profile.profile==="quick";switch(e){case"topic":return n?{stage:"outline",actor:"agent",tool:"outline_save",args:{episodeId:r},why:"Outline next (Gate 1 is optional in the quick profile)."}:{stage:"gate1",actor:"human",command:Ce(t,1),why:"The human decides Gate 1 (topic) before the outline."};case"gate1":return{stage:"outline",actor:"agent",tool:"outline_save",args:{episodeId:r},why:"Outline the chapters."};case"outline":return{stage:"research",actor:"agent",tool:"facts_upsert",args:{episodeId:r},why:"Research (research_plan has the plan), then save the rows with facts_upsert."};case"research":return{stage:"factcheck",actor:"agent",tool:"factcheck_record",args:{episodeId:r},why:"A different session fact-checks every row (factcheck_plan lists them)."};case"factcheck":return{stage:"script",actor:"agent",tool:"script_save",args:{episodeId:r},why:"Write the script from checked facts only."};case"script":return{stage:"gate2",actor:"human",command:Ce(t,2),why:"The human decides Gate 2 (script + facts)."};case"gate2":return{stage:"vo",actor:"human",tool:"vo_save",args:{episodeId:r},why:"The human records the voice-over; save it with vo_save."};case"vo":return y0(t);case"shotplan":return{stage:"shots",actor:"agent",tool:"get_style_guide",args:{styleId:t.style},why:"Read the style guide, then shots_context and shots_patch per chapter."};case"shots":return{stage:"compile",actor:"agent",tool:"shots_compile",args:{episodeId:r},why:"Validate and compile the timeline."};case"compile":return{stage:"review",actor:"agent",tool:"review_shots",args:Pf(t),why:"Look at the shots as images before the animatic."};case"review":return{stage:"animatic",actor:"agent",tool:"render_animatic",args:{episodeId:r},why:"Render the 540p animatic."};case"animatic":return n?{stage:"final",actor:"agent",tool:"render_final",args:{episodeId:r},why:"Render the final (Gate 3 is optional in the quick profile)."}:{stage:"gate3",actor:"human",command:Ce(t,3),why:"The human decides Gate 3 (animatic by shot id)."};case"gate3":return{stage:"final",actor:"agent",tool:"render_final",args:{episodeId:r},why:"Render the 1080p final."};case"final":return{stage:"package",actor:"agent",tool:"package_make",args:{episodeId:r},why:"Build the description, chapters, sources and disclosure for this final."};case"package":return{stage:"thumbnail",actor:"agent",tool:"thumbnail_make",args:{episodeId:r},why:"Make the thumbnail."};case"thumbnail":return ro()?{stage:"qa",actor:"agent",tool:"qa_run",args:{episodeId:r},why:"Run automated QA on the final and its package."}:{stage:"package_view",actor:"agent",tool:"package_get",args:{episodeId:r},why:`${xi} Show the human the package before Gate 4.`};case"qa":return{stage:"package_view",actor:"agent",tool:"package_get",args:{episodeId:r},why:"Show the human the package before Gate 4."};case"package_view":return{stage:"gate4",actor:"human",command:Ce(t,4),why:"The human decides Gate 4 on the package package_get showed."};case"gate4":return{stage:"done",actor:"human",why:"The human uploads by hand; no tool uploads."}}}function f0(t,e,r){let n=t.missingAsset;return n?{stage:e,actor:"agent",tool:uf[n],args:{},why:n==="geodata"?`The ${t.style} style draws on open map data that is not downloaded yet (~116 MB, once): call geodata_install, poll job_status until it succeeds, then render.`:`The ${t.style} style renders in headless Chrome and none is installed: call browser_install (~100 MB, once) or install Google Chrome, poll job_status, then render.`,...r?{then:r}:{}}:null}function y0(t){return t.operatorStyle?{stage:"shotplan",actor:"agent",tool:"shotplan_make",args:{episodeId:t.id},why:"Build the timed shot-plan skeleton from words.json."}:{stage:"shotplan",actor:"agent",tool:"plan_shots",args:{episodeId:t.id,save:!0},why:`Plan the shots with the ${t.style} style defaults and save them.`}}function Pf(t){return t.files.shotRange?{episodeId:t.id,range:t.files.shotRange}:{episodeId:t.id}}function $2(t,e){let r=t.files,n=t.id,s=g0(t,e);switch(e){case"topic":return r.topic?null:{stage:e,actor:"agent",tool:"topic_save",args:{episodeId:n},why:"The episode has no topic yet: save the topic, promise and title directions (01-topic/gate1.md).",then:s};case"outline":return r.outline?null:{stage:e,actor:"agent",tool:"outline_save",args:{episodeId:n},why:"No outline yet (02-outline/outline.md).",then:s};case"research":return r.factsRows>0?null:{stage:e,actor:"agent",tool:"facts_upsert",args:{episodeId:n},why:"No facts yet: research every number and claim (with your own tools; research_plan gives the plan and the row shape), then save them with facts_upsert {episodeId, actor: your researcher id e.g. researcher-a1, facts:[{id, claim, source, url, quote, on_screen?}]}.",alternatives:[{stage:"research",actor:"agent",tool:"research_plan",args:{episodeId:n},why:"Read first: the research plan from the outline (read only)."}],then:{stage:"factcheck",actor:"agent",tool:"factcheck_record",args:{episodeId:n},why:"A different session checks every row."}};case"factcheck":{let o=[...t.facts?.unverified??[],...t.facts?.noStatus??[]];return r.factcheckLog&&!o.length?null:{stage:e,actor:"agent",tool:"factcheck_record",args:{episodeId:n},why:(o.length?`Facts ${o.join(", ")} are not checked: a session that is NOT the researcher checks each against its source`:"No fact-check log yet (03-research/factcheck.md): a session that is NOT the researcher checks every row")+" and records it with factcheck_record {episodeId, actor: a different id e.g. checker-b2, results:[{id, status: verified|computed|disputed|scenario, note}]}. factcheck_plan lists what to check.",alternatives:[{stage:"factcheck",actor:"agent",tool:"factcheck_plan",args:{episodeId:n},why:"Read first: what to check per fact (read only)."}],then:{stage:"script",actor:"agent",tool:"script_save",args:{episodeId:n},why:"Write the script from checked facts only."}}}case"script":return r.scriptVo?null:{stage:e,actor:"agent",tool:"script_save",args:{episodeId:n},why:"No script yet: save scriptMd (chapters), scriptVo (the exact words to read) and meta ({title, hook_line, chapters}).",then:s};case"vo":return r.words&&r.wordsFresh?null:r.voWav?{stage:e,actor:"agent",tool:"vo_align",args:{episodeId:n},why:r.words?"06-vo/words.json is older than vo.wav or script_vo.txt: re-align the voice-over.":"Align 06-vo/vo.wav to the script (background job; poll job_status).",then:{stage:"vo",actor:"wait",tool:"job_status",why:"Poll the alignment job."}}:{stage:e,actor:"human",tool:"vo_save",args:{episodeId:n},why:"The human records the voice-over reading 04-script/script_vo.txt word for word; when they give you the file, call vo_save {episodeId, file}.",then:{stage:"vo",actor:"agent",tool:"vo_align",args:{episodeId:n},why:"Align the recording to the script (a background job)."}};case"shotplan":{if(r.shotplan||r.shots)return null;let o=y0(t);return{...o,stage:e,why:`No shot plan yet. ${o.why}`,then:s}}case"shots":{if(r.shots&&!r.shotsSkeleton)return null;let o=r.shots?"shots.json is still the untouched plan_shots skeleton (default pacing, no writing)":"No shots.json yet",i=r.shots?{stage:"shots",actor:"agent",tool:"shots_patch",args:{episodeId:n},why:"Write one chapter at a time with shots_patch {episodeId, upsert:[shots]} (shots_validate checks a draft); then shots_compile."}:{stage:"shots",actor:"agent",tool:"shots_save",args:{episodeId:n},why:"Save the whole Episode (shots_validate checks a draft first); then shots_compile."};return t.seen?.styleGuide?t.seen?.shotsContext?{...i,stage:e,why:`${o}: ${i.why} Every on-screen number needs the factId of an eligible fact; aim at the style's pacing, transitions and SFX bands.`,then:{stage:"compile",actor:"agent",tool:"shots_compile",args:{episodeId:n},why:"Validate and compile; read the timing stats against the style bands."}}:{stage:e,actor:"agent",tool:"shots_context",args:{episodeId:n},why:`${o}: load the facts, plan and writer prompt for this episode.`,then:i}:{stage:e,actor:"agent",tool:"get_style_guide",args:{styleId:t.style},why:`${o}: read the ${t.style} style guide first (pacing, transitions, SFX, look).`,then:{stage:"shots",actor:"agent",tool:"shots_context",args:{episodeId:n},why:"Facts, plan and writer prompt for the episode."}}}case"compile":if(r.compiledFresh&&r.compileOutOfBand.length){let o=r.compileOutOfBand.map(i=>`${i.label} = ${i.value} (band ${i.band[0]}\u2013${i.band[1]})`);return{stage:e,actor:"agent",tool:"shots_patch",args:{episodeId:n},why:`The last shots_compile is outside the ${t.style} bands QA checks: ${o.join("; ")}. Fix it with shots_patch before rendering (shot lengths: split or merge shots / move vo lines; transitions: set non-cut transitions on ~15 % of shots; SFX: add sfx cues), then shots_compile again.`,blockers:o.map(i=>({problem:`Compile timing out of band: ${i}`,fix:"shots_patch, then shots_compile."})),then:{stage:"compile",actor:"agent",tool:"shots_compile",args:{episodeId:n},why:"Recompile and re-check the bands."}}}return r.compiledFresh?null:{stage:e,actor:"agent",tool:"shots_compile",args:{episodeId:n},why:r.validated?"shots.json changed after the last compile: validate and compile again.":"Validate and compile shots.json into the frame-exact timeline.",alternatives:[{stage:e,actor:"agent",tool:"shots_validate",args:{episodeId:n},why:"Only list the issues (nothing written)."}],then:s};case"review":{if(r.reviewFresh||r.animatic?.fresh||r.final?.fresh)return null;let o=f0(t,e,s);return o||{stage:e,actor:"agent",tool:"review_shots",args:Pf(t),why:"Look at the compiled shots as images (the vision loop) and fix what is off with shots_patch before rendering the animatic.",then:s}}case"animatic":{if(r.animatic?.fresh||t.profile.profile==="quick"&&r.final?.fresh)return null;let o=f0(t,e,s);return o||{stage:e,actor:"agent",tool:"render_animatic",args:{episodeId:n},why:r.animatic?"The newest animatic is older than the current shots: render it again.":"Render the 540p animatic (background job).",then:s}}case"final":return r.final?.fresh?null:{stage:e,actor:"agent",tool:"render_final",args:{episodeId:n},why:r.final?"The newest final is older than the current shots: render it again.":"Render the 1080p final (background job).",then:s};case"qa":return!ro()||r.qa?.passed&&r.qa.fresh?null:!r.qa||!r.qa.fresh?{stage:e,actor:"agent",tool:"qa_run",args:{episodeId:n},why:r.qa?"The package changed after the last QA run: run QA again (it reads the package metadata).":"Run automated QA on the newest final and its package (background job).",then:s}:t.seen?.packageViewed||t.gates[3]?.state==="approved"?null:{stage:e,actor:"agent",tool:"package_get",args:{episodeId:n},why:`QA failed ${r.qa.failing.length} check(s) on ${r.qa.run}: read ${r.qa.report} and fix the cause (shots \u2192 shots_patch, shots_compile, render_final; package text \u2192 package_make), re-make the package after a new final, then run qa_run again. If the human accepts the failures they can still decide Gate 4.`,blockers:r.qa.failing.map(o=>({problem:`QA FAIL ${o}`,fix:`See ${r.qa.report}.`})),alternatives:[{stage:"final",actor:"agent",tool:"render_final",args:{episodeId:n},why:"Re-render after a shot or audio fix, then package_make and qa_run."}],then:{stage:"gate4",actor:"human",command:Ce(t,4),why:"Show the package (package_get) with the QA failures; the human accepts them or sends the episode back."}};case"package":{if(r.packaged&&r.packageFresh)return null;let o=[!r.scriptMeta&&"04-script/meta.json",!r.words&&"06-vo/words.json",!r.factsFile&&"03-research/facts.csv"].filter(Boolean);return{stage:e,actor:"agent",tool:"package_make",args:{episodeId:n},why:r.packaged?"The package is older than the newest final: build it again (QA checks the package against the final).":"Build the package (description, chapters, sources, credits, disclosure) before QA.",...o.length?{blockers:[{problem:`package_make needs ${o.join(", ")}.`,fix:o.includes("04-script/meta.json")?`script_save {episodeId: "${n}", meta: {title, hook_line, chapters}}`:"Finish the earlier stage first."}]}:{},then:s}}case"package_view":return t.seen?.packageViewed||t.gates[3]?.state==="approved"?null:{stage:e,actor:"agent",tool:"package_get",args:{episodeId:n},why:ro()?"Show the human the package (description, chapters, sources, thumbnail sheet) and the QA result before Gate 4.":`${xi} Show the human the package (description, chapters, sources, thumbnail sheet) before Gate 4.`,then:s};case"thumbnail":return r.thumbnail?null:{stage:e,actor:"agent",tool:"thumbnail_make",args:{episodeId:n},why:"Make the thumbnail (part of the package QA checks and the human reviews).",then:s}}}function E2(t,e,r){let n=t.gates[e-1],s=`gate${e}`,o=t.profile.required.includes(e),i=g0(t,s);if(n.state==="approved")return null;if(n.state==="none"){if(!o)return r.push({gate:e,name:n.name,command:Ce(t,e),why:`Optional in the ${t.profile.profile} profile: the human may approve Gate ${e} (${n.name}) now, or skip it later with --skip-earlier.`}),null;if(e===2){let h=t.facts,m=[...h?.gate2Blockers??[...h?.disputed.length?[`disputed facts ${h.disputed.join(", ")}`]:[],...h?.scenario.length&&!t.hypothetical?[`scenario facts ${h.scenario.join(", ")} in a non-hypothetical episode`]:[]],...t.files.factsFile?[]:["no facts file"]];if(m.length)return{stage:s,actor:"agent",tool:"facts_upsert",args:{episodeId:t.id},why:`Gate 2 would be refused (${m.join("; ")}): fix the facts first (better source + a fresh fact-check by a session that is not the researcher, or drop the claim from the script).`,blockers:m.map(g=>({problem:`Gate 2 blocker: ${g}.`,fix:"facts_upsert (researcher), then factcheck_record from a different session; or drop the claim from the script (script_save)."})),then:{stage:s,actor:"human",command:Ce(t,2),why:"Then the human decides Gate 2."}}}let f=nl(t,e);return{stage:s,actor:"human",command:Ce(t,e),alternatives:[...f.map(h=>({stage:`gate${h}`,actor:"human",command:Ce(t,h),why:`Or approve the optional Gate ${h} (${t.gates[h-1].name}) first instead of skipping it.`})),...Ef(t.dir,e)],why:`Gate ${e} (${n.name}) is ${o?"required":"optional"} and has no decision: the human reviews it and types the command in their own terminal${f.length?` (--skip-earlier records that optional Gate ${f.join(" and ")} ${f.length>1?"are":"is"} skipped)`:""}. No tool can approve a gate.`,checklist:[...Rf(t,e),...rl[s]],...r.length?{optionalGates:r.filter(h=>!f.includes(h.gate))}:{},then:i}}if(n.state==="stale"){let f=n.changedPins?.length?`${n.changedPins.join(", ")} changed after the approval`:n.staleReason??"an earlier gate is not approved";return{stage:s,actor:"human",command:Ce(t,e),alternatives:Ef(t.dir,e),why:`Gate ${e} (${n.name}) is stale: ${f}. The human re-reviews and re-approves (or the agent undoes the change).`,checklist:[...Rf(t,e),...rl[s]],then:i}}let a=n.at?Date.parse(n.at):0,c=t.gateInputsMtime[e]>a,l=n.note?` Their notes: ${n.note}`:" (no notes; ask the human what to change)",d=n.state==="sent_back"?"sent back":"rejected";if(c)return{stage:s,actor:"human",command:Ce(t,e),alternatives:Ef(t.dir,e),why:`The human ${d} Gate ${e} (${n.name}) and the stage has been redone since.${l} The human decides it again.`,checklist:[...Rf(t,e),...rl[s]],then:i};let p=R2[e](t);return{stage:p.stage,step:m0[s],actor:"agent",tool:p.tool,args:p.args,why:`The human ${d} Gate ${e} (${n.name}).${l} Redo the ${p.stage} stage${n.state==="rejected"?" (confirm with the user that the episode should continue)":""}, then the human decides Gate ${e} again.`,...p.alternatives?{alternatives:p.alternatives}:{},then:{stage:s,actor:"human",command:Ce(t,e),why:`Then the human decides Gate ${e} again.`}}}var S2,m0,rl,x2,R2,sl=v(()=>{"use strict";_i();un();no();S2=["topic",1,"outline","research","factcheck","script",2,"vo","shotplan","shots","compile","review","animatic",3,"final","package","thumbnail","qa","package_view",4],m0={topic:1,gate1:1,outline:2,research:3,factcheck:4,script:5,gate2:6,vo:7,shotplan:8,shots:9,compile:10,review:11,animatic:12,gate3:13,final:14,package:15,thumbnail:15,qa:16,package_view:17,gate4:17,done:17,wait:0},rl={topic:["01-topic/gate1.md exists: the topic, who it is for, the promise, 2\u20133 title directions."],outline:["02-outline/outline.md exists: chapters with the beat each one lands."],research:["03-research/facts.csv has one row per number or claim the video makes, each with a source, url and quote.","Every number you plan to show has an on_screen string."],factcheck:["Every fact has a status: verified / computed / disputed / scenario (no unverified rows).","The checker session is a different actor than the researcher (decision #13).","03-research/factcheck.md logs the checks."],script:["04-script/script_vo.txt holds the exact words the human will read.","04-script/script.md holds the chapters table.","04-script/meta.json has {title, hook_line, chapters:[{anchor,title}]} (package_make needs it)."],gate1:["Gate 1 reads approved in gate_status."],gate2:["Gate 2 reads approved (and fresh) in gate_status."],vo:["06-vo/vo.wav is the human's recording of script_vo.txt.","06-vo/words.json is newer than vo.wav and script_vo.txt (vo_align job succeeded)."],shotplan:["The shot plan skeleton exists (07-shots/shotplan.json, or the style's planned shots)."],shots:["07-shots/shots.json covers every shot of the plan.","Every on-screen number carries a factId of an eligible fact (R14); UI ordinals like STEP 3 / 12 or EXHIBIT 01 are exempt.","shots_validate reports 0 errors."],compile:["shots_compile succeeded: shots.validated.json + shots.compiled.json are newer than shots.json.","Timing stats are inside the style targets."],review:["review_shots looked at the shots as images; every issue was fixed with shots_patch and recompiled."],animatic:["08-render/<run>/animatic.mp4 rendered from the current shots.validated.json."],gate3:["Gate 3 reads approved in gate_status."],final:["08-render/<run>/final.mp4 rendered from the current shots.validated.json, audio mastered to \u221214 LUFS (render.json audio.lufs)."],package:["12-package/description.md, meta.json and package.json are newer than the final (re-make it after every new final)."],thumbnail:["A thumbnail is in 12-package/ (or 12-package/thumbs/)."],qa:["09-qa/<final run>/qa.json exists for the newest final, newer than the package (QA reads the package metadata).","0 FAIL, or the human accepts the listed failures at Gate 4."],package_view:["package_get showed the human the final's package (description, chapters, thumbnail sheet) and the QA result."],gate4:["Gate 4 reads approved in gate_status."],done:["The human uploads the final and the package by hand. No tool uploads, publishes or schedules."]},x2=t=>Math.round((Date.now()-Date.parse(t))/6e4);R2={1:t=>({stage:"topic",tool:"topic_save",args:{episodeId:t.id}}),2:t=>({stage:"script",tool:"script_save",args:{episodeId:t.id},alternatives:[{stage:"research",actor:"agent",tool:"facts_upsert",args:{episodeId:t.id},why:"If the notes are about facts: fix the rows, then factcheck_record by a different session."}]}),3:t=>({stage:"shots",tool:"shots_patch",args:{episodeId:t.id},alternatives:[{stage:"review",actor:"agent",tool:"review_shots",args:Pf(t),why:"Look at the shots named in the notes first."}]}),4:t=>({stage:"package",tool:"package_make",args:{episodeId:t.id},alternatives:[{stage:"thumbnail",actor:"agent",tool:"thumbnail_make",args:{episodeId:t.id},why:"If the notes are about the thumbnail."}]})}});import{readFileSync as I2,statSync as j2}from"node:fs";import P2 from"node:path";function T2(t,e){try{let r=P2.join(t,e);return j2(r).isFile()?I2(r,"utf8"):""}catch{return""}}function A2(t,e){let r=O2.map(n=>T2(t,n)).join(`
|
|
50
|
+
`);return new Set(e.filter(n=>new RegExp(`(^|[^A-Za-z0-9_-])${N2(n)}(?![A-Za-z0-9_-])`).test(r)))}function b0(t,e,r){let n=A2(t,e.map(i=>i.id)),s={unchecked:[],disputed:[],scenario:[],noChecker:[],selfChecked:[]};for(let i of e){let a=(i.status??"").toLowerCase()||"(none)",c=a==="verified"||a==="computed"||a==="scenario"&&r;if(!((i.on_screen??"").trim()||n.has(i.id)))continue;let l=(i.checker??"").trim().split(/\s+/)[0]??"",d=(i.researcher??"").trim(),p=!1;a==="disputed"?s.disputed.push(i.id):a==="scenario"&&!r?s.scenario.push(i.id):c||(s.unchecked.push(i.id),p=!0),p||(l?d&&l===d&&s.selfChecked.push(i.id):s.noChecker.push(i.id))}let o=[];return s.unchecked.length&&o.push(`facts used by the script or shots are not fact-checked (unverified or no status): ${s.unchecked.join(", ")}`),s.disputed.length&&o.push(`disputed facts: ${s.disputed.join(", ")} (fix or remove them; never waivable)`),s.scenario.length&&o.push(`scenario facts ${s.scenario.join(", ")} but episode.json does not flag the episode hypothetical`),s.noChecker.length&&o.push(`facts with no checker recorded: ${s.noChecker.join(", ")} (an independent session must check them with factcheck_record)`),s.selfChecked.length&&o.push(`facts checked by their own researcher: ${s.selfChecked.join(", ")} (decision #13: the checker must be a different session)`),o}var O2,N2,w0=v(()=>{"use strict";O2=["04-script/script.md","04-script/script_vo.txt","04-script/meta.json","07-shots/shots.json","07-shots/shots.validated.json"];N2=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")});import{createHash as Af,createPublicKey as C2,verify as L2}from"node:crypto";import{closeSync as D2,existsSync as fn,lstatSync as Cf,openSync as M2,readdirSync as al,readFileSync as mn,readSync as F2,realpathSync as v0,statfsSync as q2,statSync as Lf}from"node:fs";import G2 from"node:os";import re from"node:path";function Oe(t){let e=Af("sha256"),r=M2(t,"r"),n=Buffer.allocUnsafe(1<<20);try{let s;for(;(s=F2(r,n,0,n.length,null))>0;)e.update(n.subarray(0,s))}finally{D2(r)}return e.digest("hex")}function E0(t){return Af("sha256").update(t).digest("hex")}function R0(t,e){let r=re.resolve(t,e),n=re.relative(t,r);return n.startsWith("..")||re.isAbsolute(n)?null:r}function cl(t,e,r){if(e.startsWith("_gates/")||e.includes("\\"))return null;let n=R0(t,e);if(!n)return null;try{let s=Cf(n);if(!s.isFile())return null;let o=v0(n),i=v0(t),a=re.relative(i,o);if(a.startsWith("..")||re.isAbsolute(a))return null;let c=`${s.dev}:${s.ino}:${s.size}:${s.mtimeMs}:${s.ctimeMs}`;if(r&&s.mtimeMs<=r.unchangedSince&&s.ctimeMs<=r.unchangedSince)return r.expected;let l=x0.get(o);if(l&&l.stamp===c)return l.sha;let d=Oe(o);return x0.set(o,{stamp:c,sha:d}),d}catch{return null}}function H2(){let t=process.env.SUNDOWNREEL_HOME?re.resolve(process.env.SUNDOWNREEL_HOME):re.join(G2.homedir(),".sundownreel");return re.join(t,"keys")}function as(){return re.join(H2(),"gate-ed25519.pub")}function B2(t){return Af("sha256").update(t.export({type:"spki",format:"der"})).digest("hex").slice(0,16)}function hn(){let t=as();try{let e=Cf(t);if(!e.isFile()||e.size>4096)return null;let r=C2(mn(t));return r.asymmetricKeyType!=="ed25519"?null:{key:r,keyId:B2(r)}}catch{return null}}function K2(t){if(!ol(t))return"not a JSON object";if(t.v!==_0)return"unsigned or unknown record format (no v:1)";let{episode:e,gate:r,decision:n,decided_by:s,at:o,key_id:i}=t;if(typeof e!="string"||!e)return"missing episode";if(r!==1&&r!==2&&r!==3&&r!==4)return"bad gate number";if(typeof n!="string"||!W2.has(n))return"unknown decision";if(typeof s!="string")return"missing decided_by";if(typeof o!="string"||Number.isNaN(Date.parse(o)))return"missing or bad timestamp";if(typeof i!="string")return"missing key_id";let a=t.pins??{};if(!ol(a)||!Object.values(a).every(h=>typeof h=="string"&&J2.test(h)))return"bad pins";let c=t.flags??{};if(!ol(c)||!Object.values(c).every(h=>["boolean","string","number"].includes(typeof h)))return"bad flags";let l=t.skipped_gates??[];if(!Array.isArray(l)||!l.every(h=>Number.isInteger(h)&&h>=1&&h<=4))return"bad skipped_gates";let d=t.delta??[];if(!Array.isArray(d)||!d.every(h=>typeof h=="string"))return"bad delta";let p=t.supersedes??null;if(p!==null&&typeof p!="string")return"bad supersedes";let f=t.note??"";return typeof f!="string"?"bad note":{v:_0,episode:e,gate:r,decision:n,decided_by:s,at:o,pins:k0(a),flags:k0(c),skipped_gates:[...new Set(l)].sort((h,m)=>h-m),supersedes:p,delta:[...d].sort(),note:f,key_id:i}}function Z2(t){return JSON.stringify(t)}function Y2(t,e,r){let n=ol(t)?t.sig:void 0;if(typeof n!="string"||!n)return{ok:!1,reason:"unsigned"};let s=K2(t);if(typeof s=="string")return{ok:!1,reason:s};if(!r.key)return{ok:!1,reason:"no approval key installed on this machine"};if(s.key_id!==r.key.keyId)return{ok:!1,reason:`signed by another key (${s.key_id}), not this machine's ${r.key.keyId}`};let o=!1;try{o=L2(null,Buffer.from(Z2(s)),r.key.key,Buffer.from(n,"base64"))}catch{o=!1}if(!o)return{ok:!1,reason:"bad signature"};if(s.gate!==r.gate)return{ok:!1,reason:`record is for Gate ${s.gate}, found in gate${r.gate}.jsonl`};if(s.episode!==re.basename(r.dir))return{ok:!1,reason:`record is for episode "${s.episode}"`};if(!s.decided_by.startsWith("human:"))return{ok:!1,reason:`not a human decision (${s.decided_by})`};if(s.decision==="approved"){for(let a of Object.keys(s.pins))if(!R0(r.dir,a)||a.startsWith("_gates/"))return{ok:!1,reason:`pin outside the episode: ${a}`};let i=z2[r.gate].filter(a=>!Object.keys(s.pins).some(c=>a.test.test(c)));if(i.length)return{ok:!1,reason:`approval does not pin ${i.map(a=>a.role).join(", ")}`};if(r.gate===2&&typeof s.flags.hypothetical!="boolean")return{ok:!1,reason:"Gate 2 approval without the hypothetical flag"}}return{ok:!0,rec:s,line:e}}function X2(t,e,r={}){let n=[],s=Date.parse(e.at);for(let[o,i]of Object.entries(e.pins))cl(t,o,r.fast?{unchangedSince:s,expected:i}:void 0)!==i&&n.push(o);if(e.gate===2){let o=ll(t),i=o?re.relative(t,o).split(re.sep).join("/"):null;i&&!(i in e.pins)&&n.push(`${i} (not pinned)`),e.flags.hypothetical!==Ct(t)&&n.push("episode.json hypothetical flag")}return typeof e.flags.gateProfile=="string"&&e.flags.gateProfile!==br(t).profile&&n.push("episode.json gateProfile"),typeof e.flags.style=="string"&&e.flags.style!==Ee(t)&&n.push("episode.json style"),n}function Q2(t,e,r={}){return Df(t,e,r).info}function Df(t,e,r={}){let n={gate:e,name:U2[e],state:"none"},s=V2[e].find(f=>fn(re.join(t,f)));s&&(n.readingSheet=s);let o=hn();o||(n.detail=Ni);let i=re.join(t,"_gates",`gate${e}.jsonl`),a="";try{Cf(i).isFile()&&(a=mn(i,"utf8"))}catch{return{info:n,record:null}}let c=[],l=null;a.split(/\r?\n/).forEach((f,h)=>{if(!f.trim())return;let m;try{m=JSON.parse(f)}catch{c.push(`${S0}: line ${h+1}: not JSON`);return}let g=Y2(m,h+1,{dir:t,gate:e,key:o});if(!g.ok){c.push(`${S0}: line ${h+1}: ${g.reason}`);return}(!l||Date.parse(g.rec.at)>=Date.parse(l.rec.at))&&(l={rec:g.rec,line:g.line})}),c.length&&(n.ignoredRecords=c.length,n.ignored=c);let d=l;if(!d)return{info:n,record:null};let p=d.rec;if(delete n.detail,n.decidedBy=p.decided_by,n.at=p.at,n.signed=!0,n.keyId=p.key_id,p.note&&(n.note=p.note),p.decision==="approved"){let f=X2(t,p,r);n.state=f.length?"stale":"approved",f.length&&(n.changedPins=f),p.skipped_gates.length&&(n.skippedGates=p.skipped_gates)}else n.state=p.decision;return{info:n,record:p}}function tt(t,e={}){return Mf([1,2,3,4].map(r=>Q2(t,r,e)))}function Mf(t){for(let e of t)if(e.state==="approved"){for(let r of t.slice(0,e.gate-1))if(r.state!=="approved"&&!(r.state==="none"&&e.skippedGates?.includes(r.gate))){e.state="stale",e.staleReason=`Gate ${r.gate} is ${r.state}${r.state==="none"?" and this approval did not skip it":""}`;break}}return t}function I0(t){if(t.state==="stale"){let e=[];return t.changedPins?.length&&e.push(`${t.changedPins.join(", ")} changed after approval`),t.staleReason&&e.push(t.staleReason),`stale: ${e.join("; ")||"an earlier gate is not approved"}`}return t.state==="none"?`none \u2014 ${t.detail??"not approved"}`:t.state}function At(t,e,r){let n=N(t),s=tt(n)[e-1];if(s.state!=="approved")throw new Nf(`Refused: ${r} needs Gate ${e} (${s.name}) approved for ${t}; it is ${I0(s)}. Gates are approved only by the human, in the Studio or the CLI (\`sundownreel-gate approve <videoDir> --gate N\`, typed in their own terminal). No MCP tool can approve or override a gate, and records not signed by that CLI are ignored. Ask the user to review and approve it there, then try again.`)}function ll(t){for(let e of["03-research/facts.checked.csv","03-research/facts.csv"]){let r=re.join(t,e);if(fn(r))return r}return null}function dl(t){let e=ll(t);if(!e)return{file:null,facts:null};let r=Ac(mn(e,"utf8"));return{file:e,facts:r.filter(n=>n.id).map(n=>({...n,id:n.id}))}}function j0(t,e){let r=(t??"").trim().toLowerCase();return r==="verified"||r==="computed"||r==="scenario"&&e}function Ai(t){let e=re.join(t,"episode.json");if(!fn(e))return null;try{return JSON.parse(mn(e,"utf8"))}catch{return null}}function Ct(t){return Ai(t)?.hypothetical===!0}function P0(t){try{return Lf(t).mtimeMs}catch{return 0}}function tL(t,e){let r=re.join(t,"08-render"),n=null,s=[];try{s=al(r)}catch{return null}for(let o of s){let i=P0(re.join(r,o,e));i&&(!n||i>n.mtime)&&(n={run:o,rel:`08-render/${o}/${e}`,mtime:i})}return n}function $0(t,e){let r=tL(t,e);if(!r)return null;let n="07-shots/shots.validated.json",s=!1;if(et(t,n)){let o;try{o=JSON.parse(mn(re.join(t,"08-render",r.run,"render.json"),"utf8")).inputs?.[n]}catch{o=void 0}s=typeof o=="string"?o===cl(t,n):r.mtime>=Sr(t,n)}return{run:r.run,rel:r.rel,fresh:s,mtime:r.mtime}}function rL(t,e,r){let n=`09-qa/${e}/qa.json`,s;try{s=JSON.parse(mn(re.join(t,n),"utf8"))}catch{return null}let o=(s.checks??[]).filter(a=>a.result==="FAIL").map(a=>`${a.check??a.id??"?"}${a.value!==void 0?` (${typeof a.value=="string"?a.value:JSON.stringify(a.value)})`:""}`.slice(0,240)),i=s.summary??{};return{run:e,report:`09-qa/${e}/qa.md`,passed:!(i.FAIL>0)&&o.length===0,failing:o,counts:i,fresh:Sr(t,n)>=r}}function po(t,e,r=0){let n;try{n=al(re.join(t,e))}catch{return[]}let s=[];for(let o of n){let i=`${e}/${o}`;if(s.push(i),r>0){let a=!1;try{a=Lf(re.join(t,i)).isDirectory()}catch{}a&&s.push(...po(t,i,r-1))}}return s}function O0(t,e){try{return JSON.parse(mn(re.join(t,e),"utf8"))}catch{return null}}function T0(t,e){try{return Oe(re.join(t,e))}catch{return null}}function nL(t,e){let r=O0(t,"07-shots/shots.origin.json");return!r||!/^(plan_shots|shotplan_make)$/.test(r.via??"")?!1:r.sha256===T0(t,e)}function sL(t,e){let r=O0(t,"07-shots/compile-stats.json");return!r||r.sha256!==T0(t,e)?[]:r.outOfBand??[]}function oL(t,e,r,n){let s=Math.max(Lr(e,r),n),o=Tf.get(t);return o===void 0?(Tf.set(t,s),!0):s>o?(Dg("package_get",t),Tf.delete(t),!1):!0}function iL(t){for(let e of["07-shots/shots.validated.json","07-shots/shots.json"])try{let n=(JSON.parse(mn(re.join(t,e),"utf8")).shots??[]).map(s=>s.id).filter(s=>typeof s=="string");if(n.length)return`${n[0]}..${n[n.length-1]}`}catch{}return null}function lL(t,e,r){let n;try{n=(r??ts({episodeId:t,status:ul,limit:200})).filter(l=>l.episodeId===t)}catch{n=[]}let s=Date.now(),o=l=>l.status,i=n.filter(l=>o(l)==="queued"||o(l)==="running").map(l=>({jobId:l.id,type:l.type,status:l.status,progress:l.progress,message:l.message,updatedAt:l.updatedAt,abandoned:s-Date.parse(l.updatedAt)>(o(l)==="running"?aL:cL)})),a=new Map;for(let l of n){let d=a.get(l.type);(!d||l.createdAt>d.createdAt)&&a.set(l.type,l)}let c=[...a.values()].filter(l=>o(l)==="interrupted"&&Date.parse(l.updatedAt)>e(l.type)).map(l=>({jobId:l.id,type:l.type,message:l.message||l.error||"interrupted",updatedAt:l.updatedAt,rerun:eo(l.type)}));return{active:i,interrupted:c}}function ho(t,e={}){let r=N(t),n=e.gates??tt(r,e),s=Ee(r),o=Ct(r),{file:i,facts:a}=dl(r),c=a??[],l=b=>c.filter(H=>(H.status??"").trim().toLowerCase()===b).map(H=>H.id),d="07-shots/shots.json",p="07-shots/shots.validated.json",f="07-shots/shots.compiled.json",h=Sr(r,p),m=$0(r,"animatic.mp4"),g=$0(r,"final.mp4"),y=et(r,"12-package/package.json")?"12-package/package.json":et(r,"08-package/description.md")?"08-package/description.md":null,w=[...po(r,"12-package",1),...po(r,"08-package",1)],S=Math.max(Sr(r,"07-shots/review.json"),Lr(r,po(r,"08-render/review"))),$=et(r,"06-vo/words.json"),k=Sr(r,"06-vo/words.json"),I=Lr(r,w.filter(b=>/\/thumb[^/]*\.(png|jpe?g|webp)$/i.test(b))),C=Lr(r,po(r,"09-qa").map(b=>`${b}/qa.json`)),xe=lL(t,b=>/animatic/.test(b)?m?.mtime??0:/final/.test(b)?g?.mtime??0:/vo_align|align/.test(b)?k:/qa/.test(b)?C:/thumb/.test(b)?I:/review/.test(b)?S:0,e.jobs),ue=null;if(!e.fast)try{let b=q2(r);ue=b.bavail*b.bsize/1024**3}catch{ue=null}return{id:t,dir:r,style:s,operatorStyle:oe(s),profile:br(r),hypothetical:o,gates:n,keyInstalled:hn()!==null,missingAsset:(()=>{let b=G_(s);return b&&p0(b)?b:null})(),files:{topic:et(r,"01-topic/gate1.md"),outline:et(r,"02-outline/outline.md"),factsFile:i?re.relative(r,i).split(re.sep).join("/"):null,factsRows:c.length,factcheckLog:et(r,"03-research/factcheck.md"),scriptVo:et(r,"04-script/script_vo.txt"),scriptMeta:et(r,"04-script/meta.json"),voWav:et(r,"06-vo/vo.wav"),words:$,wordsFresh:$&&k>=Sr(r,"06-vo/vo.wav")&&k>=Sr(r,"04-script/script_vo.txt"),shotplan:et(r,"07-shots/shotplan.json"),shots:et(r,d),shotsSkeleton:nL(r,d),validated:et(r,p),compiledFresh:et(r,p)&&et(r,f)&&h>=Sr(r,d),compileOutOfBand:sL(r,d),shotRange:e.fast?null:iL(r),reviewFresh:h>0&&S>=h,animatic:m&&{run:m.run,rel:m.rel,fresh:m.fresh},final:g&&{run:g.run,rel:g.rel,fresh:g.fresh},qa:g?rL(r,g.run,Lr(r,w)):null,packaged:y!==null,packageFresh:y!==null&&(!g||Sr(r,y)>=g.mtime),thumbnail:w.some(b=>/\/thumb[^/]*\.(png|jpe?g|webp)$/i.test(b))},seen:{styleGuide:Ra("get_style_guide",s),shotsContext:Ra("shots_context",t),packageViewed:Ra("package_get",t)&&oL(t,r,w,g?.mtime??0)},facts:a?{disputed:l("disputed"),unverified:l("unverified"),noStatus:c.filter(b=>!(b.status??"").trim()).map(b=>b.id),scenario:l("scenario"),noOnScreen:c.filter(b=>!(b.on_screen??"").trim()).map(b=>b.id),gate2Blockers:b0(r,c,o)}:null,gateInputsMtime:{1:Lr(r,po(r,"01-topic")),2:Lr(r,["04-script/script_vo.txt","04-script/script.md","04-script/meta.json","03-research/facts.csv","03-research/facts.checked.csv","03-research/factcheck.md"]),3:Math.max(Lr(r,[d,p]),m?.mtime??0),4:Math.max(Lr(r,w),g?.mtime??0)},jobs:xe.active,interrupted:xe.interrupted,diskFreeGb:ue,minFreeGb:Number(process.env.REELFORGE_MIN_FREE_GB??"1.5")}}function Ff(t,e={}){return uo(ho(t,e))}function N0(t,e,r,n){let s=new Map(r.map(o=>[o.id,o]));for(let o of eL){if(typeof o=="number"){let c=e[o-1];if(c.state==="approved"||c.state==="none"&&!n.includes(o))continue;let l=c.state==="sent_back"&&c.note?` Their notes: ${c.note}`:"";return`Gate ${o} (${c.name}) is ${I0(c)}.${l} The human reviews and decides it in the Studio or in their own terminal (sundownreel-gate approve|send-back|reject ${t} --gate ${o}); no tool can approve it. Wait for their decision and notes.`}let i=s.get(o),a=il.find(c=>c.id===o);if(i&&!i.done)return`Next stage: ${i.label} (${a?.owner}).`}return"Everything is done. The human uploads by hand from the Studio checklist; no tool uploads."}function A0(t){let e=N(t),r=tt(e),n=il.map(c=>{let l=c.present(e);return{id:c.id,label:c.label,owner:c.owner,done:l.length>0,files:l}}),s=ho(t,{gates:r}),o=uo(s),i=Ti(s.profile),a=r.flatMap(c=>(c.ignored??[]).map(l=>`Gate ${c.gate}: ${l}`));return r.some(c=>c.detail===Ni)&&a.unshift(`No gate approval key on this machine: every gate is ${Ni}.`),{id:t,dir:e,example:t.startsWith("_"),style:s.style,operatorStyle:s.operatorStyle,gateProfile:i,hypothetical:s.hypothetical,factsFile:s.files.factsFile,stages:n,gates:r.map(c=>({...c,requirement:i.gates[`gate${c.gate}`],...c.state==="approved"?{}:{command:Ce(s,c.gate)}})),next:o,nextAction:N0(e,r,n,s.profile.required),blockers:jf(s),stale:If(s),activeJobs:s.jobs,interruptedJobs:s.interrupted,gateWarnings:a}}function C0(t={}){let e=Wt();if(!fn(e))return{videosRoot:e,episodes:[]};let r=t.operator??Ae(),n=[];try{n=ts({status:ul,limit:1e3})}catch{n=[]}let o=al(e).filter(i=>{if(i.startsWith("."))return!1;try{return Lf(re.join(e,i)).isDirectory()}catch{return!1}}).sort().map(i=>{try{let a=N(i),c=Ee(a);if(!r&&oe(c))return{id:i,operatorOnly:!0,note:"Operator-only (the private cartoon style); not available on this install."};let l=tt(a,{fast:!0}),d=ho(i,{fast:!0,gates:l,jobs:n}),p=uo(d),f=il.filter(h=>h.present(a).length>0).map(h=>h.id);return{id:i,example:i.startsWith("_"),style:c,gateProfile:d.profile.profile,hypothetical:d.hypothetical,lastStage:f[f.length-1]??null,gates:Object.fromEntries(l.map(h=>[`gate${h.gate}`,h.state])),gateRequirements:E_(d.profile),nextAction:N0(a,l,il.map(h=>({id:h.id,label:h.label,done:f.includes(h.id)})),d.profile.required),next:{step:p.step,stage:p.stage,actor:p.actor,...p.tool?{tool:p.tool}:{},...p.args?{args:p.args}:{},...p.command?{command:p.command}:{},why:p.why},blockers:p.blockers.length}}catch(a){return{id:i,error:a instanceof Error?a.message:String(a),fix:"Check videos/<id>/ (episode.json must be valid JSON; the folder must be readable). episode_status gives the details."}}});return{videosRoot:e,episodes:o}}var U2,V2,_0,Ni,S0,z2,x0,J2,W2,ol,k0,Nf,tr,Of,il,eL,et,Sr,Tf,Lr,aL,cL,ul,er=v(()=>{"use strict";qo();mr();h0();un();sl();vi();w0();Pe();Xt();wr();U2={1:"topic + title direction",2:"script + facts",3:"animatic by shot id",4:"package (the human uploads by hand)"},V2={1:["01-topic/gate1.md"],2:["04-script/gate2.md"],3:["07-shots/gate3.md","08-render/gate3.md"],4:["12-package/gate4.md","08-package/gate4.md"]},_0=1,Ni="not approved (no approval key \u2014 run sundownreel-gate on this machine)",S0="unverified gate record (ignored)",z2={1:[{role:"01-topic/gate1.md",test:/^01-topic\/gate1\.md$/}],2:[{role:"04-script/script_vo.txt",test:/^04-script\/script_vo\.txt$/},{role:"03-research/facts.csv (or facts.checked.csv)",test:/^03-research\/facts(\.checked)?\.csv$/}],3:[{role:"07-shots/shots.validated.json",test:/^07-shots\/shots\.validated\.json$/},{role:"an animatic (08-render/<run>/animatic.mp4)",test:/^08-render\/(?:[^/]+\/)?animatic\.mp4$/}],4:[{role:"12-package/package.json (or 08-package/description.md)",test:/^(12-package\/package\.json|08-package\/description\.md)$/}]};x0=new Map;J2=/^[0-9a-f]{64}$/,W2=new Set(["approved","sent_back","rejected"]),ol=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),k0=t=>Object.fromEntries(Object.keys(t).sort().map(e=>[e,t[e]]));Nf=class extends Error{};tr=(...t)=>e=>t.filter(r=>fn(re.join(e,r))),Of=(t,e)=>r=>{let n=re.join(r,t);return fn(n)?al(n).filter(s=>fn(re.join(n,s,e))).map(s=>`${t}/${s}/${e}`):[]},il=[{id:"topic",label:"Topic",owner:"agent (scout) + human",present:tr("01-topic/gate1.md")},{id:"outline",label:"Outline",owner:"agent (writer)",present:tr("02-outline/outline.md")},{id:"research",label:"Research (facts.csv)",owner:"agent (researcher)",present:tr("03-research/facts.csv","03-research/facts.checked.csv")},{id:"factcheck",label:"Independent fact-check",owner:"agent (fresh fact-checker)",present:tr("03-research/factcheck.md")},{id:"script",label:"Script",owner:"agent (writer)",present:tr("04-script/script_vo.txt")},{id:"vo",label:"Voice-over + alignment",owner:"human records, tool aligns",present:tr("06-vo/words.json")},{id:"shotplan",label:"Shot plan skeleton",owner:"tool (shotplan_make / plan_shots)",present:tr("07-shots/shotplan.json")},{id:"shots",label:"Shot DSL (shots.json)",owner:"agent (shot-DSL writer)",present:tr("07-shots/shots.json")},{id:"validated",label:"Validated + compiled shots",owner:"tool (shots_compile)",present:tr("07-shots/shots.validated.json","07-shots/shots.compiled.json")},{id:"animatic",label:"Animatic",owner:"tool (render_animatic)",present:Of("08-render","animatic.mp4")},{id:"final",label:"Final render",owner:"tool (render_final; Gate 3 in strict, Gate 2 in quick)",present:Of("08-render","final.mp4")},{id:"qa",label:"QA",owner:"tool (QA)",present:Of("09-qa","qa.json")},{id:"package",label:"Package",owner:"agent (packager) + tool",present:t=>[...tr("12-package/package.json")(t),...tr("08-package/description.md")(t)]}],eL=["topic",1,"outline","research","factcheck","script",2,"vo","shotplan","shots","validated","animatic",3,"final","qa","package",4];et=(t,e)=>fn(re.join(t,e)),Sr=(t,e)=>P0(re.join(t,e));Tf=new Map;Lr=(t,e)=>e.reduce((r,n)=>Math.max(r,Sr(t,n)),0);aL=60*6e4,cL=360*6e4,ul=["queued","running","interrupted","succeeded","failed","cancelled"]});function Oi(){return process.env.SUNDOWNREEL_OPERATOR!=="1"?{enabled:!1,reason:"SUNDOWNREEL_OPERATOR is not 1"}:hn()?{enabled:!0,reason:"operator machine"}:{enabled:!1,reason:`no gate approval public key at ${as()} (run sundownreel-gate key on the operator machine)`}}function Ae(){return Oi().enabled}function fo(t="The cartoon profile"){let e=Oi();if(!e.enabled)throw new qf(`${t} is operator-only: it is not part of any Sundown Reel subscription tier. It runs only on the operator's machine (SUNDOWNREEL_OPERATOR=1 plus the local gate key); here: ${e.reason}.`)}var qf,Xt=v(()=>{"use strict";er();qf=class extends Error{}});import{appendFileSync as dL,existsSync as Te,mkdirSync as G0,readdirSync as uL,readFileSync as yn,renameSync as pL,statSync as mo,writeFileSync as U0}from"node:fs";import M from"node:path";function Dr(t,e){G0(M.dirname(t),{recursive:!0});let r=`${t}.tmp-${process.pid}`;U0(r,e),pL(r,t)}function Uf(t,e,r){try{if(tt(t)[e-1].state==="approved")return`Gate ${e} was approved; changing ${r} makes it stale until the human re-approves.`}catch{}}function V0(t){let e=t.episodeId;if(Bh(e),e.startsWith("_")||e.toLowerCase().startsWith("lab"))throw new Error("Ids starting with _ or lab are reserved for internal test episodes. Use e.g. 2026-12-01-robot-rent.");let r=t.title.trim();if(!r)throw new Error("An episode needs a title.");let n=M.join(Wt(),e);if(Te(n))throw new Error(`Episode "${e}" already exists. Call episode_status.`);for(let i of L0)G0(M.join(n,i),{recursive:!0});let s={schema:1,id:e,title:r,profile:"cartoon",hypothetical:t.hypothetical===!0,...t.style?{style:t.style}:{},...t.gateProfile?{gateProfile:t.gateProfile}:{},...t.format?{format:t.format}:{},budgetUsd:5,createdAt:new Date().toISOString(),createdBy:"agent (episode_create)"};Dr(M.join(n,"episode.json"),`${JSON.stringify(s,null,2)}
|
|
51
|
+
`);let o=t.gateProfile==="quick";return{episode:e,dir:n,created:["episode.json",...L0.map(i=>`${i}/`)],hypothetical:s.hypothetical,...t.style?{style:t.style}:{},...t.gateProfile?{gateProfile:t.gateProfile}:{},...t.format?{format:t.format}:{},next:o?"Save the topic (topic_save) and outline; Gate 1 is optional in the quick profile. Then research with facts_upsert.":"Propose topic + title directions to the user; Gate 1 (01-topic/gate1.md) is their call. Then research with facts_upsert."}}function z0(t,e){if(!mL.test(t))throw new Error(`actor must be your ${e} session id (3\u201380 chars: letters, digits, . _ : -).`);if(t.toLowerCase().startsWith("human:"))throw new Error('actor is an agent session id; "human:" actors exist only in gate records signed by sundownreel-gate.')}function gL(t){if(Te(M.join(t,"03-research/facts.checked.csv")))throw new Error("This episode has a legacy 03-research/facts.checked.csv that overrides facts.csv. Ask the user to merge it into facts.csv first.");return M.join(t,pl)}function H0(t){let e=gL(t),r=Te(e)?to(yn(e,"utf8")):{header:[],rows:[]},n=[...r.header];for(let s of hL)n.includes(s)||n.push(s);return{file:e,header:n,rows:r.rows}}function B0(t){let e=N(t),r=["03-research/facts.checked.csv",pl].find(s=>Te(M.join(e,s)))??null;if(!r)return{episode:t,file:null,facts:[],note:"No facts yet. Add them with facts_upsert."};let n=to(yn(M.join(e,r),"utf8"));return{episode:t,file:r,header:n.header,facts:n.rows,factcheck:gn(M.join(e,"03-research/factcheck.md"))}}function J0(t,e,r){z0(e,"researcher");let n=N(t),s=Uf(n,2,"facts.csv"),{file:o,header:i,rows:a}=H0(n),c=[],l=[];for(let d of r){if(!fL.test(d.id))throw new Error(`Fact id "${d.id}" must look like F1, F12 or F12a.`);let p={};for(let[h,m]of Object.entries(d))typeof m=="string"&&(p[h]=m.replace(/\r?\n/g," ").trim());p.status="unverified",p.checker="",p.researcher=e;let f=a.findIndex(h=>h.id===d.id);f>=0?(a[f]={...a[f],...p},l.push(d.id)):(a.push(p),c.push(d.id))}return Dr(o,Vh(i,a)),{episode:t,file:pl,added:c,updated:l,status:"unverified",...s?{warning:s}:{},next:"A fresh fact-checker session (a different actor id) checks each row against its source and records the result with factcheck_record."}}function W0(t,e,r){z0(e,"fact-checker");let n=N(t),s=Uf(n,2,"facts.csv"),{file:o,header:i,rows:a}=H0(n);if(!a.length)throw new Error("There are no facts to check. The researcher adds them with facts_upsert first.");let c=[];for(let f of r){let h=a.find(m=>m.id===f.id);h?h.researcher?h.researcher===e&&c.push(`${f.id}: researched by ${e}; the fact-check must come from a different session (decision #13)`):c.push(`${f.id}: has no researcher recorded; re-save it with facts_upsert first`):c.push(`${f.id}: not in facts.csv`)}if(c.length)throw new Error(`Nothing recorded:
|
|
52
|
+
${c.join(`
|
|
53
|
+
`)}`);let l=new Date().toISOString().slice(0,10),d=[`
|
|
54
|
+
## Fact-check by ${e}, ${new Date().toISOString()}
|
|
55
|
+
`];for(let f of r){let h=a.find(g=>g.id===f.id);h.status=f.status,h.checker=`${e} ${l}`;let m=(f.note??"").replace(/\r?\n/g," ").trim();m&&(h.notes=h.notes?`${h.notes} | check: ${m}`:`check: ${m}`),d.push(`- ${f.id}: **${f.status}**${m?` \u2014 ${m}`:""}`)}Dr(o,Vh(i,a));let p=M.join(n,"03-research/factcheck.md");return Te(p)||U0(p,`# Independent fact-check: ${t}
|
|
56
|
+
`),dL(p,`${d.join(`
|
|
57
|
+
`)}
|
|
58
|
+
`),{episode:t,recorded:r.map(f=>`${f.id}=${f.status}`),checker:e,...s?{warning:s}:{}}}function K0(t,e){try{return JSON.parse(t)}catch{return e}}function Z0(t){let e=N(t),r=gn(M.join(e,"04-script/meta.json"));return{episode:t,scriptMd:gn(M.join(e,"04-script/script.md")),scriptVo:gn(M.join(e,"04-script/script_vo.txt")),meta:r?K0(r,{error:"04-script/meta.json is not valid JSON"}):null,outline:gn(M.join(e,"02-outline/outline.md"))}}function D0(t,e){let r=Vf(t);if(!r.length)return!1;for(let n=0;n+r.length<=e.length;n++)if(r.every((s,o)=>e[n+o]===s))return!0;return!1}function M0(t,e){let r=t.trim().split(/\s+/).filter(n=>Y0(n));for(let n=Math.min(3,r.length);n<=Math.min(8,r.length);n++){let s=r.slice(0,n).join(" "),o=Vf(s),i=0;for(let a=0;a+o.length<=e.length;a++)o.every((c,l)=>e[a+l]===c)&&i++;if(i===1)return s}return r.slice(0,Math.min(6,r.length)).join(" ")}function bL(t,e,r){let n=Vf(e),s=e.split(/\n\s*\n|\n/).map(i=>i.trim()).filter(Boolean),o=r.split(`
|
|
59
|
+
`);return t.map((i,a)=>{if(!i||typeof i!="object")throw new Error(`meta.chapters[${a}] must be {anchor, title}.`);let c=i,l=typeof c.anchor=="string"?c.anchor.trim():"";if(l&&D0(l,n))return i;let d=typeof c.vo=="string"?c.vo:typeof c.startsWith=="string"?c.startsWith:null,p=null;if(d&&D0(d,n)&&(p=d),!p&&l&&yL.test(l)){let f=o.findIndex(h=>new RegExp(`(^|[^a-z0-9-])${l}([^a-z0-9-]|$)`).test(h)&&!/^\s*\|/.test(h));if(f>=0)for(let h of o.slice(f+1)){let m=s.find(g=>h.trim()&&g.startsWith(h.trim().slice(0,40)));if(m){p=m;break}}}if(p)return{...c,anchor:M0(p,n),...l&&l!==p?{slug:l}:{}};if(a===0)return i;throw new Error(`meta.chapters[${a}].anchor ${JSON.stringify(l)} is not in script_vo.txt. A chapter anchor is the first 3\u20136 words of the chapter's first VO line, exactly as read (e.g. "${M0(s[Math.min(a,s.length-1)]??"",n)}"); package_make times the chapter by finding it in words.json. To keep an outline slug, pass {anchor: ${JSON.stringify(l||"town-reacts")}, title, vo: "<first words of its VO line>"}.`)})}function X0(t,e){let r=N(t);if(e.scriptMd===void 0&&e.scriptVo===void 0&&e.meta===void 0)throw new Error("Pass scriptMd, scriptVo and/or meta.");let n=e.scriptVo!==void 0?Uf(r,2,"script_vo.txt"):void 0,s=[];if(e.scriptMd!==void 0&&(Dr(M.join(r,"04-script/script.md"),e.scriptMd.endsWith(`
|
|
60
|
+
`)?e.scriptMd:`${e.scriptMd}
|
|
61
|
+
`),s.push("04-script/script.md")),e.scriptVo!==void 0){if(!e.scriptVo.trim())throw new Error("scriptVo is empty.");Dr(M.join(r,"04-script/script_vo.txt"),e.scriptVo.endsWith(`
|
|
62
|
+
`)?e.scriptVo:`${e.scriptVo}
|
|
63
|
+
`),s.push("04-script/script_vo.txt")}if(e.meta!==void 0){let o=e.meta.chapters;if(o!==void 0&&!Array.isArray(o))throw new Error("meta.chapters must be a list of {anchor, title}.");if(Array.isArray(o)){let i=e.scriptVo??gn(M.join(r,"04-script/script_vo.txt")),a=e.scriptMd??gn(M.join(r,"04-script/script.md"));i&&(e={...e,meta:{...e.meta,chapters:bL(o,i,a??"")}})}Dr(M.join(r,"04-script/meta.json"),`${JSON.stringify(e.meta,null,1)}
|
|
64
|
+
`),s.push("04-script/meta.json")}return{episode:t,wrote:s,...n?{warning:n}:{}}}function Q0(t,e={}){let r=N(t);for(let p of["06-vo/vo.wav","04-script/script_vo.txt"])if(!Te(M.join(r,p)))throw new Error(`${p} is missing. The human records the VO and puts it at videos/${t}/06-vo/vo.wav.`);let n=process.env.ELEVENLABS_API_KEY?.trim(),s=e.allowSpend===!1,o=!!n&&!s,i=M.join(r,"06-vo/vo.wav"),a=M.join(r,"04-script/script_vo.txt"),c=M.join(r,"06-vo/words.json"),l=o?"live":s?"dry-run":q0(c,i)?"kept":"estimated";o&&At(t,2,"A paid VO alignment");let d=ft("cartoon_vo_align",void 0,async p=>{if(l==="kept"||l==="estimated"&&q0(c,i))return{episode:t,mode:"kept",output:"06-vo/words.json",note:F0};Xe(p,5,o?"Aligning with ElevenLabs (paid, ~$0.22 per audio hour).":s?"Dry run: no request is sent.":"No ElevenLabs key: estimating word timing from the script.");let f=yn(a,"utf8");if(o){let m=await h_(i,f,n);Dr(c,`${JSON.stringify(m,null,0)}
|
|
65
|
+
`);let g=m.words[m.words.length-1];return{episode:t,mode:l,output:"06-vo/words.json",log:`${m.words.length} words, ${g.end.toFixed(1)}s, loss=${m.loss} (re-align if high)`}}if(s)return{episode:t,mode:l,output:null,log:JSON.stringify(p_(i,f,"06-vo/words.json"),null,1)};let h=m_(f,f_(i));return Dr(c,`${JSON.stringify(h,null,0)}
|
|
66
|
+
`),{episode:t,mode:l,estimated:!0,output:"06-vo/words.json",log:`${h.words.length} estimated words, ${h.words[h.words.length-1]?.end.toFixed(1)??"0.0"}s`,warning:zh}},{episodeId:t});return{episode:t,mode:l,jobId:d.id,...l==="estimated"?{warning:zh}:{},...l==="kept"?{note:F0}:{},poll:"Call job_status with jobId."}}function q0(t,e){if(!Te(t))return!1;try{if(mo(t).mtimeMs<mo(e).mtimeMs)return!1;let r=JSON.parse(yn(t,"utf8"));return r.estimated!==!0&&Array.isArray(r.words)}catch{return!1}}async function eS(t,e={}){let r=N(t);if(!Te(M.join(r,"06-vo/words.json")))throw new Error("06-vo/words.json is missing. Run vo_align first.");let n=[r,...e.fps?["--fps",String(e.fps)]:[],...e.libraryVersion?["--library-version",e.libraryVersion]:[]],s=await Wh("shotplan.py",n,{timeoutMs:12e4}),o=M.join(r,"07-shots/shotplan.stats.json");if(!Te(M.join(r,"07-shots/shotplan.json")))throw new Error(`shotplan.py wrote nothing (exit ${s.code}):
|
|
67
|
+
${Fc(s.stderr||s.stdout)}`);return{episode:t,wrote:["07-shots/shotplan.json","07-shots/shotplan.stats.json"],pacing:s.code===0?"PASS":"FAIL",stats:Te(o)?JSON.parse(yn(o,"utf8")):null,log:Fc(s.stdout,20)}}function Gf(t,e){let r=M.join(t,"08-render");return Te(r)?uL(r).map(s=>M.join(r,s,e)).filter(s=>Te(s)).sort((s,o)=>mo(o).mtimeMs-mo(s).mtimeMs)[0]??null:null}function wL(t){let e=Array.isArray(t?.checks)?t.checks:[],r={PASS:0,FAIL:0,SKIP:0};for(let s of e)(s.result==="PASS"||s.result==="FAIL"||s.result==="SKIP")&&(r[s.result]+=1);let n=e.filter(s=>s.result==="FAIL").map(s=>({id:s.id,check:s.check,value:s.value,...s.band!==void 0&&s.band!==null&&s.band!==""?{band:s.band}:{}}));return{summary:r,failures:n,qa:t}}function tS(t,e){let r=N(t),n;if(e){let d=M.resolve(r,e),p=M.relative(r,d);if(p.startsWith("..")||M.isAbsolute(p))throw new Error("video must be a path inside the episode folder, e.g. 08-render/final_ab12cd34/final.mp4.");n=d}else n=Gf(r,"final.mp4")??Gf(r,"animatic.mp4");if(!n||!Te(n))throw new Error("No render to check. Run render_animatic or render_final first.");let s=M.relative(r,n).split(M.sep).join("/"),o;if(M.basename(n)==="final.mp4"){let d=M.join(r,"12-package","package.json");if(!Te(d))throw new Error(`Refused: ${t} has no 12-package/package.json yet. Call package_make first (QA reads the package metadata), then qa_run.`);let p=!1;try{p=Object.keys(JSON.parse(yn(d,"utf8")).files??{}).includes(s)}catch{}if(mo(d).mtimeMs<mo(n).mtimeMs||!p)throw new Error(`Refused: 12-package/package.json is older than ${s} (or does not list it). Call package_make first (QA reads the package metadata), then qa_run.`)}else o="QA on an animatic: loudness and package checks only mean something on the final (render_final \u2192 package_make \u2192 qa_run).";let i=M.join(r,"09-qa",M.basename(M.dirname(n))),a=M.relative(r,i).split(M.sep).join("/"),c=[r,"--video",n,"--out",i],l=ft("cartoon_qa",void 0,async d=>{Xe(d,5,`QA on ${M.relative(r,n)}.`);let p=await Wh("qa.py",c,{timeoutMs:60*6e4}),f=M.join(i,"qa.json");if(!Te(f))throw new Error(`qa.py wrote no ${a}/qa.json (exit ${p.code}):
|
|
68
|
+
${Fc(p.stderr||p.stdout)}`);return{episode:t,video:M.relative(r,n),passed:p.code===0,...wL(K0(yn(f,"utf8"),null)),qaJson:`${a}/qa.json`,report:`${a}/qa.md`}},{episodeId:t});return{episode:t,video:s,jobId:l.id,...o?{warning:o}:{},poll:"Call job_status with jobId."}}async function rS(t){let e=N(t);for(let i of["04-script/meta.json","06-vo/words.json",pl])if(!Te(M.join(e,i)))throw new Error(`${i} is missing; package_make needs it.`);__(e,{operator:Ae()});let r=Te(M.join(e,"12-package","description.md"))?"12-package":"08-package",n={};for(let i of["description.md","meta.json"]){let a=M.join(e,r,i);Te(a)&&(n[`${r}/${i}`]=Oe(a))}let s=Gf(e,"final.mp4");s&&(n[M.relative(e,s).split(M.sep).join("/")]=Oe(s));let o={schema:1,episode:t,files:n,createdAt:new Date().toISOString(),note:"Built by package_make. The human uploads by hand after Gate 4."};return Dr(M.join(e,"12-package","package.json"),`${JSON.stringify(o,null,2)}
|
|
69
|
+
`),{episode:t,wrote:[...Object.keys(n).filter(i=>i.startsWith(r)),"12-package/package.json"],description:gn(M.join(e,r,"description.md")),note:"The human reviews the package at Gate 4 and uploads by hand. No tool uploads."}}var gn,L0,pl,hL,fL,mL,Y0,Vf,yL,F0,hl=v(()=>{"use strict";mr();vi();g_();S_();Xt();er();Pe();no();gn=t=>Te(t)?yn(t,"utf8"):null;L0=["01-topic","02-outline","03-research","04-script","06-vo","07-shots","08-render","09-qa","12-package"];pl="03-research/facts.csv",hL=["id","claim","value","unit","on_screen","as_of","source_name","source_date","url","quote","status","checker","researcher","notes"],fL=/^F\d{1,4}[a-z]?$/,mL=/^[A-Za-z0-9][A-Za-z0-9._:-]{2,79}$/;Y0=t=>t.toLowerCase().replace(/[^a-z0-9$%]+/g,""),Vf=t=>t.split(/\s+/).map(Y0).filter(Boolean),yL=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;F0="Kept the existing 06-vo/words.json: it is a real alignment (not estimated), and without ELEVENLABS_API_KEY vo_align would only replace it with estimated timing. To re-align a new recording, add the key and run vo_align again, or delete 06-vo/words.json first to accept estimated timing."});import{existsSync as vL,readFileSync as _L}from"node:fs";import zf from"node:path";function fl(t){return t.filter(e=>e.trim().startsWith("|")&&!/^\|\s*-/.test(e.trim())).slice(1).map(e=>e.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(r=>r.trim()))}function SL(t,e="LIBRARY.md"){let r=new Map,n="";for(let b of t.split(/\r?\n/)){let H=/^## (.+)$/.exec(b);H?(n=H[1].trim(),r.set(n,[])):r.get(n)?.push(b)}let s=b=>[...r.entries()].find(([H])=>H.startsWith(b))?.[1]??[],o=b=>b.find(H=>H.trim()!=="")??"",i=fl(s("Cast")).map(b=>ml(b[0])),a=s("Poses"),c=fl(a).map(b=>ml(b[0])),l=bn(a.find(b=>b.startsWith("**Expressions**"))??""),d=bn(a.find(b=>b.startsWith("**Mouths**"))??""),p={},f=null;for(let b of s("Sets")){let H=/^### `([^`]+)`/.exec(b);if(H){f={cameras:[],marks:{},screens:[],hasReverse:!1,cameraZ:{}},p[H[1]]=f;continue}if(f)if(b.startsWith("- **Camera presets:**")){for(let se of b.matchAll(/`([^`]+)` \(x (-?[\d.]+), z (-?[\d.]+)/g))f.cameras.push(se[1]),f.cameraZ[se[1]]=go(se[3]);f.hasReverse=/reverse cards available/.test(b)}else if(b.startsWith("- **Marks:**"))for(let se of b.matchAll(/`([^`]+)` \(x (-?[\d.]+), z (-?[\d.]+)(?:, facing (-?1))?\)/g))f.marks[se[1]]={x:go(se[2]),z:go(se[3]),...se[4]?{facing:go(se[4])}:{}};else if(b.startsWith("- **Screens**")){f.screenSizes={};for(let se of b.matchAll(/`([^`]+)` \((\d+)×(\d+)\)/g))f.screens.push(se[1]),f.screenSizes[se[1]]={w:go(se[2]),h:go(se[3])}}else b.trim()&&!b.startsWith("-")&&!f.description&&(f.description=b.trim())}let h=fl(s("Props")).map(b=>({ref:ml(b[0]),size:b[1],description:b[2]})),m=fl(s("In-world text")).map(b=>({kind:ml(b[0]).replace(/:$/,""),description:b[1]})),g=(s("Charts").find(b=>b.includes("chart.kind"))??"").split(/Data shapes|Every chart/)[0],y=bn(g).filter(b=>b!=="chart.kind"),w=s("SFX"),S=o(w),$=S.startsWith("_")?[]:bn(S),k=bn(w.find(b=>b.includes("adds these automatically"))??""),I=o(s("Music")),C=I.startsWith("_")?[]:bn(I),ne=s("Transitions"),xe=bn(ne.find(b=>b.startsWith("`transitionOut`"))??"").filter(b=>b!=="transitionOut"),ue=bn(ne.find(b=>b.startsWith("`grade`"))??"").filter(b=>b!=="grade");return{source:e,sets:p,casts:i,poses:c,expressions:l,mouths:d,props:h,textKinds:m,chartKinds:y,transitions:xe,grades:ue,sfx:$,music:C,autoSfx:k}}function oS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[r,n]of Object.entries(t))typeof n=="number"&&Number.isFinite(n)&&(e[r]=n);return e}function xL(t,e){let r=i=>Array.isArray(i)?i.map(String):[],n=Array.isArray(t.props)?t.props.map(i=>typeof i=="string"?{ref:i}:i):[],s=Array.isArray(t.textKinds)?t.textKinds.map(i=>typeof i=="string"?{kind:i.replace(/:$/,"")}:i):[],o=t.sets??{};if(!Object.keys(o).length||!Array.isArray(t.casts))throw new gl(`${e} has no sets or casts; regenerate it from the engine.`);return{source:e,libraryVersion:typeof t.libraryVersion=="string"?t.libraryVersion:void 0,sets:o,casts:r(t.casts),poses:r(t.poses),expressions:r(t.expressions),mouths:r(t.mouths),props:n,textKinds:s,chartKinds:r(t.chartKinds),transitions:r(t.transitions),grades:r(t.grades),sfx:r(t.sfx),music:r(t.music),autoSfx:r(t.autoSfx),castHeights:oS(t.castHeights),nearClip:typeof t.nearClip=="number"?t.nearClip:void 0,styles:Array.isArray(t.styles)?t.styles:void 0,styleIds:Array.isArray(t.styleIds)?r(t.styleIds):void 0,defaultStyle:typeof t.defaultStyle=="string"?t.defaultStyle:void 0}}function kL(){let t=[];process.env.REELFORGE_LIBRARY_INDEX&&t.push(zf.resolve(process.env.REELFORGE_LIBRARY_INDEX));for(let e of[_t(),Se()])t.push(zf.join(e,"library","library-index.json"),zf.join(e,"library","LIBRARY.md"));return t}function yo(){if(nS)return nS;let t=[];for(let e of kL()){if(t.push(e),!vL(e))continue;let r=_L(e,"utf8");if(e.endsWith(".json"))return xL(JSON.parse(r),e);let n=SL(r,e);if(Object.keys(n.sets).length&&n.casts.length)return n}throw new gl(`No engine library index found. Looked in: ${t.join(", ")}. Generate library/LIBRARY.md (or library-index.json) from the engine, or set REELFORGE_LIBRARY_INDEX.`)}function iS(t,e=()=>[],r){let n=new Set(t.props.map(i=>i.ref)),s=new Set(t.textKinds.map(i=>i.kind)),o={};for(let[i,a]of Object.entries(t.sets)){let c=sS(a.textOpts),l=sS(a.opts),d=oS(a.cameraZoom);o[i]={cameras:a.cameras,marks:a.marks,screens:a.screens,hasReverse:a.hasReverse,cameraZ:a.cameraZ,...d?{cameraZoom:d}:{},...c?{textOpts:c}:{},...l?{opts:l}:{}}}return{sets:o,casts:t.casts,poses:t.poses,refExists:i=>i.startsWith("cast/")?!0:i.startsWith("prop/")?n.has(i):s.has(i.split(":")[0]),chartDataIssues:e,...t.castHeights?{castHeights:t.castHeights}:{},...t.nearClip!=null?{nearClip:t.nearClip}:{},...r?.length?{styles:r}:{}}}function yl(t){return{source:t.source,libraryVersion:t.libraryVersion,sets:Object.fromEntries(Object.entries(t.sets).map(([e,r])=>[e,{description:r.description,cameraPresets:r.cameras,reverseCards:r.hasReverse,marks:r.marks,screens:r.screenSizes??Object.fromEntries(r.screens.map(n=>[n,null])),...r.opts?{opts:r.opts}:{},...r.textOpts?{textOpts:r.textOpts,note:"textOpts are drawn as on-screen text: a number there needs set.factIds"}:{}}])),cast:t.casts,poses:t.poses,expressions:t.expressions,mouths:t.mouths,props:t.props,textKinds:t.textKinds.map(e=>({ref:`${e.kind}:<anything>`,description:e.description})),chartKinds:t.chartKinds,transitions:t.transitions,grades:t.grades,sfx:t.sfx,music:t.music,autoSfx:t.autoSfx,rules:["Use only ids listed here. Anything else is a library request in 07-shots/library-requests.md (closest existing asset as fallback).","Every number shown on screen needs a factId whose status is verified or computed (scenario only in episodes flagged hypothetical).","Do not place auto sfx by hand; the compiler adds them."]}}var gl,nS,bn,go,ml,sS,Hf=v(()=>{"use strict";pe();Pe();gl=class extends Error{},nS=null,bn=t=>[...t.matchAll(/`([^`]+)`/g)].map(e=>e[1]),go=t=>Number(t);ml=t=>t.replace(/^`|`$/g,"");sS=t=>Array.isArray(t)?t.filter(e=>typeof e=="string"):void 0});function cs(t,e){let r=[{type:"text",text:JSON.stringify(t)}];for(let n of e)n.caption&&r.push({type:"text",text:n.caption}),r.push({type:"image",data:typeof n.data=="string"?n.data:n.data.toString("base64"),mimeType:n.mimeType??"image/jpeg"});return new bl(r)}function bo(t){return t instanceof bl?t.isError?{content:t.content,isError:!0}:{content:t.content}:{content:[{type:"text",text:JSON.stringify(t)}]}}var bl,wo=v(()=>{"use strict";bl=class{constructor(e,r=!1){this.content=e;this.isError=r}content;isError}});async function Ci(t={}){let e=t.styleId??(t.episodeId?Ee(N(t.episodeId)):null),r=e?await Ne(e):null;if(r&&oe(r))return fo(`The ${e} style (the private paper-cutout cartoon)`),{operator:!0,styleId:r,entitlements:null};if(Ae())return{operator:!0,styleId:r,entitlements:null};if(t.open)return{operator:!1,styleId:r,entitlements:null};let n=await Cr();return r&&await M_(r,n),{operator:!1,styleId:r,entitlements:n}}var Bf=v(()=>{"use strict";lo();Pe();Xt();wr();ln()});import{existsSync as $L}from"node:fs";import aS from"node:path";import{pathToFileURL as EL}from"node:url";function RL(t){let e=J(),r=t==="@reelforge/dsl"?"dsl/index.mjs":t==="@reelforge/dsl/semantic"?"dsl/semantic.mjs":null;return e&&r&&$L(aS.join(e,r))?EL(aS.join(e,r)).href:null}async function cS(t){try{return await import(RL(t)??t)}catch(e){let r=e instanceof Error?e.message:String(e);throw new Li(`The Shot DSL package (${t}) could not be loaded: ${r}. It must be installed as a workspace dependency and built to JavaScript for the node runtime.`)}}async function Di(){if(wl.core)return wl.core;let t="@reelforge/dsl",e=await cS(t);if(typeof e.EpisodeSchema?.safeParse!="function"||typeof e.compile!="function")throw new Li(`${t} does not export EpisodeSchema/compile; the installed version is incompatible.`);return e}async function Jf(){if(wl.semantic)return wl.semantic;let t="@reelforge/dsl/semantic",e=await cS(t);if(typeof e.semanticCheck!="function"||typeof e.resolve!="function")throw new Li(`${t} does not export semanticCheck/resolve; the installed version is incompatible.`);return e}function lS(t,e){let r=t.map(i=>typeof i=="symbol"?String(i.description??""):i),n="EPISODE",s=r;if(r[0]==="shots"&&typeof r[1]=="number"){let a=e?.shots?.[r[1]]?.id;n=typeof a=="string"&&a?a:`shots[${r[1]}]`,s=r.slice(2)}let o="";for(let i of s)o+=typeof i=="number"?`[${i}]`:o?`.${i}`:String(i);return{shot:n,path:o||"(shot)"}}var Li,wl,dS=v(()=>{"use strict";pe();Li=class extends Error{},wl={}});function Wf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function mS(t){if(t==="")return[];if(!t.startsWith("/"))throw new be(`JSON pointer "${t}" must start with "/".`);return t.slice(1).split("/").map(e=>{let r=e.replace(/~1/g,"/").replace(/~0/g,"~");if(hS.has(r))throw new be(`JSON pointer token "${r}" is not allowed.`);return r})}function uS(t,e,r){let n=mS(e.path);if(!n.length)throw new be(`${r}: path "" would replace the whole shot; use upsert instead.`);if((e.op==="add"||e.op==="replace")&&e.value===void 0)throw new be(`${r}: ${e.op} needs a value.`);let s=t;for(let a of n.slice(0,-1))if(Array.isArray(s)){let c=Number(a);if(!Number.isInteger(c)||c<0||c>=s.length)throw new be(`${r}: ${e.path}: no array index ${a}.`);s=s[c]}else if(Wf(s)){if(!(a in s))throw new be(`${r}: ${e.path}: no field "${a}".`);s=s[a]}else throw new be(`${r}: ${e.path}: "${a}" is inside a non-object.`);let o=n[n.length-1],i=e.value===void 0?void 0:structuredClone(e.value);if(Array.isArray(s)){let a=o==="-"?s.length:Number(o);if(!Number.isInteger(a)||a<0)throw new be(`${r}: ${e.path}: bad array index "${o}".`);if(e.op==="add"){if(a>s.length)throw new be(`${r}: ${e.path}: index ${a} past the end.`);s.splice(a,0,i)}else{if(a>=s.length)throw new be(`${r}: ${e.path}: no array index ${a}.`);e.op==="replace"?s[a]=i:s.splice(a,1)}return}if(!Wf(s))throw new be(`${r}: ${e.path}: parent is not an object or array.`);if(e.op==="add")s[o]=i;else{if(!(o in s))throw new be(`${r}: ${e.path}: no field "${o}" to ${e.op}.`);e.op==="replace"?s[o]=i:delete s[o]}}function IL(t,e){let r=/^(S\d{3}[a-z]?)\.\.(S\d{3}[a-z]?)$/.exec(e);if(r){let s=t.findIndex(i=>Mr(i)===r[1]),o=t.findIndex(i=>Mr(i)===r[2]);if(s<0||o<0)throw new be(`target ${e}: ${s<0?r[1]:r[2]} is not in the episode.`);if(o<s)throw new be(`target ${e}: ${r[2]} comes before ${r[1]}.`);return Array.from({length:o-s+1},(i,a)=>s+a)}if(!fS.test(e))throw new be(`target "${e}" must be a shot id (S014), a range (S010..S020) or EPISODE.`);let n=t.findIndex(s=>Mr(s)===e);if(n<0)throw new be(`target ${e} is not in the episode.`);return[n]}function pS(t){return[typeof t.startAbs=="number"?t.startAbs:Number.POSITIVE_INFINITY,Mr(t)]}function jL(t,e){let[r,n]=pS(t),[s,o]=pS(e);return r!==s?r<s:n<o}function gS(t,e){let r=structuredClone(t);Array.isArray(r.shots)||(r.shots=[]);let n=new Set,s=[];for(let[i,a]of Object.entries(e.header??{})){if(i==="shots"||hS.has(i))throw new be(`header cannot set "${i}".`);r[i]=structuredClone(a)}for(let i of e.remove??[]){let a=r.shots.findIndex(c=>Mr(c)===i);if(a<0)throw new be(`remove: ${i} is not in the episode.`);r.shots.splice(a,1),s.push(i)}let o=new Set;for(let i of e.upsert??[]){if(!Wf(i))throw new be("upsert: every item must be one shot object.");let a=Mr(i);if(!fS.test(a))throw new be(`upsert: shot id ${JSON.stringify(i.id)} must look like S001 or S014a.`);if(o.has(a))throw new be(`upsert: ${a} appears twice.`);o.add(a);let c=structuredClone(i),l=r.shots.findIndex(d=>Mr(d)===a);if(l>=0)r.shots[l]=c;else{let d=r.shots.findIndex(p=>jL(c,p));r.shots.splice(d<0?r.shots.length:d,0,c)}n.add(a)}for(let[i,a]of(e.ops??[]).entries()){if(!["add","replace","remove"].includes(a.op))throw new be(`ops[${i}]: op must be add, replace or remove.`);if(a.target==="EPISODE"){if(mS(a.path)[0]==="shots")throw new be(`ops[${i}]: EPISODE ops cannot touch /shots; target the shots instead.`);uS(r,a,`ops[${i}] EPISODE`);continue}for(let c of IL(r.shots,a.target))uS(r.shots[c],a,`ops[${i}] ${Mr(r.shots[c])}`),n.add(Mr(r.shots[c]))}return{episode:r,touched:[...n],removed:s}}var be,hS,fS,Mr,yS=v(()=>{"use strict";be=class extends Error{},hS=new Set(["__proto__","prototype","constructor"]),fS=/^S\d{3}[a-z]?$/;Mr=t=>typeof t.id=="string"?t.id:""});import{existsSync as wS,readFileSync as PL}from"node:fs";import Mi from"node:path";function Fi(){if(process.env.REELFORGE_AUDIO_ROOT)return Mi.resolve(process.env.REELFORGE_AUDIO_ROOT);let t=Mi.join(_t(),"engine-remotion","public");return wS(t)?t:Mi.join(Se(),"engine-remotion","public")}function bS(t){if(!wS(t))return{};try{let e=JSON.parse(PL(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Kf(){let t=Fi();return{root:t,sfx:bS(Mi.join(t,"sfx","sfx-index.json")),music:bS(Mi.join(t,"music","music-index.json"))}}var vS=v(()=>{"use strict";pe();Pe()});import{copyFileSync as Zf,existsSync as Re,mkdirSync as _l,readdirSync as OL,readFileSync as Sl,renameSync as TL,rmSync as SS,statfsSync as NL,writeFileSync as vl}from"node:fs";import A from"node:path";import{fileURLToPath as AL}from"node:url";import{spawn as CL}from"node:child_process";function ds(t){return JSON.parse(Sl(t,"utf8"))}function vo(t,e){_l(A.dirname(t),{recursive:!0});let r=`${t}.tmp-${process.pid}`;vl(r,e),TL(r,t)}function Xf(t,e){let r=A.join(t,Le);if(!Re(r))throw new Error(`${e} has no ${Le} yet. Write it (shots_save), then validate.`);try{return ds(r)}catch(n){throw new Error(`${Le} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}async function qL(t,e,r,n){let s=[],o=n??Ee(t),i=await Ne(o),a=await Ne(r.style??"cutout");i!==a&&s.push({shot:"EPISODE",path:"style",msg:`shots.json style "${r.style??"cutout (default)"}" ${FL} "${o}" in episode.json. Fix: project_set_style {episodeId: "${e}", styleId: "${a}"} to switch the episode, or project_set_style {episodeId: "${e}", styleId: "${i}", restyle: true} to restyle the shots`,level:"error"});let c=await Tt();if(c)s.push(...await C_(r));else{let l=(await Ei()).error??"the style registry could not load";oe(i)?s.push({shot:"EPISODE",path:"style",msg:`style registry unavailable, style checks skipped: ${l}`,level:"warn"}):s.push({shot:"EPISODE",path:"style",msg:`cannot check style "${i}": ${l}`,level:"error"})}return{issues:s,style:i,registry:!!c}}function GL(t){let e=new Set;return t.filter(r=>{if(!/^unknown style/.test(r.msg))return!0;let n=`${r.shot}|${r.path}|${r.level}`;return e.has(n)?!1:(e.add(n),!0)})}async function kS(t,e){let r=N(t),n=e.shots!==void 0,s=n?e.shots:Xf(r,t),o=await Di(),i=[],a=o.EpisodeSchema.safeParse(s);if(!a.success){for(let y of a.error.issues)i.push({...lS(y.path,s),msg:y.message,level:"error"});return{dir:r,draft:n,raw:s,issues:i,stage:"schema",ep:null,lib:null,libData:null,factsFile:null,style:null,styleRegistry:null}}let c=a.data;c.videoId!==t&&i.push({shot:"EPISODE",path:"videoId",msg:`videoId "${c.videoId}" does not match the episode folder "${t}"`,level:"error"}),c.hypothetical===!0&&!Ct(r)&&i.push({shot:"EPISODE",path:"hypothetical",msg:`shots.json sets hypothetical: true but videos/${t}/episode.json does not flag the episode hypothetical (a human sets that flag at Gate 2)`,level:"error"});let l=await Jf(),d=yo(),p=iS(d,o.chartDataIssues,await O_()),{file:f,facts:h}=e.noFacts?{file:null,facts:null}:dl(r);i.push(...l.semanticCheck(c,p,h,new Set(d.sfx),{noFacts:e.noFacts===!0}));let m=await qL(r,t,c,e.expectStyle);i.push(...m.issues);let g=GL(i);return{dir:r,draft:n,raw:s,issues:g,stage:"semantic",ep:c,lib:p,libData:d,factsFile:f,style:m.style,styleRegistry:m.registry}}function $S(t,e,r){let n=e.issues.filter(a=>a.level==="error"),s=e.issues.filter(a=>a.level==="warn"),o=[...n,...s].map(ML),i=o.slice(0,r);return o.length>i.length&&i.push(`\u2026 ${o.length-i.length} more line(s); pass maxLines to see them`),{episode:t,source:e.draft?"draft (not saved)":Le,valid:n.length===0,errors:n.length,warnings:s.length,failedAt:n.length?e.stage:void 0,lines:i,factsFile:e.factsFile?A.relative(e.dir,e.factsFile):null,library:e.libData?.source,...e.style?{style:e.style,styleRegistry:e.styleRegistry?"loaded":"unavailable"}:{},summary:n.length?`INVALID: ${n.length} error(s), ${s.length} warning(s)`:`VALID with ${s.length} warning(s)`}}async function Qf(t,e={}){let r=await kS(t,e);return $S(t,r,e.maxLines??xS)}async function UL(t){let e=await Tt(),r;try{r=e?.findStyle(t)?.qaBands}catch{r=void 0}let n={...qi,transitionShare:{...qi.transitionShare,band:[.1,.2]},sfxOnsetsPerSec:{...qi.sfxOnsetsPerSec,band:[2,3.2]}},s=r?.q2;return s?.mean&&(n.contentMean={band:s.mean,label:`content shot mean (s), ${t} band`}),s?.median&&(n.contentMedian={band:s.median,label:`content shot median (s), ${t} band`}),s?.segPerMin&&(n.segmentsPerMin={band:s.segPerMin,label:`segments per minute, ${t} band`}),s?.transitions&&(n.transitionShare={band:[s.transitions[0]/(s.transitions[0]>1?100:1),s.transitions[1]/(s.transitions[1]>1?100:1)],label:qi.transitionShare.label}),r?.q9?.sfxPerSec&&(n.sfxOnsetsPerSec={band:r.q9.sfxPerSec,label:qi.sfxOnsetsPerSec.label}),n}async function ES(){let t=await L_();return t?{autoSfx:t}:{}}async function RS(t,e){let r=await kS(t,e),n=$S(t,r,e.maxLines??xS);if(!n.valid||!r.ep||!r.lib)return{rep:n,compiled:null,stats:null,dir:r.dir};let s=await Di(),i=(await Jf()).resolve(r.ep,r.lib),a=Kf(),c=s.compile(i,a.sfx,a.music,await ES()),l=s.timingStats(c);return e.write!==!1&&!r.draft&&(vo(A.join(r.dir,ls),JSON.stringify(i,null,1)),vo(A.join(r.dir,xl),JSON.stringify(c,null,1))),{rep:n,compiled:c,stats:l,dir:r.dir}}function VL(t,e){if(!(t>0))return!1;for(let r=0;r<=t;r++)if(r/t>=e[0]&&r/t<=e[1])return!0;return!1}async function kl(t,e={}){let{rep:r,compiled:n,stats:s}=await RS(t,e);if(!n||!s)return{...r,compiled:!1};let o=await UL(Ee(N(t))),i=Object.fromEntries(Object.entries(o).map(([c,l])=>{let d=s[c];return[c,{label:l.label,value:d,band:l.band,inBand:d>=l.band[0]&&d<=l.band[1]}]})),a=(s.transitionShare*100).toFixed(0);if(r.source===Le){let c=Object.entries(i).filter(([,l])=>!l.inBand).map(([l,d])=>({key:l,label:d.label,value:d.value,band:d.band})).filter(l=>l.key!=="transitionShare"||VL(s.shots,l.band));try{vo(A.join(N(t),DL),`${JSON.stringify({sha256:Oe(A.join(N(t),Le)),outOfBand:c},null,1)}
|
|
70
|
+
`)}catch{}}return{...r,compiled:!0,wrote:r.source===Le?[ls,xl]:[],stats:{...s,transitionsPct:Number(a),totalFrames:n.totalFrames,sfxOnsets:n.sfx.length},targets:i,missingSfx:n.missingSfx,audioRoot:Fi(),summary:`VALID ${s.shots} shots, ${s.seconds} s \xB7 content mean ${s.contentMean} s / median ${s.contentMedian} s \xB7 ${s.segmentsPerMin} seg/min \xB7 transitions ${a}% \xB7 sfx ${s.sfxOnsetsPerSec}/s`+(n.missingSfx.length?` \xB7 ${n.missingSfx.length} sfx ids without licensed files`:"")}}async function _o(t,e,r,n={}){At(t,2,"Writing shots.json");let s=N(t);if(!e||typeof e!="object"||Array.isArray(e))throw new Error("shots must be one Episode JSON object.");let o=e.videoId;if(o!==t)throw new Error(`shots.videoId must be "${t}" (got ${JSON.stringify(o)}).`);let i=await Qf(t,{shots:e,...n.expectStyle?{expectStyle:n.expectStyle}:{}});if(!i.valid)throw new wn(`Not saved: the Shot DSL from ${r} does not validate (${i.summary}). Nothing was written; fix these lines and try again.`,{episode:t,saved:!1,validation:{...i,source:r}});let a=`${JSON.stringify(e,null,1)}
|
|
71
|
+
`,c=E0(a),l=A.join(s,Le),d=Re(l)&&Oe(l)===c,p=null;if(!d){let f=A.join(s,"07-shots","versions");_l(f,{recursive:!0});let h=OL(f).map(m=>/^shots\.v(\d+)\./.exec(m)?.[1]).filter(Boolean).reduce((m,g)=>Math.max(m,Number(g)),0)+1;p=`07-shots/versions/shots.v${String(h).padStart(3,"0")}.${c.slice(0,8)}.json`,vo(A.join(s,p),a),vo(l,a)}return vo(A.join(s,LL),`${JSON.stringify({via:r,sha256:c,at:new Date().toISOString()})}
|
|
72
|
+
`),{episode:t,saved:Le,sha256:c,unchanged:d,version:p,validation:{...i,source:Le}}}async function IS(t){let e=N(t),r=A.join(e,"07-shots/shotplan.json");if(!Re(r))return{saved:!1,reason:"no 07-shots/shotplan.json"};if(Re(A.join(e,Le)))return{saved:!1,reason:"shots.json already exists (not overwritten)"};if(tt(e)[1]?.state!=="approved")return{saved:!1,reason:"Gate 2 is not approved yet; shots_patch starts from the shotplan header later"};let n=ds(r),s;try{let i=yo().sets,a=Array.isArray(i)?i.filter(c=>typeof c=="string"):i&&typeof i=="object"?Object.keys(i):[];s=a.find(c=>c.startsWith("set/office"))??a[0]}catch{s=void 0}let o=(n.shots??[]).map(i=>{let{anchorWord:a,...c}=i;return c.kind==="world"&&c.set===void 0&&s?{...c,set:{ref:s}}:c});try{return{saved:!0,sha256:(await _o(t,{...n,videoId:t,shots:o},"shotplan_make")).sha256,shotCount:o.length}}catch(i){return{saved:!1,reason:i instanceof Error?i.message:String(i)}}}async function jS(t,e){return _o(t,e,"shots_save")}function zL(t,e){let r=/^(S\d{3}[a-z]?)\.\.(S\d{3}[a-z]?)$/.exec(e);if(!r)throw new Error(`range "${e}" must look like S010..S040.`);let n=t.findIndex(o=>o.id===r[1]),s=t.findIndex(o=>o.id===r[2]);if(n<0||s<0)throw new Error(`range ${e}: ${n<0?r[1]:r[2]} is not in the episode.`);return t.slice(Math.min(n,s),Math.max(n,s)+1)}function PS(t,e,r){let n=N(t),s=Xf(n,t),o=Oe(A.join(n,Le));if(!e?.length&&!r)return{episode:t,sha256:o,shots:s};let{shots:i,...a}=s;if(r)return{episode:t,sha256:o,header:a,shots:zL(i??[],r)};let c=new Set(e),l=(i??[]).filter(p=>p.id&&c.has(p.id)),d=[...c].filter(p=>!l.some(f=>f.id===p));return{episode:t,sha256:o,header:a,shots:l,missing:d}}function HL(t){return Re(t)?Sl(t,"utf8"):null}function BL(t){if(!Re(t))return null;try{let e=ds(t);return(Array.isArray(e)?e:e.words??[]).length}catch{return null}}async function OS(t){let e=N(t),r=Ct(e),n=await Ne(Ee(e)),s=oe(n),o=A.join(rs(),"shot-dsl-writer.md"),{file:i,facts:a}=dl(e),c=A.join(e,"07-shots/shotplan.json"),l=null;if(Re(c)){let h;try{h=ds(c)}catch(y){throw new Error(`07-shots/shotplan.json is not valid JSON (${y instanceof Error?y.message:String(y)}). Re-run shotplan_make.`)}let m=h;l=(Array.isArray(m)?m:m.shots??[]).map(y=>({id:y.id,startAbs:y.startAbs,dur:y.dur,vo:y.vo,anchorWord:y.anchorWord}))}let d=`07-shots/plan.${n}.json`,p=["04-script/script.md","04-script/script_vo.txt","06-vo/words.json","07-shots/shotplan.json",d,Le].map(h=>({path:h,exists:Re(A.join(e,h))})),f={script:HL(A.join(e,"04-script/script_vo.txt")),voWords:BL(A.join(e,"06-vo/words.json")),inputs:p,facts:a?a.map(h=>({id:h.id,on_screen:h.on_screen??"",status:h.status??"",onScreenAllowed:j0(h.status,r)&&!!(h.on_screen??"").trim()})):null,factsFile:i?A.relative(e,i):null};if(!s){let h;try{h=await lf(n)}catch(g){h={id:n,error:g instanceof Error?g.message:String(g)}}let m=null;if(Re(A.join(e,d)))try{m=(ds(A.join(e,d)).shots??[]).map(y=>({id:y.id,startAbs:y.startAbs,dur:y.dur,vo:y.vo,beat:y.beat}))}catch{m={error:`${d} is not valid JSON; re-run plan_shots`}}return{episode:t,hypothetical:r,styleId:n,style:h,mcpNotes:[`Style ${n}: write kind "beat" shots with a style-neutral beat (see style.promptGuide); add look only for this style's kinds menu.`,"plan_shots {episodeId, save: true} writes the style's deterministic skeleton as shots.json (needs Gate 2); then refine chapter by chapter with shots_patch.","get_style_guide {styleId} returns the full guide; shots_validate checks dsl + facts + this style's rules; shots_compile reports timing.","You never approve gates, override checks, upload or publish. The human does that in the Studio or their own terminal."],...f,plan:m}}return{episode:t,hypothetical:r,styleId:n,writerPrompt:Re(o)?{path:o,text:Sl(o,"utf8")}:{path:o,text:null,note:"prompts/shot-dsl-writer.md is missing from this install."},mcpNotes:["Use tools, not file paths: shots_types gives the DSL types and library ids, script_get the locked script, facts_get the fact table.","Write chapter by chapter with shots_patch (upsert shots by id, or JSON-patch a shot range); shots_save replaces the whole episode. Both refuse an invalid DSL and write nothing.","shots_validate checks a draft without saving (max 3 fix loops, then ask the user). shots_compile reports timing against the style targets.","render_still shows one frame; render_animatic needs Gate 2; render_final needs Gate 3.","You never approve gates, override checks, upload or publish. The human does that in the Studio or their own terminal."],...f,shotplan:l}}function TS(t){let e=NL(t),r=e.bavail*e.bsize;if(r<_S())throw new Error(`Refused: only ${(r/1024**3).toFixed(2)} GB free on the disk holding ${t}; renders need ${(_S()/1024**3).toFixed(1)} GB. Free space first.`)}async function NS(t){let{rep:e,compiled:r,dir:n}=await RS(t,{});if(!r)throw new Error(`Refused: ${Le} does not validate (${e.summary}). Fix it first:
|
|
73
|
+
${e.lines.slice(0,30).join(`
|
|
74
|
+
`)}`);return{compiled:r,dir:n}}function AS(t){let e=A.join(t,"06-vo","vo.wav"),r=A.join(t,"06-vo","words.json");return{vo:Re(e)?e:null,words:Re(r)?r:null}}async function $l(t){let e=N(t),r=Ee(e);return await df(r),yf(r)}async function CS(t,e){let r=[...new Set(t.shots.map(n=>n.style).filter(n=>!!n))];for(let n of r){await df(n);let s=await yf(n);if(s.family!==e){let o=t.shots.find(i=>i.style===n).id;throw new Error(`Refused: shot ${o} uses style ${s.styleId} (renderer ${s.family}) but the episode renders with ${e}. One episode renders with one backend: remove the per-shot style override or pick a style of the same renderer family.`)}}}async function em(t,e,r,n){let s=await $l(t),o=s.renderer;await o.version();let{compiled:i,dir:a}=await NS(t);await CS(i,s.family);let c=i.shots.find(g=>g.id===e);if(!c)throw new Error(`Shot ${e} is not in ${t}. Shot ids look like S001 or S014a.`);let l=c.len/i.fps,d=Math.min(Math.max(r??l/2,0),Math.max(0,l-1/i.fps)),p=c.from+Math.round(d*i.fps);TS(a);let f=A.join(a,"08-render","stills",`${e}-f${String(p).padStart(6,"0")}.png`);_l(A.dirname(f),{recursive:!0});let{words:h}=AS(a),m=await o.still({shots:A.join(a,ls),shotId:e,t:d,scale:n??.5,out:f,frame:p,publicDir:Fi(),...h?{words:h}:{}});return{episode:t,shotId:e,t:Number(d.toFixed(3)),frame:p,style:s.styleId,rendererFamily:s.family,...m}}function JL(t,e,r){let n=A.join(e,"inputs");_l(n,{recursive:!0});let s=A.join(n,"shots.validated.json"),o=A.join(n,"shots.compiled.json");Zf(r.validated,s),Zf(r.compiled,o);let{vo:i,words:a}=AS(t),c=null;a&&(c=A.join(n,"words.json"),Zf(a,c));let l={[ls]:Oe(s),[xl]:Oe(o),...Re(A.join(t,Le))?{[Le]:Oe(A.join(t,Le))}:{},...c?{"06-vo/words.json":Oe(c)}:{},...i?{"06-vo/vo.wav":Oe(i)}:{}};return{shots:s,compiled:o,words:c,vo:i,voSha:i?l["06-vo/vo.wav"]:null,hashes:l}}function KL(t){let e=r=>{let n=new RegExp(`"input_${r}"\\s*:\\s*"(-?[\\d.]+|-?inf)"`).exec(t),s=n?Number(n[1]):NaN;return Number.isFinite(s)?s:null};return{lufs:e("i"),truePeak:e("tp"),lra:e("lra")}}async function ZL(t,e){let r=A.join(an(),"scripts","master_audio.sh");if(!Re(r))throw new Gi(`Audio master not installed: ${r} is missing. Install the pipeline (or set REELFORGE_PIPELINE), then render_final again.`);let{code:n,stdout:s,stderr:o}=await new Promise((c,l)=>{let d=CL("bash",[r,t,e],{env:gf(),stdio:["ignore","pipe","pipe"]}),p="",f="",h=setTimeout(()=>d.kill("SIGKILL"),3*36e5);d.stdout.on("data",m=>p+=m.toString()),d.stderr.on("data",m=>f+=m.toString()),d.on("error",m=>(clearTimeout(h),l(m))),d.on("close",m=>(clearTimeout(h),c({code:m,stdout:p,stderr:f})))}),i=(o.trim()||s.trim()).split(/\r?\n/).slice(-6).join(`
|
|
75
|
+
`);if(n!==0||!Re(e))throw new Gi(`master_audio.sh failed (exit ${n}): ${i||"no output"}`);return{...KL(`${s}
|
|
76
|
+
${o}`),log:i||void 0}}async function LS(t,e,r,n,s){let o=s.totalFrames,i=await $l(t);await CS(s,i.family);let a=i.renderer,c=await a.version();if(e==="final"&&!a.final)throw new Error(`The installed renderer (${a.id}) cannot render finals.`);let l=N(t);TS(l);let d=Ks(e),p=A.join(l,"08-render",d),f=A.join(p,`${e}.mp4`),h=e==="final"?A.join(p,"final_raw.mp4"):f,m=JL(l,p,n),g=Fi(),y={schema:1,kind:e,renderId:d,renderer:a.id,rendererVersion:c,rendererFamily:i.family,style:i.styleId,height:e==="animatic"?540:1080,gate:`Gate ${r} approved at enqueue and re-checked at job start`,inputs:m.hashes,inputCopies:"inputs/ (the job renders these copies, not the live 07-shots files)",audioRoot:g,totalFrames:o,sandbox:"none: the renderer runs with an allowlisted env (no keys); the SVG\u2192resvg path makes no network calls by construction",createdAt:new Date().toISOString()};vl(A.join(p,"render.json"),JSON.stringify(y,null,2));let w=ft(`cartoon_${e}`,void 0,async S=>{if(e==="final"?MS(t):At(t,r,"Rendering the animatic"),m.vo&&(!Re(m.vo)||Oe(m.vo)!==m.voSha))throw new Error("06-vo/vo.wav changed after the render was queued. Queue it again.");Xe(S,1,`Rendering ${t} ${e} with ${a.id}.`);let $={shots:m.shots,compiled:m.compiled,out:h,publicDir:g,...m.vo?{vo:m.vo}:{},...m.words?{words:m.words}:{}},k=(xe,ue)=>Xe(S,xe*100,ue),I=e==="final"?await a.final($,k):await a.animatic({...$,height:540},k),C;if(e==="final"){Xe(S,97,"Mastering audio (\u221214 LUFS, \u22121.5 dBTP).");let xe=Oe(h),ue=await(WL??ZL)(h,f);if(!Re(f))throw new Gi(`The audio master wrote no ${A.relative(l,f)}.`);let b=ue.lufs!==null&&ue.truePeak!==null?Math.abs(ue.lufs-Yf.lufs)<=1&&ue.truePeak<=-1:null;C={lufs:ue.lufs,truePeak:ue.truePeak,lra:ue.lra,target:{lufs:Yf.lufs,tp:Yf.tp},withinTarget:b,tool:"master_audio.sh",raw:{path:A.relative(l,h),sha256:xe,kept:!1}},SS(h,{force:!0})}let ne={...y,output:{path:A.relative(l,f),sha256:Oe(f)},...C?{audio:C}:{},finishedAt:new Date().toISOString()};return vl(A.join(p,"render.json"),JSON.stringify(ne,null,2)),{episode:t,renderId:d,...I,path:f,...C?{audio:C}:{}}},{episodeId:t});return{episode:t,renderId:d,jobId:w.id,status:w.status,poll:"Call job_status with jobId until succeeded or failed."}}async function DS(t){At(t,2,"Rendering the animatic"),await(await $l(t)).renderer.version();let{compiled:e,dir:r}=await NS(t);return LS(t,"animatic",2,{validated:A.join(r,ls),compiled:A.join(r,xl)},e)}function MS(t){let e=N(t),{profile:r}=br(e);if(r==="strict")return At(t,3,"The final render"),3;At(t,2,"The final render (quick film profile)");let n=tt(e)[2];if(n.state==="sent_back"||n.state==="rejected")throw new Error(`Refused: the human ${n.state==="sent_back"?"sent back":"rejected"} Gate 3 (animatic) for ${t}${n.note?` with notes: ${n.note}`:""}. Address the notes (shots_patch, render_animatic) and let the human decide Gate 3 again before the final render.`);return 2}async function FS(t){let e=MS(t);await(await $l(t)).renderer.version();let r=N(t),n=A.join(r,ls);if(!Re(n))throw new Error(`${t} has no ${ls}. Run shots_compile.`);let s=await Di(),o=Kf(),i=s.compile(ds(n),o.sfx,o.music,await ES()),a=A.join(r,"07-shots",`.final-compiled-${process.pid}.json`);vl(a,JSON.stringify(i,null,1));try{return await LS(t,"final",e,{validated:n,compiled:a},i)}finally{SS(a,{force:!0})}}async function qS(t,e){At(t,2,"Writing shots.json");let r=N(t),n;if(Re(A.join(r,Le)))n=Xf(r,t),Array.isArray(n.shots)||(n.shots=[]);else{let c=await Ne(Ee(r)),l=[A.join(r,"07-shots/shotplan.json"),A.join(r,`07-shots/plan.${c}.json`)].find(p=>Re(p)),d=l?{...ds(l)}:{};delete d.shots,!oe(c)&&d.style===void 0&&(d.style=c),n={...d,videoId:t,shots:[]}}let{episode:s,touched:o,removed:i}=gS(n,e);return{...await _o(t,s,"shots_patch"),touched:o,removed:i,shotCount:s.shots.length}}function YL(){let t=[];try{let r=AL(import.meta.resolve("@reelforge/dsl"));t.push(A.join(A.dirname(A.dirname(r)),"src","types.ts"))}catch{}let e=J();e&&t.push(A.join(e,"dsl","types.ts")),t.push(A.join(Se(),"dsl","src","types.ts"));for(let r of t)if(Re(r))return{path:"@reelforge/dsl/src/types.ts",text:Sl(r,"utf8")};return null}async function GS(t={}){let e=await Di(),r=YL(),n=t.styleId??(t.episodeId?Ee(N(t.episodeId)):"cutout"),s=await Ne(n),o={dslVersion:e.DSL_VERSION,styleId:s,types:r??{path:null,text:null,note:"The DSL type file is not part of this install."}};return oe(s)?{...o,library:yl(yo()),episodeHeader:"{dslVersion: 1, videoId: <episode id>, fps: 30, width: 1920, height: 1080, libraryVersion, shots: [...]}"}:{...o,style:await lf(s),episodeHeader:`{dslVersion: 1, videoId: <episode id>, style: "${s}", fps: 30, width: 1920, height: 1080, libraryVersion, shots: [{id, startAbs, dur, vo, kind: "beat", beat: {...}, look?: {...}}]}`}}var wn,Le,ls,xl,LL,DL,xS,ML,FL,qi,_S,Yf,Gi,WL,Ui=v(()=>{"use strict";mr();Ys();dS();Pe();er();wr();Hf();yS();pe();bf();no();ln();vS();wn=class extends Error{constructor(r,n){super(r);this.report=n}report},Le="07-shots/shots.json",ls="07-shots/shots.validated.json",xl="07-shots/shots.compiled.json",LL="07-shots/shots.origin.json",DL="07-shots/compile-stats.json",xS=200;ML=t=>`${t.level==="warn"?"WARN ":""}${t.shot} ${t.path}: ${t.msg}`,FL="differs from the episode style";qi={contentMean:{band:[2.2,2.4],label:"content shot mean (s)"},contentMedian:{band:[1.8,2.2],label:"content shot median (s), target ~2.0"},segmentsPerMin:{band:[29,31],label:"segments per minute"},transitionShare:{band:[.12,.2],label:"share of non-cut transitions, target ~16 %"},sfxOnsetsPerSec:{band:[2,3],label:"SFX onsets per second (incl. auto SFX)"}};_S=()=>Number(process.env.REELFORGE_MIN_FREE_GB??"1.5")*1024**3;Yf={lufs:-14,tp:-1.5},Gi=class extends Error{},WL=null});function US(t){let e=XL(t),r=QL(t),n=e??"N",s=/stale/.test(t);return`${/sent_back|sent back/.test(t)?`Address the human's notes and redo the stage; then the human decides Gate ${n} again`:s?`Gate ${n} went stale (a pinned file changed after approval): undo the change, or the human re-reviews and re-approves`:`The human reviews and approves Gate ${n}`} in their own terminal: ${yr()} approve <videoDir> --gate ${n} (add --skip-earlier when the episode's quick profile lets them skip an optional earlier gate). No tool can approve a gate. Call ${r?`gate_status {episodeId: "${r}"}`:"gate_status"} for the exact command, then next_step.`}function eD(t){let e=[];if(!t||typeof t!="object")return e;let r=Object.getPrototypeOf(t);for(;r&&e.length<8;){let s=r.constructor?.name;s&&s!=="Object"&&e.push(s),r=Object.getPrototypeOf(r)}let n=t.name;return typeof n=="string"&&!e.includes(n)&&e.push(n),e}function tm(t){let e=t instanceof Error?t.message:String(t??""),r=eD(t),n=VS.find(o=>o.classes?.some(i=>r.includes(i)));return n?n.fix(e):VS.find(o=>o.message?.test(e))?.fix(e)}function zS(t){let e=t instanceof Error?t.message:String(t),r=tm(t);return r&&!e.includes(r)?`${e}
|
|
77
|
+
How to fix: ${r}`:e}var XL,QL,VS,HS=v(()=>{"use strict";_i();pe();XL=t=>(/needs Gate (\d)/.exec(t)??/Gate (\d)/.exec(t))?.[1]??null,QL=t=>/ for ([A-Za-z0-9_][A-Za-z0-9._-]{0,119})[;: ]/.exec(t)?.[1]??null;VS=[{classes:["RendererNotInstalledError"],message:/Renderer not installed/i,fix:()=>"Build the headless renderer: `npm run build -w @reelforge/engine-resvg` in the Sundown Reel install (or set REELFORGE_RENDER_CLI to the reelforge-render CLI). Then run doctor and retry."},{classes:["DslUnavailableError"],message:/Shot DSL package .* could not be loaded|does not export (EpisodeSchema|semanticCheck)/i,fix:()=>"Build the Shot DSL to JavaScript: `npm run build -w @reelforge/dsl` in the Sundown Reel install, then run doctor and retry."},{classes:["LibraryUnavailableError"],message:/No engine library index|has no sets or casts/i,fix:()=>"Generate the engine library index: `npm run library -w @reelforge/engine` (writes library/LIBRARY.md), or set REELFORGE_LIBRARY_INDEX to a library-index.json. Then library_index."},{classes:["PipelineNotInstalledError"],message:/Pipeline not installed|No module named|python3?: (command )?not found|ENOENT.*python/i,fix:t=>J()?"This tool needs the Python pipeline, which the npm package does not include (use the full Sundown Reel install, or point REELFORGE_PIPELINE at its pipeline/ folder). It is not needed for rendering, package_make, vo_align or thumbnails.":(/REELFORGE_PIPELINE/.test(t)?"Point REELFORGE_PIPELINE at the Sundown Reel pipeline/ folder (it holds scripts/*.py). ":"")+"Set up the Python pipeline: `python3.12 -m venv pipeline/.venv && pipeline/.venv/bin/pip install -r pipeline/requirements.txt` (or point REELFORGE_PYTHON at a Python with numpy, opencv, PIL, scipy). doctor checks it."},{classes:["AssetsMissingError"],message:/geodata_install|browser_install/,fix:t=>/geodata_install/.test(t)?"Run geodata_install (background job, ~116 MB, once), poll job_status until it succeeds, then retry the render.":"Run browser_install (background job, ~100 MB, once) or install Google Chrome / set RF3D_CHROME, poll job_status, then retry the render."},{classes:["OperatorOnlyError"],message:/is operator-only/i,fix:()=>"That style is the private operator cartoon and is not in any plan. Pick a customer style with list_styles (see get_style_guide), and create the episode with that style."},{classes:["LicenseError"],message:/licen[cs]e key is configured|isn't connected yet|was disconnected|SUNDOWNREEL_LICENSE|subscription inactive|License server unreachable|licen[cs]e token/i,fix:t=>/on hold/i.test(t)?"The Sundown Reel plan is on hold (this machine is still connected). The user contacts hello@sundownreel.com to resolve it; then retry. Do not call sundownreel_connect for this.":/inactive/i.test(t)?"The Sundown Reel plan is not active (this machine is still connected). The user renews it from their dashboard at https://sundownreel.com/account; then retry. Do not call sundownreel_connect for this.":/was disconnected/i.test(t)?"This machine's connection was removed (disconnected from the dashboard) and has been forgotten here. Call sundownreel_connect (no reconnect flag needed), then have the user approve this machine in the browser page it opens. Then retry.":/isn't connected yet/i.test(t)?"Call sundownreel_connect, then have the user approve this machine in the browser page it opens. Then retry.":J()?"Call sundownreel_connect and have the user approve this machine in the browser page it opens, then retry (doctor shows the licence state).":"Set up the licence: run sundownreel-init (or set SUNDOWNREEL_LICENSE_KEY in the MCP server's env to the key from the Sundown Reel account page), restart the MCP server, then run doctor."},{classes:["StyleTierError"],message:/not (included|available) (in|on) (your|this) (plan|tier)|requires the \w+ (plan|tier)/i,fix:()=>"This style needs a higher plan. Pick a style your plan includes (list_styles shows which), or the user upgrades on the Sundown Reel site."},{classes:["StageOrderError"],message:/needs Gate \d/,fix:US},{message:/Refused: the human (sent back|rejected) Gate \d/,fix:t=>`${US(t)} Address the notes first (shots_patch \u2192 shots_compile \u2192 render_animatic).`},{message:/Unknown episode "|Invalid episode id/,fix:()=>"Call episode_list for the episode ids on this machine (or episode_create to start one), then retry with that id."},{classes:["RefusedWithReport"],message:/does not validate|invalid DSL|Nothing was (saved|written)|not saved/i,fix:()=>"Fix the listed issues: shots_validate {episodeId} for the full list (one line per issue with shot id and path), then shots_patch only the shots named, and validate again (max 3 loops)."},{message:/only [\d.]+ GB free|ENOSPC|no space left on device/i,fix:()=>"Free disk space (old 08-render/<run> folders you no longer need are the biggest), then retry. Renders need REELFORGE_MIN_FREE_GB (default 1.5 GB) free."},{message:/(spawn (ffmpeg|ffprobe)\b.*ENOENT)|((ffmpeg|ffprobe)\b.*(not found|not installed|no such file))/i,fix:()=>"Install ffmpeg (macOS: `brew install ffmpeg`; Debian/Ubuntu: `sudo apt install ffmpeg`) so ffmpeg and ffprobe are on the MCP server's PATH (or set FFMPEG_PATH), then run doctor."},{message:/words\.json is missing|Run vo_align first/i,fix:()=>"The voice-over has to be recorded and aligned first: vo_save {episodeId, file}, then vo_align and poll job_status."},{message:/changed after the render was queued|Queue it again/i,fix:()=>"An input changed while the job waited: queue the render again (render_animatic / render_final)."},{message:/stale/i,fix:()=>"A gate approval no longer matches the files (gate_status shows what changed). Undo the change, or the human re-approves with the command gate_status prints."}]});function Fr(t){if(t instanceof wn){let e=tm(t);return{isError:!0,content:[{type:"text",text:JSON.stringify({error:t.message,...t.report,...e?{fix:e}:{}})}]}}return{isError:!0,content:[{type:"text",text:zS(t)}]}}async function L(t,e){try{let r=await Ci(t);return bo(await e(r))}catch(r){return Fr(r)}}var vn=v(()=>{"use strict";Bf();Ui();HS();wo()});function BS(t){return t.replace(/[&<>"']/g,e=>{switch(e){case"&":return"&";case"<":return"<";case">":return">";case'"':return""";default:return"'"}})}function tD(t){let e='fill="none" stroke="#1c1915" stroke-width="8" stroke-linecap="round" stroke-linejoin="round"';return t==="pressure"?`<svg viewBox="0 0 360 360" aria-hidden="true">
|
|
78
|
+
<circle class="draw" cx="160" cy="190" r="92" ${e}/>
|
|
79
|
+
<path class="draw" d="M230 150h48l18 40-18 40h-48" ${e}/>
|
|
80
|
+
<path class="draw" d="M120 98h80" ${e}/>
|
|
81
|
+
<path class="draw" d="M150 70c20-28 48-28 68 0" ${e} stroke="#c4622d"/>
|
|
82
|
+
<path class="draw" d="M168 48c12-18 28-18 40 0" ${e} stroke="#c4622d"/>
|
|
83
|
+
</svg>`:t==="path"?`<svg viewBox="0 0 360 360" aria-hidden="true">
|
|
84
|
+
<path class="draw" d="M40 70h200" ${e}/>
|
|
85
|
+
<path class="draw" d="M40 290h200" ${e}/>
|
|
86
|
+
<path class="draw" d="M240 70 L300 160 L240 290" ${e}/>
|
|
87
|
+
<path class="draw" d="M300 150h28" ${e} stroke="#c4622d"/>
|
|
88
|
+
<circle class="draw" cx="336" cy="150" r="10" ${e} stroke="#c4622d"/>
|
|
89
|
+
</svg>`:t==="sound"?`<svg viewBox="0 0 360 360" aria-hidden="true">
|
|
90
|
+
<path class="draw" d="M70 150h46l54-48v156l-54-48H70z" ${e}/>
|
|
91
|
+
<path class="draw" d="M210 130c28 18 28 82 0 100" ${e} stroke="#c4622d"/>
|
|
92
|
+
<path class="draw" d="M240 100c48 32 48 128 0 160" ${e}/>
|
|
93
|
+
<path class="draw" d="M270 74c68 44 68 168 0 212" ${e}/>
|
|
94
|
+
</svg>`:t==="balance"?`<svg viewBox="0 0 360 360" aria-hidden="true">
|
|
95
|
+
<path class="draw" d="M180 250 L140 310 H220 Z" ${e}/>
|
|
96
|
+
<path class="draw" d="M48 168 H312" ${e}/>
|
|
97
|
+
<path class="draw" d="M48 168 l36 54 h-72z" ${e} stroke="#c4622d"/>
|
|
98
|
+
<path class="draw" d="M312 168 l36 54 h-72z" ${e} stroke="#c4622d"/>
|
|
99
|
+
<path class="draw" d="M180 168 V250" ${e}/>
|
|
100
|
+
</svg>`:`<svg viewBox="0 0 360 360" aria-hidden="true">
|
|
101
|
+
<circle class="draw" cx="180" cy="180" r="28" ${e} stroke="#c4622d"/>
|
|
102
|
+
<path class="draw" d="M180 80 V120" ${e}/>
|
|
103
|
+
<path class="draw" d="M180 240 V280" ${e}/>
|
|
104
|
+
<path class="draw" d="M80 180 H120" ${e}/>
|
|
105
|
+
<path class="draw" d="M240 180 H280" ${e}/>
|
|
106
|
+
<path class="draw" d="M110 110 l28 28" ${e}/>
|
|
107
|
+
<path class="draw" d="M222 222 l28 28" ${e}/>
|
|
108
|
+
<path class="draw" d="M250 110 l-28 28" ${e}/>
|
|
109
|
+
</svg>`}function JS(t){let e=t.width/1920,r=a=>`${Math.max(1,Math.round(a*e))}px`,n=String(t.index+1).padStart(2,"0"),s=String(t.total).padStart(2,"0"),o=t.text.length>90?58:76,i=t.durationSec.toFixed(2);return`<!doctype html>
|
|
110
|
+
<html lang="en">
|
|
111
|
+
<head>
|
|
112
|
+
<meta charset="utf-8"/>
|
|
113
|
+
<script src="./gsap.min.js"></script>
|
|
114
|
+
<style>
|
|
115
|
+
html, body { margin: 0; background: #f3ecdf; }
|
|
116
|
+
#root {
|
|
117
|
+
position: relative;
|
|
118
|
+
width: ${t.width}px;
|
|
119
|
+
height: ${t.height}px;
|
|
120
|
+
overflow: hidden;
|
|
121
|
+
background:
|
|
122
|
+
linear-gradient(180deg, rgba(196,98,45,0.08), transparent 28%),
|
|
123
|
+
repeating-linear-gradient(0deg, rgba(28,25,21,0.045) 0 1px, transparent 1px ${r(56)}),
|
|
124
|
+
repeating-linear-gradient(90deg, rgba(28,25,21,0.045) 0 1px, transparent 1px ${r(56)}),
|
|
125
|
+
#f3ecdf;
|
|
126
|
+
color: #1c1915;
|
|
127
|
+
font-family: "Liberation Sans", "DejaVu Sans", sans-serif;
|
|
128
|
+
}
|
|
129
|
+
.clip { position: absolute; inset: 0; }
|
|
130
|
+
.top, .bottom {
|
|
131
|
+
position: absolute;
|
|
132
|
+
left: ${r(72)};
|
|
133
|
+
right: ${r(72)};
|
|
134
|
+
display: flex;
|
|
135
|
+
justify-content: space-between;
|
|
136
|
+
letter-spacing: 0.16em;
|
|
137
|
+
text-transform: uppercase;
|
|
138
|
+
font-size: ${r(18)};
|
|
139
|
+
}
|
|
140
|
+
.top { top: ${r(48)}; }
|
|
141
|
+
.bottom { bottom: ${r(42)}; align-items: center; }
|
|
142
|
+
.rule {
|
|
143
|
+
height: ${r(3)};
|
|
144
|
+
background: #c4622d;
|
|
145
|
+
transform-origin: left center;
|
|
146
|
+
flex: 1;
|
|
147
|
+
margin-right: ${r(24)};
|
|
148
|
+
}
|
|
149
|
+
.stage {
|
|
150
|
+
position: absolute;
|
|
151
|
+
top: ${r(120)};
|
|
152
|
+
bottom: ${r(110)};
|
|
153
|
+
left: ${r(72)};
|
|
154
|
+
right: ${r(72)};
|
|
155
|
+
display: grid;
|
|
156
|
+
grid-template-columns: 1.05fr 0.95fr;
|
|
157
|
+
gap: ${r(48)};
|
|
158
|
+
align-items: center;
|
|
159
|
+
}
|
|
160
|
+
svg { width: 100%; height: ${r(520)}; }
|
|
161
|
+
.draw { stroke-dasharray: 900; stroke-dashoffset: 900; }
|
|
162
|
+
.copy { max-width: 16em; }
|
|
163
|
+
.kicker {
|
|
164
|
+
color: #8d3f16;
|
|
165
|
+
letter-spacing: 0.14em;
|
|
166
|
+
text-transform: uppercase;
|
|
167
|
+
font-size: ${r(18)};
|
|
168
|
+
margin-bottom: ${r(18)};
|
|
169
|
+
}
|
|
170
|
+
h1 {
|
|
171
|
+
font-family: "Liberation Serif", "DejaVu Serif", Georgia, serif;
|
|
172
|
+
font-weight: 500;
|
|
173
|
+
font-size: ${r(o)};
|
|
174
|
+
line-height: 1.18;
|
|
175
|
+
margin: 0;
|
|
176
|
+
}
|
|
177
|
+
.mark {
|
|
178
|
+
position: absolute;
|
|
179
|
+
top: ${r(40)};
|
|
180
|
+
right: ${r(72)};
|
|
181
|
+
width: ${r(36)};
|
|
182
|
+
height: ${r(36)};
|
|
183
|
+
border: ${r(2)} solid #1c1915;
|
|
184
|
+
border-radius: 50%;
|
|
185
|
+
}
|
|
186
|
+
</style>
|
|
187
|
+
</head>
|
|
188
|
+
<body>
|
|
189
|
+
<div id="root" data-composition-id="shot" data-start="0" data-duration="${i}" data-width="${t.width}" data-height="${t.height}">
|
|
190
|
+
<section id="card" class="clip" data-start="0" data-duration="${i}" data-track-index="1">
|
|
191
|
+
<div class="mark"></div>
|
|
192
|
+
<div class="top"><span>Chalkline</span><span>${n} / ${s}</span></div>
|
|
193
|
+
<div class="stage">
|
|
194
|
+
<div id="diagram">${tD(t.motif)}</div>
|
|
195
|
+
<div class="copy">
|
|
196
|
+
<div id="kicker" class="kicker">${BS(t.topic)}</div>
|
|
197
|
+
<h1 id="line">${BS(t.text)}</h1>
|
|
198
|
+
</div>
|
|
199
|
+
</div>
|
|
200
|
+
<div class="bottom"><div id="rule" class="rule"></div><span>one line, one shot</span></div>
|
|
201
|
+
</section>
|
|
202
|
+
</div>
|
|
203
|
+
<script>
|
|
204
|
+
const timeline = gsap.timeline({ paused: true });
|
|
205
|
+
timeline.fromTo("#rule", { scaleX: 0 }, { scaleX: 1, duration: 0.45, ease: "power2.out" }, 0);
|
|
206
|
+
timeline.fromTo("#diagram .draw", { strokeDashoffset: 900 }, { strokeDashoffset: 0, duration: 0.9, ease: "power2.inOut", stagger: 0.06 }, 0.05);
|
|
207
|
+
timeline.fromTo("#line", { y: 28, opacity: 0 }, { y: 0, opacity: 1, duration: 0.5, ease: "power3.out" }, 0.2);
|
|
208
|
+
timeline.fromTo("#kicker", { opacity: 0 }, { opacity: 1, duration: 0.35 }, 0.05);
|
|
209
|
+
window.__timelines = window.__timelines || {};
|
|
210
|
+
window.__timelines.shot = timeline;
|
|
211
|
+
</script>
|
|
212
|
+
</body>
|
|
213
|
+
</html>`}var WS=v(()=>{"use strict"});import{existsSync as KS,readdirSync as rD,readFileSync as nD}from"node:fs";import ZS from"node:path";function El(){let t=Hm();if(!KS(t))return[];let e=Ae();return rD(t).filter(r=>KS(ZS.join(t,r,"style.json"))).map(r=>JSON.parse(nD(ZS.join(t,r,"style.json"),"utf8"))).filter(r=>r.tier!=="operator"||e).sort((r,n)=>r.name.localeCompare(n.name))}function us(t){let e=El().find(r=>r.id===t);if(!e)throw new Error(`Unknown style "${t}". Call list_styles.`);return e}function oD(t){return sD[t]??null}function YS(t,e){let r=oD(t.id);if(!r)throw new Error(`No renderer is registered for ${t.id}.`);return r(e)}var sD,Rl=v(()=>{"use strict";Xt();WS();pe();sD={chalkline:JS}});import{existsSync as jl,mkdirSync as iD,readFileSync as rm,renameSync as aD,writeFileSync as cD}from"node:fs";import qr from"node:path";function QS(t,e){iD(qr.dirname(t),{recursive:!0});let r=`${t}.tmp-${process.pid}`;cD(r,e),aD(r,t)}async function ex(t={}){let e=[],r;try{e=(await io(t)).map(a=>({...a,profile:"episode"}))}catch(a){r=a instanceof Error?a.message:String(a)}let s=!t.family&&!t.renderer?El().filter(a=>a.profile!=="cartoon"&&a.tier!=="operator").filter(a=>(!t.aspect||a.aspect===t.aspect)&&(!t.readyOnly||a.status==="ready")).map(a=>({id:a.id,name:a.name,profile:"project",status:a.status,tier:a.tier,aspects:[a.aspect],pitch:a.summary,renderable:a.status==="ready",tools:"project_create {styleId} \u2192 script_save \u2192 plan_shots {projectId} \u2192 render_shot / assemble_export"})):[],o=await tx(null).catch(()=>null),i=o?await Yt(o):null;return{count:e.length+s.length,defaultStyle:i,styles:[...e,...s],...r?{registryError:r}:{},next:"get_style_guide {styleId} for one style's guide; episode_create {episodeId, title, style} starts an episode in it (project styles use project_create)."}}async function tx(t){if(Ae())return"cutout";let e=await Zt(),r=i=>i!=="max"||t?.styles==="all",n=e.DEFAULT_STYLE_ID?await Ne(e.DEFAULT_STYLE_ID):null;if(n&&!oe(n)){let i=await cn(n);if(i.status==="ready"&&r(i.tier))return i.id}let s=e.listStyles({}).filter(i=>!oe(i.id)),o=s.find(i=>i.status==="ready"&&r(i.tier))??s.find(i=>r(i.tier))??(t===null?s.find(i=>i.status==="ready"):void 0);if(!o)throw new Error(`No style is available on this plan yet (${s.map(i=>`${i.id}: ${i.status}/${i.tier}`).join(", ")}). Pass style explicitly (list_styles).`);return o.id}function dD(t){return t.split(/\r?\n\s*\r?\n/).map(e=>e.replace(/\s+/g," ").trim()).filter(Boolean).map((e,r)=>({id:`L${String(r+1).padStart(3,"0")}`,text:e}))}function uD(t){if(!jl(t))return{words:[],placeholder:!1};let e=Pl(t);return{words:(Array.isArray(e)?e:e.words??[]).filter(s=>typeof s.text=="string"&&typeof s.start=="number"&&typeof s.end=="number").map(s=>({text:String(s.text),start:Number(s.start),end:Number(s.end)})),placeholder:!Array.isArray(e)&&e.placeholder===!0}}function pD(t,e){let r=e.filter(a=>rx(a.text)),n=t.map(a=>lD(a.text).length),s=n.reduce((a,c)=>a+c,0);if(!r.length||!s)return null;let o=r.length/s;if(o<.85||o>1.15)return null;let i=0;return t.map((a,c)=>{let l=Math.min(r.length-1,Math.round(i*o));i+=n[c];let d=Math.max(l+1,Math.min(r.length,Math.round(i*o)));return{...a,t0:Number(r[l].start.toFixed(3)),t1:Number(r[d-1].end.toFixed(3))}})}function hD(t){let e=t.shots,r=e.map(i=>Number(i.dur??0)).sort((i,a)=>i-a),n=e[e.length-1],s={};for(let i of e){let a=i.beat?.kind??"(no beat)";s[a]=(s[a]??0)+1}let o=i=>Math.round(i*100)/100;return{shotCount:e.length,seconds:n?o(Number(n.startAbs??0)+Number(n.dur??0)):0,durations:r.length?{min:o(r[0]),median:o(r[Math.floor(r.length/2)]),max:o(r[r.length-1])}:null,beatKinds:s,firstShots:e.slice(0,3).map(i=>({id:i.id,startAbs:i.startAbs,dur:i.dur,vo:typeof i.vo=="string"&&i.vo.length>90?`${i.vo.slice(0,87)}\u2026`:i.vo,beat:i.beat}))}}async function nm(t){let e=t;try{e=await Yt(t)}catch{}let r=(await io({},{includeOperator:!0})).find(o=>o.id===e||o.id===t),n=!!r&&r.aspects.length>0&&r.aspects.every(o=>o==="9:16"),s=XS[e]??XS[t];if(!(!n&&!s))return n?{aspect:"9:16",width:1080,height:1920,fps:s??30}:{aspect:"16:9",width:1920,height:1080,fps:s??30}}function fD(t){try{let e=JSON.parse(rm(qr.join(t,"episode.json"),"utf8")).format;return e&&typeof e.fps=="number"&&typeof e.width=="number"&&typeof e.height=="number"?e:void 0}catch{return}}async function Ol(t,e={}){let r=N(t),n=await Ne(Ee(r)),s=await vr(e.styleId??n),o=qr.join(r,"04-script/script_vo.txt");if(!jl(o))throw new Error(`${t} has no 04-script/script_vo.txt yet. Write the script first: script_save {episodeId: "${t}", scriptVo}.`);let i=dD(rm(o,"utf8"));if(!i.length)throw new Error("04-script/script_vo.txt is empty. Write the VO text (paragraphs separated by blank lines).");let{words:a,placeholder:c}=uD(qr.join(r,"06-vo/words.json")),l=a.length?pD(i,a):null,d=fD(r)??await nm(s),p=await N_(s,l??i,a,{fps:e.fps??d?.fps??30,videoId:t,hypothetical:Ct(r)});if(d){let y=p;y.fps=e.fps??d.fps,y.width=d.width,y.height=d.height,y.format={...d,...e.fps?{fps:e.fps}:{}}}let f=`07-shots/plan.${s}.json`;QS(qr.join(r,f),`${JSON.stringify(p,null,1)}
|
|
214
|
+
`);let h=l?`aligned to 06-vo/words.json${c?" (placeholder words, not a recorded VO)":""}`:a.length?"estimated (~2.6 words/s): 06-vo/words.json does not match the script closely enough; re-run vo_align after editing the script":"estimated (~2.6 words/s): record the VO, vo_save + vo_align, then plan again for exact timing",m={episode:t,style:await Yt(s),registryStyleId:s,episodeStyle:await Yt(n),lines:i.length,timing:h,wrote:[f],...hD(p)};if(!e.save)return{...m,saved:!1,next:s===n?`plan_shots {episodeId: "${t}", save: true} writes this plan as shots.json (needs Gate 2), then get_style_guide + shots_patch per chapter.`:`This plan is in ${s} but the episode is ${n}: project_set_style {episodeId: "${t}", styleId: "${s}"} first to use it.`};if(s!==n)throw new Error(`Not saved: the plan is in ${s} but episode.json says ${n}. Switch first with project_set_style {episodeId: "${t}", styleId: "${s}"}, then plan_shots {episodeId: "${t}", save: true}. The plan is in ${f}.`);if(At(t,2,"Writing shots.json"),jl(qr.join(r,Il))&&!e.overwrite){let y=0;try{y=(Pl(qr.join(r,Il)).shots??[]).length}catch{}throw new Error(`Not saved: ${Il} already exists (${y} shots). The new plan is in ${f}: merge chapters with shots_patch, or pass overwrite: true (the old file stays in 07-shots/versions/).`)}let g=await _o(t,p,"plan_shots");return{...m,saved:!0,shots:{saved:g.saved,sha256:g.sha256,version:g.version,summary:g.validation.summary,lines:g.validation.lines.slice(0,20)},next:`get_style_guide {styleId: "${s}"}, then refine chapter by chapter with shots_patch and check with shots_validate; shots_compile for timing.`}}async function nx(t,e,r={}){let n=N(t),s=await vr(e),o=await cn(s).catch(()=>null),i=qr.join(n,"episode.json"),a=Ai(n);if(!a)throw new Error(`${t} has no readable episode.json. Recreate it with episode_create or fix the JSON by hand.`);let c=Ee(n),l=await Ne(c),d=tt(n)[1],p=qr.join(n,Il),f=jl(p),h=[],m=null,g=null;if(f)try{g=await Ne(Pl(p).style??"cutout")}catch{g=null}if(r.restyle&&f&&g!==s){try{At(t,2,"Restyling shots.json")}catch(k){return{episode:t,from:await Yt(l),to:await Yt(s),changed:!1,restyled:!1,refused:k instanceof Error?k.message:String(k),next:`Writing shots needs Gate 2 approved. Without restyle, project_set_style {episodeId: "${t}", styleId: "${s}"} switches episode.json now; restyle the shots (restyle: true) or re-plan them (plan_shots {episodeId: "${t}", save: true, overwrite: true}) after the human approves Gate 2.`}}let w=Pl(p),S=await A_(w,s),$=await _o(t,S,"project_set_style (restyle)",{expectStyle:s});m={saved:$.saved,sha256:$.sha256,version:$.version,validation:$.validation.summary}}let y=a.style!==s;if(y){let w=br(n).profile,S={...a,style:s,gateProfile:a.gateProfile??w};if(QS(i,`${JSON.stringify(S,null,2)}
|
|
215
|
+
`),d.state==="approved"){let $=tt(n)[1].state;h.push($==="stale"?`Gate 2 pins episode.json, so it is now stale: the human must re-approve Gate 2 (sundownreel-gate approve ${n} --gate 2) before renders or further shot writes.`:`The style changed after the human approved Gate 2 (approved in ${l}). Tell the user: they approved the script and facts for another style, and should re-approve Gate 2 (sundownreel-gate approve ${n} --gate 2) if they want the record to show it.`)}}return f&&!m&&g!==s&&h.push(`shots.json is still in ${g??"an unreadable style"}: shots_validate refuses it until you restyle (project_set_style {episodeId: "${t}", styleId: "${s}", restyle: true}, needs Gate 2) or re-plan (plan_shots {episodeId: "${t}", save: true, overwrite: true}).`),o&&o.status!=="ready"&&h.push(`${o.name} is planned: plan and write now; renders are refused until its renderer (${o.renderer}) ships.`),{episode:t,from:await Yt(l),to:await Yt(s),registryStyleId:s,changed:y,restyled:m??!1,gateProfile:br(n).profile,...h.length?{warnings:h}:{},next:f?`shots_validate {episodeId: "${t}"} to check the shots in ${s}.`:`get_style_guide {styleId: "${s}"}; after Gate 2, plan_shots {episodeId: "${t}", save: true}.`}}async function sx(t,e){return t?vr(t):tx(e)}var Il,Pl,rx,lD,XS,ox,sm=v(()=>{"use strict";Pe();er();Xt();wr();Ui();Rl();ln();Il="07-shots/shots.json";Pl=t=>JSON.parse(rm(t,"utf8"));rx=t=>t.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,""),lD=t=>t.split(/\s+/).map(rx).filter(Boolean);XS={blockfolk:24};ox=(t,e)=>e??Kh(t)});import{readFileSync as ix,existsSync as ax}from"node:fs";import cx from"node:path";async function lx(t){try{return fo(),bo(await t())}catch(e){return Fr(e)}}function px(t){let e=lx,r=t.registerTool.bind(t),n=new Set(["shotplan_make"]),s=(o,i,a)=>{J()&&n.has(o)||r(o,i,a)};s("episode_list",{title:"List cartoon episodes",description:je+"List episodes (folders under <studio>/videos/) with style, gateProfile, per-gate required/optional, gate states, a compact next step and blocker count. A broken folder gives an error row with a fix; the private cartoon episodes are id-only for non-operators. Read only. Start with next_step if unsure.",inputSchema:{}},async()=>L({},o=>C0({operator:o.operator}))),s("episode_status",{title:"Episode status",description:je+"One episode, every style: stages, style, gateProfile (quick: Gates 2+4 required, 1+3 optional; strict: all four), each gate's state (none/approved/stale/sent_back/rejected), requirement and the exact human command while not approved, next (same object as next_step), blockers and stale items as [{problem, fix}], activeJobs, gateWarnings. Gate states come only from records in _gates/gateN.jsonl signed by sundownreel-gate on this machine; anything else is ignored and listed. Read only. Only the human decides gates (`sundownreel-gate approve <videoDir> --gate N`).",inputSchema:{episodeId:De}},async o=>L({episodeId:o.episodeId},()=>A0(o.episodeId))),s("library_index",{title:"Engine library index",description:je+"Every id the Shot DSL may use: sets with camera presets, marks and screens; cast; poses; expressions; props; in-world text kinds; chart kinds; transitions; grades; licensed sfx and music ids. Anything else is a library request.",inputSchema:{}},async()=>lx(()=>yl(yo()))),s("shots_context",{title:"Shot DSL writer context",description:je+"Everything the Shot DSL writer needs for one episode: for the cartoon the versioned writer prompt and engine library; for other styles the style guide summary and the plan from plan_shots; plus the facts (which may go on screen), the shot plan skeleton and which input files exist. Read only. Call get_style_guide first for non-cartoon styles.",inputSchema:{episodeId:De}},async o=>L({episodeId:o.episodeId},()=>OS(o.episodeId))),s("shots_get",{title:"Get shots",description:je+"Return the saved 07-shots/shots.json and its sha256: whole, only the listed shot ids, or a chapter range like S010..S040 (keeps results small on long episodes). Read only.",inputSchema:{episodeId:De,shotIds:u.array(dx).max(200).optional(),range:u.string().regex(/^S\d{3}[a-z]?\.\.S\d{3}[a-z]?$/,"a range like S010..S040").optional()}},async o=>L({episodeId:o.episodeId},()=>PS(o.episodeId,o.shotIds,o.range))),s("shots_save",{title:"Save shots",description:je+"Replace the whole 07-shots/shots.json (snapshotted to 07-shots/versions/). It is validated first: an invalid DSL is refused with the issue list and nothing is written. Refused unless Gate 2 (script + facts) is approved (signed by sundownreel-gate) and fresh. For chapter-sized edits use shots_patch.",inputSchema:{episodeId:De,shots:om}},async o=>L({episodeId:o.episodeId},()=>jS(o.episodeId,o.shots))),s("shots_validate",{title:"Validate shots",description:je+`Run the Shot DSL schema and the library + fact checks on the saved shots.json, or on a draft passed in "shots" (not saved). Returns one line per issue, e.g. "S041 actors[1].bubble: bubble \u2264 6 words"; warnings start with WARN. Every on-screen number needs a factId whose status is verified or computed (scenario only in episodes flagged hypothetical). UI ordinals that number the video's own sections ("STEP 3 / 12", "EXHIBIT 01", "Chapter 2") need no fact. noFacts is allowed only for internal test episodes (ids starting with _ or lab).`,inputSchema:{episodeId:De,shots:om.optional(),noFacts:u.boolean().optional(),maxLines:u.number().int().min(1).max(2e3).optional()}},async o=>L({episodeId:o.episodeId},()=>Qf(o.episodeId,{shots:o.shots,noFacts:o.noFacts,maxLines:o.maxLines}))),s("shots_compile",{title:"Compile shots",description:je+"Validate, then compile the Shot DSL into the frame-exact timeline with auto SFX. Writes shots.validated.json and shots.compiled.json for the saved file. Returns timing stats against the style targets: content shot mean/median, segments per minute, transition share, SFX density, and SFX ids without licensed files.",inputSchema:{episodeId:De,shots:om.optional(),noFacts:u.boolean().optional(),maxLines:u.number().int().min(1).max(2e3).optional()}},async o=>L({episodeId:o.episodeId},()=>kl(o.episodeId,{shots:o.shots,noFacts:o.noFacts,maxLines:o.maxLines}))),s("render_animatic",{title:"Render animatic",description:je+"Background job: render the 540p animatic into 08-render/<renderId>/ with render.json, using the renderer for the episode's style (resvg-2d, engine-3d or engine-geo; a planned style is refused with what to do). Needs Gate 2 approved (signed by sundownreel-gate; re-checked when the job starts) and a valid shots.json. Inputs are copied into the run folder when queued. Poll job_status. In the strict profile the human reviews it at Gate 3; in quick film Gate 3 is optional.",inputSchema:{episodeId:De}},async o=>L({episodeId:o.episodeId},()=>DS(o.episodeId))),s("facts_get",{title:"Get facts",description:je+"Return the fact table (03-research/facts.csv) and the fact-check log. Read only.",inputSchema:{episodeId:De}},async o=>L({episodeId:o.episodeId},()=>B0(o.episodeId))),s("facts_upsert",{title:"Add or update facts (researcher)",description:je+"Researcher: add or update rows of facts.csv by id. Every written row gets status unverified, an empty checker, and researcher = actor. Status changes only through factcheck_record by a different session.",inputSchema:{episodeId:De,actor:ux,facts:u.array(mD).min(1).max(200)}},async o=>L({episodeId:o.episodeId},()=>J0(o.episodeId,o.actor,o.facts))),s("factcheck_record",{title:"Record fact-check (independent checker)",description:je+"Fact-checker: set verified / computed / disputed / scenario on facts after checking each against its source. actor must differ from the row's researcher (decision #13); it is recorded as checker and logged to factcheck.md. scenario numbers go on screen only in episodes flagged hypothetical.",inputSchema:{episodeId:De,actor:ux,results:u.array(u.object({id:u.string(),status:u.enum(["verified","computed","disputed","scenario"]),note:u.string().max(2e3).optional()})).min(1).max(200)}},async o=>L({episodeId:o.episodeId},()=>W0(o.episodeId,o.actor,o.results))),s("script_get",{title:"Get episode script",description:je+"Return 04-script/script.md, script_vo.txt, meta.json and the outline. Read only. (Chalkline projects use script_scaffold.)",inputSchema:{episodeId:De}},async o=>L({episodeId:o.episodeId},()=>Z0(o.episodeId))),s("vo_align",{title:"Align voice-over",description:je+`Background job: align the human's 06-vo/vo.wav to script_vo.txt \u2192 06-vo/words.json with ElevenLabs forced alignment. With ELEVENLABS_API_KEY configured it is a live (paid) alignment and needs Gate 2. Without a key it spends nothing: it writes ESTIMATED word timing ("estimated": true) so the episode can continue, with a warning that shots and captions may drift; an existing real (non-estimated) words.json that is newer than vo.wav is kept, not overwritten (mode "kept"). Poll job_status.`,inputSchema:{episodeId:De,dryRun:u.boolean().optional().describe("Print the exact ElevenLabs request (key redacted) and send nothing.")}},async o=>L({episodeId:o.episodeId},()=>Q0(o.episodeId,o.dryRun?{allowSpend:!1}:{}))),s("shotplan_make",{title:"Make shot plan",description:je+"Cartoon (cutout) episodes only: build the timed shot-plan skeleton 07-shots/shotplan.json (ids, startAbs, dur, VO) from 06-vo/words.json with the Python pipeline and return its pacing stats. With Gate 2 approved and no shots.json yet it also saves that skeleton as shots.json (placeholder set), so you then write it chapter by chapter with shots_context + shots_patch. Every other style uses plan_shots {episodeId, save: true}.",inputSchema:{episodeId:De,fps:u.number().int().min(24).max(30).optional(),libraryVersion:u.string().max(40).optional()}},async o=>L({episodeId:o.episodeId},async()=>{let i=await eS(o.episodeId,{fps:o.fps,libraryVersion:o.libraryVersion}),a;try{a={saved:!0,via:"plan_shots (style registry plan)",shotCount:(await Ol(o.episodeId,{save:!0})).shotCount}}catch(c){let l=await IS(o.episodeId);a={...l,...l.saved?{via:"shotplan"}:{reason:`${c instanceof Error?c.message:String(c)} | shotplan: ${l.reason}`}}}return{...i,shotsSkeleton:a,...a.saved?{wrote:[...i.wrote,"07-shots/shots.json"]}:{}}})),s("shots_patch",{title:"Patch shots (chapter-sized)",description:je+"Edit shots.json a chapter at a time: header (top-level fields, used to start the file), remove (shot ids), upsert (whole shots by id; new ids inserted in time order), ops (JSON Patch add/replace/remove on a shot, a range S010..S020, or EPISODE). The result is validated as a whole: if invalid, the issue list comes back and nothing is written. Needs Gate 2 (signed by sundownreel-gate).",inputSchema:{episodeId:De,header:u.record(u.unknown()).optional(),remove:u.array(dx).max(400).optional(),upsert:u.array(u.record(u.unknown())).max(200).optional(),ops:u.array(gD).max(500).optional()}},async o=>L({episodeId:o.episodeId},()=>qS(o.episodeId,{header:o.header,remove:o.remove,upsert:o.upsert,ops:o.ops}))),s("shots_types",{title:"Shot DSL reference",description:je+"The Shot DSL v1 TypeScript types plus what you may use for this episode's style: for the cartoon (operator) the full engine library; for other styles the style guide summary (prompt guide, kinds menu, look schema). Pass episodeId (or styleId). Read only.",inputSchema:{episodeId:De.optional(),styleId:u.string().max(60).optional()}},async o=>{let i=o.episodeId,a=o.styleId;return!i&&!a&&!Ae()?Fr(new Error("Pass episodeId (or styleId). Call list_styles or episode_list first.")):L({episodeId:i,styleId:a},()=>GS({episodeId:i,styleId:a}))}),s("render_final",{title:"Render final",description:je+"Background job: render the 1080p final through the episode style's renderer into 08-render/<renderId>/, then master the audio (pipeline master_audio.sh: -14 LUFS, -1.5 dBTP, 48 kHz AAC) to final.mp4 and record the measured loudness in render.json. Gate: strict profile \u2192 Gate 3 approved (renders exactly the shots.validated.json it pinned); quick film \u2192 Gate 2 approved and Gate 3 not sent back/rejected. Re-checked when the job starts. Poll job_status. Next: package_make, thumbnail_make, then qa_run. No upload.",inputSchema:{episodeId:De}},async o=>L({episodeId:o.episodeId},()=>FS(o.episodeId))),s("qa_run",{title:"Run QA",description:je+"Background job: automated QA (loudness, timing, on-screen text vs facts, OCR, package metadata, ...) on the newest final (else animatic) or the given video path inside the episode \u2192 09-qa/qa.json + qa.md. Run it on the final AFTER package_make (QA reads the package). Poll job_status; fix every FAIL, re-render, re-run.",inputSchema:{episodeId:De,video:u.string().max(300).optional()}},async o=>L({episodeId:o.episodeId},()=>tS(o.episodeId,o.video))),s("package_make",{title:"Make package",description:je+"Build 12-package/description.md + meta.json (hook, chapters, sources, credits, disclosure) from the script meta, VO words and facts, after render_final. Then thumbnail_make, then qa_run. The human reviews the package at Gate 4 (package_get shows it in chat) and uploads by hand.",inputSchema:{episodeId:De}},async o=>L({episodeId:o.episodeId},()=>rS(o.episodeId))),t.registerPrompt("style-shot-writer",{title:"Style shot writer",description:"How to write Shot DSL for any style from its guide (get_style_guide), chapter by chapter, with the review_shots vision loop (prompts/style-shot-writer.md).",argsSchema:{episodeId:u.string().optional()}},({episodeId:o})=>{let i=cx.join(rs(),"style-shot-writer.md"),a=ax(i)?ix(i,"utf8"):"prompts/style-shot-writer.md is missing from this install.";return{messages:[{role:"user",content:{type:"text",text:(o?`Episode: ${o}. Start with next_step, get_style_guide and shots_context.
|
|
216
|
+
|
|
217
|
+
`:"")+a}}]}}),t.registerPrompt("shot-dsl-writer",{title:"Shot DSL writer",description:"The versioned SHOT-DSL WRITER prompt for the cartoon profile (prompts/shot-dsl-writer.md).",argsSchema:{episodeId:u.string().optional()}},({episodeId:o})=>{let i=cx.join(rs(),"shot-dsl-writer.md"),a=ax(i)?ix(i,"utf8"):"prompts/shot-dsl-writer.md is missing from this install.";return{messages:[{role:"user",content:{type:"text",text:(o?`Episode: ${o}. Start with shots_context and shots_types, write chapter by chapter with shots_patch, check with shots_validate (max 3 loops), then look with review_shots.
|
|
218
|
+
|
|
219
|
+
`:"")+a}}]}})}var je,De,dx,om,ux,mD,gD,im=v(()=>{"use strict";pe();Ft();er();Pe();hl();Hf();Xt();wo();vn();Ui();sm();je="Episode profile (every style; videos/<id>/ under the studio home; the private cartoon style is operator-only). ",De=u.string().regex(/^[A-Za-z0-9_][A-Za-z0-9._-]{0,119}$/,"an episode folder name under videos/, e.g. 2026-11-28-robot-dollar-hour").describe("Episode folder name under videos/ (from episode_list)."),dx=u.string().regex(/^S\d{3}[a-z]?$/,"a shot id like S001 or S014a"),om=u.record(u.unknown()).describe("One Shot DSL v1 Episode object: {dslVersion: 1, videoId, fps: 30, width: 1920, height: 1080, libraryVersion, shots: [...]}."),ux=u.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{2,79}$/,"an actor id is 3-80 chars: a letter or digit first, then letters, digits, '.', '_', ':' or '-' (no spaces or <>), e.g. researcher-a1 or checker-b2").describe("Your session id for this role, 3-80 chars matching ^[A-Za-z0-9][A-Za-z0-9._:-]{2,79}$, e.g. researcher-a1 or checker-b2. The researcher and the fact-checker must differ."),mD=u.object({id:u.string(),claim:u.string().max(1e3),value:u.string().max(200).optional(),unit:u.string().max(100).optional(),on_screen:u.string().max(200).optional(),as_of:u.string().max(60).optional(),source_name:u.string().max(300).optional(),source_date:u.string().max(60).optional(),url:u.string().max(1e3).optional(),quote:u.string().max(2e3).optional(),notes:u.string().max(2e3).optional()}),gD=u.object({target:u.string().describe('"S014", a range "S010..S020", or "EPISODE" for top-level fields'),op:u.enum(["add","replace","remove"]),path:u.string().describe("JSON pointer inside the shot, e.g. /camera/preset"),value:u.unknown().optional()})});function Al(t){let e=4*t.D+4*t.O+4*t.X+3*t.L+2*t.G;return Math.round((e*100/85-4*t.R)*10)/10}function Ll(t,e){for(let r of Gr){let n=t[r];if(typeof n!="number"||!Number.isInteger(n)||n<0||n>5)throw new Error(`${e}: ${r} must be an integer 0\u20135 (rubric anchors at 1, 3, 5).`)}}function fx(t,e=lm){let r=t.map((d,p)=>p).sort((d,p)=>t[p].score-t[d].score||d-p),n=new Map,s=d=>{let p=t[d];return p.R>=5?cm:p.R>am?`R=${p.R} > ${am}`:(p.anchors??[]).some(f=>f.trim())?null:"no anchor (rule a)"},o=d=>(t[d].cluster??"").trim().toLowerCase(),i=(d,p)=>p?d.filter(f=>o(f)===p).length:0,a=[];for(let d of r){let p=s(d);if(p){n.set(d,p);continue}if(a.length>=e){n.set(d,"slate full");continue}if(i(a,o(d))>=Tl){n.set(d,`cluster "${t[d].cluster}" already has ${Tl} (rule c)`);continue}a.push(d)}let c=Math.floor(a.length*.3),l=d=>dm(t[d].kind);for(;a.filter(l).length<c;){let d=[...a].reverse().find(h=>!l(h));if(d===void 0)break;let p=a.filter(h=>h!==d),f=r.find(h=>!a.includes(h)&&l(h)&&!s(h)&&i(p,o(h))<Tl);if(f===void 0)break;a.splice(a.indexOf(d),1,f),n.delete(f),n.set(d,"swapped out for a news-pegged idea (rule d)")}return a.sort((d,p)=>t[p].score-t[d].score||d-p),{picks:a,why:n}}var Gr,Nl,ps,hx,cm,Cl,lm,am,Tl,Dl,dm,Ml,mx,gx,Fl=v(()=>{"use strict";Gr=["D","O","X","L","G","R"],Nl=[{axis:"D",name:"Demand",question:"How many people search for the core keyword each month?",weight:4,anchors:{5:"1M+ monthly searches",3:"about 100K\u2013300K",1:"under 20K, or no data"},evidence:"Keyword volume from a keyword tool if you have one (cite it with the date); otherwise score 2\u20133 and say it is an estimate."},{axis:"O",name:"Outlier proof",question:"Has a comparable video broken out far beyond its channel's size?",weight:4,anchors:{5:"a 100\xD7+ breakout, or 1M+ views on a channel under 100K subscribers",3:"10\u201330\xD7 breakouts, or a few comparable videos past 100K views",1:"no comparable videos"},evidence:"Name the comparable video (title, views, breakout multiple, channel size) and where you saw it."},{axis:"X",name:"Outlandishness",question:"Can a 12-year-old picture it instantly, and does it make you say 'wait, what?'",weight:4,anchors:{5:"a literal, absurd image (a robot paid $1 an hour; everyone's money shrinks 1,000\xD7)",3:"provocative but abstract",1:"plain news"},evidence:"Editorial judgement: describe the one image the thumbnail would show."},{axis:"L",name:"Longevity",question:"Will people still search for it in a year?",weight:3,anchors:{5:"evergreen",3:"relevant for months",1:"decays within days or weeks"},evidence:"Editorial judgement; news pegs score low here but still help a slate (see the slate rule)."},{axis:"G",name:"Gap",question:"How little competition is there for this angle?",weight:2,anchors:{5:"nobody covers it with real numbers or in this visual style",3:"some coverage",1:"saturated: many near-identical videos"},evidence:"Search the platform for the premise and count close copies."},{axis:"R",name:"Fact / legal risk (subtracted)",question:"How risky is it to say on camera?",weight:-4,anchors:{5:"defamation or a political minefield, or the key numbers cannot be verified: we don't make it",3:"names real companies or touches politics, but sourced",1:"pure hypothetical or arithmetic"},evidence:"Count the claims about named people or companies; each needs a primary source or two major outlets."}],ps="score = round((4\xB7D + 4\xB7O + 4\xB7X + 3\xB7L + 2\xB7G) \xF7 85 \xD7 100 \u2212 4\xB7R, 1)",hx=["Max 100 (all 5s with R = 0). Clicks first (demand, outlier proof, absurdity), then lasting value (longevity), then gap.","Each risk level costs 4 points. Hard gate: R = 5 means the idea is rejected, whatever it scores.","D and O should rest on cited data; X, L, G and R are editorial estimates. Rescore when the data changes."];cm="REJECT (R=5)",Cl=t=>t.R>=5;lm=10,am=3,Tl=3,Dl=["(a) The idea cites at least one anchor: a real, checkable source its numbers rest on (URL, filing, dataset, or a fact id). Sourced numbers are the moat against pure-math what-if channels.",`(b) Fact risk R \u2264 ${am} (R = 5 is rejected outright; R = 4 stays in the bank but not on the slate).`,`(c) At most ${Tl} ideas per cluster (topic family), so the first videos don't all feel the same.`,"(d) At least 30% of the slate is news-pegged (3 of 10): news decays, evergreen waits. If short, the lowest-scoring evergreen pick is swapped for the best eligible news-pegged idea.","Production order is not score order: news-pegged slate picks ship first (their interest decays in weeks); evergreen picks wait without losing value."],dm=t=>/news|peg|decay/i.test(t??"");Ml=["Give 3 title variants per idea. Lead with 'What If\u2026' for evergreen ideas, or with a hard number for a news peg.","60 characters or fewer where possible; at most one word in ALL CAPS.","The video must pay off the title and thumbnail. A question mark does not excuse a false or unsupported claim.","Every number in a title or thumbnail needs a fact the research can verify (or compute, with the formula shown).","Thumbnail words: 2\u20134 words, one emotion, one absurd object. No real person's face, no fake news logo."],mx=["No real-person likeness or caricature. Real people appear only as sourced quotes on cards or as silhouettes with a name card; prefer companies and mechanisms over individuals.","Never say or imply a real person or company did something the sources don't say. Allegation stories are process-only (who reported what, when).","No third-party IP: no brands as characters, no game or film characters, no superheroes, no copied formats, scripts or thumbnails. Logos only small, for identification.","Every on-screen number needs a fact id with a primary source (filing, official release, the organisation's own page) or two independent major outlets, or an arithmetic row with its formula.","Social posts and AI summaries are leads, not sources. Check the original report date (recycled stories) and the exact wording (misquotes).","Hypotheticals are labelled as hypotheticals. Invented inputs ('if a robot cost $1 an hour') are scenario numbers: allowed on screen only when the episode is flagged hypothetical, and the script frames them as 'imagine/if'.","No buy/sell advice, price targets, 'guaranteed', get-rich framing, fake urgency or rage bait. Explain mechanisms; 'what to watch', never 'what to buy'.","Real-time numbers (prices, net worth, odds) get an as-of date and are re-read on script-lock day."],gx=["evergreen","news (decays in weeks)","evergreen + news peg"]});import{existsSync as Vi,mkdirSync as yD,readdirSync as yx,readFileSync as vx,renameSync as bD,statSync as wD,writeFileSync as vD}from"node:fs";import Ur from"node:path";function hs(){return Ur.join(_t(),"ideas")}function bx(t,e){yD(Ur.dirname(t),{recursive:!0});let r=`${t}.tmp-${process.pid}`;vD(r,e),bD(r,t)}function um(t=new Date){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function ql(t){let e=t.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9]+/g," ").split(" ").filter(n=>n&&!_D.has(n)),r="";for(let n of e.slice(0,5)){let s=r?`${r}-${n}`:n;if(s.length>40)break;r=s}return r||"idea"}function Gl(t,e=um()){let r=`${e}-${ql(t)}`,n=r;for(let s=2;Vi(Ur.join(Wt(),n));s++)n=`${r}-${s}`;return n}function wx(t){let e=(t??[]).map(r=>r.replace(/\s+/g," ").trim()).filter(Boolean);return e.length?e:void 0}function SD(t){t.forEach((o,i)=>{if(!o.title?.trim())throw new Error(`ideas[${i}]: title is empty.`);if(!o.premise?.trim())throw new Error(`ideas[${i}] "${o.title}": premise is empty (one sentence: the absurd image + the real number behind it).`);Ll(o,`ideas[${i}] "${o.title}"`)});let e=t.map(o=>({...o,title:o.title.trim(),premise:o.premise.trim(),anchors:wx(o.anchors),titleVariants:wx(o.titleVariants),score:Al(o),gate:Cl(o)?cm:"",news:dm(o.kind)})),{picks:r,why:n}=fx(e);return e.map((o,i)=>i).sort((o,i)=>e[i].score-e[o].score||o-i).map((o,i)=>{let a=r.indexOf(o);return{...e[o],rank:i+1,slate:a>=0,...a>=0?{slot:a+1}:{excluded:n.get(o)??"not picked"}}})}function xD(t){let e=t;for(let r=2;Vi(Ur.join(hs(),`${e}.json`));r++)e=`${t}-${r}`;return e}function kD(t){let e=["Rank","Slot","Idea","Kind",...Gr,"Score","Gate / why not"],r=t.ideas.map(s=>[s.rank,s.slot??"",s.title.replace(/\|/g,"/"),s.kind??"",...Gr.map(o=>s[o]),s.score.toFixed(1),s.gate||s.excluded||""].join(" | ")),n=t.ideas.filter(s=>s.slate).map(s=>[`### Slot ${s.slot}: ${s.title} (${s.score.toFixed(1)})`,`- Premise: ${s.premise}`,s.titleVariants?.length?`- Title variants: ${s.titleVariants.join(" \xB7 ")}`:"",s.hook?`- Hook: ${s.hook}`:"",s.thumbnail?`- Thumbnail: ${s.thumbnail}`:"",s.anchors?.length?`- Anchors: ${s.anchors.join(" \xB7 ")}`:"",s.styleId?`- Style: ${s.styleId}`:""].filter(Boolean).join(`
|
|
220
|
+
`));return[`# Idea slate: ${t.name}`,"",`Saved ${t.savedAt}. ${ps}. R = 5 is rejected.`,"",`| ${e.join(" | ")} |`,`|${e.map(()=>"---").join("|")}|`,...r.map(s=>`| ${s} |`),"","## Slate rule",...Dl.map(s=>`- ${s}`),"","## The slate","",...n.flatMap(s=>[s,""])].join(`
|
|
221
|
+
`)}function Sx(t,e={}){if(e.slateName!==void 0&&!_x.test(e.slateName))throw new Error(`slateName "${e.slateName}" must be letters, digits, . _ - (max 80), e.g. ${um()}-ai-jobs.`);let r=SD(t),n=e.slateName??xD(`${um()}-slate`),s={schema:1,name:n,savedAt:new Date().toISOString(),formula:ps,...e.styleId?{styleId:e.styleId}:{},ideas:r},o=Ur.join(hs(),`${n}.json`),i=Ur.join(hs(),`${n}.md`);return bx(o,`${JSON.stringify(s,null,1)}
|
|
222
|
+
`),bx(i,`${kD(s)}
|
|
223
|
+
`),{slate:s,name:n,files:[o,i]}}function Ul(t){if(!_x.test(t))return null;let e=Ur.join(hs(),`${t}.json`);if(!Vi(e))return null;try{let r=JSON.parse(vx(e,"utf8"));return Array.isArray(r.ideas)?r:null}catch{return null}}function xx(t){let e=/^([A-Za-z0-9][A-Za-z0-9._-]{0,79})#(\d{1,3})$/.exec(t.trim());if(!e)return null;let r=Ul(e[1]),n=r?.ideas.find(s=>s.rank===Number(e[2]));return r&&n?{slate:r.name,idea:n}:null}function kx(t=60){let e=[],r=hs();if(Vi(r)){let o=yx(r).filter(a=>a.endsWith(".json")).map(a=>({f:a,t:wD(Ur.join(r,a)).mtimeMs})).sort((a,c)=>c.t-a.t),i=0;for(let{f:a}of o){if(i>=t)break;let c=Ul(a.replace(/\.json$/,""));if(!c)continue;let l=c.ideas.map(d=>d.title).slice(0,t-i);i+=l.length,e.push({name:c.name,titles:l})}}let n=[],s=Wt();if(Vi(s)){for(let o of yx(s))if(!(o.startsWith("_")||o.toLowerCase().startsWith("lab")))try{let i=JSON.parse(vx(Ur.join(s,o,"episode.json"),"utf8"));typeof i.title=="string"&&i.title.trim()&&n.push(i.title.trim())}catch{}}return{slates:e,episodes:n}}var _x,_D,zi=v(()=>{"use strict";Pe();Fl();_x=/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/;_D=new Set(["what","if","a","an","the","of","for","to","and","or","in","on","at","is","are","was","were","you","your","every","just","it","its","be","by","with","got"])});import{existsSync as $D,readdirSync as Ix,readFileSync as ED,statSync as jx}from"node:fs";import hm from"node:path";function RD(){let t=Wt();return $D(t)?Ix(t).filter(e=>{if(e.startsWith("."))return!1;try{return jx(hm.join(t,e)).isDirectory()}catch{return!1}}).sort():[]}function ID(t){let e=hs(),r=[];try{r=Ix(e).filter(l=>l.endsWith(".json")).map(l=>({name:l.replace(/\.json$/,""),t:jx(hm.join(e,l)).mtimeMs})).sort((l,d)=>d.t-l.t)}catch{return null}let n=r.map(l=>Ul(l.name)).find(l=>l!==null);if(!n)return null;let s=new Set;for(let l of t)try{let d=JSON.parse(ED(hm.join(Wt(),l,"episode.json"),"utf8"));typeof d.title=="string"&&s.add(Ex(d.title))}catch{}let o=l=>s.has(Ex(l.title))||t.some(d=>d.endsWith(`-${ql(l.title)}`)||d.includes(`-${ql(l.title)}-`)),a=[...n.ideas].filter(l=>!l.gate&&typeof l.title=="string").sort((l,d)=>Number(d.slate)-Number(l.slate)||(l.slot??99)-(d.slot??99)||l.rank-d.rank).find(l=>!o(l));if(!a)return null;let c=a.styleId??n.styleId;return{slate:n.name,idea:a,...c?{styleId:c}:{}}}function pm(t){let{idea:e}=t;return{tool:"episode_create",args:{episodeId:Gl(e.title),title:e.title,...t.styleId?{style:t.styleId}:{}},why:`The newest idea slate (${t.slate}) has an idea that is not an episode yet: #${e.rank} "${e.title}" (score ${e.score}; ref ${t.slate}#${e.rank}). Confirm the pick with the user (or another idea from the slate) and the style, then create the episode.`,then:{stage:"topic",actor:"agent",tool:"topic_save",args:{},why:"Save the topic, promise and title directions for the new episode."},checklist:["The user confirmed the idea and the style.","episode_create made videos/<id>/ with episode.json (style, gateProfile)."]}}function fm(t,e){if(t)return Ff(t);let r=RD(),n={step:0,stage:"start",actor:"agent",tool:"doctor",args:{},why:"No episodes yet: check the setup first (doctor: licence, renderer, ffmpeg, Python, disk), then generate ideas.",then:{stage:"start",actor:"agent",tool:"ideas_generate",args:{},why:"Generate a scored idea slate; save it with ideas_save; then episode_create {episodeId, title, style}."},checklist:["doctor reports no blocking problem.","The user picked an idea from the slate.","episode_create made videos/<id>/ with the chosen style."],blockers:[]};Ia()?Object.assign(n,{tool:"ideas_save",why:"You generated an idea slate: score and save it with ideas_save {ideas:[\u2026]} (one object per idea, the shape ideas_generate returned); the user then picks one.",then:{stage:"start",actor:"agent",tool:"episode_create",args:{},why:"episode_create {episodeId, title, style} from the picked idea."},alternatives:[{stage:"start",actor:"agent",tool:"ideas_generate",args:{},why:"A fresh slate instead."}]}):Mg()&&Object.assign(n,{tool:"ideas_generate",why:"doctor has run: generate a scored idea slate (count 5\u201330), then save it with ideas_save.",then:{stage:"start",actor:"agent",tool:"ideas_save",args:{},why:"Save the slate; the user picks one; then episode_create {episodeId, title, style}."},alternatives:[{stage:"start",actor:"agent",tool:"doctor",args:{},why:"Re-check the setup."}]});let s=Ia()?null:ID(r),o=s?pm(s):null,i=o?{stage:"start",actor:"agent",tool:o.tool,args:o.args,why:`Or start a new video: ${o.why}`}:$x;if(!r.length)return s?{...n,...pm(s),alternatives:[{stage:"start",actor:"agent",tool:"doctor",args:{},why:"Check the setup (licence, renderer, ffmpeg, Python, disk) if it has not been checked."},{stage:"start",actor:"agent",tool:"ideas_generate",args:{},why:"A fresh slate instead."}]}:n;let a=[];try{a=ts({status:ul,limit:1e3})}catch{a=[]}let c=[],l=[];for(let p of r)try{let f=N(p),h=Ee(f);if(!e.operator&&oe(h)){c.push({id:p,operatorOnly:!0});continue}let m=uo(ho(p,{fast:!0,jobs:a})),g=p.startsWith("_");if(m.stage==="done")continue;c.push({id:p,style:h,example:g,step:m.step,stage:m.stage,actor:m.actor,...m.tool?{tool:m.tool}:{},...m.command?{command:m.command}:{},why:m.why}),g||l.push(m)}catch(f){c.push({id:p,error:f instanceof Error?f.message:String(f),fix:`episode_status {episodeId: "${p}"} shows the details.`})}if(!l.length)return s?{...n,...pm(s),alternatives:[{...$x,why:"A fresh slate instead."}],episodes:c}:Ia()?{...n,episodes:c}:{...n,tool:"ideas_generate",why:c.length?"No episode you can work on is in progress here: start a new video with a scored idea slate.":"Every episode here is done (the human uploads by hand): start a new video with a scored idea slate.",then:{stage:"start",actor:"agent",tool:"ideas_save",args:{},why:"Save the slate; the user picks one; then episode_create {episodeId, title, style}."},episodes:c};l.sort((p,f)=>Rx[p.actor]-Rx[f.actor]||String(f.episodeId).localeCompare(String(p.episodeId)));let d=Ff(l[0].episodeId);return{...d,suggestedEpisode:d.episodeId,episodes:c,or:i}}function Px(t,e){let r=N(t),n=hn(),s=[1,2,3,4].map(d=>Df(r,d)),o=Mf(s.map(d=>d.info)),i=ho(t,{gates:o}),a=Ti(i.profile),c=o.map((d,p)=>{let f=s[p].record,h=a.gates[`gate${d.gate}`],m=f&&f.decision==="approved"?Object.entries(f.pins).map(([S,$])=>{let k=cl(r,S);return{path:S,approved:$,current:k,changed:k!==$}}):[],g=o.slice(0,d.gate-1).find(S=>S.state!=="approved"&&!nl(i,d.gate).includes(S.gate)),y=d.state==="approved",w=y?`Approved by ${d.decidedBy} at ${d.at}${d.skippedGates?.length?` (skipped Gate ${d.skippedGates.join(", ")})`:""}.`:d.state==="none"?`${h==="required"?"Required":"Optional"} and not decided${d.detail?` (${d.detail})`:""}.`:d.state==="stale"?`Stale: ${[d.changedPins?.length?`${d.changedPins.join(", ")} changed after approval`:"",d.staleReason??""].filter(Boolean).join("; ")}. Re-approve after review, or undo the change.`:`The human ${d.state==="sent_back"?"sent it back":"rejected it"}${d.note?`: ${d.note}`:""}. Redo the stage, then the human decides again.`;return{gate:d.gate,name:d.name,state:d.state,requirement:h,...d.decidedBy?{decidedBy:d.decidedBy}:{},...d.at?{at:d.at}:{},...d.signed?{signed:!0}:{},...d.note?{note:d.note}:{},...d.skippedGates?.length?{skippedGates:d.skippedGates}:{},...d.staleReason?{staleReason:d.staleReason}:{},drift:d.changedPins??[],pins:m,...f&&Object.keys(f.flags).length?{flags:f.flags}:{},...d.readingSheet?{readingSheet:d.readingSheet}:{},ignored:d.ignored??[],...y?{alternatives:[Qe(r,d.gate,"send-back")]}:{command:Ce(i,d.gate),alternatives:[Qe(r,d.gate,"send-back"),Qe(r,d.gate,"reject")]},...!y&&g?{blockedBy:`Gate ${g.gate} (${g.name}) is ${g.state}: decide it first (${Ce(i,g.gate)}).`}:{},why:w}}),l=[];n||l.push(`No gate approval key on this machine: every gate is ${Ni}. The human runs \`${yr()} key\` once.`);for(let d of c)for(let p of d.ignored)l.push(`Gate ${d.gate}: ${p}`);return{episode:t,dir:r,style:i.style,gateProfile:a,key:n?{installed:!0,keyId:n.keyId}:{installed:!1},gates:e?c.filter(d=>d.gate===e):c,warnings:l,note:"Read only. Gates are decided only by the human, in their own terminal, with the commands shown. No tool can approve, override or upload.",next:"next_step {episodeId} for what to do now."}}var $x,Ex,Rx,Ox=v(()=>{"use strict";_i();qo();er();Pe();wr();zi();mr();sl();$x={stage:"start",actor:"agent",tool:"ideas_generate",args:{},why:"Or start a new video: generate a scored idea slate, save it (ideas_save), then episode_create {episodeId, title, style}."};Ex=t=>t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();Rx={agent:0,wait:1,human:2}});function Nx(t,e){if(e||!t||typeof t!="object")return t;let r={...t},n=typeof r.episodeId=="string"?r.episodeId:null;return n?("profile"in r&&!Yd(`${n}:profile`,JSON.stringify([r.profile,r.style]))&&(delete r.profile,delete r.style,r.unchanged="profile and style as in the first next_step for this episode (pass full: true to repeat them)"),Array.isArray(r.checklist)&&r.checklist.length&&!Yd(`${n}:checklist:${String(r.stage)}`,JSON.stringify(r.checklist))&&delete r.checklist,r):t}function Ax(t){let e=t.registerTool.bind(t);e("next_step",{title:"Next step",description:jD,inputSchema:{episodeId:Tx.optional(),full:u.boolean().optional().describe("Always include profile, style and checklist (by default they are sent once per episode / stage and again when they change).")}},async r=>{let n=r.episodeId,s=r.full===!0;return n?L({episodeId:n},o=>Nx(fm(n,{operator:o.operator}),s)):L({open:!0},o=>Nx(fm(void 0,{operator:o.operator}),s))}),e("gate_status",{title:"Gate status",description:PD,inputSchema:{episodeId:Tx,gate:u.number().int().min(1).max(4).optional().describe("Only this gate (1 topic, 2 script + facts, 3 animatic, 4 package).")}},async r=>L({episodeId:r.episodeId},()=>Px(r.episodeId,r.gate)))}var Tx,jD,PD,Cx=v(()=>{"use strict";Ft();vn();Ox();qo();Tx=u.string().regex(/^[A-Za-z0-9_][A-Za-z0-9._-]{0,119}$/,"an episode folder name under videos/, e.g. 2026-12-01-robot-rent").describe("Episode folder name under videos/ (from episode_list)."),jD="Episode profile (every style). Returns the ONE next action in the guided flow, idea \u2192 upload-ready video: {stage, actor: agent|human|wait, tool + args (ready to call), command (human gate steps: the exact `sundownreel-gate approve <videoDir> --gate N` the human types in their own terminal, with --skip-earlier when the quick profile lets them skip an optional gate), why, then (the step after), checklist (what done means), blockers [{problem, fix}], profile (quick: Gates 2+4 required, 1+3 optional; strict: all four), style}; profile/style are sent once per episode and checklist once per stage unless they change (full: true repeats them). Reads the files, signed gate records, facts, QA results and running jobs (actor wait \u2192 poll job_status {jobId}). Without episodeId: first run \u2192 doctor, then ideas_generate, then ideas_save (remembered for this server session); else every in-progress episode with its next action and the one to work on now. Call it at the start of every session and after each step. Read only: it never approves a gate (only the human can) and nothing uploads.";PD="Episode profile (every style). Read-only detail of the human gate records, like `sundownreel-gate status`: per gate the state (none/approved/stale/sent_back/rejected), decided_by, at, note, every pinned file with approved vs current sha (drift), skipped gates, ignored unsigned/forged/foreign-key records, required vs optional under the episode's gate profile, and the exact human command to (re-)approve, send back or reject. Only records signed by sundownreel-gate on this machine count. It never approves: show the command to the user."});function zl(t){for(let e of t){let r=e.trim().replace(/@\d+$/,""),n=Lx.get(r)??Lx.get(OD[r]??"");if(n)return n}return null}function Mx(t){let e=(t.aspects??[]).includes("9:16")&&!(t.aspects??[]).includes("16:9");return{styleId:t.id,name:t.name,aspect:e?"9:16":"16:9",runtime:e?"30\u201360 s":"8\u201315 min",pace:"see get_style_guide (pacing)",bestFor:t.pitch?[t.pitch]:[],avoid:[],numbers:"Every number rides on a beat with a fact id; the style decides digits, words or a counter.",structure:e?Dx:Vl,shotVocabulary:(t.kinds??[]).map(r=>`${r.id}: ${r.describe} (beats: ${r.beats.join(", ")})`)}}var Vl,Dx,mm,gm,Je,ym,OD,Lx,Fx=v(()=>{"use strict";Gc();Vl=[{part:"cold open",share:"0:00\u20130:15 (about 40 words)",what:"The absurd premise as one concrete image, one real number, and a promise ('by the end of this video\u2026'). No logo, no greeting. The premise is visible in shot 1."},{part:"setup",share:"0:15\u20131:00",what:"The normal world through one relatable (original) character; the rules of the scenario; a card states the question."},{part:"escalation ladder",share:"1:00 to about 55%",what:"4\u20136 rungs. Each rung: a new consequence, a real number with a fact id, a visual gag, a card. Each rung bigger or weirder than the last; an open loop every 60\u201390 s."},{part:"twist",share:"about 70%",what:"The counter-intuitive turn: who actually pays, or what doesn't happen. The shareable 'huh'."},{part:"reality check",share:"last ~15%",what:"What is real today vs hypothetical, in sourced numbers. What it means for a normal person: what to watch, never what to buy."},{part:"button",share:"last 10\u201315 s",what:"A callback gag and a one-line tease of the next scenario. No 'smash that like button'."}],Dx=[{part:"hook",share:"0\u20133 s",what:"Speech by 0.3 s; three fast shots: the subject, the odd detail, the wide with a number."},{part:"story",share:"3 s to ~85%",what:"One shot per phrase (about 1.2\u20131.5 s each); one idea per line; captions 1\u20132 words at a time."},{part:"landing",share:"last ~2 s",what:"The payoff line holds; no end card."}],mm=[{minutes:10,words:"1,500\u20131,650",use:"default; news pegs"},{minutes:12,words:"1,800\u20131,950",use:"most evergreen ideas"},{minutes:15,words:"2,300\u20132,450",use:"big evergreen deep dives"}],gm="Narration runs at about 150\u2013165 words per minute. Long-form mid-roll ads need 8:00+, so don't go under 8:30.",Je=Vl,ym=[{styleId:"ledger-cartoon",name:"Ledger Cartoon",aspect:"16:9",runtime:"10\u201315 min",pace:"a cut about every 2.4 s, tightening to ~2.1 s late; hard cuts; type-on cards at ~19 chars/s",bestFor:["outlandish money what-ifs with real numbers","AI, jobs, billionaires, bubbles, prices"],avoid:["caricatures of real people (silhouettes + quote cards only)"],numbers:"Printed ON something in the world: an LED strip, a receipt, a tag on a cash pile, a wall calendar; counters roll inside props.",structure:Je,shotVocabulary:["one oversized physical stand-in per scene (balloon = bubble, printing press = earnings)","original cast acting in lit sets","black type-on question cards"]},{styleId:"gridpaper",name:"Gridpaper",aspect:"16:9",runtime:"8\u201312 min",pace:"one step per narration beat, 3\u20138 s; locked camera; an icon or label pops every 1\u20131.5 s",bestFor:["ladders and ranks (salary steps, tax brackets, net-worth tiers)","step-by-step 'how it climbs' stories"],avoid:["stories without a sequence","scenes that need acting characters"],numbers:"Handwritten step labels, a date tile per step, a header counter 'STEP n / N'.",structure:[{part:"cold open",share:"0:00\u20130:15",what:"Jump straight to the absurd top step, then 'how do you get there?'"},{part:"the ladder",share:"most of the runtime",what:"One step per beat: title + code, an icon pops, a stamp or quote, the figure hops up and the view re-centres."},{part:"twist step",share:"about 70%",what:"A step that breaks the pattern (a lock, a trap door, a skipped rung)."},{part:"reality check + button",share:"last ~15%",what:"Which steps are real today (sourced); tease the next ladder."}],shotVocabulary:["staircase of labelled steps on graph paper","insignia and stamp pops","rows of cloned mini-figures with name labels"]},{styleId:"shadowbox",name:"Shadowbox",aspect:"16:9",runtime:"8\u201312 min",pace:"scenes of 3\u20136 s; half of scene changes are page-lifts; toy-like pops",bestFor:["friendly money explainers for a broad audience","household budgets, saving, prices"],avoid:["dark or violent topics"],numbers:"On props: a paper strip that types itself, taped torn-edge tags.",structure:Je,shotVocabulary:["craft-paper dioramas in a shallow box","felt characters","page-lift reveals of a board"]},{styleId:"evidence-lamp",name:"Evidence Lamp",aspect:"16:9",runtime:"10\u201315 min",pace:"shots 2\u20134.5 s; the focus moves to a new exhibit every 1.2\u20132 s; hard cuts only between topics",bestFor:["investigations of public records: filings, budgets, court documents","'follow the money' stories"],avoid:["anything not backed by a document you can show re-typeset"],numbers:"Typeset on log cards and document lines, called out by thin red index annotations.",structure:[{part:"cold open",share:"0:00\u20130:20",what:"The single most surprising line in the records, enlarged under the lens."},{part:"exhibits",share:"most of the runtime",what:"One exhibit per beat: the camera glides to it, the lens enlarges the detail, an annotation names it."},{part:"twist",share:"about 70%",what:"Two exhibits that contradict each other side by side."},{part:"reality check + button",share:"last ~15%",what:"What the records prove and what they don't; the open question."}],shotVocabulary:["flat-lay desk of prints, index cards, contact sheets","camera glides over one plane","lens enlargement of a detail"]},{styleId:"kraft-dossier",name:"Kraft Dossier",aspect:"16:9",runtime:"10\u201315 min",pace:"shots ~1.5 s (1.1\u20132.4 s); everything steps at 12 fps",bestFor:["paper-documentary money history","how a scheme, company or crisis unfolded (process only)"],avoid:["real-person likeness (figures are generic halftone archetypes)"],numbers:"Typed slips, torn red labels, newspaper-clipping style slips (our own text).",structure:Je,shotVocabulary:["one paper sheet per shot with 1\u20133 objects","split-pin cut-out puppets","paper maps of cut countries"]},{styleId:"stickfolk",name:"Stickfolk",aspect:"16:9",runtime:"10\u201315 min",pace:"shots ~1.9 s (1.6\u20132.4 s); hard cuts",bestFor:["big what-ifs told through scale (one person \u2192 a crowd of hundreds)","population, time and money scale"],avoid:["topics without a scale reveal"],numbers:"Small dark UI chips with a label and a counter.",structure:Je,shotVocabulary:["dark-faced stick people with a glowing rim","toy-like miniature environments in warm film light","scale reveals and crowds"]},{styleId:"terra-relief",name:"Terra Relief",aspect:"16:9",runtime:"12\u201320 min",pace:"map passages of 10\u201318 s joined by slow dissolves; evidence cards 4\u20136 s",bestFor:["history and geography what-ifs","trade routes, borders, resources on real terrain (open data, credited)"],avoid:["fast-paced punchline humour"],numbers:"Classical serif labels that write themselves; evidence cards between passages.",structure:[{part:"cold open",share:"0:00\u20130:30",what:"Wide map, one question, one number."},{part:"passages",share:"most of the runtime",what:"One passage per idea: territories spread, monuments rise, arrows draw; the camera holds, then makes one move in a narration pause."},{part:"evidence cards",share:"between passages",what:"A card with the sourced number or quote."},{part:"what-if turn + close",share:"last ~25%",what:"Redraw the map under the hypothetical; close on the real map today."}],shotVocabulary:["relief map from real elevation data","translucent territory fills","rising monument icons, tapered arrows"]},{styleId:"docket-3d",name:"Docket 3D",aspect:"16:9",runtime:"12\u201320 min",pace:"body shots 1.7\u20132.6 s; flash montages in the cold open",bestFor:["true-story money documentaries from public records","corporate collapses, frauds (process only, sourced)"],avoid:["real faces (mannequins and silhouettes only)","news footage"],numbers:"Giant numbers lying in the scene, timeline beams, calendar walls, bar fields.",structure:Je,shotVocabulary:["dark glossy 3D stages","featureless mannequin crowds","public-record document cards"]},{styleId:"orbit-survey",name:"Orbit Survey",aspect:"16:9",runtime:"8\u201315 min",pace:"slow descents, holds for measurements; one site per chapter",bestFor:["measure-it stories about real places: megaprojects, data centres, mines, cities"],avoid:["places without open imagery (credited open data only)"],numbers:"A big thin amber number with a label and a source line; a live scale bar and altitude readout.",structure:[{part:"cold open",share:"0:00\u20130:20",what:"Drop from orbit onto the site; one number lands."},{part:"sites",share:"most of the runtime",what:"Per site: descend, measure, light up the subject, state the sourced number."},{part:"twist + close",share:"last ~25%",what:"Compare the site to something familiar at the same scale; credits on screen."}],shotVocabulary:["graded open orthophoto imagery","survey lines with tick values","spotlight in true colour"]},{styleId:"stagelit-stick",name:"Stagelit Stick",aspect:"16:9",runtime:"10\u201315 min",pace:"one shot per line, 2.5\u20133.5 s; quick 0.5\u20130.8 s inserts for a punch word",bestFor:["everyday-life what-ifs (a family, a diner, a street)"],avoid:["data-dense chapters"],numbers:"Counter tiles and label pills inside the set.",structure:Je,shotVocabulary:["flat drawn characters with a cream halo inside low-poly 3D sets","big dolly pull-backs","warm golden-hour light"]},{styleId:"gilded-noir",name:"Gilded Noir",aspect:"16:9",runtime:"10\u201315 min",pace:"shots 2.5\u20135 s; cuts only; the field colour changes on most cuts",bestFor:["period money crime and heist stories (process only)","boom-and-bust history"],avoid:["modern tech stories"],numbers:"Giant condensed headlines; a gold number rolling inside a stepped frame.",structure:Je,shotVocabulary:["one saturated poster field per shot","paper silhouettes walking on twos","letter-drop chapter titles"]},{styleId:"plinth-city",name:"Plinth City",aspect:"16:9",runtime:"8\u201312 min",pace:"shots 2\u20134.5 s; hard cuts; one data rule recolours the model per shot",bestFor:["housing, rent, zoning and city data stories"],avoid:["stories without spatial data"],numbers:"A left-side stat block: index, label, giant thin number, unit, source line.",structure:Je,shotVocabulary:["white model district on a dark plinth from open footprint data","one hero building singled out","decade sweeps"]},{styleId:"exploded-view",name:"Exploded View",aspect:"16:9",runtime:"6\u201310 min",pace:"labels arrive one after another; slow pushes onto one part",bestFor:["what's inside the price: a card, a coin, a meter, a phone bill","cost breakdowns"],avoid:["branded products (generic objects only)"],numbers:"A right-hand column of part names and spec lines with leader lines.",structure:[{part:"cold open",share:"0:00\u20130:15",what:"The whole object and its price."},{part:"teardown",share:"most of the runtime",what:"Parts float apart one by one; each part = one cost or mechanism, labelled."},{part:"twist + close",share:"last ~20%",what:"The one part that costs the most (or nothing); reassemble."}],shotVocabulary:["product stage, matte clay parts","leader lines to labels","callouts on sub-parts"]},{styleId:"frontline",name:"Front Line",aspect:"16:9",runtime:"10\u201315 min",pace:"shots 6\u201312 s",bestFor:["market-share and trade 'campaigns' told as fronts on a map","historical campaigns"],avoid:["current conflicts (political minefield)"],numbers:"A date chip, faction badges and token counts.",structure:Je,shotVocabulary:["dark relief map","hatched faction washes","glowing thrust arrows with tokens"]},{styleId:"static-rules",name:"Static Rules",aspect:"16:9",runtime:"6\u201312 min",pace:"locked camera; numbered rules typed on; caps subtitle follows the narration",bestFor:["'the rules of\u2026' formats: hidden rules of money, contracts, fine print"],avoid:["upbeat topics"],numbers:"Rule boxes and a tape timecode; big white numbers with a red underline.",structure:[{part:"cold open",share:"0:00\u20130:20",what:"The case header and Rule 1 typed on."},{part:"rules",share:"most of the runtime",what:"One rule per chapter: the normal behaviour, then the strange detail, then why."},{part:"final rule + close",share:"last ~15%",what:"The rule that breaks the others; what it means in real life (sourced)."}],shotVocabulary:["flat white pictograms on black","numbered rule boxes","dotted sight lines and glowing eyes"]},{styleId:"glyph-story",name:"Glyph Story",aspect:"16:9",runtime:"6\u201310 min",pace:"long holds (the stillness is the style); one spotlight move per beat",bestFor:["who-gets-what stories with a small cast of archetypes","simple fables about money"],avoid:["data-heavy chapters"],numbers:"Typed name labels; a tally grid of repeated icons for counts.",structure:Je,shotVocabulary:["icon people on an empty pale field","type-on name labels","spotlight-and-blur emphasis"]},{styleId:"desk-chronicle",name:"Desk Chronicle",aspect:"16:9",runtime:"12\u201315 min",pace:"shots ~3 s (2.8\u20134.5 s); hard cuts and paper puffs",bestFor:["history-desk explainers: empires, trade, money history"],avoid:["modern brands and real faces"],numbers:"A hand-lettered number rolls above the map; a brass plaque counter.",structure:Je,shotVocabulary:["parchment map on a lamp-lit desk","a narrator's pencil hand","big-headed archetype puppets in field vignettes"]},{styleId:"blockfolk",name:"Blockfolk",aspect:"9:16",runtime:"30\u201360 s",pace:"shots 1.2\u20131.5 s; 9 cuts in the first 10 s; 1\u20132-word captions",bestFor:["one-scenario story shorts"],avoid:["anything resembling a well-known block game (original voxel world only)"],numbers:"Pixel-font captions and placards held by villagers.",structure:Dx,shotVocabulary:["original voxel miniature world","boxy villagers with placards","a camera that never stops moving"]},{styleId:"fieldbook",name:"Fieldbook",aspect:"16:9",runtime:"10\u201315 min",pace:"calm; trees grow branch by branch; map cards between landscapes",bestFor:["land, food, climate and resource economics"],avoid:["fast punchline humour"],numbers:"Handwritten labels and pigment data zones on real country outlines.",structure:Je,shotVocabulary:["watercolour journal pages","growing trees","country outlines with data zones"]},{styleId:"block-print",name:"Block Print",aspect:"16:9",runtime:"8\u201312 min",pace:"shots 1\u20133 s with many under 1 s",bestFor:["moody money parables","power and inequality stories (no real faces)"],avoid:["light-hearted topics"],numbers:"Carved bone-white type; one red accent object.",structure:Je,shotVocabulary:["bone-on-black relief print","drawn light rays and spotlight pools","wireframe rooms"]},{styleId:"period-canvas",name:"Period Canvas",aspect:"16:9",runtime:"12\u201320 min",pace:"one slow tableau per sentence (3.5\u20137.5 s); dissolves or dips",bestFor:["pre-modern money history: banking houses, trade companies, bubbles of the past"],avoid:["modern topics"],numbers:"Serif callouts, unrolling banners, date ribbons.",structure:Je,shotVocabulary:["candle-lit tableaux in 2.5D depth layers","name callouts with hairline leaders","seals and ribbons"]},{styleId:"brush-scroll",name:"Brush Scroll",aspect:"16:9",runtime:"6\u201310 min",pace:"strokes draw on in order; ink-bloom transitions",bestFor:["reflective long-view stories: compounding, time, patience"],avoid:["dense numbers (words are a whisper)"],numbers:"Small italic captions with a red square bullet.",structure:Je,shotVocabulary:["rice paper and wet ink","stroke-order calligraphy of our own design","ink-bloom scene changes"]},{styleId:"diecut-saga",name:"Die-Cut Saga",aspect:"16:9",runtime:"8\u201312 min",pace:"scenes ~2.5 s; impact flashes on beats",bestFor:["epic-tone stories with ORIGINAL characters"],avoid:["any franchise or game characters (absolute IP block)"],numbers:"Sticker-style tags and impact captions.",structure:Je,shotVocabulary:["chibi die-cut stickers on blurred painted stages","impact flashes and speed lines"]}],OD=Zh,Lx=new Map(ym.map(t=>[t.styleId,t]))});function qx(t){return{...zl([t.id,...t.aliases??[]])??Mx(t),styleId:t.id,name:t.name,status:t.status,tier:t.tier}}async function ND(t,e){if(await Tt()){let s;try{s=await vr(t)}catch{throw Hi(t)}let o=(await io({},{includeOperator:e})).find(i=>i.id===s||i.registryId===s);if(!o||!e&&Bi([o.id,...o.aliases??[]]))throw Hi(t);return qx(o)}let n=zl([t]);if(!n||!e&&Bi([t,n.styleId]))throw Hi(t);return{...n,status:"unknown (style registry not loaded)",tier:"unknown"}}async function AD(t){let e=n=>({styleId:n.styleId,name:n.name,aspect:n.aspect,runtime:n.runtime,bestFor:n.bestFor,avoid:n.avoid,numbers:n.numbers,...n.status?{status:n.status}:{},...n.tier?{tier:n.tier}:{}});if(await Tt()){let n=(await io({readyOnly:!0},{includeOperator:t})).filter(s=>t||!Bi([s.id,...s.aliases??[]]));if(n.length)return{source:"ready styles in the registry",formats:n.map(s=>e(qx(s)))}}return{source:"the Standard catalogue (style registry not loaded: status unknown)",formats:ym.filter(n=>TD.includes(n.styleId)||t&&n.styleId==="ledger-cartoon").map(n=>e(n))}}async function Gx(t,e){let r=Math.min(30,Math.max(5,Math.round(t.count??12))),n=t.styleId?await ND(t.styleId,e.operator):null,s=n?null:await AD(e.operator),o=kx(),i=[...new Set([...o.episodes,...o.slates.flatMap(c=>c.titles)])],a={title:"What If a Robot Worked for $1 an Hour?",premise:"A humanoid robot rents for $1/hour; we hire one and watch who is still employed by the end. Anchor: a published estimate of robot labour cost per hour.",D:5,O:5,X:5,L:4,G:3,R:1,kind:"evergreen + news peg",cluster:"AI & jobs",...n?{styleId:n.styleId}:{},anchors:["<primary source URL the key number rests on, with its date>"],titleVariants:["What If a Robot Worked for $1 an Hour?","The $1 Robot That Wants Your Job","I Hired a Robot for $1/Hour. Here's the Bill."],hook:"First ~40 words of narration: the absurd image, one real number, the promise.",thumbnail:"\u201C$1/HOUR\u201D \u2014 an original robot character holding one dollar bill"};return{task:`Brainstorm ${r} video ideas${t.niche?` for this niche: ${t.niche}`:""}${t.constraints?`. Constraints from the user: ${t.constraints}`:""}. Each idea: one outlandish, instantly picturable premise backed by at least one real, checkable number. Score every idea on the rubric (integers 0\u20135) with a one-line reason per axis in your head, then call ideas_save with ALL of them: the tool computes the scores, rejects R = 5 and picks the slate. If you have web search or keyword/outlier tools, use them for D (demand) and O (outlier proof) and cite what you used in anchors; otherwise mark D and O as estimates (score them 2\u20133) and say so to the user. This tool makes no network calls.`,count:r,rubric:Nl.map(c=>({axis:c.axis,name:c.name,question:c.question,weight:c.weight,anchors:c.anchors,evidence:c.evidence})),formula:ps,formulaNotes:hx,slateRule:Dl,slateSize:lm,kinds:gx,clusters:"Give each idea a short cluster name (topic family, e.g. 'AI & jobs', 'billionaires', 'prices'); the slate allows at most 3 per cluster.",titleRules:Ml,topicRules:mx,episodeFormat:n?{...n,lengthTargets:n.aspect==="16:9"?mm:void 0,lengthNote:n.aspect==="16:9"?gm:void 0}:{note:"No style chosen. Ideas are style-neutral (one script renders in any style); pick a style at episode_create. Call ideas_generate {styleId} for one style's full template.",sharedStructure:Vl,lengthTargets:mm,lengthNote:gm,...s},avoidRepeating:i.slice(0,80),saveShape:{tool:"ideas_save",args:{slateName:"<optional, e.g. 2026-12-01-ai-jobs>",ideas:[a,"\u2026one object per idea"]}},next:{tool:"ideas_save",why:"Persist and rank the ideas (scores, R = 5 gate, slate rule); it returns episode_create args for the top idea."}}}var TD,Bi,Hi,Ux=v(()=>{"use strict";wr();ln();Fx();Fl();zi();TD=["gridpaper","shadowbox","glyph-story","stagelit-stick","plinth-city","exploded-view","frontline"],Bi=t=>t.some(e=>oe(e)||zl([e])?.styleId==="ledger-cartoon"),Hi=t=>new Error(`Unknown style "${t}". Call list_styles for the styles you can use.`)});import{existsSync as Vx,mkdirSync as CD,readFileSync as LD,renameSync as DD,writeFileSync as MD}from"node:fs";import So from"node:path";function Hl(t,e){CD(So.dirname(t),{recursive:!0});let r=`${t}.tmp-${process.pid}`;MD(r,e),DD(r,t)}function FD(t){return`${t.state}${t.decidedBy?` by ${t.decidedBy}`:""}${t.at?` at ${t.at}`:""}${t.note?` (note: "${t.note}")`:""}`}function qD(t){let e=t.profile.optional.includes(1),r=t.score?["## Score","",`| ${Gr.join(" | ")} | Score |`,`|${Gr.map(()=>"---").join("|")}|---|`,`| ${Gr.map(n=>t.score[n]).join(" | ")} | **${t.score.score.toFixed(1)}** |`,"",`${ps}. ${Nl.map(n=>`${n.axis} = ${n.name}`).join(", ")}.${Cl(t.score)?" **R = 5: the rubric rejects this idea.**":""}`,""]:[];return[`# Gate 1 \u2014 topic + title direction: ${t.title}`,"",`Episode \`${t.id}\` \xB7 style \`${t.style}\` \xB7 gate profile **${t.profile.profile}** (Gate 1 is ${e?"optional: you may skip it":"required"}) \xB7 ${t.hypothetical?"flagged **hypothetical** (scenario numbers allowed on screen, labelled)":"not flagged hypothetical"}`,"","## The idea","",`- **Premise:** ${gt(t.premise)}`,...t.angle?[`- **Angle:** ${gt(t.angle)}`]:[],...t.audience?[`- **Audience:** ${gt(t.audience)}`]:[],...t.ideaRef?[`- **From slate:** ${t.ideaRef}`]:[],...t.anchors?.length?["- **Anchors (sources the numbers will rest on):**",...t.anchors.map(n=>` - ${gt(n)}`)]:[],"",...r,"## Title options (pick one, or write your own)","",...t.titleOptions.map((n,s)=>`${s+1}. [ ] ${gt(n)} (${gt(n).length} chars)`),"",`Title rules: ${Ml.slice(0,3).join(" ")}`,"","## Your decision","","Read the idea and the titles. You decide one of three things, in your own terminal (no agent or tool can do this for you):","","- **Approve** the topic and a title direction (say which title in the note if you like):",` \`${Qe(t.dir,1,"approve")}\``,"- **Send it back** with what to change (the agent revises this sheet):",` \`${Qe(t.dir,1,"send-back")}\``,"- **Reject** the topic:",` \`${Qe(t.dir,1,"reject")}\``,...e?["","In the quick profile you may also skip Gate 1 and decide at Gate 2 (script + facts) with `--skip-earlier`."]:[],"","Approving pins this file by its hash: if it changes afterwards, Gate 1 goes stale until you approve again.",""].join(`
|
|
224
|
+
`)}function zx(t,e){let r=N(t),n=gt(e.title??""),s=gt(e.premise??"");if(!n)throw new Error("title is empty.");if(!s)throw new Error("premise is empty: one or two sentences, the absurd image plus the real number behind it.");let o=[...new Set((e.titleOptions??[]).map(gt).filter(Boolean))];if(!o.length)throw new Error("Give at least one title option (3 is the norm: see the title rules in ideas_generate).");let i=So.join(r,"01-topic/gate1.md"),a=tt(r)[0],c;if(Vx(i)&&a.state!=="none"){if(!e.overwrite)throw new Error(`Gate 1 already has a decision: ${FD(a)}. Rewriting 01-topic/gate1.md would make it stale. `+(a.state==="sent_back"?"It was sent back, so a revision is expected: call topic_save again with overwrite: true and address the note.":"Only rewrite it if the user asked to change the topic, then call topic_save again with overwrite: true."));c=a.state==="approved"||a.state==="stale"?`Gate 1 was ${a.state}; this rewrite makes it stale (and every later gate approved on top of it) until the human re-approves: ${Qe(r,1,"approve")}`:`Gate 1 was ${a.state}; the human reviews the revised sheet: ${Qe(r,1,"approve")}`}let l=e.ideaRef?xx(e.ideaRef):null,d=null,p=e.score&&Object.keys(e.score).length?e.score:l?Object.fromEntries(Gr.map($=>[$,l.idea[$]])):null;p&&(Ll(p,"score"),d={...p,score:Al(p)});let f=e.anchors?.length?e.anchors.map(gt).filter(Boolean):l?.idea.anchors,h=Ee(r),m=br(r),g=Ct(r),y=qD({id:t,dir:r,title:n,premise:s,titleOptions:o,angle:e.angle,audience:e.audience,ideaRef:e.ideaRef,score:d,anchors:f,style:h,profile:m,hypothetical:g});Hl(i,y);let w={schema:1,episode:t,title:n,premise:s,titleOptions:o,...e.angle?{angle:gt(e.angle)}:{},...e.audience?{audience:gt(e.audience)}:{},...e.ideaRef?{ideaRef:e.ideaRef}:{},...d?{score:d}:{},...f?.length?{anchors:f}:{},style:h,savedAt:new Date().toISOString()};Hl(So.join(r,"01-topic/topic.json"),`${JSON.stringify(w,null,1)}
|
|
225
|
+
`);let S=m.optional.includes(1);return{episode:t,wrote:["01-topic/gate1.md","01-topic/topic.json"],...e.ideaRef&&!l?{note:`ideaRef "${e.ideaRef}" did not match a saved idea (<slate>#<rank>); recorded as text only.`}:{},...d?{score:d.score}:{},gate1:{state:a.state,required:!S,humanCommand:Qe(r,1,"approve"),...S?{skip:"Quick profile: the human may skip Gate 1 and approve Gate 2 with --skip-earlier."}:{}},...c?{warning:c}:{},next:{tool:"outline_save",args:{episodeId:t,outlineMd:"<cold open, setup, 4\u20136 escalation rungs (consequence + number needed + gag), twist, reality check, button>"},why:S?"Gate 1 is optional here: show the user the title options and the gate command, and keep going with the outline.":"Show the user 01-topic/gate1.md and the approve command (Gate 1 is required in the strict profile). Outline while they decide; research needs the approved topic."}}}function Hx(t,e){let r=N(t),n=e.outlineMd??"";if(!n.trim())throw new Error("outlineMd is empty.");let s=(e.chapters??[]).map((l,d)=>{let p=(l.anchor??"").trim();if(!GD.test(p))throw new Error(`chapters[${d}].anchor "${l.anchor}" must be a lowercase slug like cold-open or rung-3 (outline anchors are slugs; script_save meta.chapters anchors are the first VO words of the chapter, or the slug plus vo: "<first VO words>").`);if(!l.title?.trim())throw new Error(`chapters[${d}] needs a title.`);return{anchor:p,title:gt(l.title),beats:(l.beats??[]).map(gt).filter(Boolean)}}),o=s.find((l,d)=>s.findIndex(p=>p.anchor===l.anchor)!==d);if(o)throw new Error(`chapter anchor "${o.anchor}" is used twice.`);Hl(So.join(r,"02-outline/outline.md"),n.endsWith(`
|
|
226
|
+
`)?n:`${n}
|
|
227
|
+
`);let i=["02-outline/outline.md"];s.length&&(Hl(So.join(r,"02-outline/outline.json"),`${JSON.stringify({schema:1,episode:t,chapters:s,savedAt:new Date().toISOString()},null,1)}
|
|
228
|
+
`),i.push("02-outline/outline.json"));let a=tt(r)[1],c=Ai(r);return{episode:t,wrote:i,chapters:s.length,...a.state==="approved"?{note:"Gate 2 (script + facts) is already approved; an outline change only matters if the script changes too (script_save makes Gate 2 stale)."}:{},next:{tool:"research_plan",args:{episodeId:t},why:`Turn every number the outline needs into sourced facts${c?.hypothetical===!0?" (scenario inputs labelled hypothetical)":""}.`}}}function Bx(t){let e=So.join(t,"01-topic/topic.json");if(!Vx(e))return null;try{return JSON.parse(LD(e,"utf8"))}catch{return null}}var gt,GD,bm=v(()=>{"use strict";er();Pe();wr();sl();Fl();zi();gt=t=>t.replace(/\s+/g," ").trim();GD=/^[a-z0-9][a-z0-9-]{0,47}$/});import{existsSync as UD,readFileSync as Zx}from"node:fs";import xo from"node:path";function Xx(t){let e=new Map;for(let r of t)if(r.id)for(let n of new Set([...Jl(r.value??""),...Jl(r.on_screen??"")]))e.set(n,[...e.get(n)??[],r.id]);return e}function QD(t,e,r){let n=new Set(r.map(i=>i.id).filter(Boolean)),s=Xx(r),o=[];return e.split(/\r?\n/).forEach((i,a)=>{let c=i.trim();if(!c||/^[-*_|: ]+$/.test(c))return;let l=[...c.matchAll(XD)].map(m=>m[1]),d=c;for(let m of Yx)d=d.replace(m," ");let p=[];if(JD.test(d)&&p.push("money"),WD.test(d)&&p.push("percent"),KD.test(d)&&p.push("year"),/\d/.test(d)&&!p.length&&p.push("number"),ZD.test(d)&&p.push("magnitude"),YD.test(d)&&p.push("superlative"),!p.length&&!l.length)return;l.length&&p.push("fact-ref");let f=new Set(l.filter(m=>n.has(m)));for(let m of Jl(d))for(let g of s.get(m)??[])f.add(g);let h=l.filter(m=>!n.has(m));o.push({where:`${t}:${a+1}`,text:c.length>240?`${c.slice(0,237)}\u2026`:c,signals:p,coveredBy:[...f],...h.length?{unknownRefs:h}:{}})}),o}function Qx(t){let e=ll(t);return e?{file:xo.relative(t,e).split(xo.sep).join("/"),rows:to(Zx(e,"utf8")).rows.filter(r=>r.id)}:{file:null,rows:[]}}function Jx(t){return`F${t.reduce((r,n)=>Math.max(r,Number(/^F(\d{1,4})/.exec(n.id)?.[1]??0)),0)+1}`}function ek(t){let e=N(t),r=Ct(e),n=Bx(e),{file:s,rows:o}=Qx(e),i=[["02-outline/outline.md",Bl(xo.join(e,"02-outline/outline.md"))],["04-script/script_vo.txt",Bl(xo.join(e,"04-script/script_vo.txt"))],["01-topic/gate1.md",n?null:Bl(xo.join(e,"01-topic/gate1.md"))]];if(n){let p=[n.title,n.premise,...Array.isArray(n.titleOptions)?n.titleOptions:[]].filter(f=>typeof f=="string").join(`
|
|
229
|
+
`);i.unshift(["01-topic/topic.json",p])}let a=i.flatMap(([p,f])=>f?QD(p,f,o):[]),c=a.filter(p=>!p.coveredBy.length),l={};for(let p of o)l[p.status||"(none)"]=(l[p.status||"(none)"]??0)+1;let d=i.filter(([,p])=>p).map(([p])=>p);return{episode:t,hypothetical:r,topic:n?{title:n.title,premise:n.premise,anchors:n.anchors??[]}:null,read:d,...d.length?{}:{note:"No topic, outline or script yet: save them first (topic_save, outline_save) so the plan can list the claims that need facts."},sourceChecklist:HD,factColumns:VD,exampleRows:zD,exampleNote:"Format examples only. Every row you save must come from a source you opened yourself; fill quote and source_date from that source.",idRules:BD,existingFacts:{file:s,count:o.length,ids:o.map(p=>p.id),statusCounts:l,nextId:Jx(o)},claimsNeedingFacts:{total:a.length,uncovered:c.length,list:(c.length?c:a).slice(0,Wx),...Math.max(c.length,a.length)>Wx?{truncated:!0}:{},how:"Lines with digits, %, money, years, magnitude words or superlatives. coveredBy = fact ids whose value/on_screen number appears in the line or that the line cites as [F#]. Spoken numbers in words are only partly caught: read the script too."},researcherRule:"facts_upsert writes every row as status unverified with an empty checker and researcher = your actor id. You never verify your own rows. A DIFFERENT session (a fresh fact-checker with its own actor id) runs factcheck_plan \u2192 factcheck_record. Re-saving a row resets it to unverified.",...r?{scenarioRule:"This episode is flagged hypothetical: scenario inputs are allowed on screen once the checker marks them scenario. Label them 'hypothetical' in notes."}:{scenarioRule:"This episode is NOT flagged hypothetical: invented numbers may not appear on screen. Only verified or computed facts can."},next:{tool:"facts_upsert",args:{episodeId:t},fill:{actor:"Your researcher session id (letters/digits first, then letters, digits, . _ : -; 3-80 chars), e.g. researcher-a1.",facts:`Array of rows. Next new id: ${Jx(o)}. Fields: id, claim (required); value, unit, on_screen, as_of, source_name, source_date, url, quote, notes (optional).`},then:"Ask for a fresh session to fact-check (factcheck_plan, then factcheck_record with a different actor)."}}}function eM(t,e){let r=`${t.notes??""}`.toLowerCase(),n=[t.url?"Open the url yourself (not the researcher's notes): it loads and is the named source.":"No url: it cannot be verified. Leave it out of your results (stays unverified) or record disputed with note 'needs a source'.",t.quote?"The quote appears verbatim in the source, and says what the claim says (attribution exact: who, where, when).":"No quote: find the sentence in the source; if none supports the claim, record disputed.",`value ${t.value||"(empty)"} ${t.unit||""} matches the source exactly (no re-rounding, right unit and currency).`,"source_date is the original report date (search for the earliest report; recycled stories get re-dated)."];return t.on_screen?n.push(`on_screen "${t.on_screen}" shows the same number as value (rounded only as the script says 'about'; unit/currency/period correct).`):n.push("No on_screen string: fine if it is never shown; any shot that shows it needs one first (researcher re-saves)."),(t.as_of||/real[- ]?time|refresh|live/.test(r))&&n.push(`as_of ${t.as_of||"(missing)"} is present and current; real-time values are re-read on script-lock day.`),(/comput|formula|=|arithmetic/.test(r)||/our arithmetic/i.test(t.source_name??""))&&n.push("Computed row: recompute it from the referenced fact ids and record computed if it matches."),/hypothetical|scenario/.test(r)&&n.push(e?"Scenario input: record scenario (allowed on screen in this hypothetical episode, labelled as hypothetical).":"Scenario input in an episode NOT flagged hypothetical: it may not go on screen; record disputed with that note."),/odds|market|polymarket|kalshi|probabilit|chance|bet/i.test(`${t.claim} ${r}`)&&n.push("Odds or market: check the exact market question, the resolution rules and the reading time."),n}function tk(t){let e=N(t),r=Ct(e),{file:n,rows:s}=Qx(e);if(!s.length)return{episode:t,file:n,toCheck:[],note:"There are no facts yet. The researcher adds them first (research_plan \u2192 facts_upsert).",next:{tool:"research_plan",args:{episodeId:t}}};let o=h=>(h.status??"").trim().toLowerCase(),i=s.filter(h=>o(h)===""||o(h)==="unverified"),a=s.filter(h=>o(h)==="disputed"),c=s.filter(h=>["verified","computed","scenario"].includes(o(h))),l=[...new Set(s.map(h=>h.researcher).filter(Boolean))],d=Bl(xo.join(e,"04-script/script_vo.txt")),p;if(d){let h=Xx(s);p=[],d.split(/\r?\n/).forEach((m,g)=>{let y=m;for(let w of Yx)y=y.replace(w," ");for(let w of Jl(y))h.has(w)||p.push({line:g+1,number:w,text:m.trim().slice(0,160)})})}let f=["verified","computed","disputed",...r?["scenario"]:[]];return{episode:t,file:n,hypothetical:r,counts:{total:s.length,toCheck:i.length,disputed:a.length,done:c.length},toCheck:i.map(h=>({id:h.id,claim:h.claim,value:h.value,unit:h.unit,on_screen:h.on_screen,as_of:h.as_of,source_name:h.source_name,source_date:h.source_date,url:h.url,quote:h.quote,notes:h.notes,researcher:h.researcher||"(none: the researcher must re-save it with facts_upsert before it can be checked)",checks:eM(h,r)})),...a.length?{disputed:a.map(h=>({id:h.id,claim:h.claim,notes:h.notes})),disputedRule:"Disputed rows block the script. The researcher fixes and re-saves them (facts_upsert), which makes them unverified again for a new check."}:{},...p?{scriptNumbersWithoutFacts:p.slice(0,Kx),...p.length>Kx?{scriptNumbersTruncated:p.length}:{},scriptNumbersNote:"Digits in 04-script/script_vo.txt that match no fact's value or on_screen. Report them to the user: each needs a fact (researcher) or a rewrite (writer). Numbers spoken as words are not detected."}:{},checkerRule:`You are the independent fact-checker (decision #13): your actor id must differ from the researcher of every row you record${l.length?` (researchers here: ${l.join(", ")})`:""}. Re-open each source yourself; don't rely on the researcher's reasoning. Rows you can't settle stay unverified: leave them out of results.`,allowedStatuses:f,statusMeaning:{verified:"value, unit, quote, date and attribution match a primary source or two independent major outlets",computed:"our arithmetic over verified facts, formula in notes, recomputed by you",disputed:"wrong, misquoted, mis-dated or unsupported; say what would fix it in note",...r?{scenario:"an invented input of this hypothetical episode, clearly labelled"}:{}},next:i.length?{tool:"factcheck_record",args:{episodeId:t},fill:{actor:"Your fact-checker session id, different from the researcher (letters/digits first, then letters, digits, . _ : -; 3-80 chars), e.g. checker-b2.",results:`Array of {id, status, note}. First pending row: ${i[0].id}. status is one of allowedStatuses; note says which source and date you checked.`},then:"When no row is disputed or unverified, write the script (script_save)."}:a.length?{tool:"facts_upsert",args:{episodeId:t},fill:{actor:"the researcher's session id",facts:"the corrected disputed rows"},why:"Nothing left to check, but disputed rows block the script: the researcher fixes them first."}:{tool:"script_save",args:{episodeId:t},why:"Every fact is settled (verified / computed / scenario): write the script."}}}var Bl,VD,zD,HD,BD,JD,WD,KD,ZD,YD,XD,Yx,Jl,Wx,Kx,rk=v(()=>{"use strict";er();vi();Pe();bm();Bl=t=>UD(t)?Zx(t,"utf8"):null,VD=[{column:"id",meaning:"F1, F2, F12a\u2026 stable once a script or shot cites it"},{column:"claim",meaning:"the claim in plain words, worded as the source words it (no re-rounding)"},{column:"value",meaning:"the bare number as the source gives it, e.g. 1232 or 0.43"},{column:"unit",meaning:"USD per week, %, people, USD billions\u2026"},{column:"on_screen",meaning:"the exact string the video may show, e.g. $1,232/week (leave empty if never shown)"},{column:"as_of",meaning:"the date (and time + zone for real-time values) the number is true for"},{column:"source_name",meaning:"who published it: agency, company filing, paper, outlet"},{column:"source_date",meaning:"the ORIGINAL publication date (earliest report), not a re-share"},{column:"url",meaning:"the page or document the checker will open"},{column:"quote",meaning:"the sentence from the source, verbatim"},{column:"status",meaning:"set by the tools: unverified on every researcher write; verified / computed / disputed / scenario by the checker"},{column:"checker",meaning:"set by factcheck_record (checker session + date)"},{column:"researcher",meaning:"set by facts_upsert (your actor id)"},{column:"notes",meaning:"formula for computed rows (e.g. = F1 / 40), 'hypothetical' for scenario inputs, 'refresh on lock' for real-time values, snapshot path"}],zD=[{id:"F1",claim:"Median usual weekly earnings of full-time wage and salary workers, Q3 2026 (not seasonally adjusted)",value:"1232",unit:"USD per week",on_screen:"$1,232/week",as_of:"2026-Q3",source_name:"U.S. Bureau of Labor Statistics, Usual Weekly Earnings news release",source_date:"<release date shown on the release>",url:"https://www.bls.gov/news.release/wkyeng.htm",quote:"<the release's own sentence, copied verbatim>",notes:"snapshot 03-research/sources/bls-wkyeng.html"},{id:"F2",claim:"That is about $30.80 an hour for a 40-hour week",value:"30.80",unit:"USD per hour",on_screen:"\u2248 $30.80/hour",as_of:"2026-Q3",source_name:"our arithmetic",notes:"computed: = F1 / 40"}],HD=["Primary sources first: official statistics (national statistics offices, central banks), company filings and investor-relations releases, court and legislative records, peer-reviewed papers or working papers, the organisation's own page.","No primary source? Two independent major outlets that each report the number (not one citing the other).","Social posts, AI summaries, forums and aggregators are leads, never sources: find the original.","source_date is the original report date. Search for the earliest report: old stories get re-shared as new.","Copy the exact sentence into quote. Attribution exact: who said it, where, when (no misquotes, no paraphrase in quote marks).","Real-time numbers (prices, net worth, market odds) get as_of with a time and timezone and 'refresh on lock' in notes; they are re-read on script-lock day.","Prediction markets or odds: record the exact market question and resolution rule in notes.","Computed rows: our arithmetic, with the formula over fact ids in notes (= F1 / 40); the script says 'that works out to about\u2026'.","Scenario inputs (invented numbers that drive the what-if, e.g. 'if a robot cost $1 an hour'): 'hypothetical' in notes; they may appear on screen only in an episode flagged hypothetical, framed as 'imagine/if'.","Snapshot each source page into 03-research/sources/ when you can save files; otherwise put the access date in notes.","Add 3\u20135 surprise facts that could power the twist (who actually pays, what doesn't happen).","Target: 15\u201340 rows for a 10\u201315 minute video; one number per row."],BD=["Ids are F + 1\u20134 digits + an optional lowercase letter: F1, F12, F12a.","One number per row. Never reuse an id for a different claim; once a script line or shot cites it, keep it stable (add F12a rather than renumbering).","Cite facts in the script as [F12] after the sentence; every on-screen number in shots carries its factId."],JD=/[$€£¥]\s?\d|\b\d[\d,.]*\s?(dollars?|bucks|usd|euros?|pounds?|cents?)\b/i,WD=/\d\s?(%|percent\b|per cent\b)/i,KD=/\b(1[6-9]\d\d|20\d\d)s?\b/,ZD=/\b(thousand|million|billion|trillion|hundreds?|dozens?|half|twice|double|triple|quarter|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety)\b/i,YD=/\b(biggest|largest|greatest|richest|poorest|highest|lowest|fastest|slowest|cheapest|most expensive|oldest|youngest|longest|smallest|worst|best-selling|record|all-time|first[- ]ever|ever recorded|number one|no\. ?1)\b/i,XD=/\[(F\d{1,4}[a-z]?)\]/g,Yx=[/^\s*(#+\s*)?\d+[.)]\s+/,/\b(rung|chapter|step|part|act|beat|scene|shot|slot|option|take)\s*#?\d+\b/gi,/\b\d{1,2}:\d{2}(:\d{2})?\b/g,/\[F\d{1,4}[a-z]?\]/g,/\bS\d{3}[a-z]?\b/g],Jl=t=>[...t.matchAll(/\d[\d,]*(?:\.\d+)?/g)].map(e=>e[0].replace(/,/g,"").replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"").replace(/^0+(?=\d)/,""));Wx=80;Kx=40});import{existsSync as tM,readFileSync as rM}from"node:fs";import nM from"node:path";function pM(t){let e=t.find(n=>n.slot===1);if(e)return{idea:e};let r=t.find(n=>!n.gate);return r?{idea:r,note:`No idea met the slate rule; this is the best-scoring idea that is not rejected (${r.excluded}).`}:null}function hM(t,e={operator:!0}){let r=[...new Set(t.ideas.map(c=>c.styleId).filter(Boolean))];if(!e.operator){for(let c of r)if(Bi([c]))throw Hi(c)}let{slate:n,name:s,files:o}=Sx(t.ideas,{slateName:t.slateName,...r.length===1?{styleId:r[0]}:{}}),i=pM(n.ideas),a=n.ideas.map(c=>({rank:c.rank,...c.slot?{slot:c.slot}:{},title:c.title,score:c.score,...c.gate?{gate:c.gate}:{},...c.excluded?{out:c.excluded}:{},kind:c.kind,...c.cluster?{cluster:c.cluster}:{}}));return{slate:s,files:o,counts:{ideas:n.ideas.length,onSlate:n.ideas.filter(c=>c.slate).length,rejected:n.ideas.filter(c=>c.gate).length},ranked:a,productionOrder:"News-pegged slate picks first (their interest decays in weeks); evergreen picks keep.",next:i?{tool:"episode_create",args:{episodeId:Gl(i.idea.title),title:i.idea.title,...i.idea.styleId?{style:i.idea.styleId}:{},.../^\s*what if\b/i.test(i.idea.title)?{hypothetical:!0}:{}},ideaRef:`${s}#${i.idea.rank}`,why:`Top slate idea. Show the user the slate first: they may pick another (any rank works; use its title). hypothetical: true lets labelled scenario numbers go on screen (the human confirms it at Gate 2); drop it for a purely factual video. After episode_create: topic_save {episodeId, title, premise, titleOptions, ideaRef: "${s}#${i.idea.rank}"}.`,...i.note?{note:i.note}:{}}:{tool:"ideas_generate",why:"Every idea was rejected (R = 5). Brainstorm safer angles: mechanisms over people, sourced numbers, labelled hypotheticals."}}}function wm(t,e){let r=nM.join(rs(),t),n=tM(r)?rM(r,"utf8"):`prompts/${t} is missing from this install.`;return e?`${e}
|
|
230
|
+
|
|
231
|
+
${n}`:n}function ok(t){let e=t.registerTool.bind(t);e("ideas_generate",{title:"Generate ideas (rubric + format)",description:iM,inputSchema:{count:u.number().int().min(5).max(30).optional().describe("How many ideas to brainstorm: an integer from 5 to 30 (default 12)."),styleId:sk.optional().describe("Style to fit the ideas to (its episode-format template comes back). Omit for style-neutral ideas."),niche:u.string().max(300).optional().describe("The channel's niche or theme, e.g. 'AI and money what-ifs'."),constraints:u.string().max(1e3).optional().describe("Anything else from the user: audience, length, topics to avoid.")}},async r=>L({},n=>Gx({count:r.count,styleId:r.styleId,niche:r.niche,constraints:r.constraints},{operator:n.operator}))),e("ideas_save",{title:"Score and save ideas",description:aM,inputSchema:{ideas:u.array(sM).min(1).max(60),slateName:u.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/,"letters, digits, . _ - (max 80)").optional().describe("File name under <studio>/ideas/. Default <date>-slate (never overwrites); an explicit name re-saves that slate (a rescore).")}},async r=>L({},n=>hM({ideas:r.ideas,slateName:r.slateName},{operator:n.operator}))),e("topic_save",{title:"Save topic (Gate 1 sheet)",description:cM,inputSchema:{episodeId:Wl,title:u.string().min(1).max(200),premise:u.string().min(1).max(2e3),titleOptions:u.array(u.string().min(1).max(200)).min(1).max(6).describe("3 title variants is the norm."),angle:u.string().max(1e3).optional().describe("The original take: what this video shows that others don't."),audience:u.string().max(500).optional(),ideaRef:u.string().max(100).optional().describe("'<slate>#<rank>' from ideas_save (fills score and anchors)."),score:oM.optional(),anchors:u.array(u.string().max(500)).max(20).optional(),overwrite:u.boolean().optional().describe("Rewrite gate1.md although Gate 1 has a decision (makes Gate 1 stale).")}},async r=>{let n=r.episodeId;return L({episodeId:n},()=>zx(n,r))}),e("outline_save",{title:"Save outline",description:lM,inputSchema:{episodeId:Wl,outlineMd:u.string().min(1).max(6e4),chapters:u.array(u.object({anchor:u.string().max(48).describe(`lowercase slug, e.g. cold-open, rung-3. Later, script_save meta.chapters keeps the slug only with vo: "<first words of the chapter's VO line>" (package_make times chapters by VO words).`),title:u.string().min(1).max(120),beats:u.array(u.string().max(500)).max(30).optional()})).max(40).optional()}},async r=>{let n=r.episodeId;return L({episodeId:n},()=>Hx(n,{outlineMd:r.outlineMd,chapters:r.chapters}))}),e("research_plan",{title:"Research plan (researcher)",description:dM,inputSchema:{episodeId:Wl}},async r=>{let n=r.episodeId;return L({episodeId:n},()=>ek(n))}),e("factcheck_plan",{title:"Fact-check plan (independent checker)",description:uM,inputSchema:{episodeId:Wl}},async r=>{let n=r.episodeId;return L({episodeId:n},()=>tk(n))}),t.registerPrompt("idea-scout",{title:"Idea scout",description:"Brainstorm, score and save a slate of video ideas with ideas_generate \u2192 ideas_save (prompts/idea-scout.md).",argsSchema:{niche:u.string().optional(),styleId:u.string().optional(),count:u.string().optional()}},({niche:r,styleId:n,count:s})=>{let o=[r&&`Niche: ${r}.`,n&&`Style: ${n}.`,s&&`Count: ${s}.`].filter(Boolean).join(" ");return{messages:[{role:"user",content:{type:"text",text:wm("idea-scout.md",o)}}]}}),t.registerPrompt("researcher",{title:"Researcher",description:"Build the episode's fact table with research_plan \u2192 facts_upsert (prompts/researcher.md).",argsSchema:{episodeId:u.string().optional()}},({episodeId:r})=>({messages:[{role:"user",content:{type:"text",text:wm("researcher.md",r?`Episode: ${r}.`:"")}}]})),t.registerPrompt("fact-checker",{title:"Fact-checker",description:"Independently check every fact with factcheck_plan \u2192 factcheck_record, as a different session from the researcher (prompts/fact-checker.md).",argsSchema:{episodeId:u.string().optional()}},({episodeId:r})=>({messages:[{role:"user",content:{type:"text",text:wm("fact-checker.md",r?`Episode: ${r}.`:"")}}]}))}var nk,Kl,Wl,Lt,sk,sM,oM,iM,aM,cM,lM,dM,uM,ik=v(()=>{"use strict";Ft();Pe();vn();Ux();rk();zi();bm();nk="Ideas (every style; no episode needed). ",Kl="Episode profile (every style). ",Wl=u.string().regex(/^[A-Za-z0-9_][A-Za-z0-9._-]{0,119}$/,"an episode folder name under videos/, e.g. 2026-12-01-robot-rent").describe("Episode folder name under videos/ (from episode_list)."),Lt=t=>u.number().int().min(0).max(5).describe(t),sk=u.string().min(1).max(80).describe("A style id from list_styles."),sM=u.object({title:u.string().min(1).max(200).describe("Lead title (3 variants go in titleVariants)."),premise:u.string().min(1).max(1e3).describe("One or two sentences: the absurd image + the real number behind it."),D:Lt("Demand 0\u20135 (5: 1M+ monthly searches; 3: 100K\u2013300K; 1: <20K)."),O:Lt("Outlier proof 0\u20135 (5: 100\xD7+ breakout or 1M+ views on a <100K channel; 3: 10\u201330\xD7; 1: no comps)."),X:Lt("Outlandishness 0\u20135 (5: a literal absurd image; 3: provocative but abstract; 1: plain news)."),L:Lt("Longevity 0\u20135 (5: evergreen; 3: months; 1: days or weeks)."),G:Lt("Gap 0\u20135 (5: nobody does it with real numbers or cartoons; 1: saturated)."),R:Lt("Fact/legal risk 0\u20135, subtracted (5: defamation/political minefield or unverifiable = rejected; 3: named companies, sourced; 1: pure hypothetical)."),kind:u.string().max(60).optional().describe("evergreen | news (decays in weeks) | evergreen + news peg."),cluster:u.string().max(60).optional().describe("Topic family, e.g. 'AI & jobs' (max 3 per cluster on the slate)."),styleId:sk.optional(),anchors:u.array(u.string().max(500)).max(20).optional().describe("Sources the key numbers rest on (URL + date, or a fact id). The slate needs at least one."),titleVariants:u.array(u.string().max(200)).max(6).optional(),hook:u.string().max(1e3).optional().describe("First ~40 words of narration."),thumbnail:u.string().max(300).optional().describe("2\u20134 thumbnail words + the one image.")}),oM=u.object({D:Lt("Demand"),O:Lt("Outlier proof"),X:Lt("Outlandishness"),L:Lt("Longevity"),G:Lt("Gap"),R:Lt("Risk")}).describe("The idea's rubric scores (from ideas_save); the sheet shows the computed score."),iM=nk+"Start here for a new video (after doctor on first run). Returns the scoring rubric (D demand, O outlier proof, X outlandishness, L longevity, G gap, R risk; 1/3/5 anchors each), the formula, the slate rule, title rules, the topic hard rules (no real-person likeness or caricature, no third-party IP or brands, every on-screen number needs a fact, hypotheticals labelled), the episode-format template of the chosen style (or a summary of the ready styles), titles already used (avoid repeats) and the exact ideas_save shape. It makes no network calls: research demand and outliers with your own tools if you have them and cite them in anchors. count (optional) is an integer from 5 to 30, default 12. Next: brainstorm, score, then ideas_save with every idea.",aM=nk+"Score and save a batch of ideas: computes round((4D+4O+4X+3L+2G)/85\xD7100 \u2212 4R, 1) per idea (same as pipeline/scripts/score.py), rejects R = 5, ranks them, picks the slate (\u22651 anchor, R \u2264 3, \u22643 per cluster, \u226530% news-pegged) and writes <studio>/ideas/<slate>.json + .md. Returns the ranked list (why each non-slate idea is out) and next: episode_create args for the top slate idea (episodeId like 2026-12-01-robot-rent, title, style). Show the user the slate and let them pick; any idea can become an episode.",cM=Kl+"After episode_create: write the Gate 1 reading sheet 01-topic/gate1.md (chosen idea, premise, score breakdown, title options, the decision the human makes and the exact `sundownreel-gate approve|send-back|reject <videoDir> --gate 1` commands) plus 01-topic/topic.json. ideaRef '<slate>#<rank>' pulls the score and anchors from a saved slate. Refuses to rewrite gate1.md once Gate 1 has a decision unless overwrite: true (that makes Gate 1 stale; after a send-back it is expected). It never decides the gate. Gate 1 is required in strict, optional in quick. Next: outline_save.",lM=Kl+"Save the outline: 02-outline/outline.md (cold open, setup, 4\u20136 escalation rungs each with its consequence + the number it needs + a gag, twist, reality check, button) and, with chapters [{anchor, title, beats[]}], 02-outline/outline.json. Overwrites the previous outline. Next: research_plan.",dM=Kl+"Read-only plan for the RESEARCHER: source checklist (primary sources first, original dates, verbatim quotes, as_of for real-time numbers), the facts.csv columns with filled example rows, fact id rules (F1, F12a), the existing facts and next free id, and every line of the topic/outline/script that looks like it needs a fact (digits, %, money, years, magnitude words, superlatives) with the facts that already cover it. Next: facts_upsert with your researcher actor id (every row is saved unverified); then a different session fact-checks.",uM=Kl+"Read-only plan for the independent FACT-CHECKER (a different session from the researcher, decision #13): every fact still unverified or without status, each with what to check (source reachable, quote verbatim, value/unit/as_of, original date, on_screen formatting, computed formula, market definitions), disputed rows that block the script, digits in the narration that no fact covers, the allowed statuses (scenario only in an episode flagged hypothetical) and the exact factcheck_record call. Next: factcheck_record, then script_save."});import{createHash as lk}from"node:crypto";import{createReadStream as dk,createWriteStream as uk,existsSync as pk,mkdirSync as hk,readFileSync as fM,renameSync as mM,rmSync as Zl}from"node:fs";import ko from"node:path";import{Readable as gM,Transform as yM}from"node:stream";import{pipeline as bM}from"node:stream/promises";import{createGunzip as wM}from"node:zlib";function _m(){let t=vM,e=process.env.SUNDOWNREEL_GEODATA_URL?.trim()||null;return{version:t,metadataUrl:`${_M()}/${Yl.replace("/","%2f")}/${t}`,tarballUrl:e,target:pf(),sizeMb:116}}async function xM(t,e,r){let n=Buffer.alloc(0),s=null,o={},i=null,a=0,c=0,l=async p=>{for(n=n.length?Buffer.concat([n,p]):p;;){if(i){let C=Math.min(i.left,n.length);if(C&&(i.stream.write(n.subarray(0,C))||await new Promise(xe=>i.stream.once("drain",()=>xe())),n=n.subarray(C),i.left-=C),i.left>0)return;let ne=i.stream;a=i.pad,i=null,await new Promise(xe=>ne.end(()=>xe())),c++,r?.(c);continue}if(a){let C=Math.min(a,n.length);if(n=n.subarray(C),a-=C,a)return;continue}if(n.length<512)return;let f=n.subarray(0,512);if(n=n.subarray(512),f.every(C=>C===0))continue;let h=(C,ne)=>f.toString("utf8",C,C+ne).replace(/\0.*$/s,""),m=parseInt(h(124,12).trim()||"0",8),g=h(156,1)||"0",y=(512-m%512)%512;if(g==="x"||g==="L"||g==="g"){for(;n.length<m+y;)return void(n=Buffer.concat([f,n]));let C=n.subarray(0,m).toString("utf8");if(n=n.subarray(m+y),g==="L")s=C.replace(/\0.*$/s,"");else if(g==="x")for(let ne of C.matchAll(/\d+ (\w+)=([^\n]*)\n/g))o[ne[1]]=ne[2];continue}let w=h(345,155),S=o.path??s??(w?`${w}/${h(0,100)}`:h(0,100));o={},s=null,S=S.replace(/^package\//,"");let k=(g==="0"||g==="\0")&&(S.startsWith("data/geo/")||S==="data-manifest.json"),I=ko.resolve(e,S);if(k&&ko.relative(e,I).startsWith(".."))throw new Error(`Refusing tar entry outside the target: ${S}`);if(!k){a=m+y;continue}if(hk(ko.dirname(I),{recursive:!0}),i={stream:uk(I),left:m,pad:y},m===0){let C=i.stream;i=null,await new Promise(ne=>C.end(()=>ne())),c++}}},d=dk(t).pipe(wM());for await(let p of d)await l(p);return c}async function $M(t,e){let r=JSON.parse(fM(e,"utf8")),n=0;for(let[s,o]of Object.entries(r.files??{})){let i=ko.join(t,"data","geo",o.path);if(!pk(i))throw new Error(`Geodata is incomplete: ${o.path} (${s}) is missing.`);let a=await kM(i);if(a!==o.sha256)throw new Error(`Geodata checksum mismatch for ${o.path}: expected ${o.sha256}, got ${a}. Nothing was installed.`);n++}return n}function EM(){let t=J(),r=[process.env.SUNDOWNREEL_GEODATA_MANIFEST,t&&ko.join(t,"engine-geo","data-manifest.json"),new URL("../../../engine-geo/data-manifest.json",import.meta.url).pathname].find(n=>!!n&&pk(n));if(!r)throw new Error("The geodata checksum manifest (engine-geo/data-manifest.json) is not in this install.");return r}async function fk(t=()=>{}){let e=_m(),r=e.target,n=`${r}.installing-${process.pid}`;Zl(n,{recursive:!0,force:!0}),hk(n,{recursive:!0});let s=ko.join(n,"geodata.tgz");try{let o=e.tarballUrl,i=null;if(!o){t(2,`Looking up ${Yl}@${e.version} on the npm registry.`);let m=await ak(e.metadataUrl,{headers:{accept:"application/json"},signal:AbortSignal.timeout(6e4)});if(!m.ok)throw new Error(`npm registry lookup for ${Yl}@${e.version} failed: HTTP ${m.status}`);let g=(await m.json()).dist;if(!g?.tarball||!g.integrity?.startsWith("sha512-"))throw new Error(`The registry returned no tarball/integrity for ${Yl}@${e.version}.`);o=g.tarball,i=g.integrity}t(4,`Downloading the geodata (~${e.sizeMb} MB) from ${new URL(o).host}.`);let a=await ak(o,{signal:AbortSignal.timeout(30*6e4)});if(!a.ok||!a.body)throw new Error(`Geodata download failed: HTTP ${a.status}`);let c=Number(a.headers.get("content-length")??0),l=lk("sha512"),d=0,p=new vm(m=>{l.update(m),d+=m.length,c&&t(4+Math.round(d/c*60),`Downloaded ${(d/1e6).toFixed(0)} of ${(c/1e6).toFixed(0)} MB.`)});if(await bM(gM.fromWeb(a.body),p,uk(s)),i&&`sha512-${l.digest("base64")}`!==i)throw new Error("The downloaded geodata does not match the registry's integrity hash. Nothing was installed.");t(66,"Unpacking.");let f=await xM(s,n);Zl(s,{force:!0}),t(85,"Verifying checksums.");let h=await $M(n,EM());return Zl(r,{recursive:!0,force:!0}),mM(n,r),t(99,"Installed."),{target:r,files:f,verified:h,bytes:d,source:i?"npm registry (integrity verified)":`${new URL(o).host} (checksums verified)`}}catch(o){throw Zl(n,{recursive:!0,force:!0}),o}}async function mk(){let t=await import("@puppeteer/browsers"),e;try{let n=await import("puppeteer-core");e=n.PUPPETEER_REVISIONS?.["chrome-headless-shell"]??n.PUPPETEER_REVISIONS?.chrome}catch{}let r=t.detectBrowserPlatform();if(!r)throw new Error(`No chrome-headless-shell build for this platform (${process.platform}/${process.arch}). Install Google Chrome or set RF3D_CHROME.`);return e||(e=await t.resolveBuildId(t.Browser.CHROMEHEADLESSSHELL,r,"stable")),{api:t,buildId:e}}async function gk(){let{api:t,buildId:e}=await mk(),r=t.detectBrowserPlatform(),n=t.getDownloadUrl(t.Browser.CHROMEHEADLESSSHELL,r,e);return{browser:"chrome-headless-shell",buildId:e,platform:r,url:n.toString(),cacheDir:Bc()}}async function yk(t=()=>{}){if(ck)return ck(t);let{api:e,buildId:r}=await mk(),n=e.detectBrowserPlatform();return t(3,`Downloading chrome-headless-shell ${r} for ${n}.`),{executablePath:(await e.install({browser:e.Browser.CHROMEHEADLESSSHELL,buildId:r,cacheDir:Bc(),platform:n,downloadProgressCallback:(o,i)=>{i&&t(3+Math.round(o/i*90),`Downloaded ${(o/1e6).toFixed(0)} of ${(i/1e6).toFixed(0)} MB.`)}})).executablePath}}var Yl,vM,_M,SM,ak,kM,vm,ck,bk=v(()=>{"use strict";pe();un();Yl="@sundownreel/mcp-geodata",vM="0.1.0",_M=()=>(process.env.SUNDOWNREEL_REGISTRY?.trim()||"https://registry.npmjs.org").replace(/\/$/,""),SM=null,ak=(t,e)=>(SM??fetch)(t,e);kM=t=>new Promise((e,r)=>{let n=lk("sha256");dk(t).on("data",s=>n.update(s)).on("error",r).on("end",()=>e(n.digest("hex")))});vm=class extends yM{constructor(r){super();this.tap=r}tap;_transform(r,n,s){this.tap(r),s(null,r)}},ck=null});function wk(t){let e=t.registerTool.bind(t);e("doctor",{title:"Doctor (setup check)",description:RM,inputSchema:{online:u.boolean().optional().describe("Also validate the licence with the licence server (one network call). Default false: signed offline cache only.")}},async r=>L({open:!0},()=>u0({online:r.online===!0}))),e("geodata_install",{title:"Download the map data",description:"Background job: download the open geodata the 4 map styles need (terra-relief, frontline, orbit-survey, fieldbook; ~116 MB, once) into the app state home, verified against the registry integrity hash and the published sha256 checksums. The npm package does not carry it so first start is instant. Call it when doctor, next_step or a render says the map data is missing, then poll job_status. dryRun: true only reports what would be downloaded. No licence needed.",inputSchema:{dryRun:u.boolean().optional(),force:u.boolean().optional().describe("Download again even if the data is already installed.")}},async r=>L({open:!0},async()=>{let n=_m(),s=ns();return r.dryRun===!0?{dryRun:!0,installed:!!s,source:s,plan:{...n,tarballUrl:n.tarballUrl??`resolved from ${n.metadataUrl}`}}:s&&r.force!==!0?{installed:!0,folder:s,note:"The geodata is already installed."}:{installed:!1,jobId:ft("geodata_install",void 0,async i=>({...await fk((a,c)=>Xe(i,a,c))})).id,poll:"Call job_status with jobId. About 116 MB; the map styles render once it succeeds."}})),e("browser_install",{title:"Download the 3D renderer's browser",description:"Background job: download chrome-headless-shell (~100 MB, once) into the app state home. The 3D styles (stagelit-stick, plinth-city, exploded-view, docket-3d, blockfolk) draw with it; skip this when Google Chrome, Chromium or Edge is already installed or RF3D_CHROME is set. Call it when doctor, next_step or a render says Chrome is missing, then poll job_status. dryRun: true only reports the revision and URL. No licence needed.",inputSchema:{dryRun:u.boolean().optional(),force:u.boolean().optional()}},async r=>L({open:!0},async()=>{let n=dn();return r.dryRun===!0?{dryRun:!0,installed:!!n,executablePath:n,plan:await gk()}:n&&r.force!==!0?{installed:!0,executablePath:n,note:"chrome-headless-shell is already installed."}:{installed:!1,jobId:ft("browser_install",void 0,async o=>({...await yk((i,a)=>Xe(o,i,a))})).id,poll:"Call job_status with jobId. About 100 MB; the 3D styles render once it succeeds."}}))}var RM,vk=v(()=>{"use strict";Ft();vn();un();bk();mr();Kc();RM='Setup check (every profile, no licence needed). Run it first in a new install, and whenever a tool says something is not installed or configured. Checks node \u2265 22, ffmpeg + ffprobe (FFMPEG_PATH honoured), free disk at the studio home, both homes writable, the studio .env (permissions + which allow-listed key NAMES are set; never values), licence (from the signed cache: no network unless online:true), operator mode, the gate approval key + sundownreel-gate CLI, the render backend per family (2D resvg, 3D + Chrome, map), the Shot DSL build, the style registry, the Python pipeline (qa_run, shotplan_make, package_make), the thumbnails CLI and the optional ElevenLabs key. Returns {summary, ready: {episodes, render, voAlign, qa, thumbnails}, checks: [{id, status: ok|warn|fail, detail, fix}], homes (studio vs app state home and the precedence rules), next: the single most important fix, or "call next_step"}. Show the user each fix verbatim; fixes that say "in your own terminal" (the gate key command) are for the human to type, never for Claude to run. Fast (< 2 s), no renders.'});import{randomBytes as IM,createHash as _k,timingSafeEqual as jM}from"node:crypto";import{createReadStream as Sk,existsSync as td,readdirSync as PM,readFileSync as Sm,realpathSync as Ql,statSync as rd}from"node:fs";import{createServer as OM}from"node:http";import rt from"node:path";function TM(t,e){let r=t.headers.host;if(r!==`127.0.0.1:${e}`&&r!==`localhost:${e}`)return{status:403,reason:"Host not allowed."};let n=t.headers.origin;if(n!==void 0&&n!==`http://127.0.0.1:${e}`&&n!==`http://localhost:${e}`)return{status:403,reason:"Cross-origin requests are not allowed."};if(t.method!=="GET"&&t.method!=="HEAD")return{status:405,reason:"Only GET and HEAD."};let s=new URL(t.url||"/",`http://127.0.0.1:${e}`);return NM(s.searchParams.get("t"))?null:{status:401,reason:"Missing or wrong preview token: open the exact URL the episode_open_preview (or open_preview) tool returned."}}function NM(t){if(!t)return!1;let e=_k("sha256").update(t).digest(),r=_k("sha256").update(ms).digest();return jM(e,r)}function Ek(t,e){let r=rt.relative(t,e);return r!==""&&!r.startsWith("..")&&!rt.isAbsolute(r)}function CM(t,e,r){if(!e||e.includes("\0")||e.includes("\\"))return null;let n=rt.posix.normalize(e);if(n.startsWith("/")||n.split("/").includes("..")||r&&!r.some(o=>o.test(n))||!$k[rt.extname(n).toLowerCase()])return null;let s=rt.join(t,n);if(!td(s))return null;try{let o=Ql(t),i=Ql(s);return!Ek(o,i)||!rd(i).isFile()?null:i}catch{return null}}function xk(t,e,r){let n=rd(r).size,o={"content-type":$k[rt.extname(r).toLowerCase()]??"application/octet-stream","accept-ranges":"bytes","cache-control":"no-store","x-content-type-options":"nosniff"},i=t.headers.range;if(i){let a=/^bytes=(\d*)-(\d*)$/.exec(i.trim()),c=a&&a[1]?Number(a[1]):NaN,l=a&&a[2]?Number(a[2]):NaN;if(a&&!a[1]&&a[2]?(c=Math.max(0,n-Number(a[2])),l=n-1):a&&a[1]&&!a[2]&&(l=n-1),!a||!Number.isFinite(c)||!Number.isFinite(l)||c>l||c>=n){e.writeHead(416,{...o,"content-range":`bytes */${n}`}),e.end();return}if(l=Math.min(l,n-1),e.writeHead(206,{...o,"content-range":`bytes ${c}-${l}/${n}`,"content-length":String(l-c+1)}),t.method==="HEAD")return void e.end();Sk(r,{start:c,end:l}).pipe(e);return}if(e.writeHead(200,{...o,"content-length":String(n)}),t.method==="HEAD")return void e.end();Sk(r).pipe(e)}function We(t){return t.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e]||e)}function Rk(t,e){return`<!doctype html>
|
|
232
|
+
<html lang="en">
|
|
233
|
+
<head>
|
|
234
|
+
<meta charset="utf-8"/>
|
|
235
|
+
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
|
236
|
+
<meta name="referrer" content="no-referrer"/>
|
|
237
|
+
<title>${We(t)}</title>
|
|
238
|
+
<style>${LM}</style>
|
|
239
|
+
</head>
|
|
240
|
+
<body>${e}</body>
|
|
241
|
+
</html>`}function DM(t){let e=Js(),r=Nc(),n=r[0];if(t)try{n=$e(t)}catch{n=r[0]}let s=`t=${encodeURIComponent(ms)}`,i=(n?.shots??[]).map(l=>{let p=n?.renders?.[l.id]??n?.renders?.[`preview:${l.id}`]?`<video controls preload="metadata" src="/media/${n?.id}/${encodeURIComponent(l.id)}.mp4?${s}"></video>`:`<div class="ph">Shot ${We(l.id)} is not rendered yet.</div>`;return`<article><h2>${We(l.id)}</h2><p>${We(l.text)}</p>${p}</article>`}).join(""),a=n?.exports?.length?n.exports.map(l=>`<video controls preload="metadata" src="/media/${n.id}/${encodeURIComponent(rt.basename(l.path))}?${s}"></video><p>${We(l.resolution)}</p>`).join(""):'<div class="ph">No export yet.</div>',c=r.map(l=>`<a href="/?project=${l.id}&${s}"${l.id===n?.id?' aria-current="page"':""}>${We(l.title)}</a>`).join("");return Rk(`${e.name} preview`,`<header><h1>${We(e.name)} preview</h1><p class="muted">Local review page. Films stay on this computer.</p></header>
|
|
242
|
+
<nav>${c||"<span>No projects yet.</span>"}</nav>
|
|
243
|
+
<main>
|
|
244
|
+
<section class="wide"><h2>Export</h2>${n?a:""}</section>
|
|
245
|
+
${i}
|
|
246
|
+
</main>`)}function MM(t,e){if(!/^p_[a-f0-9]{8}$/.test(t)||!/^[\w.-]+\.mp4$/.test(e))return null;let r;try{r=$e(t)}catch{return null}let n=Tr(t),s=e.replace(/\.mp4$/,""),o=r.renders?.[s]??r.renders?.[`preview:${s}`],i=r.exports?.find(c=>rt.basename(c.path)===e),a=o?.path??i?.path??rt.join(n,"renders",e);if(!td(a))return null;try{let c=Ql(a);return Ek(Ql(n),c)&&rd(c).isFile()?c:null}catch{return null}}function Ji(t,e,r,n=3){let s=[],o=(i,a)=>{let c=rt.join(t,i);if(!(!td(c)||a<0))for(let l of PM(c)){let d=i?`${i}/${l}`:l,p;try{p=rd(rt.join(t,d))}catch{continue}p.isDirectory()?o(d,a-1):r.test(l)&&s.push({rel:d,mtime:p.mtimeMs,bytes:p.size})}};return o(e,n),s.sort((i,a)=>a.mtime-i.mtime)}function FM(t){let e=N(t),r=`t=${encodeURIComponent(ms)}`,n=m=>`/ep/${encodeURIComponent(t)}/f/${m.split("/").map(encodeURIComponent).join("/")}?${r}`,s=(()=>{try{return JSON.parse(Sm(rt.join(e,"episode.json"),"utf8"))}catch{return{}}})(),o=Ji(e,"08-render",/^(final|animatic)\.mp4$/),i=Ji(e,"08-render/review",/\.jpe?g$/,0).slice(0,12),a=[...Ji(e,"08-render/stills",/\.png$/,0),...Ji(e,"08-render/stills/cache",/\.jpe?g$/,1)].sort((m,g)=>g.mtime-m.mtime).slice(0,48),c=td(rt.join(e,"12-package"))?"12-package":"08-package",l=Ji(e,c,/^(thumb.*|contact)\.(png|jpe?g|webp)$/,1).sort((m,g)=>m.rel.localeCompare(g.rel)),d=(()=>{try{return Sm(rt.join(e,c,"description.md"),"utf8").slice(0,2e4)}catch{return null}})(),p=(()=>{try{return JSON.parse(Sm(rt.join(e,"07-shots/review.json"),"utf8"))}catch{return null}})(),f=(m,g)=>`<figure>${g==="img"?`<img loading="lazy" src="${n(m.rel)}" alt="${We(m.rel)}"/>`:`<video controls preload="metadata" src="${n(m.rel)}"></video>`}<figcaption>${We(m.rel)} \xB7 ${(m.bytes/1024).toFixed(0)} KB</figcaption></figure>`,h=(m,g,y=!0)=>`<section${y?' class="wide"':""}><h2>${We(m)}</h2>${g}</section>`;return Rk(`${s.title??t} \xB7 preview`,`<header><h1>${We(s.title??t)}</h1><p class="muted">${We(t)}${s.style?` \xB7 style ${We(s.style)}`:""} \xB7 local preview, nothing leaves this computer. Reload after new renders.</p></header>
|
|
247
|
+
<main>
|
|
248
|
+
${h("Videos",o.length?`<div class="grid">${o.map(m=>f(m,"video")).join("")}</div>`:'<div class="ph">No animatic or final yet (render_animatic, render_final).</div>')}
|
|
249
|
+
${h("Review sheets",(p?`<p class="muted">Last review ${We(p.range??"")} at ${We(p.at??"")}: ${(p.issues??[]).length} issue line(s).</p>`:"")+(i.length?`<div class="grid">${i.map(m=>f(m,"img")).join("")}</div>`:'<div class="ph">No review sheet yet (review_shots).</div>'))}
|
|
250
|
+
${h("Stills",a.length?`<div class="grid">${a.map(m=>f(m,"img")).join("")}</div>`:'<div class="ph">No stills yet (render_still).</div>')}
|
|
251
|
+
${h("Thumbnails",l.length?`<div class="grid">${l.map(m=>f(m,"img")).join("")}</div>`:'<div class="ph">No thumbnails yet (thumbnail_make).</div>')}
|
|
252
|
+
${h("Package description",d?`<pre>${We(d)}</pre>`:'<div class="ph">No package yet (package_make).</div>')}
|
|
253
|
+
</main>`)}function fs(t,e,r){t.writeHead(e,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store","x-content-type-options":"nosniff"}),t.end(r)}function qM(t,e){let r=Wi,n=TM(t,r);if(n)return fs(e,n.status,n.reason);e.setHeader("referrer-policy","no-referrer"),e.setHeader("x-frame-options","DENY"),e.setHeader("content-security-policy","default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'; frame-ancestors 'none'");let s=new URL(t.url||"/",`http://127.0.0.1:${r}`),o=s.pathname.split("/").filter(Boolean).map(i=>{try{return decodeURIComponent(i)}catch{return"\0"}});try{if(o[0]==="media"&&o.length===3){let i=MM(o[1],o[2]);return i?xk(t,e,i):fs(e,404,"Not found.")}if(o[0]==="ep"&&o[1]){let i;try{i=N(o[1])}catch{return fs(e,404,"Unknown episode.")}if(o.length===2)return e.writeHead(200,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),void e.end(t.method==="HEAD"?void 0:FM(o[1]));if(o[2]==="f"&&o.length>3){let a=CM(i,o.slice(3).join("/"),AM);return a?xk(t,e,a):fs(e,404,"Not found.")}return fs(e,404,"Not found.")}return o.length===0?(e.writeHead(200,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),void e.end(t.method==="HEAD"?void 0:DM(s.searchParams.get("project")))):fs(e,404,"Not found.")}catch(i){return fs(e,500,i instanceof Error?i.message:String(i))}}function kk(t,e){return new Promise((r,n)=>{let s=i=>{t.off("listening",o),n(i)},o=()=>{t.off("error",s);let i=t.address();r(typeof i=="object"&&i?i.port:e)};t.once("error",s),t.once("listening",o),t.listen(e,"127.0.0.1")})}async function Ik(){if(ed?.listening)return{port:Wi,token:ms,origin:`http://127.0.0.1:${Wi}`};Xl||(Xl=(async()=>{let e=Number(process.env.SUNDOWNREEL_PREVIEW_PORT??47321),r=OM(qM),n;try{n=await kk(r,Number.isInteger(e)&&e>=0?e:47321)}catch(s){if(s.code!=="EADDRINUSE")throw s;n=await kk(r,0)}return r.unref(),ed=r,Wi=n,n})().finally(()=>{Xl=null}));let t=await Xl;return{port:t,token:ms,origin:`http://127.0.0.1:${t}`}}function GM(){return`http://127.0.0.1:${Wi||Number(process.env.SUNDOWNREEL_PREVIEW_PORT||47321)}/?t=${encodeURIComponent(ms)}`}async function jk(){let t=!!ed?.listening;return await Ik(),{url:GM(),alreadyRunning:t}}async function Pk(t){N(t);let e=!!ed?.listening,{port:r}=await Ik();return{url:`http://127.0.0.1:${r}/ep/${encodeURIComponent(t)}?t=${encodeURIComponent(ms)}`,port:r,alreadyRunning:e}}var ed,Wi,Xl,ms,$k,AM,LM,xm=v(()=>{"use strict";Pc();Pe();Ys();ed=null,Wi=0,Xl=null,ms=IM(24).toString("base64url");$k={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".mp4":"video/mp4",".wav":"audio/wav",".json":"application/json; charset=utf-8",".md":"text/plain; charset=utf-8",".txt":"text/plain; charset=utf-8"},AM=[/^07-shots\/review\.json$/,/^08-render\//,/^09-qa\//,/^12-package\//,/^08-package\//,/^06-vo\/vo\.wav$/];LM=`
|
|
254
|
+
:root { color-scheme: light dark; --bg: #f3ecdf; --fg: #1c1915; --card: #fff; --line: rgba(28,25,21,0.14); --accent: #8d3f16; }
|
|
255
|
+
@media (prefers-color-scheme: dark) { :root { --bg: #16130f; --fg: #f3ecdf; --card: #221d17; --line: rgba(243,236,223,0.16); --accent: #e08a55; } }
|
|
256
|
+
* { box-sizing: border-box; }
|
|
257
|
+
body { margin: 0; font-family: system-ui, -apple-system, "Segoe UI", sans-serif; background: var(--bg); color: var(--fg); }
|
|
258
|
+
header { padding: 24px 16px 8px; max-width: 1200px; margin: 0 auto; }
|
|
259
|
+
h1 { font-weight: 600; margin: 0 0 6px; font-size: 1.5rem; }
|
|
260
|
+
h2 { font-size: 1.05rem; margin: 0 0 10px; }
|
|
261
|
+
nav { display: flex; gap: 12px; flex-wrap: wrap; padding: 0 16px 16px; max-width: 1200px; margin: 0 auto; }
|
|
262
|
+
a { color: var(--accent); }
|
|
263
|
+
main { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr)); gap: 16px; padding: 8px 16px 48px; max-width: 1200px; margin: 0 auto; }
|
|
264
|
+
section, article { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: 12px; min-width: 0; }
|
|
265
|
+
.wide { grid-column: 1 / -1; }
|
|
266
|
+
img, video { width: 100%; height: auto; display: block; background: #1c1915; border-radius: 4px; }
|
|
267
|
+
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 220px), 1fr)); gap: 10px; }
|
|
268
|
+
figure { margin: 0; } figcaption { font-size: 0.8rem; opacity: 0.75; margin-top: 4px; word-break: break-all; }
|
|
269
|
+
pre { white-space: pre-wrap; word-break: break-word; font-size: 0.85rem; max-height: 480px; overflow: auto; margin: 0; }
|
|
270
|
+
.ph { min-height: 80px; display: grid; place-items: center; border: 1px dashed var(--accent); color: var(--accent); text-align: center; padding: 12px; border-radius: 6px; }
|
|
271
|
+
.muted { opacity: 0.7; font-size: 0.9rem; }`});import{spawn as UM}from"node:child_process";import{existsSync as nd,mkdirSync as $m,readFileSync as VM,renameSync as Em,rmSync as Ok,statSync as Tk,statfsSync as zM}from"node:fs";import rr from"node:path";function Nk(t){let e=process.env[t==="ffmpeg"?"FFMPEG_PATH":"FFPROBE_PATH"];if(e&&nd(e))return e;if(t==="ffprobe"&&process.env.FFMPEG_PATH){let r=rr.join(rr.dirname(process.env.FFMPEG_PATH),"ffprobe");if(nd(r))return r}for(let r of[...(process.env.PATH??"").split(rr.delimiter).filter(Boolean),...HM]){let n=rr.join(r,t);if(nd(n))return n}return null}function sd(t){let e=Nk(t);if(!e)throw new km(`${t} was not found. Fix: install it (macOS: \`brew install ffmpeg\`; Linux: your package manager), or set ${t==="ffmpeg"?"FFMPEG_PATH":"FFPROBE_PATH"} to the binary, then run doctor.`);return e}function Ki(t,e,r={}){return new Promise((n,s)=>{let o=UM(t,e,{stdio:["ignore","pipe","pipe"],env:Rm(),...r.signal?{signal:r.signal}:{}}),i="",a="",c=setTimeout(()=>o.kill("SIGKILL"),r.timeoutMs??12e4);o.stdout.on("data",l=>{i+=l.toString(),i.length>2e5&&(i=i.slice(-2e5))}),o.stderr.on("data",l=>{a+=l.toString(),a.length>2e4&&(a=a.slice(-2e4))}),o.on("error",l=>{clearTimeout(c),s(l)}),o.on("close",(l,d)=>{if(clearTimeout(c),l===0)return n({stdout:i,stderr:a});let p=a.trim().split(/\r?\n/).slice(-6).join(`
|
|
272
|
+
`);s(new Error(`${rr.basename(t)} failed (${d??`exit ${l}`}): ${p}`))})})}function Rm(){let t=["PATH","HOME","TMPDIR","LANG","LC_ALL","REELFORGE_HOME","SUNDOWNREEL_STUDIO","FFMPEG_PATH"],e={};for(let r of t)process.env[r]&&(e[r]=process.env[r]);return e}function BM(t){try{let e=zM(t);return Number(e.bavail)*Number(e.bsize)}catch{return null}}function gs(t,e=0){let r=Number(process.env.REELFORGE_MIN_FREE_GB??"1.5"),n=BM(t);if(n===null)return;let s=r*1024**3+e;if(n<s)throw new Error(`Refused: only ${(n/1024**3).toFixed(2)} GB free on the disk holding ${t}; this needs ${(s/1024**3).toFixed(1)} GB. Free space first (old 08-render/<run> folders are the biggest), then retry.`)}async function od(t,e,r={}){let n=sd("ffmpeg"),s=r.maxWidth??960,o=r.targetBytes??15e4;$m(rr.dirname(e),{recursive:!0});let i=`${e}.tmp-${process.pid}.jpg`,a=0;for(let c of[4,7,11,16,24])if(await Ki(n,["-hide_banner","-loglevel","error","-y","-i",t,"-vf",`scale='min(${s},iw)':-2:flags=lanczos`,"-frames:v","1","-q:v",String(c),i],{timeoutMs:6e4}),a=Tk(i).size,a<=o)break;return Em(i,e),{path:e,bytes:a}}async function JM(){if($o!==null)return $o;let t=Eo();if(!t)return $o=!1;try{let{stdout:e}=await Ki(t,["-hide_banner","-filters"],{timeoutMs:15e3});$o=/\sdrawtext\s/.test(e)}catch{$o=!1}return $o}function WM(){for(let t of["engine-resvg/fonts/ArchivoBlack.ttf","engine/fonts/ArchivoBlack.ttf"]){let e=rr.join(Se(),t);if(nd(e))return e}return null}async function Ak(t,e,r,n={}){if(!t.length)throw new Error("contactSheet: no images.");let s=sd("ffmpeg"),o=t.length,i=o===1?1:o<=4?2:o<=9?3:4,a=Math.ceil(o/i),c=n.maxWidth??1536,l=Math.min(o===1?960:480,Math.floor(c/i/2)*2),d=Math.round(l*9/16/2)*2,p=WM(),f=p&&await JM(),h=[];t.forEach((w,S)=>{let $=`[${S}:v]scale=${l}:${d}:force_original_aspect_ratio=decrease:flags=lanczos,pad=${l}:${d}:(ow-iw)/2:(oh-ih)/2:color=0x1c1915,setsar=1,format=yuv420p`;if(f){let k=(e[S]??String(S+1)).replace(/[^A-Za-z0-9 ._#-]/g,"").slice(0,40),I=p.replace(/\\/g,"/").replace(/:/g,"\\:").replace(/'/g,"");$+=`,drawtext=fontfile='${I}':text='${k}':x=8:y=8:fontsize=${Math.max(14,Math.round(d/11))}:fontcolor=white:box=1:boxcolor=black@0.65:boxborderw=6`}h.push(`${$}[t${S}]`)}),h.push(`${t.map((w,S)=>`[t${S}]`).join("")}concat=n=${o}:v=1:a=0,tile=${i}x${a}:padding=4:color=0x1c1915[out]`),$m(rr.dirname(r),{recursive:!0});let m=`${r}.tmp-${process.pid}.jpg`,g=n.targetBytes??45e4,y=0;for(let w of[4,7,11,16])if(await Ki(s,["-hide_banner","-loglevel","error","-y",...t.flatMap(S=>["-i",S]),"-filter_complex",h.join(";"),"-map","[out]","-frames:v","1","-q:v",String(w),m],{timeoutMs:12e4}),y=Tk(m).size,y<=g)break;return Em(m,r),{path:r,bytes:y,cols:i,rows:a,tileWidth:l,labels:!!f}}function Ck(t){let e=VM(t);return Ok(t,{force:!0}),e}async function Im(t){let e=sd("ffprobe"),{stdout:r}=await Ki(e,["-v","error","-show_entries","format=duration:stream=codec_type,codec_name,sample_rate,channels","-of","json",t],{timeoutMs:6e4}),n=JSON.parse(r),s=(n.streams??[]).find(i=>i.codec_type==="audio");if(!s)throw new Error(`${rr.basename(t)} has no audio stream. Fix: export the recording as wav, mp3, m4a, aiff or flac.`);let o=Number(n.format?.duration);if(!Number.isFinite(o))throw new Error(`ffprobe could not read the duration of ${rr.basename(t)}. Fix: re-export the recording.`);return{duration:o,codec:s.codec_name??null,sampleRate:s.sample_rate?Number(s.sample_rate):null,channels:s.channels??null}}async function Lk(t,e,r={}){let n=sd("ffmpeg");$m(rr.dirname(e),{recursive:!0});let s=`${e}.tmp-${process.pid}.wav`;try{await Ki(n,["-hide_banner","-loglevel","error","-y","-i",t,"-vn","-map_metadata","-1","-ac","1","-ar","48000","-c:a","pcm_s16le",s],{timeoutMs:r.timeoutMs??30*6e4,...r.signal?{signal:r.signal}:{}}),Em(s,e)}finally{Ok(s,{force:!0})}}var HM,Eo,km,$o,id=v(()=>{"use strict";pe();HM=["/opt/homebrew/bin","/usr/local/bin","/usr/bin"];Eo=()=>Nk("ffmpeg"),km=class extends Error{};$o=null});import{spawn as KM}from"node:child_process";import{existsSync as Me,readdirSync as ad,readFileSync as Om,statSync as cd}from"node:fs";import ZM from"node:os";import ie from"node:path";function jm(t,e=YM){if(!Me(t))return null;let r=Om(t,"utf8");return r.length>e?`${r.slice(0,e)}
|
|
273
|
+
\u2026 (${r.length-e} more characters)`:r}function ys(t){if(!Me(t))return null;try{return JSON.parse(Om(t,"utf8"))}catch(e){return{error:`not valid JSON: ${e instanceof Error?e.message:String(e)}`}}}function XM(t,e){let r=ie.join(t,"08-render");return Me(r)?ad(r).map(s=>ie.join(r,s,e)).filter(s=>Me(s)).sort((s,o)=>cd(o).mtimeMs-cd(s).mtimeMs)[0]??null:null}async function Fk(t,e,r,n){if(Eo()){let s=ie.join(ZM.tmpdir(),`sundownreel-img-${process.pid}-${Date.now()}.jpg`);return await od(t,s,{maxWidth:r,targetBytes:n}),{data:Ck(s),mimeType:"image/jpeg",caption:e}}return cd(t).size<=15e5?{data:Om(t),mimeType:t.endsWith(".png")?"image/png":"image/jpeg",caption:e}:null}function QM(t){let e=ie.join(t,"09-qa"),r=Me(e)?ad(e).filter(n=>Me(ie.join(e,n,"qa.json"))).sort():[];if(r.length){let n=r[r.length-1];return{status:"ran",run:n,report:`09-qa/${n}/qa.md`}}return{status:"QA not run",...ro()?{note:"Run qa_run before Gate 4."}:{note:xi}}}async function qk(t){let e=N(t),r=Me(ie.join(e,"12-package"))?ie.join(e,"12-package"):ie.join(e,"08-package"),n=Dk(e,r),s=jm(ie.join(r,"description.md")),o=ys(ie.join(r,"meta.json")),i=ys(ie.join(e,"04-script","meta.json")),a=["titles.json","titles.md","titles.txt"].map(k=>ie.join(r,k)).find(k=>Me(k)),c=["chapters.txt","chapters.md"].map(k=>ie.join(r,k)).find(k=>Me(k)),l=ie.join(r,"thumbs"),d=ys(ie.join(l,"thumbs.json")),p=ys(ie.join(r,"thumbs.json")),f=Me(l)?ad(l).filter(k=>/^thumb.*\.(png|jpe?g|webp)$/i.test(k)).sort():[],h=Me(r)?ad(r).filter(k=>/^thumb.*\.(png|jpe?g|webp)$/i.test(k)).sort():[],m=XM(e,"final.mp4");if(!s&&!o&&!f.length&&!h.length)throw new Error(`${t} has no package yet. Fix: run package_make {episodeId: "${t}"}, then thumbnail_make, then package_get.`);let g={episode:t,folder:n,title:o?.title??i?.title??null,titles:a?a.endsWith(".json")?ys(a):jm(a,4e3):i?.titles??null,chapters:c?jm(c,6e3):o?.chapters??i?.chapters??null,description:s,meta:o,manifest:ys(ie.join(r,"package.json")),thumbnails:{files:[...f.map(k=>`${n}/thumbs/${k}`),...h.map(k=>`${n}/${k}`)],thumbs:d,...p?{overrides:p}:{},contactSheet:Me(ie.join(l,"contact.png"))?`${n}/thumbs/contact.png`:null},final:m?{path:Dk(e,m),bytes:cd(m).size}:null,qa:QM(e),gate4:"Only the human approves Gate 4 (in their own terminal) and uploads by hand. No tool uploads, publishes or schedules.",next:{tool:"episode_open_preview",args:{episodeId:t},why:"Open the local preview page to watch the final and see every thumbnail full size."}},y=[],w=ie.join(l,"contact.png"),S=f[0]?ie.join(l,f[0]):h[0]?ie.join(r,h[0]):null,$=Me(w)?w:S;if($){let k=await Fk($,Me(w)?"Thumbnail contact sheet":`Thumbnail ${ie.basename($)}`,1280,3e5);k&&y.push(k)}return y.length?cs(g,y):g}function eF(){let t=process.env.SUNDOWNREEL_THUMBNAILS_CLI;if(t){if(!Me(t))throw new Error(`SUNDOWNREEL_THUMBNAILS_CLI=${t} does not exist. Fix: point it at thumbnails/dist/make.mjs or unset it.`);return ie.resolve(t)}let e=Se(),r=ie.join(e,"thumbnails","dist","make.mjs");if(!Me(r))throw new Error(`The thumbnail maker is not built (${r} is missing). Fix: run \`node thumbnails/build.mjs\` in ${e}, then retry thumbnail_make.`);return r}function tF(t,e,r){return new Promise((n,s)=>{let o=KM(process.execPath,[t,...e],{env:Rm(),stdio:["ignore","pipe","pipe"],signal:r}),i="",a="",c=setTimeout(()=>o.kill("SIGKILL"),10*6e4);o.stdout.on("data",l=>i+=l.toString()),o.stderr.on("data",l=>a+=l.toString()),o.on("error",l=>{clearTimeout(c),s(l)}),o.on("close",(l,d)=>{if(clearTimeout(c),l===0)return n({stdout:i,stderr:a});let p=(a.trim()||i.trim()).replace(/^thumbnails:\s*/gm,"");if(l===1){s(new Pm(`The thumbnail headline breaks a rule: ${p.split(/\r?\n/).slice(-6).join(" ")}. Fix: thumbnail text is at most 3 words in total and every number needs a verified/computed fact (scenario only in hypothetical episodes). Edit the variants in 12-package/thumbs.json ({variants: [{template, text: ["\u2026"]}]}; templates: reaction, versus, number, object) or fix the facts, then run thumbnail_make again.`));return}s(new Error(`thumbnail maker failed (${d??`exit ${l}`}): ${p.split(/\r?\n/).slice(-6).join(`
|
|
274
|
+
`)}`))})})}function Mk(t){let e=ie.join(t,"12-package","thumbs");return{folder:"12-package/thumbs",variants:(ys(ie.join(e,"thumbs.json"))?.variants??[]).map((n,s)=>({n:s+1,file:n.file?`12-package/thumbs/${n.file}`:null,template:n.template,text:n.text})),contactSheet:Me(ie.join(e,"contact.png"))?"12-package/thumbs/contact.png":null}}async function Gk(t,e={}){let r=N(t),n=eF();gs(r);let s=Math.max(1,Math.min(12,Math.round(e.variants??4))),o,i=new Promise(m=>o=m),a=ft("thumbnail_make",void 0,async(m,g)=>{try{return await tF(n,[r,"--variants",String(s)],g.signal),o({ok:!0}),{episode:t,...Mk(r)}}catch(y){throw o({ok:!1,error:y}),y}},{episodeId:t,lane:"light"}),c=e.waitMs??Number(process.env.SUNDOWNREEL_THUMBNAIL_WAIT_MS??45e3),l,d=await Promise.race([i,new Promise(m=>l=setTimeout(()=>m(null),c))]);if(clearTimeout(l),!d)return{episode:t,jobId:a.id,status:"running",poll:"Call job_status with jobId, then package_get to see the thumbnails."};if(!d.ok)throw d.error;let p={episode:t,jobId:a.id,...Mk(r),next:{tool:"package_get",args:{episodeId:t},why:"Show the whole package (description, chapters, thumbnails) for the human's Gate 4 review."},note:"Pick the strongest variant with the human; edit 12-package/thumbs.json to change text or template and run thumbnail_make again."},f=ie.join(r,"12-package","thumbs","contact.png"),h=Me(f)?await Fk(f,"Thumbnail contact sheet",1280,3e5):null;return h?cs(p,[h]):p}var YM,Dk,Pm,Uk=v(()=>{"use strict";Pe();mr();wo();pe();no();id();YM=2e4;Dk=(t,e)=>ie.relative(t,e).split(ie.sep).join("/");Pm=class extends Error{}});import{existsSync as Zi,mkdirSync as rF,readdirSync as nF,readFileSync as ld,renameSync as sF,rmSync as oF,statSync as dd,writeFileSync as iF}from"node:fs";import yt from"node:path";function Jk(t){return JSON.parse(ld(t,"utf8"))}function cF(t,e,r){let n=t.len/e,s=Math.min(Math.max(r??n/2,0),Math.max(0,n-1/e));return{t:s,frame:t.from+Math.round(s*e)}}function lF(t,e,r){let n=t.len/e;return r==="start"?Math.min(.1,n/4):r==="end"?Math.max(0,n-1/e):n/2}function Hk(t,e,r,n,s){return yt.join(t,"08-render","stills","cache",e.slice(0,16),`${r}-f${String(n).padStart(6,"0")}-s${s}.jpg`)}async function Wk(t){let e=N(t),r=await kl(t,{maxLines:2e3});if(!r.compiled||!Zi(yt.join(e,zk))||!Zi(yt.join(e,Vk)))throw new wn(`Refused: 07-shots/shots.json does not validate (${r.summary}), so nothing can be rendered.`,{lines:r.lines.slice(0,60),next:{tool:"shots_patch",args:{episodeId:t},why:"Fix the listed lines, then review again."}});let n=Jk(yt.join(e,zk));return{dir:e,timeline:n,sha:Oe(yt.join(e,Vk)),lines:r.lines}}async function Kk(t,e,r,n,s,o,i,a){let c=cF(n,s,o),l=Hk(e,r,n.id,c.frame,i);if(Zi(l))return{shotId:n.id,frame:c.frame,t:c.t,jpeg:l,bytes:dd(l).size,cached:!0};gs(e);let d=await em(t,n.id,c.t,i),p=Hk(e,r,n.id,d.frame,i),f;try{f=await od(d.path,p,{maxWidth:960,targetBytes:15e4})}catch(h){throw new ud(`The still rendered but could not be turned into a JPEG: ${h instanceof Error?h.message:String(h)}`,d)}finally{a||oF(d.path,{force:!0})}return{shotId:n.id,frame:d.frame,t:d.t,jpeg:f.path,bytes:f.bytes,cached:!1,...a?{png:d.path}:{}}}async function Zk(t,e,r,n){if(!aF.test(e))throw new Error(`Shot ids look like S001 or S014a (got "${e}").`);let s=n??.5;if(!Eo()){let p=await em(t,e,r,s),f=N(t),h=dd(p.path).size,m={...p,path:Ro(f,p.path),image:null,note:"ffmpeg was not found, so no small JPEG was made (doctor explains how to install it)."};return h<=15e5?cs({...m,image:{mimeType:"image/png",bytes:h}},[{data:ld(p.path),mimeType:"image/png"}]):m}let{dir:o,timeline:i,sha:a}=await Wk(t),c=i.shots.find(p=>p.id===e);if(!c)throw new Error(`Shot ${e} is not in ${t}. Call shots_get {episodeId: "${t}"} for the shot ids.`);let l;try{l=await Kk(t,o,a,c,i.fps,r,s,!0)}catch(p){if(!(p instanceof ud))throw p;return{episode:t,shotId:e,t:Number(p.still.t.toFixed(3)),frame:p.still.frame,scale:s,kind:c.kind,validatedSha:a,path:Ro(o,p.still.path),image:null,note:p.message}}let d={episode:t,shotId:e,t:Number(l.t.toFixed(3)),frame:l.frame,scale:s,kind:c.kind,...c.vo?{vo:c.vo}:{},style:c.style??i.style,validatedSha:a,cached:l.cached,...l.png?{path:Ro(o,l.png)}:{},image:{path:Ro(o,l.jpeg),mimeType:"image/jpeg",bytes:l.bytes},next:{tool:"review_shots",args:{episodeId:t,range:e},why:"Look at a whole chapter at once; fix issues with shots_patch."}};return cs(d,[{data:ld(l.jpeg),mimeType:"image/jpeg",caption:`${t} ${e} frame ${l.frame}`}])}function dF(t,e,r){let n,s=[];if(e.range){let o=/^(S\d{3}[a-z]?)(?:\.\.(S\d{3}[a-z]?))?$/.exec(e.range);if(!o)throw new Error(`range "${e.range}" must look like S010..S020 (or one shot id).`);let i=t.findIndex(c=>c.id===o[1]),a=t.findIndex(c=>c.id===(o[2]??o[1]));if(i<0||a<0)throw new Error(`range ${e.range}: ${i<0?o[1]:o[2]} is not in the episode. Call shots_get for the ids.`);n=t.slice(Math.min(i,a),Math.max(i,a)+1)}else if(e.shotIds?.length){let o=new Set(e.shotIds);n=t.filter(i=>o.has(i.id));for(let i of o)n.some(a=>a.id===i)||s.push(i)}else n=t;return{picked:n.slice(0,r),missing:s,truncated:Math.max(0,n.length-r)}}function uF(t){return t?[t.kind,t.head,t.sub,Array.isArray(t.items)?t.items.join(" / "):void 0].filter(r=>typeof r=="string"&&r).join(" \xB7 ").slice(0,240)||JSON.stringify(t).slice(0,240):void 0}function pF(t){let e=yt.join(t,"09-qa");if(!Zi(e))return null;let r=nF(e).map(n=>yt.join(e,n,"qa.json")).filter(n=>Zi(n)).sort((n,s)=>dd(s).mtimeMs-dd(n).mtimeMs);if(!r.length)return null;try{let s=(Jk(r[0]).checks??[]).filter(o=>o.result&&o.result!=="PASS").map(o=>`${o.result} ${o.check??o.id??"?"}: ${typeof o.value=="string"?o.value:JSON.stringify(o.value)}${o.note?` (${o.note})`:""}`);return{run:Ro(t,yt.dirname(r[0])),rows:s}}catch{return null}}async function Yk(t,e={}){let r=N(t);if(gs(r),!Eo())throw new Error("review_shots needs ffmpeg to make the contact sheet. Fix: install ffmpeg (macOS: `brew install ffmpeg`) or set FFMPEG_PATH, then run doctor.");let n=Math.min(bs,Math.max(1,e.max??bs)),s=e.at??"mid",o=e.scale??.5,{timeline:i,sha:a,lines:c}=await Wk(t),{picked:l,missing:d,truncated:p}=dF(i.shots,e,n);if(!l.length)throw new Error(`No shots matched in ${t}${d.length?` (unknown: ${d.join(", ")})`:""}. Call shots_get for the ids.`);let f=[],h=[];for(let b of l)try{f.push(await Kk(t,r,a,b,i.fps,lF(b,i.fps,s),o,!1))}catch(H){let se=H instanceof Error?H.message:String(H);if(/^Refused: only .* GB free/.test(se))throw H;h.push({shotId:b.id,error:se.split(`
|
|
275
|
+
`).slice(0,3).join(" ").slice(0,400)})}if(!f.length)throw new wn(`Refused: none of the ${l.length} shot(s) rendered, so there is nothing to look at.`,{failures:h,next:{tool:"render_still",args:{episodeId:t,shotId:l[0].id},why:"Render one shot to see the full renderer error."}});let m=f[0].shotId,g=f[f.length-1].shotId,y=yt.join(r,"08-render","review",`sheet-${a.slice(0,12)}-${m}-${g}-${s}.jpg`),w=await Ak(f.map(b=>b.jpeg),f.map((b,H)=>`${H+1} ${b.shotId}`),y),S=pF(r),$=new Map(i.shots.map(b=>[b.id,b])),k=l.map(b=>{let H=f.find(xr=>xr.shotId===b.id),se=h.find(xr=>xr.shotId===b.id),wt=c.filter(xr=>Bk(xr,b.id)),_n=S?S.rows.filter(xr=>Bk(xr,b.id)):[];return{shotId:b.id,...H?{tile:f.indexOf(H)+1,frame:H.frame,t:Number(H.t.toFixed(3)),cached:H.cached}:{tile:null,error:se?.error},kind:$.get(b.id)?.kind,dur:Number((b.len/i.fps).toFixed(2)),...b.vo?{vo:b.vo}:{},...b.beat?{beat:uF(b.beat)}:{},...b.style&&b.style!==i.style?{style:b.style}:{},...wt.length?{validator:wt}:{},..._n.length?{qa:_n}:{}}}),I=[...k.flatMap(b=>b.validator??[]),...k.flatMap(b=>(b.qa??[]).map(H=>`${b.shotId} QA ${H}`)),...h.map(b=>`${b.shotId} render failed: ${b.error}`)],C={at:new Date().toISOString(),validatedSha:a,frameAt:s,range:`${m}..${g}`,sheet:Ro(r,w.path),shots:k.map(b=>({shotId:b.shotId,tile:b.tile,frame:"frame"in b?b.frame:null})),issues:I};rF(yt.join(r,"07-shots"),{recursive:!0});let ne=yt.join(r,`${Tm}.tmp-${process.pid}`);iF(ne,`${JSON.stringify(C,null,1)}
|
|
276
|
+
`),sF(ne,yt.join(r,Tm));let xe=f.map((b,H)=>`${H+1}=${b.shotId}`).join(" "),ue={episode:t,validatedSha:a,frameAt:s,sheet:{path:C.sheet,bytes:w.bytes,grid:`${w.cols}x${w.rows}`,labels:w.labels,order:`row-major, left to right: ${xe}`},shots:k,...h.length?{skipped:h}:{},...d.length?{unknownShotIds:d}:{},...p?{more:`${p} more shot(s) in this selection; review them in another call (max ${n} per sheet).`}:{},issues:I.length,wrote:[Tm,C.sheet],next:I.length?{tool:"shots_patch",args:{episodeId:t},why:"Fix what the sheet and the issue lines show, then shots_compile and review again."}:{tool:"next_step",args:{episodeId:t},why:"If the sheet looks right, continue (next_step names the step: usually render_animatic)."},lookFor:"Check each tile: characters inside the frame and not cut by the edge, text readable and not overlapping, numbers match the VO, the beat lands, camera not inside props, continuity with the neighbour shots."};return cs(ue,[{data:ld(w.path),mimeType:"image/jpeg",caption:`Contact sheet ${m}..${g} (${xe})`}])}var Vk,zk,Tm,bs,aF,Ro,ud,Bk,Xk=v(()=>{"use strict";Pe();er();Ui();wo();id();Vk="07-shots/shots.validated.json",zk="07-shots/shots.compiled.json",Tm="07-shots/review.json",bs=16,aF=/^S\d{3}[a-z]?$/,Ro=(t,e)=>yt.relative(t,e).split(yt.sep).join("/");ud=class extends Error{constructor(r,n){super(r);this.still=n}still};Bk=(t,e)=>new RegExp(`(^|[^A-Za-z0-9])${e}([^0-9a-z]|$)`).test(t)});import{createHash as hF}from"node:crypto";import{accessSync as fF,constants as mF,copyFileSync as gF,createReadStream as yF,existsSync as Nm,lstatSync as bF,mkdirSync as wF,readdirSync as vF,rmSync as _F,statSync as SF,writeFileSync as xF}from"node:fs";import bt from"node:path";function $F(t){return new Promise((e,r)=>{let n=hF("sha256");yF(t).on("data",s=>n.update(s)).on("error",r).on("end",()=>e(n.digest("hex")))})}function EF(t){if(!bt.isAbsolute(t))throw new Error(`file must be an absolute path to the recording (got "${t}"). Fix: ask the user for the full path, e.g. /Users/<name>/Desktop/vo.wav.`);let e=bt.normalize(t),r;try{r=bF(e)}catch{throw new Error(`No file at ${e}. Fix: check the path with the user (drag the file into the chat to get its exact path).`)}if(r.isSymbolicLink())throw new Error(`${e} is a symbolic link. Fix: pass the path of the real recording file.`);if(!r.isFile())throw new Error(`${e} is not a regular file. Fix: pass the recording itself (wav, mp3, m4a, aiff or flac).`);try{fF(e,mF.R_OK)}catch{throw new Error(`${e} is not readable by the Sundown Reel server. Fix: check the file's permissions (or copy it to the Desktop) and retry.`)}let n=bt.extname(e).slice(1).toLowerCase();if(!Qk.includes(n))throw new Error(`${bt.basename(e)} is not a supported recording (.${n||"?"}). Fix: export it as ${Qk.join(", ")}.`);if(r.size===0)throw new Error(`${e} is empty.`);if(r.size>kF)throw new Error(`${e} is larger than 4 GB. Fix: export a compressed copy (m4a/flac) and retry.`);return{abs:e,ext:n,bytes:r.size}}async function t$(t,e,r={}){let n=N(t),s=EF(e),o=bt.join(n,"06-vo"),i=bt.join(o,"vo.wav");if(bt.resolve(s.abs).startsWith(o+bt.sep))throw new Error(`${s.abs} is already inside 06-vo/. Fix: pass the original recording from where the user saved it.`);if(Nm(i)&&!r.overwrite)throw new Error(`06-vo/vo.wav already exists for ${t}. Fix: pass overwrite: true to replace it (alignment and the shot timing then have to be redone).`);let a=await Im(s.abs);if(a.duration<1)throw new Error(`The recording is only ${a.duration.toFixed(2)} s long. Fix: check it is the full voice-over.`);if(a.duration>e$)throw new Error(`The recording is ${(a.duration/60).toFixed(0)} min long (max ${e$/3600} h). Fix: check the file.`);gs(n,Math.ceil(a.duration*96e3)+s.bytes);let c=Nm(bt.join(o,"words.json")),l=Nm(i);wF(o,{recursive:!0});let d=await $F(s.abs);await Lk(s.abs,i);let p=await Im(i);for(let g of vF(o))/^original\.[a-z0-9]+$/i.test(g)&&_F(bt.join(o,g),{force:!0});let f=`original.${s.ext}`;gF(s.abs,bt.join(o,f));let h={schema:1,source:bt.basename(s.abs),sha256:d,duration:Number(a.duration.toFixed(3)),original:`06-vo/${f}`,sourceFormat:{codec:a.codec,sampleRate:a.sampleRate,channels:a.channels},wav:{path:"06-vo/vo.wav",format:"pcm_s16le 48000 Hz mono",duration:Number(p.duration.toFixed(3)),bytes:SF(i).size},savedAt:new Date().toISOString()};xF(bt.join(o,"vo.json"),`${JSON.stringify(h,null,2)}
|
|
277
|
+
`);let m=[];return c?m.push("06-vo/words.json was aligned to the previous recording and is now stale: re-run vo_align, then rebuild the shot timing (shotplan_make or plan_shots) before rendering."):l&&m.push("The previous 06-vo/vo.wav was replaced."),a.sampleRate&&a.sampleRate<22050&&m.push(`The recording is only ${a.sampleRate} Hz: it will sound dull. A 44.1/48 kHz export is better.`),{episode:t,wrote:["06-vo/vo.wav",`06-vo/${f}`,"06-vo/vo.json"],vo:h,...m.length?{warnings:m}:{},next:{tool:"vo_align",args:{episodeId:t},why:"Align the recording to 04-script/script_vo.txt (background job; poll job_status)."}}}var Qk,kF,e$,r$=v(()=>{"use strict";Pe();id();Qk=["wav","mp3","m4a","aiff","aif","flac"],kF=4*1024**3,e$=3*3600});function s$(t){let e=t.status,r=eo(t.type);return{jobId:t.id,type:t.type,status:e,progress:t.progress,message:t.message,...t.episodeId?{episodeId:t.episodeId}:{},...t.projectId?{projectId:t.projectId}:{},createdAt:t.createdAt,updatedAt:t.updatedAt,...e==="failed"&&t.error?{error:t.error}:{},...(e==="interrupted"||e==="failed"||e==="cancelled")&&r?{rerun:{tool:r,args:t.episodeId?{episodeId:t.episodeId}:t.projectId?{projectId:t.projectId}:{}}}:{}}}function o$(t){let e=t.registerTool.bind(t);e("render_still",{title:"Render still (image)",description:Io+"Render one frame of one shot with the episode's style backend and RETURN IT AS AN IMAGE you can look at (JPEG \u2264 960 px) plus a JSON summary (frame, t, kind, vo, cached). t = seconds into the shot (default the middle); scale 0.25\u20131 (default 0.5). The PNG is kept in 08-render/stills/. Needs a saved shots.json that validates (it is compiled first) and \u2265 1.5 GB free disk. Stills are cached by validated sha + shot + frame. To check a whole chapter at once use review_shots; fix what you see with shots_patch.",inputSchema:{episodeId:ws,shotId:n$,t:u.number().min(0).max(30).optional().describe("Seconds into the shot (clamped to the shot length)."),scale:u.number().min(.25).max(1).optional()}},async r=>L({episodeId:r.episodeId},()=>Zk(r.episodeId,r.shotId,r.t,r.scale))),e("review_shots",{title:"Review shots (contact sheet)",description:Io+`Look at up to ${bs} shots at once: one still per shot (frame at start|mid|end, default mid) tiled into ONE contact-sheet image, returned with, per shot, the tile number, VO line, kind, beat, the validator lines for that shot and QA notes (from 09-qa/*/qa.json if a QA ran). Pick shots with range ("S010..S020") or shotIds; without either, the first shots. Shots that fail to render are skipped and explained. Writes 07-shots/review.json (next_step uses it to know the shots were looked at). Needs a shots.json that validates; ffmpeg; \u2265 1.5 GB free. Then fix issues with shots_patch, shots_compile and review again; when the sheet looks right, next_step (usually render_animatic).`,inputSchema:{episodeId:ws,range:u.string().regex(/^S\d{3}[a-z]?(\.\.S\d{3}[a-z]?)?$/,'a range like "S010..S020"').optional(),shotIds:u.array(n$).min(1).max(bs).optional(),at:u.enum(["start","mid","end"]).optional().describe("Which frame of each shot (default mid)."),max:u.number().int().min(1).max(bs).optional().describe(`Shots per sheet (default and max ${bs}).`)}},async r=>L({episodeId:r.episodeId},()=>Yk(r.episodeId,{range:r.range,shotIds:r.shotIds,at:r.at,max:r.max}))),e("vo_save",{title:"Save the human's voice-over",description:Io+"Store the voice-over the HUMAN recorded (they read 04-script/script_vo.txt word for word) as 06-vo/vo.wav: file = the absolute path they give you (wav, mp3, m4a, aiff or flac; a regular readable file, not a folder or symlink). It is probed (duration), converted to WAV 48 kHz mono 16-bit (what alignment and the renderers read), the original is kept as 06-vo/original.<ext>, and 06-vo/vo.json records source name, sha256 and duration. Refuses to replace an existing vo.wav unless overwrite: true; replacing it after alignment makes 06-vo/words.json stale (re-run vo_align and the shot timing). Never generate or fetch a voice yourself. Next: vo_align {episodeId}.",inputSchema:{episodeId:ws,file:u.string().min(2).max(4096).describe("Absolute path to the human's recording, e.g. /Users/<name>/Desktop/vo.m4a."),overwrite:u.boolean().optional()}},async r=>L({episodeId:r.episodeId},()=>t$(r.episodeId,r.file,{overwrite:r.overwrite}))),e("package_get",{title:"Show the package (Gate 4)",description:Io+"Everything the human reviews at Gate 4 in one result: 12-package description.md, meta.json, package.json, titles, chapters, thumbs.json and the thumbnail contact sheet AS AN IMAGE, plus the newest final render. Read only. Show it to the human; only they approve Gate 4 (`sundownreel-gate approve <videoDir> --gate 4` in their own terminal) and they upload by hand. Needs package_make (and thumbnail_make for the sheet).",inputSchema:{episodeId:ws}},async r=>L({episodeId:r.episodeId},()=>qk(r.episodeId))),e("thumbnail_make",{title:"Make thumbnails",description:Io+"Render 1\u201312 thumbnail variants (default 4; templates reaction, versus, number, object) as 1280\xD7720 PNGs into 12-package/thumbs/ with contact.png and thumbs.json, from the episode's title, facts and cast (code-drawn, no image AI). Returns the variant list and the contact sheet AS AN IMAGE (or a jobId to poll if it takes long). Headline rules: at most 3 words; every number needs a verified/computed fact. A rule failure says exactly what to fix: edit 12-package/thumbs.json {variants: [{template, text}]} and run it again. Next: package_get.",inputSchema:{episodeId:ws,variants:u.number().int().min(1).max(12).optional()}},async r=>L({episodeId:r.episodeId},()=>Gk(r.episodeId,{variants:r.variants}))),e("episode_open_preview",{title:"Open episode preview page",description:Io+"Start (once) the local preview page on 127.0.0.1 and return the episode's URL: the animatic/final videos, review contact sheets, stills, thumbnails and the package description. Give the URL to the human to open in their browser; it works only on this computer and carries a private token (don't post it anywhere). Read only.",inputSchema:{episodeId:ws}},async r=>L({episodeId:r.episodeId},async()=>{let{url:n,alreadyRunning:s}=await Pk(r.episodeId);return{episode:r.episodeId,url:n,alreadyRunning:s,note:"Local only (127.0.0.1) with a per-session token. Reload the page after new renders. Nothing is uploaded."}})),e("job_list",{title:"List background jobs",description:"Both profiles. Background jobs on this machine (renders, alignment, QA, thumbnails), newest first: status queued|running|succeeded|failed|interrupted|cancelled, progress and message. Jobs survive a server restart: one that was running when the server stopped reads `interrupted` with the tool to re-run (rerun). Filter by episodeId and/or status; limit (default 20). Poll one job with job_status.",inputSchema:{episodeId:ws.optional(),status:u.array(u.enum(RF)).min(1).max(6).optional(),limit:u.number().int().min(1).max(200).optional()}},async r=>L({},()=>{let n=ts({episodeId:r.episodeId,status:r.status,limit:r.limit??20}),s=n.filter(o=>o.status==="queued"||o.status==="running").length;return{jobs:n.map(s$),count:n.length,active:s,...s?{next:{tool:"job_status",args:{jobId:n.find(o=>o.status==="running"||o.status==="queued").id},why:"Poll the active job."}}:{}}})),e("job_cancel",{title:"Cancel a background job",description:"Both profiles. Cancel a queued or running background job by jobId: a queued job never starts; a running one is stopped (its renderer/ffmpeg child processes are killed) and reads `cancelled`. Finished jobs are left as they are. Partial outputs of a cancelled render are not used. Re-run the original tool to start again.",inputSchema:{jobId:u.string().regex(/^job_[a-f0-9]{8}$/,"a job id like job_1a2b3c4d (from job_list)")}},async r=>L({},()=>{let n=a_(r.jobId),s=eo(n.job.type);return{jobId:n.jobId,cancelled:n.cancelled,status:n.status,note:n.note,job:s$(n.job),...n.cancelled&&s?{rerun:{tool:s,args:n.job.episodeId?{episodeId:n.job.episodeId}:{}}}:{}}}))}var Io,ws,n$,RF,i$=v(()=>{"use strict";Ft();vn();mr();xm();Uk();Xk();r$();Io="Episode profile (every style; the private cartoon is operator-only). ",ws=u.string().regex(/^[A-Za-z0-9_][A-Za-z0-9._-]{0,119}$/,"an episode folder name under videos/, e.g. 2026-12-01-robot-rent").describe("Episode folder name under videos/ (from episode_list)."),n$=u.string().regex(/^S\d{3}[a-z]?$/,"a shot id like S001 or S014a"),RF=["queued","running","succeeded","failed","interrupted","cancelled"]});function jo(t,e){if(e.tier==="operator"&&fo(`The ${e.name} style`),e.tier==="max"&&t.styles!=="all")throw new Error(`The Max tier is required for the ${e.name} style.`);if(e.status!=="ready")throw new Error(`${e.name} is registered but has no renderer yet. Add one under mcp/styles/${e.id}/. See mcp/styles/README.md.`)}function Am(t,e){if(e==="2160p"&&t.maxResolution!=="2160p")throw new Error("4K export requires the Max tier.")}function a$(t,e){if(t.monthlyExportLimit!=null&&e>=t.monthlyExportLimit)throw new Error(`Monthly export limit reached for the ${t.tier} tier (${t.monthlyExportLimit}).`)}function c$(t){return t==="2160p"?{width:3840,height:2160}:{width:1920,height:1080}}var pd=v(()=>{"use strict";Xt()});import{spawn as Cm}from"node:child_process";function nr(t,e,r){return new Promise((n,s)=>{let o=Cm(t,e,{cwd:r?.cwd,stdio:[r?.input!=null?"pipe":"ignore","ignore","pipe"]}),i="";o.stderr?.on("data",a=>{i+=a.toString(),i.length>12e3&&(i=i.slice(-12e3))}),o.on("error",a=>s(a)),r?.input!=null&&o.stdin&&(o.stdin.write(r.input),o.stdin.end()),o.on("close",a=>{a===0?n():s(new Error(`${t} exited ${a}: ${i.slice(-1500)}`))})})}function Yi(t){return new Promise((e,r)=>{let n=Cm("ffprobe",["-v","error","-show_entries","format=duration","-of","csv=p=0",t],{stdio:["ignore","pipe","pipe"]}),s="",o="";n.stdout?.on("data",i=>{s+=i.toString()}),n.stderr?.on("data",i=>{o+=i.toString()}),n.on("error",r),n.on("close",i=>{let a=Number(s.trim());i===0&&Number.isFinite(a)?e(a):r(new Error(`ffprobe failed: ${o.slice(-400)}`))})})}function l$(t){return new Promise(e=>{let r=Cm(t,["--version"],{stdio:"ignore"});r.on("error",()=>e(!1)),r.on("close",n=>e(n===0))})}var hd=v(()=>{"use strict"});import{existsSync as d$,readdirSync as IF}from"node:fs";import fd from"node:path";function md(){let t=jd(),e=r=>{let n=fd.join(t,r);return d$(n)?IF(n).filter(s=>s.endsWith(".wav")||s.endsWith(".mp3")).map(s=>fd.parse(s).name).sort():[]};return{sfx:e("sfx"),music:e("music")}}function Lm(t,e){let r=jd();for(let n of[".wav",".mp3"]){let s=fd.join(r,t,`${e}${n}`);if(d$(s))return s}throw new Error(`No ${t} clip named "${e}" in ${fd.join(r,t)}.`)}var Dm=v(()=>{"use strict";pe()});import{mkdirSync as jF,writeFileSync as PF}from"node:fs";import gd from"node:path";async function u$(t,e,r){if(!t.shots?.length)throw new Error("Plan shots before exporting.");let{width:n,height:s}=c$(e),o=gd.join(gd.dirname(r),"_work");jF(o,{recursive:!0});let i=[];for(let p of t.shots){let f=t.renders?.[p.id];if(!f)throw new Error(`Shot ${p.id} has not been rendered.`);let h=t.voice?.files?.[p.lineId],m=t.sfx?.find(y=>y.shotId===p.id),g=gd.join(o,`${p.id}.mp4`);await OF({video:f.path,voice:h,sfx:m?Lm("sfx",m.sfxId):void 0,sfxOffset:m?.offsetSec??.12,width:n,height:s,fallbackDuration:p.durationSec,output:g}),i.push(g)}let a=gd.join(o,"concat.txt");PF(a,i.map(p=>`file '${p.replaceAll("'","'\\''")}'`).join(`
|
|
278
|
+
`));let c=t.music?Lm("music",t.music.musicId):void 0,l=t.music?.gainDb??-18,d=Math.pow(10,l/20).toFixed(4);if(!c){await nr("ffmpeg",["-y","-f","concat","-safe","0","-i",a,"-c","copy",r]);return}await nr("ffmpeg",["-y","-f","concat","-safe","0","-i",a,"-i",c,"-filter_complex",["[0:a]aformat=sample_rates=48000:channel_layouts=stereo,asplit=2[vo][sc]",`[1:a]aformat=sample_rates=48000:channel_layouts=stereo,volume=${d}[bed]`,"[bed][sc]sidechaincompress=threshold=0.04:ratio=8:attack=20:release=400[ducked]","[vo][ducked]amix=inputs=2:duration=first:dropout_transition=0[a]"].join(";"),"-map","0:v","-map","[a]","-c:v","libx264","-preset","veryfast","-crf","18","-pix_fmt","yuv420p","-c:a","aac","-b:a","160k","-shortest",r])}async function OF(t){let e=await Yi(t.video),r=t.voice?await Yi(t.voice):t.fallbackDuration,n=Math.max(r,.4),s=Math.max(0,n-e+.2).toFixed(2),o=`[0:v]scale=${t.width}:${t.height}:force_original_aspect_ratio=decrease,pad=${t.width}:${t.height}:(ow-iw)/2:(oh-ih)/2,fps=24,format=yuv420p,tpad=stop_mode=clone:stop_duration=${s}[v]`;if(!t.voice&&!t.sfx){await nr("ffmpeg",["-y","-i",t.video,"-f","lavfi","-i","anullsrc=channel_layout=stereo:sample_rate=48000","-filter_complex",o,"-map","[v]","-map","1:a","-t",n.toFixed(3),"-c:v","libx264","-preset","veryfast","-crf","20","-pix_fmt","yuv420p","-c:a","aac",t.output]);return}let i=["-y","-i",t.video];t.voice&&i.push("-i",t.voice),t.sfx&&i.push("-i",t.sfx);let a=Math.round(t.sfxOffset*1e3),c=t.voice?1:-1,l=t.sfx?t.voice?2:1:-1,d=[o],p=[];c>0&&(d.push(`[${c}:a]aformat=sample_rates=48000:channel_layouts=stereo,apad[vo]`),p.push("[vo]")),l>0&&(d.push(`[${l}:a]aformat=sample_rates=48000:channel_layouts=stereo,volume=0.35,adelay=${a}|${a},apad[fx]`),p.push("[fx]")),d.push(`${p.join("")}amix=inputs=${p.length}:duration=first:dropout_transition=0[a]`),i.push("-filter_complex",d.join(";"),"-map","[v]","-map","[a]","-t",n.toFixed(3),"-c:v","libx264","-preset","veryfast","-crf","20","-pix_fmt","yuv420p","-c:a","aac","-b:a","160k",t.output),await nr("ffmpeg",i)}var p$=v(()=>{"use strict";pd();hd();Dm()});import{copyFileSync as TF,existsSync as f$,mkdirSync as h$,writeFileSync as m$}from"node:fs";import{createRequire as NF}from"node:module";import vs from"node:path";function CF(){let t=J();return t&&f$(vs.join(t,"vendor","gsap.min.js"))?vs.join(t,"vendor","gsap.min.js"):AF.resolve("gsap/dist/gsap.min.js")}async function g$(t){h$(t.projectDir,{recursive:!0}),h$(vs.dirname(t.outputPath),{recursive:!0}),m$(vs.join(t.projectDir,"index.html"),t.html),TF(CF(),vs.join(t.projectDir,"gsap.min.js"));let e=process.env.SUNDOWNREEL_CHROME||process.env.HYPERFRAMES_BROWSER_PATH||"/usr/local/bin/google-chrome";f$(e)&&(process.env.HYPERFRAMES_BROWSER_PATH||=e);let{createRenderJob:r,executeRenderJob:n}=await import("@hyperframes/producer"),s=process.env.SUNDOWNREEL_RENDER_QUALITY||"draft",o=r({fps:t.fps,quality:s,format:"mp4",workers:1,useGpu:!1,hdrMode:"force-sdr",strictness:"best-effort"});await n(o,t.projectDir,t.outputPath,(i,a)=>{t.onProgress?.(i.progress,a)})}async function y$(t,e){let r=vs.join(vs.dirname(e),"preview-concat.txt"),n=t.map(s=>`file '${s.replaceAll("'","'\\''")}'`).join(`
|
|
279
|
+
`);m$(r,n),await nr("ffmpeg",["-y","-f","concat","-safe","0","-i",r,"-c:v","libx264","-pix_fmt","yuv420p","-preset","veryfast","-crf","23",e])}var AF,b$=v(()=>{"use strict";hd();pe();AF=NF(import.meta.url)});function DF(t){let e=t.toLowerCase(),r="spark",n=0;for(let s of LF){let o=s.words.filter(i=>e.includes(i)).length;o>n&&(n=o,r=s.id)}return r}function Mm(t){let r=t.trim().split(/\s+/).filter(Boolean).length/2.4;return Math.round(Math.min(8,Math.max(2,r))*10)/10}function w$(t){return{topic:t,audience:"",promise:"",hook:"",facts:[],sources:[],risks:[],angle:""}}function S$(t,e){if(!t.lines?.length)throw new Error("A script needs at least one line.");if(t.lines.length>400)throw new Error("A script can have at most 400 lines.");let r=t.lines.map((n,s)=>{let o=(n.text||"").replace(/\s+/g," ").trim();if(!o)throw new Error(`Line ${s+1} is empty.`);if(o.length>220)throw new Error(`Line ${s+1} is longer than 220 characters. Split it.`);return{id:n.id&&/^l\d{2,4}$/.test(n.id)?n.id:`l${String(s+1).padStart(2,"0")}`,text:o}});return{title:(t.title||e).trim()||e,lines:r}}function x$(t){return t.lines.map((e,r)=>({id:`s${String(r+1).padStart(2,"0")}`,lineId:e.id,index:r,text:e.text,motif:DF(e.text),durationSec:Mm(e.text)}))}var LF,v$,_$,k$=v(()=>{"use strict";LF=[{id:"pressure",words:["pressure","steam","force","kettle","build","weight"]},{id:"path",words:["path","opening","narrow","through","nowhere","route"]},{id:"sound",words:["sound","hears","sing","whistle","room","happy","voice"]},{id:"balance",words:["balance","equal","cost","price","month","trade"]}];v$=["Fill this brief yourself. Sundown Reel does not research or write.","audience: who the film is for, in one sentence.","promise: what they will understand by the end.","hook: the first spoken line, specific, with no greeting.","facts: short sourced claims. sources: where each claim came from.","risks: anything you are not sure of. Do not paper over those in the script.","angle: the one argument, not a list of topics.","Save the finished object with research_save. Then call script_scaffold."].join(" "),_$=["Write the script yourself. One spoken sentence per line. No stage directions.","Line one is the hook. Do not open with hello, welcome, or the channel name.","Aim for 130 to 150 spoken words a minute. A re-hook every 8 to 12 lines.","The last line is the payoff, not a subscribe plea.","Keep each line under 220 characters so one shot can hold it.","Save with script_save as { title, lines: [{ text }] }."].join(" ")});import{spawn as MF,spawnSync as FF}from"node:child_process";import{writeFileSync as I$}from"node:fs";import $$ from"node:path";function E$(){return process.env.SUNDOWNREEL_KOKORO!=="1"?!1:(yd!=null||(yd=FF("python3",["-c","import kokoro, soundfile, numpy"],{stdio:"ignore"}).status===0),yd)}async function qF(t,e){let r=t.trim().split(/\s+/).filter(Boolean).length,n=Math.max(1.6,r/2.4).toFixed(2);await nr("ffmpeg",["-y","-f","lavfi","-i",`sine=frequency=220:duration=${n}`,"-af","volume=0.04","-ac","1","-ar","22050",e])}async function GF(t,e){await nr("espeak-ng",["-w",e,"-s","148","-v","en-us",t])}async function UF(t,e){let r=process.env.PIPER_BIN||"piper",n=process.env.PIPER_MODEL;if(!n)throw new Error("PIPER_MODEL is not set.");await new Promise((s,o)=>{let i=MF(r,["--model",n,"--output_file",e],{stdio:["pipe","ignore","pipe"]}),a="";i.stderr?.on("data",c=>{a+=c.toString()}),i.on("error",o),i.stdin?.write(t),i.stdin?.end(),i.on("close",c=>{c===0?s():o(new Error(`piper exited ${c}: ${a.slice(-800)}`))})})}async function VF(t,e){let r=`
|
|
280
|
+
import sys
|
|
281
|
+
import numpy as np
|
|
282
|
+
import soundfile as sf
|
|
283
|
+
from kokoro import KPipeline
|
|
284
|
+
text, out, voice = sys.argv[1], sys.argv[2], sys.argv[3]
|
|
285
|
+
pipe = KPipeline(lang_code="a")
|
|
286
|
+
chunks = []
|
|
287
|
+
for _g, _p, audio in pipe(text, voice=voice):
|
|
288
|
+
chunks.append(audio)
|
|
289
|
+
sf.write(out, np.concatenate(chunks), 24000)
|
|
290
|
+
`,n=$$.join($$.dirname(e),"_kokoro.py");I$(n,r);let s=process.env.SUNDOWNREEL_KOKORO_VOICE||"af_heart";await nr("python3",[n,t,e,s])}async function R$(t,e){let r=process.env.SUNDOWNREEL_ELEVENLABS_API_KEY;if(!r)throw new Error("SUNDOWNREEL_ELEVENLABS_API_KEY is not set.");let n=process.env.SUNDOWNREEL_ELEVENLABS_VOICE_ID||"21m00Tcm4TlvDq8ikWAM",s=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${n}`,{method:"POST",headers:{"xi-api-key":r,"content-type":"application/json",accept:"audio/mpeg"},body:JSON.stringify({text:t,model_id:"eleven_multilingual_v2"})});if(!s.ok)throw new Error(`ElevenLabs returned ${s.status}.`);let o=new Uint8Array(await s.arrayBuffer());I$(e,o)}async function j$(t,e){let r=(process.env.SUNDOWNREEL_TTS||"auto").toLowerCase(),n=!!process.env.PIPER_MODEL,s=!!process.env.SUNDOWNREEL_ELEVENLABS_API_KEY,o="tone-placeholder",i=!1,a=e;if(r==="piper"||r==="auto"&&n){if(!n)throw new Error("PIPER_MODEL is not set. Point it at a Piper .onnx voice.");await UF(t,e),o="piper",i=!0}else if(r==="kokoro"||r==="auto"&&E$()){if(!E$())throw new Error("Kokoro is not importable. Install the kokoro, soundfile, and numpy Python packages, and set SUNDOWNREEL_KOKORO=1.");await VF(t,e),o="kokoro",i=!0}else if(r==="elevenlabs"){if(!s)throw new Error("SUNDOWNREEL_ELEVENLABS_API_KEY is not set.");a=e.replace(/\.wav$/,".mp3"),await R$(t,a),o="elevenlabs",i=!0}else r==="espeak"||r==="auto"&&await l$("espeak-ng")?(await GF(t,e),o="espeak-ng",i=!0):r==="auto"&&s?(a=e.replace(/\.wav$/,".mp3"),await R$(t,a),o="elevenlabs",i=!0):await qF(t,e);let c=await Yi(a);return{engine:o,speech:i,path:a,durationSec:c}}var yd,P$=v(()=>{"use strict";hd();yd=null});import{mkdirSync as Fm}from"node:fs";import Vr from"node:path";function O$(t){return{id:t.id,title:t.title,topic:t.topic,styleId:t.styleId,lines:t.script?.lines.length??0,shots:t.shots?.length??0,updatedAt:t.updatedAt}}function T$(t,e){let r=us(t.styleId||"chalkline");if(r.profile==="cartoon")throw new Error(`${r.name} is an episode profile, not a project style. Use episode_list / episode_status and the shots_* tools for it.`);jo(e,r);let n=new Date().toISOString(),s={id:Ks("p"),title:t.title.trim(),topic:t.topic.trim(),styleId:r.id,createdAt:n,updatedAt:n};if(!s.title||!s.topic)throw new Error("A project needs a title and a topic.");return Ot(s),O$(s)}function N$(){return Nc().map(O$)}function A$(t){return $e(t)}function C$(t){let e=$e(t),r=e.research??w$(e.topic);return{projectId:t,brief:r,instructions:v$}}function L$(t,e){if(!e||typeof e!="object")throw new Error("A research brief is required.");let r=$e(t);return r.research={topic:String(e.topic||r.topic),audience:String(e.audience||""),promise:String(e.promise||""),hook:String(e.hook||""),facts:Array.isArray(e.facts)?e.facts.map(String).slice(0,40):[],sources:Array.isArray(e.sources)?e.sources.map(String).slice(0,40):[],risks:Array.isArray(e.risks)?e.risks.map(String).slice(0,20):[],angle:String(e.angle||"")},Ot(r),{projectId:t,saved:!0}}function D$(t){let e=$e(t);return{projectId:t,title:e.script?.title??e.title,lines:e.script?.lines??[],instructions:_$,suggestedHook:e.research?.hook||""}}function M$(t,e){let r=$e(t);return r.script=S$(e,r.title),r.shots=void 0,Ot(r),{projectId:t,lines:r.script.lines.length}}function F$(t){let e=$e(t);if(!e.script)throw new Error("Save a script before planning shots.");return e.shots=x$(e.script),Ot(e),{projectId:t,shots:e.shots}}function zF(t,e,r,n){return{text:e.text,topic:t.topic,index:e.index,total:t.shots?.length??1,motif:e.motif,durationSec:e.durationSec,width:r,height:n}}async function q$(t,e,r,n,s,o,i){let a=us(t.styleId),c=YS(a,zF(t,e,r,n)),l=Vr.join(Tr(t.id),"renders",`${e.id}-${r}x${n}`),d=Vr.join(l,"shot.mp4");return await g$({html:c,projectDir:Vr.join(l,"project"),outputPath:d,fps:s,onProgress:(p,f)=>{i&&Xe(i,p,`${e.id}: ${f}`)}}),t.renders=t.renders??{},t.renders[o]={path:d,width:r,height:n,fps:s},Ot(t),d}function G$(t,e,r,n){let s=$e(t),o=us(s.styleId);if(jo(r,o),!s.shots?.find(d=>d.id===e))throw new Error(`Unknown shot ${e}. Call plan_shots.`);let a=n?.width??o.width,c=n?.height??o.height;(a>1920||c>1080)&&Am(r,"2160p");let l=Number(process.env.SUNDOWNREEL_FPS||o.fps);return ft("render_shot",t,async d=>{let p=$e(t),f=p.shots?.find(m=>m.id===e);if(!f)throw new Error(`Unknown shot ${e}.`);let h=await q$(p,f,a,c,l,e,d);return{shotId:e,output:h,width:a,height:c,fps:l}})}function U$(t,e,r=3){let n=$e(t),s=us(n.styleId);if(jo(e,s),!n.shots?.length)throw new Error("Plan shots before rendering a preview.");let o=Number(process.env.SUNDOWNREEL_FPS||12);return ft("render_preview",t,async i=>{let a=$e(t),c=(a.shots??[]).slice(0,r),l=[];for(let p=0;p<c.length;p+=1){let f={...c[p],durationSec:Math.min(c[p].durationSec,2.4)};Xe(i,p/c.length*100,`Preview ${f.id}`);let h=await q$(a,f,960,540,o,`preview:${f.id}`,i);l.push(h)}let d=Vr.join(Tr(t),"renders","preview.mp4");return Fm(Vr.dirname(d),{recursive:!0}),await y$(l,d),{output:d,shots:c.map(p=>p.id)}})}async function V$(t,e){let r=$e(t);if(!r.script)throw new Error("Save a script before generating voice.");let n=r.script.lines.filter(i=>!e||i.id===e);if(!n.length)throw new Error("No matching script line.");let s=Vr.join(Tr(r.id),"audio");Fm(s,{recursive:!0}),r.voice=r.voice??{engine:"",speech:!1,files:{}};let o=[];for(let i of n){let a=await j$(i.text,Vr.join(s,`${i.id}.wav`));r.voice.files[i.id]=a.path,r.voice.engine=a.engine,r.voice.speech=a.speech;let c=r.shots?.find(l=>l.lineId===i.id);c&&(c.durationSec=Math.round(Math.max(Mm(i.text),a.durationSec)*10)/10),o.push({lineId:i.id,...a})}return Ot(r),{projectId:t,engine:r.voice.engine,speech:r.voice.speech,lines:o}}function z$(){return md()}function H$(t,e){let r=$e(t);if(!r.shots?.length)throw new Error("Plan shots before placing sound effects.");let n=new Set(md().sfx),s=["thud","whoosh","tick"].filter(i=>n.has(i));if(!s.length)throw new Error("The local SFX library is empty. Run npm run generate:library.");let o=e?.length?e:r.shots.map((i,a)=>({shotId:i.id,sfxId:s[a%s.length],offsetSec:.12}));return r.sfx=o.map(i=>{if(!r.shots?.some(a=>a.id===i.shotId))throw new Error(`Unknown shot ${i.shotId}.`);if(!n.has(i.sfxId))throw new Error(`Unknown sfx ${i.sfxId}.`);return{shotId:i.shotId,sfxId:i.sfxId,offsetSec:i.offsetSec??.12}}),Ot(r),{projectId:t,cues:r.sfx}}function B$(t,e,r){let n=$e(t),s=md().music,o=e||s[0];if(!o||!s.includes(o))throw new Error("No music bed in the local library. Run npm run generate:library.");return n.music={musicId:o,gainDb:r??-18},Ot(n),{projectId:t,music:n.music}}function J$(t,e,r){Am(r,e);let n=Mh().count;if(a$(r,n),!$e(t).shots?.length)throw new Error("Plan shots before exporting.");return ft("assemble_export",t,async o=>{Xe(o,5,"Assembling with FFmpeg.");let i=$e(t),a=Vr.join(Tr(t),"exports",`${HF(i.title)}-${e}.mp4`);Fm(Vr.dirname(a),{recursive:!0}),await u$(i,e,a),i.exports=i.exports??[],i.exports.push({path:a,resolution:e,createdAt:new Date().toISOString()}),Ot(i);let c=Zv();return Xe(o,100,"Export written."),{output:a,resolution:e,exportsThisMonth:c.count,limit:r.monthlyExportLimit}})}function HF(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"film"}function W$(){return jk()}function K$(t){return Kv(t)}var qm=v(()=>{"use strict";p$();pd();mr();Dm();xm();b$();k$();Rl();Ys();P$()});async function Y$(t){try{return bo(await t(await Cr()))}catch(e){return Fr(e)}}function BF(t,e,r){let n=$e(t),s=us(e);if(s.profile==="cartoon")throw new Error(`${s.name} is an episode style, not a project style. Use episode_create {style}.`);jo(r,s);let o=n.styleId;return n.styleId=s.id,Ot(n),{projectId:t,from:o,to:s.id,changed:o!==s.id,...o!==s.id&&n.renders&&Object.keys(n.renders).length?{warning:"Existing shot renders are in the old style: render_shot / render_preview again before assemble_export."}:{},next:"render_preview {projectId} to see the new style."}}function X$(t){let e=t.registerTool.bind(t);e("list_styles",{title:"List styles",description:'Both profiles. Every visual style you can make a video in: registry styles (profile "episode": id, name, family, renderer, aspects, tier standard|max, status ready|planned, pitch, palette, licensing, kinds menu, sample stills if any) plus the Chalkline project styles (profile "project"). status ready renders today; planned can be planned and written now and renders when its renderer ships. Max-tier styles need the Max plan. Filters: aspect (16:9|9:16), family, renderer (resvg-2d|engine-3d|engine-geo), readyOnly. Read only, no licence needed. Next: get_style_guide {styleId}, then episode_create {episodeId, title, style}.',inputSchema:{aspect:u.enum(["16:9","9:16"]).optional(),family:u.string().max(40).optional(),renderer:u.enum(["resvg-2d","engine-3d","engine-geo"]).optional(),readyOnly:u.boolean().optional()}},async r=>L({open:!0},()=>ex({aspect:r.aspect,family:r.family,renderer:r.renderer,readyOnly:r.readyOnly}))),e("get_style_guide",{title:"Get style guide",description:Um+"Everything to write shots in one style before you write them: promptGuide (pacing, cut rules, do/don't), lookJsonSchema (the style's shot.look payload), kinds (layout menu, each with a complete valid example shot), pacing band and transitions, library summary (who / where / icons), beat vocabulary (beat kinds, archetypes, places, icons, moods), licensing and sample stills. Read only. Next: plan_shots {episodeId} for the skeleton, then shots_patch per chapter.",inputSchema:{styleId:bd}},async r=>L({styleId:r.styleId,open:!0},()=>cf(r.styleId))),e("project_set_style",{title:"Set style",description:Um+"Switch an episode to another style: writes episode.json style (Gate 2 pins episode.json, so switching after Gate 2 makes Gate 2 stale and the human must re-approve). The gate profile the episode had is pinned so the switch never relaxes the gates. restyle: true also rewrites an existing shots.json in the new style (same shots, timing and beats; other styles' look payloads dropped) through the validated save path, which needs Gate 2 approved; without Gate 2 it tells you what to do instead. Planned styles are allowed (plan and write now; renders wait for the renderer). Chalkline projects: pass projectId + styleId instead (updates the project's style; needs a licence covering it).",inputSchema:{episodeId:Gm.optional(),projectId:Z$.optional(),styleId:bd,restyle:u.boolean().optional().describe("Also restyle an existing shots.json (needs Gate 2).")}},async r=>{let n=r.styleId;if(r.projectId&&!r.episodeId)return Y$(o=>BF(r.projectId,n,o));if(!r.episodeId)return Fr(new Error("Pass episodeId (an episode) or projectId (a Chalkline project), plus styleId."));let s=r.episodeId;return L({episodeId:s},async()=>(await Ci({styleId:n}),nx(s,n,{restyle:r.restyle===!0})))}),e("plan_shots",{title:"Plan shots",description:"Both profiles. Episode (episodeId): the style's deterministic shot skeleton from the locked script \u2014 one line per paragraph of 04-script/script_vo.txt, timed from 06-vo/words.json when it matches (else ~2.6 words/s), one `beat` shot per line (long lines split to the style's max shot), beats guessed, numbers only where facts are cited. Always writes 07-shots/plan.<style>.json and returns a summary (shot count, seconds, durations, beat-kind histogram, first 3 shots). save: true also writes it as shots.json through the validated save path (needs Gate 2; refuses an existing shots.json unless overwrite: true; the old file stays in 07-shots/versions/). styleId defaults to the episode's style. The cartoon (cutout) channel normally uses shotplan_make instead. Chalkline (projectId): one shot per script line; call after script_save.",inputSchema:{episodeId:Gm.optional(),projectId:Z$.optional(),styleId:bd.optional(),save:u.boolean().optional(),overwrite:u.boolean().optional(),fps:u.number().int().min(24).max(30).optional()}},async r=>{if(r.projectId&&!r.episodeId)return Y$(()=>F$(r.projectId));if(!r.episodeId)return Fr(new Error("Pass episodeId (an episode) or projectId (a Chalkline project)."));let n=r.episodeId,s=r.styleId;return L({episodeId:n},async()=>(s&&await Ci({styleId:s}),Ol(n,{styleId:s,save:r.save===!0,overwrite:r.overwrite===!0,fps:r.fps})))}),e("episode_create",{title:"Create episode",description:Um+"Create videos/<episodeId>/ with its stage folders and episode.json: title, hypothetical flag, style and gate profile (all pinned when the human approves Gate 2). style defaults to the default customer style your plan covers (list_styles shows it as defaultStyle); planned styles are allowed (plan and write now, render later). gateProfile: quick (Gates 2 + 4 required, 1 + 3 optional) or strict (all four); default from the style. Refuses an existing folder. Next: topic_save (Gate 1 is optional in quick), outline_save, research.",inputSchema:{episodeId:Gm,title:u.string().min(1).max(200),hypothetical:u.boolean().optional(),style:bd.optional(),gateProfile:u.enum(["quick","strict"]).optional(),format:u.object({aspect:u.enum(["16:9","9:16"]),width:u.number().int().min(320).max(3840),height:u.number().int().min(320).max(3840),fps:u.number().int().min(24).max(30)}).optional().describe("Output format; default from the style (9:16-only styles get 1080x1920, blockfolk at 24 fps).")}},async r=>{let n;try{let s=r.style||Ae()?null:await Cr();n=await sx(r.style,s)}catch(s){return Fr(s)}return L({styleId:n},async()=>({...V0({episodeId:r.episodeId,title:r.title,hypothetical:r.hypothetical,style:n,gateProfile:ox(n,r.gateProfile),format:r.format??await nm(n)}),style:await Yt(n),registryStyleId:n}))})}var Gm,bd,Z$,Um,Q$=v(()=>{"use strict";Ft();Bf();hl();Xt();im();pd();vn();lo();wo();qm();Ys();Rl();sm();ln();Gm=u.string().regex(/^[A-Za-z0-9_][A-Za-z0-9._-]{0,119}$/,"an episode folder name under videos/, e.g. 2026-12-01-robot-rent").describe("Episode folder name under videos/ (from episode_list)."),bd=u.string().regex(/^[a-z0-9][a-z0-9-]{1,31}(@\d+)?$/,"a style id from list_styles, e.g. gilded-deco").describe("Style id (or alias) from list_styles."),Z$=u.string().regex(/^p_[a-f0-9]{8}$/,"a Chalkline project id like p_1a2b3c4d").describe("Chalkline project id (project_list)."),Um="Episode profile (every style; episodes under videos/<id>/). "});var tE={};Sd(tE,{SERVER_INSTRUCTIONS:()=>eE,createSundownreelServer:()=>KF});function JF(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function wd(t){return{isError:!0,content:[{type:"text",text:t instanceof Error?t.message:String(t)}]}}async function nt(t){try{let e=await Cr();return JF(await t(e))}catch(e){return e instanceof Nt||e instanceof Error,wd(e)}}function KF(){let t=Js(),e=new jc({name:t.slug,version:"0.1.0"},{instructions:eE}),r=e.registerTool.bind(e);e.registerTool=(s,o,i)=>r(s,o,async(a,c)=>{let l=await i(a,c);return l?.isError||Lg(String(s),a),l});let n="Chalkline profile (project_* projects). ";return e.registerTool("sundownreel_connect",{title:"Connect this machine",description:"Connect this computer to your Sundown Reel account: opens your browser to approve it and returns at once with the link and a code. No licence key to paste. Pass reconnect: true to connect again.",inputSchema:{reconnect:u.boolean().optional()}},async({reconnect:s})=>{try{return{content:[{type:"text",text:await n0({reconnect:s})}]}}catch(o){return wd(o)}}),e.registerTool("project_create",{title:"Create project",description:n+"Create a Sundown Reel project on this computer. Does not write a script. styleId defaults to chalkline.",inputSchema:{title:u.string(),topic:u.string(),styleId:u.string().optional()}},async s=>nt(o=>T$(s,o))),e.registerTool("project_list",{title:"List projects",description:n+"List Sundown Reel projects stored on this computer.",inputSchema:{}},async()=>nt(()=>N$())),e.registerTool("project_get",{title:"Get project",description:n+"Return one project, including script, shots, voice, and export paths.",inputSchema:{projectId:u.string()}},async({projectId:s})=>nt(()=>A$(s))),e.registerTool("research_scaffold",{title:"Research scaffold",description:n+"Return an empty research brief and the rules for filling it. The assistant writes the research. This tool does not browse the web.",inputSchema:{projectId:u.string()}},async({projectId:s})=>nt(()=>C$(s))),e.registerTool("research_save",{title:"Save research",description:n+"Store a research brief the assistant has written.",inputSchema:{projectId:u.string(),brief:WF}},async({projectId:s,brief:o})=>nt(()=>L$(s,o))),e.registerTool("script_scaffold",{title:"Script scaffold",description:n+"Return pacing rules and the current script, if any. The assistant writes every line. This tool does not draft copy.",inputSchema:{projectId:u.string()}},async({projectId:s})=>nt(()=>D$(s))),e.registerTool("script_save",{title:"Save script",description:"Two profiles. Episode (every style): pass episodeId + scriptMd (04-script/script.md, chapters table), scriptVo (script_vo.txt, the exact VO text, one paragraph per spoken line) and/or meta ({title, hook_line, chapters:[{anchor,title}]}). A chapter anchor is the first 3\u20136 words of that chapter's first VO line (package_make finds it in words.json); an outline slug (cold-open) is accepted with {anchor: slug, title, vo: '<first words of its VO line>'} or when script.md names the slug right above the chapter's text, and is mapped to the VO words (the slug is kept as chapters[].slug). Editing script_vo.txt after Gate 2 makes the gate stale. Next: next_step (Gate 2 is the human's). Chalkline (legacy project_*): pass projectId + lines (one spoken sentence per line; clears the shot plan).",inputSchema:{episodeId:u.string().optional(),scriptMd:u.string().max(4e5).optional(),scriptVo:u.string().max(2e5).optional(),meta:u.record(u.unknown()).optional(),projectId:u.string().optional(),title:u.string().optional(),lines:u.array(u.object({id:u.string().optional(),text:u.string()})).min(1).max(400).optional()}},async s=>s.episodeId?L({episodeId:s.episodeId},()=>X0(s.episodeId,{scriptMd:s.scriptMd,scriptVo:s.scriptVo,meta:s.meta})):!s.projectId||!s.lines?wd(new Error("Pass episodeId (an episode) or projectId + lines (a Chalkline project).")):nt(()=>M$(s.projectId,{title:s.title,lines:s.lines}))),e.registerTool("render_shot",{title:"Render shot",description:n+"Render one shot in the background with HyperFrames. Returns a job id. Poll job_status until status is succeeded or failed. Renders can outlast a tool timeout.",inputSchema:{projectId:u.string(),shotId:u.string(),width:u.number().int().positive().max(3840).optional(),height:u.number().int().positive().max(2160).optional()}},async s=>nt(o=>G$(s.projectId,s.shotId,o,{width:s.width,height:s.height}))),e.registerTool("render_preview",{title:"Render preview",description:n+"Background job: render the first shots at 960x540 and concatenate a silent preview. Poll job_status.",inputSchema:{projectId:u.string(),limit:u.number().int().positive().max(12).optional()}},async({projectId:s,limit:o})=>nt(i=>U$(s,i,o))),e.registerTool("job_status",{title:"Job status",description:"Both profiles. Read a background job (render, export, alignment, QA, thumbnails). Poll until status is succeeded, failed, interrupted or cancelled. interrupted = the server restarted mid-job: re-run the tool named in the message. job_list shows recent jobs.",inputSchema:{jobId:u.string()}},async({jobId:s})=>L({},()=>{let o=i_(s)??K$(s);if(!o)throw new Error(`Unknown job ${s}. Call job_list.`);return o})),e.registerTool("generate_voice",{title:"Generate voice",description:n+"Synthesize narration for each script line. Order: Piper if PIPER_MODEL is set, Kokoro if SUNDOWNREEL_KOKORO=1, espeak-ng, ElevenLabs if a key is set, otherwise a quiet tone placeholder. Pass lineId to do one line.",inputSchema:{projectId:u.string(),lineId:u.string().optional()}},async({projectId:s,lineId:o})=>nt(()=>V$(s,o))),e.registerTool("list_library",{title:"List audio library",description:n+"List local sound effects and music beds Sundown Reel can place.",inputSchema:{}},async()=>nt(()=>z$())),e.registerTool("add_sfx",{title:"Add sound effects",description:n+"Place a library effect on each shot. Omit cues to rotate thud, whoosh, and tick. Effects are mixed at assemble time.",inputSchema:{projectId:u.string(),cues:u.array(u.object({shotId:u.string(),sfxId:u.string(),offsetSec:u.number().optional()})).optional()}},async({projectId:s,cues:o})=>nt(()=>H$(s,o))),e.registerTool("add_music",{title:"Add music",description:n+"Set the music bed for the film. It is ducked under the voice during assemble.",inputSchema:{projectId:u.string(),musicId:u.string().optional(),gainDb:u.number().optional()}},async({projectId:s,musicId:o,gainDb:i})=>nt(()=>B$(s,o,i))),e.registerTool("assemble_export",{title:"Assemble and export",description:n+"Background job. Mux each shot with its voice and effect, concatenate, duck the music bed, and write an mp4. 1080p on Standard. 2160p is a gated upscale that requires Max. Poll job_status.",inputSchema:{projectId:u.string(),resolution:u.enum(["1080p","2160p"]).optional()}},async({projectId:s,resolution:o})=>nt(i=>J$(s,o??"1080p",i))),e.registerTool("open_preview",{title:"Open preview",description:n+"Start the local preview page on 127.0.0.1 so the shots and export can be reviewed in a browser.",inputSchema:{}},async()=>nt(()=>W$())),wk(e),Ax(e),ok(e),X$(e),px(e),o$(e),e}var eE,WF,rE=v(()=>{"use strict";qo();Tv();Ft();Pc();hl();im();vn();mr();Cx();ik();vk();i$();Q$();Yc();lo();qm();eE=["Sundown Reel turns an idea into a finished, upload-ready video in one of several visual styles.","Always start with next_step (no arguments when you don't know the episode): it returns exactly one action \u2014 the tool to call with its args, or the command the HUMAN types \u2014 and why.","On a first run, or when anything fails to start, call doctor and walk the user through its fixes.","Flow: ideas_generate \u2192 ideas_save \u2192 episode_create (pick a style with list_styles / get_style_guide) \u2192 topic_save \u2192 outline_save \u2192 research_plan + facts_upsert \u2192 factcheck_plan + factcheck_record (a different actor) \u2192 script_save \u2192 [human: Gate 2] \u2192 vo_save + vo_align \u2192 plan_shots \u2192 shots_patch per chapter \u2192 shots_validate/shots_compile \u2192 review_shots (look at the images and fix) \u2192 render_animatic \u2192 [Gate 3, optional in quick film] \u2192 render_final \u2192 package_make \u2192 thumbnail_make \u2192 qa_run \u2192 package_get \u2192 [human: Gate 4] \u2192 the human uploads.","Gates are decided only by the human in their own terminal (sundownreel-gate approve <videoDir> --gate N). No tool approves, uploads or publishes. Every on-screen number needs a verified fact id."].join(`
|
|
291
|
+
`);WF=u.object({topic:u.string().optional(),audience:u.string().optional(),promise:u.string().optional(),hook:u.string().optional(),facts:u.array(u.string()).optional(),sources:u.array(u.string()).optional(),risks:u.array(u.string()).optional(),angle:u.string().optional()})});Od();import{readFileSync as ZF}from"node:fs";if(process.argv.includes("--version")||process.argv.includes("-v")){let t="0.1.0";if(t==="unknown")try{t=JSON.parse(ZF(new URL("../package.json",import.meta.url),"utf8")).version??t}catch{}process.stdout.write(`${t}
|
|
292
|
+
`),process.exit(0)}var YF=Km();for(let t of YF.warnings)process.stderr.write(`sundownreel: ${t}
|
|
293
|
+
`);var{StdioServerTransport:XF}=await Promise.resolve().then(()=>(Cg(),Ag)),{createSundownreelServer:QF}=await Promise.resolve().then(()=>(rE(),tE)),eq=QF();await eq.connect(new XF);
|