cueframe 0.3.1 → 0.4.2
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 +56 -30
- package/dist/analyze-6QSD7KHH.js +2 -0
- package/dist/chunk-7TCLKYUZ.js +12 -0
- package/dist/cueframe.js +35 -58
- package/package.json +14 -7
- package/skills/_connect.md +29 -0
- package/skills/add-music-bed/SKILL.md +7 -2
- package/skills/brand-reel/SKILL.md +8 -3
- package/skills/clip-a-talking-head/SKILL.md +7 -2
- package/skills/composing-video/SKILL.md +59 -35
- package/skills/cueframe-brand-demo/SKILL.md +14 -13
- package/skills/cueframe-cli/SKILL.md +54 -44
- package/skills/cueframe-component-authoring/SKILL.md +10 -9
- package/skills/cueframe-product-video/SKILL.md +8 -7
- package/skills/every-format-from-one-edit/SKILL.md +7 -2
- package/skills/extracting-brand-kits/SKILL.md +1 -1
- package/skills/launch-video/SKILL.md +7 -2
- package/skills/make-a-social-reel/SKILL.md +7 -2
- package/skills/rebrand-a-video/SKILL.md +7 -2
- package/dist/analyze-4EZTZEAG.js +0 -2
- package/dist/chunk-4FMFWW74.js +0 -12
package/dist/cueframe.js
CHANGED
|
@@ -1,36 +1,24 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{A as
|
|
2
|
+
import{A as Z,B as R,C as Ot,a as J,b as Ct,c as L,d as mt,e as $t,f as Tt,g as oe,h as Se,i as Rt,j as Ve,k as Fe,l as Be,m as It,n as f,o as v,p as F,q as m,r as je,s as Ze,t as j,u as I,v as A,w as g,x as T,y as x,z as O}from"./chunk-7TCLKYUZ.js";import{a as Zr}from"./chunk-3QSA3EBY.js";import{Command as Ss}from"commander";import{existsSync as pt,mkdirSync as Gr,readFileSync as Kr,writeFileSync as Hr,readdirSync as Yr,statSync as Xr}from"fs";import{homedir as Qr}from"os";import{dirname as At,join as Ge}from"path";import{fileURLToPath as en}from"url";import{agents as tn,detectGlobalAgents as Pt,upsertServer as rn}from"add-mcp";var Ke="cueframe";function nn(){let t=At(en(import.meta.url));for(let e=0;e<8;e++){let r=Ge(t,"skills");if(pt(r)&&Xr(r).isDirectory())return r;let n=At(t);if(n===t)break;t=n}return null}function on(t,e){let r=`> Installed ${e} by \`npx -y cueframe install\`. Skills and tools change often \u2014
|
|
3
3
|
> if that date is more than a week old, run \`npx -y cueframe install\` to refresh.
|
|
4
|
-
`,
|
|
5
|
-
${
|
|
6
|
-
${t}`}function
|
|
7
|
-
`).map(
|
|
8
|
-
`)||
|
|
9
|
-
`;
|
|
4
|
+
`,n=t.match(/^---\n[\s\S]*?\n---\n/);return n?`${n[0]}
|
|
5
|
+
${r}${t.slice(n[0].length)}`:`${r}
|
|
6
|
+
${t}`}function sn(t){let e=nn();e||(x(t,"install",new Error("Bundled skills/ directory not found"),f.UserError),m(f.UserError));let r=new Date().toISOString().slice(0,10),n=[],o=[];for(let s of Yr(e)){let i=Ge(e,s,"SKILL.md");if(!pt(i))continue;let a=Ge(Qr(),".claude","skills",s),d=Ge(a,"SKILL.md");if(pt(d)&&!t.force){o.push(d);continue}Gr(a,{recursive:!0}),Hr(d,on(Kr(i,"utf8"),r),"utf8"),n.push(d)}return{installed:n,skipped:o}}function an(t){return(tn[t]?.supportedTransports??[]).includes("http")}async function cn(t){return(await Pt()).map(r=>{if(!an(r))return{agent:r,wired:!1,error:"speaks stdio only \u2014 CueFrame\u2019s MCP server is remote HTTP"};try{let n=rn(r,Ke,{type:"http",url:t});return{agent:r,wired:n.success,path:n.path,error:n.error}}catch(n){return{agent:r,wired:!1,error:n instanceof Error?n.message:String(n)}}})}async function Nt(t){let e=`${je(t.target)}/v1/mcp`;if(t.dryRun){let s=await Pt();T(t,{ok:!0,dryRun:!0,mcpUrl:e,wouldWire:s,serverName:Ke},()=>{console.log(`Would wire MCP server "${Ke}" \u2192 ${e} into:`),s.length===0&&console.log(" (no agents detected on this machine)");for(let i of s)console.log(` \u2192 ${i}`);console.log("Would install the CueFrame agent skills into ~/.claude/skills"),console.log("Dry run \u2014 nothing was written.")});return}let r=await cn(e),{installed:n,skipped:o}=sn(t);n.length===0&&o.length===0&&r.length===0&&(x(t,"install",new Error("No agents detected and no skills found \u2014 nothing to install"),f.UserError),m(f.UserError)),T(t,{ok:!0,mcpUrl:e,agents:r,skills:n,skipped:o},()=>{if(console.log(`\u2713 CueFrame MCP server (${e})`),r.length===0)console.log(" No agents detected on this machine. Add it manually:"),console.log(` claude mcp add --transport http ${Ke} ${e}`),console.log(` \u2026or add the MCP server ${e} as a custom connector.`);else for(let s of r)console.log(s.wired?` \u2192 wired ${s.agent}`:` \u2717 ${s.agent}: ${s.error??"failed"}`);console.log(`\u2713 Installed ${n.length} CueFrame skill(s) into ~/.claude/skills`),o.length>0&&console.log(` ${o.length} skipped (already present \u2014 rerun with --force)`),r.some(s=>s.wired&&s.agent==="claude-code")||(console.log(" Note: only Claude Code reads that directory. Your other agents get the"),console.log(" same verbs as MCP tools from the server above \u2014 nothing else to install.")),console.log(""),console.log("Next: ask your agent to make a video \u2014 it opens a browser to authorize on"),console.log("first call. No API key needed."),console.log("Restart your agent session to load the MCP server and skills."),console.log(""),console.log("This installed no `cueframe` binary \u2014 npx leaves nothing on your PATH."),console.log("Prefer the terminal? Every command runs as `npx -y cueframe \u2026`:"),console.log(" npx -y cueframe login")})}import{existsSync as ft,mkdirSync as dn,readFileSync as Ft,writeFileSync as gt}from"fs";import{join as ht}from"path";var Mt="cueframe.json",ln="cueframe/components",He=".cueframe/";function un(t,e){let r=ht(t,".gitignore");if(ft(r)){let n=Ft(r,"utf8"),o=n.split(`
|
|
7
|
+
`).map(s=>s.trim());if(o.includes(He)||o.includes(".cueframe"))return!1;if(!e){let s=n.endsWith(`
|
|
8
|
+
`)||n.length===0?"":`
|
|
9
|
+
`;gt(r,`${n}${s}
|
|
10
10
|
# CueFrame derived render cache (regenerated; never authored)
|
|
11
|
-
${
|
|
12
|
-
`)}return!0}return e||
|
|
13
|
-
${
|
|
14
|
-
`),!0}function
|
|
15
|
-
`);let s=we(e,i),a=he(s);!a&&!o&&so(s,{recursive:!0});let f=co(e,o);j(t,{ok:!0,dryRun:o,root:e,manifest:{path:r,created:!n},componentsDir:i,componentsDirCreated:!a,gitignoreUpdated:f},()=>{console.log(`\u2713 ${o?"Would initialize":"Initialized"} CueFrame workspace at ${e}`),console.log(` ${n?"kept":"created"} ${Le} (componentsDir: ${i})`),console.log(` ${a?"exists":"created"} ${i}/`),f&&console.log(` gitignored ${te}`),console.log("Next: cueframe eject <primitive> or cueframe new component <name>")})}import{existsSync as je,mkdirSync as vo,readFileSync as re,readdirSync as Ge,statSync as jo,writeFileSync as Be}from"fs";import{dirname as Ee,join as B}from"path";import{fileURLToPath as Eo}from"url";import S from"typescript";import O from"typescript";var mo="@cueframe/primitives";function lo(t){if(!t.startsWith("."))return t;let e=t.split("/"),o=e.indexOf("lib");return o===-1||!e.slice(0,o).every(r=>r==="."||r==="..")?t:`${mo}/${e.slice(o).join("/")}`}function be(t,e){let o=O.createSourceFile(e,t,O.ScriptTarget.Latest,!1,e.endsWith(".tsx")?O.ScriptKind.TSX:O.ScriptKind.TS),r=[],n=s=>{let a;if(O.isImportDeclaration(s)||O.isExportDeclaration(s)?a=s.moduleSpecifier:O.isCallExpression(s)&&s.expression.kind===O.SyntaxKind.ImportKeyword&&(a=s.arguments[0]),a&&O.isStringLiteral(a)){let f=lo(a.text);f!==a.text&&r.push({start:a.getStart(o)+1,end:a.getEnd()-1,text:f})}O.forEachChild(s,n)};if(n(o),r.length===0)return t;r.sort((s,a)=>a.start-s.start);let i=t;for(let s of r)i=i.slice(0,s.start)+s.text+i.slice(s.end);return i}import{existsSync as oe,readFileSync as uo,readdirSync as po,statSync as fo}from"fs";import{dirname as go,join as W,parse as ho}from"path";var yo="cueframe/components";var wo="cueframe.json",bo=ge.object({componentsDir:ge.string().min(1).default(yo)}).passthrough();function U(t){let e=t,o=ho(e).root;for(;;){let r=W(e,wo);if(oe(r)){let n=uo(r,"utf8"),i=bo.parse(JSON.parse(n));return{root:e,manifest:i}}if(e===o)return null;e=go(e)}}function Je(t){return W(t.root,t.manifest.componentsDir)}function z(t,e){return W(Je(t),e)}function qe(t){let e=Je(t);return oe(e)?po(e).filter(o=>{let r=W(e,o);return fo(r).isDirectory()?oe(W(r,"index.tsx"))&&oe(W(r,"config.ts")):!1}).sort():[]}var ve="@cueframe/primitives",xo="cueframe.json";function So(){let t=Ee(Eo(import.meta.url));for(;;){let e=B(t,"packages","execution","primitives","src");if(je(e))return e;let o=Ee(t);if(o===t)return null;t=o}}function Ke(t){let e=[];for(let o of Ge(t)){if(o==="node_modules"||o==="dist"||o==="__tests__")continue;let r=B(t,o);jo(r).isDirectory()?e.push(...Ke(r)):o==="config.ts"&&e.push(r)}return e}function Co(t){let e=t;for(;S.isAsExpression(e)||S.isParenthesizedExpression(e)||typeof S.isSatisfiesExpression=="function"&&S.isSatisfiesExpression(e);)e=e.expression;return e}function $o(t,e){let o=S.createSourceFile(e,t,S.ScriptTarget.Latest,!0,S.ScriptKind.TS),r;for(let i of o.statements)if(S.isVariableStatement(i)){for(let s of i.declarationList.declarations)if(S.isIdentifier(s.name)&&s.name.text==="config"&&s.initializer){let a=Co(s.initializer);S.isObjectLiteralExpression(a)&&(r=a)}if(r)break}let n={sf:o};if(!r)return n;for(let i of r.properties){if(!S.isPropertyAssignment(i)||!(S.isIdentifier(i.name)||S.isStringLiteral(i.name)))continue;let s=i.name.text;s==="id"&&S.isStringLiteralLike(i.initializer)?n.id=i.initializer.text:s==="version"&&S.isStringLiteralLike(i.initializer)?n.version=i.initializer.text:s==="component"&&S.isIdentifier(i.initializer)&&(n.componentName=i.initializer.text)}return n}function He(t,e){let o=t.importClause;if(!o||o.isTypeOnly)return!1;if(o.name&&o.name.text===e)return!0;let r=o.namedBindings;return r&&S.isNamedImports(r)?r.elements.some(n=>!n.isTypeOnly&&n.name.text===e):!1}function ko(t,e){for(let o of t.statements)if(S.isImportDeclaration(o)&&S.isStringLiteral(o.moduleSpecifier)&&He(o,e))return o.moduleSpecifier.text}function _o(t,e,o){let r=S.createSourceFile(e,t,S.ScriptTarget.Latest,!1,S.ScriptKind.TS);for(let n of r.statements){if(!S.isImportDeclaration(n)||!S.isStringLiteral(n.moduleSpecifier)||!He(n,o))continue;let i=n.moduleSpecifier.getStart(r)+1,s=n.moduleSpecifier.getEnd()-1;return t.slice(0,i)+"./index"+t.slice(s)}return t}function D(t,e){g(t,"eject",new Error(e),m.UserError),l(m.UserError)}function Ve(t,e){E(t,"primitive",e);let o=t,r=e.dryRun??!1,n=e.force??!1;p(e,"eject_prepare",{primitive:o,dryRun:r,force:n});let i=U(process.cwd());i||D(e,"No CueFrame workspace found (no cueframe.json up-tree). Run `cueframe init` first to scaffold one.");let s=So();s||D(e,"Built-in primitive source not found \u2014 `cueframe eject` reads in-tree source and must run inside the CueFrame monorepo checkout.");let a,f;for(let P of Ke(s)){let R=$o(re(P,"utf8"),P);if(R.id===o){a=P,f=R;break}}(!a||!f)&&D(e,`Unknown primitive id "${o}". No built-in primitive declares config.id === "${o}".`),f.componentName||D(e,`Primitive "${o}" config has no \`component:\` identifier to eject.`);let u=f.componentName,c=f.version??"0.0.0",d=ko(f.sf,u);d||D(e,`Could not find the import that provides component "${u}" in ${a}.`);let h=Ee(a),x=d.replace(/^\.\//,""),b;for(let P of[".tsx",".ts"]){let R=B(h,x+P);if(je(R)){b=R;break}}b||D(e,`Component source for "${o}" not found on disk (resolved "${d}" beside ${a}).`);let _=re(b,"utf8"),J=be(_,"index.tsx"),H=`/** Owned eject of '${o}'. Adapts the ({durationInFrames, params}) mount contract to the primitive's props. */
|
|
16
|
-
export default function ${u}Owned({ params }: { durationInFrames: number; params: Record<string, unknown> }) {
|
|
17
|
-
return <${u} {...(params as Record<string, never>)} />;
|
|
18
|
-
}
|
|
19
|
-
`,ue=`${J.replace(/\s*$/,"")}
|
|
20
|
-
|
|
21
|
-
${H}`,V=re(a,"utf8"),Wt=be(V,"_config.ts"),zt=_o(Wt,"_config.ts",u),Jt=`import component from './index';
|
|
22
|
-
import { config as base } from './_config';
|
|
23
|
-
|
|
24
|
-
export const config = { ...base, component };
|
|
25
|
-
export default config;
|
|
26
|
-
`,M=z(i,o),ke=je(M);ke&&Ge(M).length>0&&!n&&D(e,`Component dir ${M} already exists and is non-empty. Pass --force to overwrite (this replaces local customizations).`);let pe={"index.tsx":ue,"_config.ts":zt,"config.ts":Jt};if(!r){vo(M,{recursive:!0});for(let[qt,Bt]of Object.entries(pe))Be(B(M,qt),Bt);let P=B(i.root,xo),R=JSON.parse(re(P,"utf8")),_e=R.components??{};_e[o]={ejectedFrom:ve,primitiveVersion:c},R.components=_e,Be(P,`${JSON.stringify(R,null,2)}
|
|
27
|
-
`)}j(e,{ok:!0,dryRun:r,primitive:o,component:u,version:c,from:ve,dir:M,files:Object.keys(pe),overwritten:ke&&n},()=>{console.log(`\u2713 ${r?"Would eject":"Ejected"} ${o} (${u}) into ${M}`);for(let R of Object.keys(pe))console.log(` ${r?"would write":"wrote"} ${R}`);r||console.log(` stamped cueframe.json components.${o} (${ve}@${c})`),console.log("Edit the source, then render it on CueFrame.")})}import{existsSync as Io,mkdirSync as Ro,readFileSync as To,readdirSync as Oo,writeFileSync as Ze}from"fs";import{join as Qe}from"path";var Po="cueframe.json";function Ao(t){return t.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join("")}function Fo(t){return t.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" ")}function xe(t,e){g(t,"new_component",new Error(e),m.UserError),l(m.UserError)}function Mo(t,e){return`import React from 'react';
|
|
11
|
+
${He}
|
|
12
|
+
`)}return!0}return e||gt(r,`# CueFrame derived render cache (regenerated; never authored)
|
|
13
|
+
${He}
|
|
14
|
+
`),!0}function Ut(t){let e=process.cwd(),r=t.dryRun??!1;g(t,"init_prepare",{cwd:e,dryRun:r});let n=ht(e,Mt),o=ft(n),s=ln;if(o)try{let l=JSON.parse(Ft(n,"utf8"));typeof l.componentsDir=="string"&&l.componentsDir.length>0&&(s=l.componentsDir)}catch{}else r||gt(n,`${JSON.stringify({componentsDir:s},null,2)}
|
|
15
|
+
`);let i=ht(e,s),a=ft(i);!a&&!r&&dn(i,{recursive:!0});let d=un(e,r);T(t,{ok:!0,dryRun:r,root:e,manifest:{path:n,created:!o},componentsDir:s,componentsDirCreated:!a,gitignoreUpdated:d},()=>{console.log(`\u2713 ${r?"Would initialize":"Initialized"} CueFrame workspace at ${e}`),console.log(` ${o?"kept":"created"} ${Mt} (componentsDir: ${s})`),console.log(` ${a?"exists":"created"} ${s}/`),d&&console.log(` gitignored ${He}`),console.log("Next: cueframe eject <primitive> or cueframe new component <name>")})}import{existsSync as Io,mkdirSync as Oo,readFileSync as Ao,readdirSync as Po,writeFileSync as Xt}from"fs";import{join as Qt}from"path";import{existsSync as rt,readFileSync as ko,readdirSync as Eo,statSync as So}from"fs";import{dirname as jo,join as Ne,parse as Co}from"path";var ze={};Zr(ze,{BRAND:()=>Fn,DIRTY:()=>de,EMPTY_PATH:()=>gn,INVALID:()=>w,NEVER:()=>bo,OK:()=>U,ParseStatus:()=>M,Schema:()=>S,ZodAny:()=>ae,ZodArray:()=>re,ZodBigInt:()=>ue,ZodBoolean:()=>me,ZodBranded:()=>De,ZodCatch:()=>ke,ZodDate:()=>pe,ZodDefault:()=>be,ZodDiscriminatedUnion:()=>Qe,ZodEffects:()=>B,ZodEnum:()=>xe,ZodError:()=>z,ZodFirstPartyTypeKind:()=>b,ZodFunction:()=>tt,ZodIntersection:()=>ye,ZodIssueCode:()=>p,ZodLazy:()=>ve,ZodLiteral:()=>_e,ZodMap:()=>Oe,ZodNaN:()=>Pe,ZodNativeEnum:()=>we,ZodNever:()=>G,ZodNull:()=>ge,ZodNullable:()=>Y,ZodNumber:()=>le,ZodObject:()=>W,ZodOptional:()=>q,ZodParsedType:()=>y,ZodPipeline:()=>Le,ZodPromise:()=>ce,ZodReadonly:()=>Ee,ZodRecord:()=>et,ZodSchema:()=>S,ZodSet:()=>Ae,ZodString:()=>ie,ZodSymbol:()=>Re,ZodTransformer:()=>B,ZodTuple:()=>H,ZodType:()=>S,ZodUndefined:()=>fe,ZodUnion:()=>he,ZodUnknown:()=>te,ZodVoid:()=>Ie,addIssueToContext:()=>h,any:()=>Bn,array:()=>Hn,bigint:()=>zn,boolean:()=>Kt,coerce:()=>wo,custom:()=>Bt,date:()=>Wn,datetimeRegex:()=>qt,defaultErrorMap:()=>Q,discriminatedUnion:()=>eo,effect:()=>po,enum:()=>lo,function:()=>io,getErrorMap:()=>Ce,getParsedType:()=>K,instanceof:()=>Dn,intersection:()=>to,isAborted:()=>Ye,isAsync:()=>$e,isDirty:()=>Xe,isValid:()=>se,late:()=>Un,lazy:()=>ao,literal:()=>co,makeIssue:()=>Ue,map:()=>oo,nan:()=>Ln,nativeEnum:()=>uo,never:()=>Gn,null:()=>Vn,nullable:()=>go,number:()=>Gt,object:()=>Yn,objectUtil:()=>yt,oboolean:()=>xo,onumber:()=>_o,optional:()=>fo,ostring:()=>vo,pipeline:()=>yo,preprocess:()=>ho,promise:()=>mo,quotelessJson:()=>mn,record:()=>no,set:()=>so,setErrorMap:()=>fn,strictObject:()=>Xn,string:()=>Zt,symbol:()=>Jn,transformer:()=>po,tuple:()=>ro,undefined:()=>qn,union:()=>Qn,unknown:()=>Zn,util:()=>$,void:()=>Kn});var $;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})($||($={}));var yt;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(yt||(yt={}));var y=$.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),K=t=>{switch(typeof t){case"undefined":return y.undefined;case"string":return y.string;case"number":return Number.isNaN(t)?y.nan:y.number;case"boolean":return y.boolean;case"function":return y.function;case"bigint":return y.bigint;case"symbol":return y.symbol;case"object":return Array.isArray(t)?y.array:t===null?y.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?y.promise:typeof Map<"u"&&t instanceof Map?y.map:typeof Set<"u"&&t instanceof Set?y.set:typeof Date<"u"&&t instanceof Date?y.date:y.object;default:return y.unknown}};var p=$.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"]),mn=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),z=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(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,d=0;for(;d<i.path.length;){let l=i.path[d];d===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],d++}}};return o(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,$.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};z.create=t=>new z(t);var pn=(t,e)=>{let r;switch(t.code){case p.invalid_type:t.received===y.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case p.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,$.jsonStringifyReplacer)}`;break;case p.unrecognized_keys:r=`Unrecognized key(s) in object: ${$.joinValues(t.keys,", ")}`;break;case p.invalid_union:r="Invalid input";break;case p.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${$.joinValues(t.options)}`;break;case p.invalid_enum_value:r=`Invalid enum value. Expected ${$.joinValues(t.options)}, received '${t.received}'`;break;case p.invalid_arguments:r="Invalid function arguments";break;case p.invalid_return_type:r="Invalid function return type";break;case p.invalid_date:r="Invalid date";break;case p.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}"`:$.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case p.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 p.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 p.custom:r="Invalid input";break;case p.invalid_intersection_types:r="Intersection results could not be merged";break;case p.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case p.not_finite:r="Number must be finite";break;default:r=e.defaultError,$.assertNever(t)}return{message:r}},Q=pn;var Dt=Q;function fn(t){Dt=t}function Ce(){return Dt}var Ue=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",d=n.filter(l=>!!l).slice().reverse();for(let l of d)a=l(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},gn=[];function h(t,e){let r=Ce(),n=Ue({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Q?void 0:Q].filter(o=>!!o)});t.common.issues.push(n)}var M=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 o of r){if(o.status==="aborted")return w;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return w;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},w=Object.freeze({status:"aborted"}),de=t=>({status:"dirty",value:t}),U=t=>({status:"valid",value:t}),Ye=t=>t.status==="aborted",Xe=t=>t.status==="dirty",se=t=>t.status==="valid",$e=t=>typeof Promise<"u"&&t instanceof Promise;var _;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(_||(_={}));var V=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}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}},Lt=(t,e)=>{if(se(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 z(t.common.issues);return this._error=r,this._error}}};function E(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=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:o}:{errorMap:(i,a)=>{let{message:d}=t;return i.code==="invalid_enum_value"?{message:d??a.defaultError}:typeof a.data>"u"?{message:d??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:d??r??a.defaultError}},description:o}}var S=class{get description(){return this._def.description}_getType(e){return K(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:K(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new M,ctx:{common:e.parent.common,data:e.data,parsedType:K(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if($e(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:K(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Lt(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:K(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return se(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=>se(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:K(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await($e(o)?o:Promise.resolve(o));return Lt(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:p.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(d=>d?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new B({schema:this,typeName:b.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 q.create(this,this._def)}nullable(){return Y.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return re.create(this)}promise(){return ce.create(this,this._def)}or(e){return he.create([this,e],this._def)}and(e){return ye.create(this,e,this._def)}transform(e){return new B({...E(this._def),schema:this,typeName:b.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new be({...E(this._def),innerType:this,defaultValue:r,typeName:b.ZodDefault})}brand(){return new De({typeName:b.ZodBranded,type:this,...E(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new ke({...E(this._def),innerType:this,catchValue:r,typeName:b.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Le.create(this,e)}readonly(){return Ee.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},hn=/^c[^\s-]{8,}$/i,yn=/^[0-9a-z]+$/,vn=/^[0-9A-HJKMNP-TV-Z]{26}$/i,_n=/^[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,xn=/^[a-z0-9_-]{21}$/i,wn=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,bn=/^[-+]?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)?)??$/,kn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,En="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",vt,Sn=/^(?:(?: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])$/,jn=/^(?:(?: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])$/,Cn=/^(([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]))$/,$n=/^(([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])$/,Tn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Rn=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Wt="((\\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])))",In=new RegExp(`^${Wt}$`);function Jt(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 On(t){return new RegExp(`^${Jt(t)}$`)}function qt(t){let e=`${Wt}T${Jt(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 An(t,e){return!!((e==="v4"||!e)&&Sn.test(t)||(e==="v6"||!e)&&Cn.test(t))}function Pn(t,e){if(!wn.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,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function Nn(t,e){return!!((e==="v4"||!e)&&jn.test(t)||(e==="v6"||!e)&&$n.test(t))}var ie=class t extends S{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==y.string){let s=this._getOrReturnCtx(e);return h(s,{code:p.invalid_type,expected:y.string,received:s.parsedType}),w}let n=new M,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),h(o,{code:p.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),h(o,{code:p.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?h(o,{code:p.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&h(o,{code:p.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")kn.test(e.data)||(o=this._getOrReturnCtx(e,o),h(o,{validation:"email",code:p.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")vt||(vt=new RegExp(En,"u")),vt.test(e.data)||(o=this._getOrReturnCtx(e,o),h(o,{validation:"emoji",code:p.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")_n.test(e.data)||(o=this._getOrReturnCtx(e,o),h(o,{validation:"uuid",code:p.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")xn.test(e.data)||(o=this._getOrReturnCtx(e,o),h(o,{validation:"nanoid",code:p.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")hn.test(e.data)||(o=this._getOrReturnCtx(e,o),h(o,{validation:"cuid",code:p.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")yn.test(e.data)||(o=this._getOrReturnCtx(e,o),h(o,{validation:"cuid2",code:p.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")vn.test(e.data)||(o=this._getOrReturnCtx(e,o),h(o,{validation:"ulid",code:p.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),h(o,{validation:"url",code:p.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),h(o,{validation:"regex",code:p.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),h(o,{code:p.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),h(o,{code:p.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),h(o,{code:p.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?qt(s).test(e.data)||(o=this._getOrReturnCtx(e,o),h(o,{code:p.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?In.test(e.data)||(o=this._getOrReturnCtx(e,o),h(o,{code:p.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?On(s).test(e.data)||(o=this._getOrReturnCtx(e,o),h(o,{code:p.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?bn.test(e.data)||(o=this._getOrReturnCtx(e,o),h(o,{validation:"duration",code:p.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?An(e.data,s.version)||(o=this._getOrReturnCtx(e,o),h(o,{validation:"ip",code:p.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?Pn(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),h(o,{validation:"jwt",code:p.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Nn(e.data,s.version)||(o=this._getOrReturnCtx(e,o),h(o,{validation:"cidr",code:p.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?Tn.test(e.data)||(o=this._getOrReturnCtx(e,o),h(o,{validation:"base64",code:p.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?Rn.test(e.data)||(o=this._getOrReturnCtx(e,o),h(o,{validation:"base64url",code:p.invalid_string,message:s.message}),n.dirty()):$.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:p.invalid_string,..._.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",..._.errToObj(e)})}url(e){return this._addCheck({kind:"url",..._.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",..._.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",..._.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",..._.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",..._.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",..._.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",..._.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",..._.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",..._.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",..._.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",..._.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",..._.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,..._.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,..._.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",..._.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,..._.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,..._.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,..._.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,..._.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,..._.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,..._.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,..._.errToObj(r)})}nonempty(e){return this.min(1,_.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}};ie.create=t=>new ie({checks:[],typeName:b.ZodString,coerce:t?.coerce??!1,...E(t)});function Mn(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var le=class t extends S{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)!==y.number){let s=this._getOrReturnCtx(e);return h(s,{code:p.invalid_type,expected:y.number,received:s.parsedType}),w}let n,o=new M;for(let s of this._def.checks)s.kind==="int"?$.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:p.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),h(n,{code:p.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),h(n,{code:p.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Mn(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),h(n,{code:p.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:p.not_finite,message:s.message}),o.dirty()):$.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,_.toString(r))}gt(e,r){return this.setLimit("min",e,!1,_.toString(r))}lte(e,r){return this.setLimit("max",e,!0,_.toString(r))}lt(e,r){return this.setLimit("max",e,!1,_.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:_.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:_.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:_.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:_.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:_.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:_.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:_.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:_.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:_.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:_.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"&&$.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)}};le.create=t=>new le({checks:[],typeName:b.ZodNumber,coerce:t?.coerce||!1,...E(t)});var ue=class t extends S{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)!==y.bigint)return this._getInvalidInput(e);let n,o=new M;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),h(n,{code:p.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),h(n,{code:p.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),h(n,{code:p.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):$.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return h(r,{code:p.invalid_type,expected:y.bigint,received:r.parsedType}),w}gte(e,r){return this.setLimit("min",e,!0,_.toString(r))}gt(e,r){return this.setLimit("min",e,!1,_.toString(r))}lte(e,r){return this.setLimit("max",e,!0,_.toString(r))}lt(e,r){return this.setLimit("max",e,!1,_.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:_.toString(o)}]})}_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:_.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:_.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:_.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:_.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:_.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}};ue.create=t=>new ue({checks:[],typeName:b.ZodBigInt,coerce:t?.coerce??!1,...E(t)});var me=class extends S{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==y.boolean){let n=this._getOrReturnCtx(e);return h(n,{code:p.invalid_type,expected:y.boolean,received:n.parsedType}),w}return U(e.data)}};me.create=t=>new me({typeName:b.ZodBoolean,coerce:t?.coerce||!1,...E(t)});var pe=class t extends S{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==y.date){let s=this._getOrReturnCtx(e);return h(s,{code:p.invalid_type,expected:y.date,received:s.parsedType}),w}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return h(s,{code:p.invalid_date}),w}let n=new M,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),h(o,{code:p.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),h(o,{code:p.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):$.assertNever(s);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:_.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:_.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}};pe.create=t=>new pe({checks:[],coerce:t?.coerce||!1,typeName:b.ZodDate,...E(t)});var Re=class extends S{_parse(e){if(this._getType(e)!==y.symbol){let n=this._getOrReturnCtx(e);return h(n,{code:p.invalid_type,expected:y.symbol,received:n.parsedType}),w}return U(e.data)}};Re.create=t=>new Re({typeName:b.ZodSymbol,...E(t)});var fe=class extends S{_parse(e){if(this._getType(e)!==y.undefined){let n=this._getOrReturnCtx(e);return h(n,{code:p.invalid_type,expected:y.undefined,received:n.parsedType}),w}return U(e.data)}};fe.create=t=>new fe({typeName:b.ZodUndefined,...E(t)});var ge=class extends S{_parse(e){if(this._getType(e)!==y.null){let n=this._getOrReturnCtx(e);return h(n,{code:p.invalid_type,expected:y.null,received:n.parsedType}),w}return U(e.data)}};ge.create=t=>new ge({typeName:b.ZodNull,...E(t)});var ae=class extends S{constructor(){super(...arguments),this._any=!0}_parse(e){return U(e.data)}};ae.create=t=>new ae({typeName:b.ZodAny,...E(t)});var te=class extends S{constructor(){super(...arguments),this._unknown=!0}_parse(e){return U(e.data)}};te.create=t=>new te({typeName:b.ZodUnknown,...E(t)});var G=class extends S{_parse(e){let r=this._getOrReturnCtx(e);return h(r,{code:p.invalid_type,expected:y.never,received:r.parsedType}),w}};G.create=t=>new G({typeName:b.ZodNever,...E(t)});var Ie=class extends S{_parse(e){if(this._getType(e)!==y.undefined){let n=this._getOrReturnCtx(e);return h(n,{code:p.invalid_type,expected:y.void,received:n.parsedType}),w}return U(e.data)}};Ie.create=t=>new Ie({typeName:b.ZodVoid,...E(t)});var re=class t extends S{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==y.array)return h(r,{code:p.invalid_type,expected:y.array,received:r.parsedType}),w;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(h(r,{code:i?p.too_big:p.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(h(r,{code:p.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(h(r,{code:p.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new V(r,i,r.path,a)))).then(i=>M.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new V(r,i,r.path,a)));return M.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:_.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:_.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:_.toString(r)}})}nonempty(e){return this.min(1,e)}};re.create=(t,e)=>new re({type:t,minLength:null,maxLength:null,exactLength:null,typeName:b.ZodArray,...E(e)});function Te(t){if(t instanceof W){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=q.create(Te(n))}return new W({...t._def,shape:()=>e})}else return t instanceof re?new re({...t._def,type:Te(t.element)}):t instanceof q?q.create(Te(t.unwrap())):t instanceof Y?Y.create(Te(t.unwrap())):t instanceof H?H.create(t.items.map(e=>Te(e))):t}var W=class t extends S{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=$.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==y.object){let l=this._getOrReturnCtx(e);return h(l,{code:p.invalid_type,expected:y.object,received:l.parsedType}),w}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof G&&this._def.unknownKeys==="strip"))for(let l in o.data)i.includes(l)||a.push(l);let d=[];for(let l of i){let c=s[l],u=o.data[l];d.push({key:{status:"valid",value:l},value:c._parse(new V(o,u,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof G){let l=this._def.unknownKeys;if(l==="passthrough")for(let c of a)d.push({key:{status:"valid",value:c},value:{status:"valid",value:o.data[c]}});else if(l==="strict")a.length>0&&(h(o,{code:p.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 c of a){let u=o.data[c];d.push({key:{status:"valid",value:c},value:l._parse(new V(o,u,o.path,c)),alwaysSet:c in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let c of d){let u=await c.key,k=await c.value;l.push({key:u,value:k,alwaysSet:c.alwaysSet})}return l}).then(l=>M.mergeObjectSync(n,l)):M.mergeObjectSync(n,d)}get shape(){return this._def.shape()}strict(e){return _.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:_.errToObj(e).message??o}:{message:o}}}:{}})}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:b.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 $.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 $.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Te(this)}partial(e){let r={};for(let n of $.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of $.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof q;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Vt($.objectKeys(this.shape))}};W.create=(t,e)=>new W({shape:()=>t,unknownKeys:"strip",catchall:G.create(),typeName:b.ZodObject,...E(e)});W.strictCreate=(t,e)=>new W({shape:()=>t,unknownKeys:"strict",catchall:G.create(),typeName:b.ZodObject,...E(e)});W.lazycreate=(t,e)=>new W({shape:t,unknownKeys:"strip",catchall:G.create(),typeName:b.ZodObject,...E(e)});var he=class extends S{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new z(a.ctx.common.issues));return h(r,{code:p.invalid_union,unionErrors:i}),w}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let d of n){let l={...r,common:{...r.common,issues:[]},parent:null},c=d._parseSync({data:r.data,path:r.path,parent:l});if(c.status==="valid")return c;c.status==="dirty"&&!s&&(s={result:c,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(d=>new z(d));return h(r,{code:p.invalid_union,unionErrors:a}),w}}get options(){return this._def.options}};he.create=(t,e)=>new he({options:t,typeName:b.ZodUnion,...E(e)});var ee=t=>t instanceof ve?ee(t.schema):t instanceof B?ee(t.innerType()):t instanceof _e?[t.value]:t instanceof xe?t.options:t instanceof we?$.objectValues(t.enum):t instanceof be?ee(t._def.innerType):t instanceof fe?[void 0]:t instanceof ge?[null]:t instanceof q?[void 0,...ee(t.unwrap())]:t instanceof Y?[null,...ee(t.unwrap())]:t instanceof De||t instanceof Ee?ee(t.unwrap()):t instanceof ke?ee(t._def.innerType):[],Qe=class t extends S{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==y.object)return h(r,{code:p.invalid_type,expected:y.object,received:r.parsedType}),w;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(h(r,{code:p.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),w)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=ee(s.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(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:b.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...E(n)})}};function _t(t,e){let r=K(t),n=K(e);if(t===e)return{valid:!0,data:t};if(r===y.object&&n===y.object){let o=$.objectKeys(e),s=$.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let d=_t(t[a],e[a]);if(!d.valid)return{valid:!1};i[a]=d.data}return{valid:!0,data:i}}else if(r===y.array&&n===y.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],d=_t(i,a);if(!d.valid)return{valid:!1};o.push(d.data)}return{valid:!0,data:o}}else return r===y.date&&n===y.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var ye=class extends S{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Ye(s)||Ye(i))return w;let a=_t(s.value,i.value);return a.valid?((Xe(s)||Xe(i))&&r.dirty(),{status:r.value,value:a.data}):(h(n,{code:p.invalid_intersection_types}),w)};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(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};ye.create=(t,e,r)=>new ye({left:t,right:e,typeName:b.ZodIntersection,...E(r)});var H=class t extends S{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==y.array)return h(n,{code:p.invalid_type,expected:y.array,received:n.parsedType}),w;if(n.data.length<this._def.items.length)return h(n,{code:p.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w;!this._def.rest&&n.data.length>this._def.items.length&&(h(n,{code:p.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let d=this._def.items[a]||this._def.rest;return d?d._parse(new V(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>M.mergeArray(r,i)):M.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};H.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new H({items:t,typeName:b.ZodTuple,rest:null,...E(e)})};var et=class t extends S{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!==y.object)return h(n,{code:p.invalid_type,expected:y.object,received:n.parsedType}),w;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new V(n,a,n.path,a)),value:i._parse(new V(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?M.mergeObjectAsync(r,o):M.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof S?new t({keyType:e,valueType:r,typeName:b.ZodRecord,...E(n)}):new t({keyType:ie.create(),valueType:e,typeName:b.ZodRecord,...E(r)})}},Oe=class extends S{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!==y.map)return h(n,{code:p.invalid_type,expected:y.map,received:n.parsedType}),w;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,d],l)=>({key:o._parse(new V(n,a,n.path,[l,"key"])),value:s._parse(new V(n,d,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let d of i){let l=await d.key,c=await d.value;if(l.status==="aborted"||c.status==="aborted")return w;(l.status==="dirty"||c.status==="dirty")&&r.dirty(),a.set(l.value,c.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let d of i){let l=d.key,c=d.value;if(l.status==="aborted"||c.status==="aborted")return w;(l.status==="dirty"||c.status==="dirty")&&r.dirty(),a.set(l.value,c.value)}return{status:r.value,value:a}}}};Oe.create=(t,e,r)=>new Oe({valueType:e,keyType:t,typeName:b.ZodMap,...E(r)});var Ae=class t extends S{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==y.set)return h(n,{code:p.invalid_type,expected:y.set,received:n.parsedType}),w;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(h(n,{code:p.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(h(n,{code:p.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(d){let l=new Set;for(let c of d){if(c.status==="aborted")return w;c.status==="dirty"&&r.dirty(),l.add(c.value)}return{status:r.value,value:l}}let a=[...n.data.values()].map((d,l)=>s._parse(new V(n,d,n.path,l)));return n.common.async?Promise.all(a).then(d=>i(d)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:_.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:_.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Ae.create=(t,e)=>new Ae({valueType:t,minSize:null,maxSize:null,typeName:b.ZodSet,...E(e)});var tt=class t extends S{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==y.function)return h(r,{code:p.invalid_type,expected:y.function,received:r.parsedType}),w;function n(a,d){return Ue({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ce(),Q].filter(l=>!!l),issueData:{code:p.invalid_arguments,argumentsError:d}})}function o(a,d){return Ue({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ce(),Q].filter(l=>!!l),issueData:{code:p.invalid_return_type,returnTypeError:d}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof ce){let a=this;return U(async function(...d){let l=new z([]),c=await a._def.args.parseAsync(d,s).catch(P=>{throw l.addIssue(n(d,P)),l}),u=await Reflect.apply(i,this,c);return await a._def.returns._def.type.parseAsync(u,s).catch(P=>{throw l.addIssue(o(u,P)),l})})}else{let a=this;return U(function(...d){let l=a._def.args.safeParse(d,s);if(!l.success)throw new z([n(d,l.error)]);let c=Reflect.apply(i,this,l.data),u=a._def.returns.safeParse(c,s);if(!u.success)throw new z([o(c,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:H.create(e).rest(te.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||H.create([]).rest(te.create()),returns:r||te.create(),typeName:b.ZodFunction,...E(n)})}},ve=class extends S{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})}};ve.create=(t,e)=>new ve({getter:t,typeName:b.ZodLazy,...E(e)});var _e=class extends S{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return h(r,{received:r.data,code:p.invalid_literal,expected:this._def.value}),w}return{status:"valid",value:e.data}}get value(){return this._def.value}};_e.create=(t,e)=>new _e({value:t,typeName:b.ZodLiteral,...E(e)});function Vt(t,e){return new xe({values:t,typeName:b.ZodEnum,...E(e)})}var xe=class t extends S{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return h(r,{expected:$.joinValues(n),received:r.parsedType,code:p.invalid_type}),w}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 h(r,{received:r.data,code:p.invalid_enum_value,options:n}),w}return U(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})}};xe.create=Vt;var we=class extends S{_parse(e){let r=$.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==y.string&&n.parsedType!==y.number){let o=$.objectValues(r);return h(n,{expected:$.joinValues(o),received:n.parsedType,code:p.invalid_type}),w}if(this._cache||(this._cache=new Set($.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=$.objectValues(r);return h(n,{received:n.data,code:p.invalid_enum_value,options:o}),w}return U(e.data)}get enum(){return this._def.values}};we.create=(t,e)=>new we({values:t,typeName:b.ZodNativeEnum,...E(e)});var ce=class extends S{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==y.promise&&r.common.async===!1)return h(r,{code:p.invalid_type,expected:y.promise,received:r.parsedType}),w;let n=r.parsedType===y.promise?r.data:Promise.resolve(r.data);return U(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ce.create=(t,e)=>new ce({type:t,typeName:b.ZodPromise,...E(e)});var B=class extends S{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===b.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{h(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return w;let d=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return d.status==="aborted"?w:d.status==="dirty"?de(d.value):r.value==="dirty"?de(d.value):d});{if(r.value==="aborted")return w;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?w:a.status==="dirty"?de(a.value):r.value==="dirty"?de(a.value):a}}if(o.type==="refinement"){let i=a=>{let d=o.refinement(a,s);if(n.common.async)return Promise.resolve(d);if(d 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"?w:(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"?w:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!se(i))return w;let a=o.transform(i.value,s);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=>se(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):w);$.assertNever(o)}};B.create=(t,e,r)=>new B({schema:t,typeName:b.ZodEffects,effect:e,...E(r)});B.createWithPreprocess=(t,e,r)=>new B({schema:e,effect:{type:"preprocess",transform:t},typeName:b.ZodEffects,...E(r)});var q=class extends S{_parse(e){return this._getType(e)===y.undefined?U(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};q.create=(t,e)=>new q({innerType:t,typeName:b.ZodOptional,...E(e)});var Y=class extends S{_parse(e){return this._getType(e)===y.null?U(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Y.create=(t,e)=>new Y({innerType:t,typeName:b.ZodNullable,...E(e)});var be=class extends S{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===y.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};be.create=(t,e)=>new be({innerType:t,typeName:b.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...E(e)});var ke=class extends S{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return $e(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new z(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new z(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ke.create=(t,e)=>new ke({innerType:t,typeName:b.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...E(e)});var Pe=class extends S{_parse(e){if(this._getType(e)!==y.nan){let n=this._getOrReturnCtx(e);return h(n,{code:p.invalid_type,expected:y.nan,received:n.parsedType}),w}return{status:"valid",value:e.data}}};Pe.create=t=>new Pe({typeName:b.ZodNaN,...E(t)});var Fn=Symbol("zod_brand"),De=class extends S{_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}},Le=class t extends S{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?w:s.status==="dirty"?(r.dirty(),de(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?w:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:b.ZodPipeline})}},Ee=class extends S{_parse(e){let r=this._def.innerType._parse(e),n=o=>(se(o)&&(o.value=Object.freeze(o.value)),o);return $e(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Ee.create=(t,e)=>new Ee({innerType:t,typeName:b.ZodReadonly,...E(e)});function zt(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Bt(t,e={},r){return t?ae.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=zt(e,n),d=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:d})}});if(!s){let i=zt(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):ae.create()}var Un={object:W.lazycreate},b;(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"})(b||(b={}));var Dn=(t,e={message:`Input not instance of ${t.name}`})=>Bt(r=>r instanceof t,e),Zt=ie.create,Gt=le.create,Ln=Pe.create,zn=ue.create,Kt=me.create,Wn=pe.create,Jn=Re.create,qn=fe.create,Vn=ge.create,Bn=ae.create,Zn=te.create,Gn=G.create,Kn=Ie.create,Hn=re.create,Yn=W.create,Xn=W.strictCreate,Qn=he.create,eo=Qe.create,to=ye.create,ro=H.create,no=et.create,oo=Oe.create,so=Ae.create,io=tt.create,ao=ve.create,co=_e.create,lo=xe.create,uo=we.create,mo=ce.create,po=B.create,fo=q.create,go=Y.create,ho=B.createWithPreprocess,yo=Le.create,vo=()=>Zt().optional(),_o=()=>Gt().optional(),xo=()=>Kt().optional(),wo={string:(t=>ie.create({...t,coerce:!0})),number:(t=>le.create({...t,coerce:!0})),boolean:(t=>me.create({...t,coerce:!0})),bigint:(t=>ue.create({...t,coerce:!0})),date:(t=>pe.create({...t,coerce:!0}))};var bo=w;var $o="cueframe/components";var To="cueframe.json",Ro=ze.object({componentsDir:ze.string().min(1).default($o)}).passthrough();function Me(t){let e=t,r=Co(e).root;for(;;){let n=Ne(e,To);if(rt(n)){let o=ko(n,"utf8"),s=Ro.parse(JSON.parse(o));return{root:e,manifest:s}}if(e===r)return null;e=jo(e)}}function Ht(t){return Ne(t.root,t.manifest.componentsDir)}function We(t,e){return Ne(Ht(t),e)}function Yt(t){let e=Ht(t);return rt(e)?Eo(e).filter(r=>{let n=Ne(e,r);return So(n).isDirectory()?rt(Ne(n,"index.tsx"))&&rt(Ne(n,"config.ts")):!1}).sort():[]}var No="cueframe.json";function Mo(t){return t.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("")}function Fo(t){return t.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ")}function xt(t,e){x(t,"new_component",new Error(e),f.UserError),m(f.UserError)}function Uo(t,e){return`import React from 'react';
|
|
28
16
|
|
|
29
17
|
/** Custom CueFrame component. Mounted as ({ durationInFrames, params }). Edit me. */
|
|
30
18
|
export default function ${e}({ params }: { durationInFrames: number; params: Record<string, unknown> }) {
|
|
31
19
|
return <div style={{ width: '100%', height: '100%', display: 'grid', placeItems: 'center' }}>{String((params as { text?: unknown }).text ?? '${t}')}</div>;
|
|
32
20
|
}
|
|
33
|
-
`}function
|
|
21
|
+
`}function Do(t,e){return`import { z } from 'zod';
|
|
34
22
|
import component from './index';
|
|
35
23
|
|
|
36
24
|
const paramsSchema = z.object({}).passthrough();
|
|
@@ -45,40 +33,29 @@ export const config = {
|
|
|
45
33
|
paramsSchema,
|
|
46
34
|
};
|
|
47
35
|
export default config;
|
|
48
|
-
`}function
|
|
49
|
-
`)}
|
|
50
|
-
${
|
|
51
|
-
`),console.log(" Shown ONCE \u2014 store it now (paste it into your integration; not saved here).")})}catch(
|
|
52
|
-
Media item ID: ${a}`,e);let{analyzeCommand:
|
|
36
|
+
`}function er(t,e){R(t,"name",e);let r=e.dryRun??!1,n=e.force??!1,o=Mo(t);o||xt(e,`name "${t}" has no alphanumeric characters to form a component identifier.`);let s=Fo(t);g(e,"new_component_prepare",{name:t,dryRun:r,force:n});let i=Me(process.cwd());i||xt(e,"No CueFrame workspace found (no cueframe.json up-tree). Run `cueframe init` first to scaffold one.");let a=We(i,t),d=Io(a);d&&Po(a).length>0&&!n&&xt(e,`Component dir ${a} already exists and is non-empty. Pass --force to overwrite (this replaces local source).`);let l={"index.tsx":Uo(t,o),"config.ts":Do(t,s)};if(!r){Oo(a,{recursive:!0});for(let[P,ne]of Object.entries(l))Xt(Qt(a,P),ne);let c=Qt(i.root,No),u=JSON.parse(Ao(c,"utf8")),k=u.components??{};k[t]={custom:!0},u.components=k,Xt(c,`${JSON.stringify(u,null,2)}
|
|
37
|
+
`)}T(e,{ok:!0,dryRun:r,name:t,component:o,dir:a,files:Object.keys(l),overwritten:d&&n},()=>{console.log(`\u2713 ${r?"Would scaffold":"Scaffolded"} custom component ${t} (${o}) into ${a}`);for(let u of Object.keys(l))console.log(` ${r?"would write":"wrote"} ${u}`);r||console.log(` stamped cueframe.json components.${t} (custom)`),console.log("Edit index.tsx, then `cueframe push "+t+"` to publish it to CueFrame.")})}import{existsSync as ot,readFileSync as st}from"fs";import{join as it}from"path";import N from"typescript";var Lo="cueframe.json",zo=["effects","transitions","text","layouts"];function Wo(t){return zo.includes(t??"")?t:"layouts"}function Jo(t){let e=t;for(;N.isAsExpression(e)||N.isParenthesizedExpression(e)||typeof N.isSatisfiesExpression=="function"&&N.isSatisfiesExpression(e);)e=e.expression;return e}function qo(t,e){for(let r of t.statements)if(N.isImportDeclaration(r)&&N.isStringLiteral(r.moduleSpecifier)&&r.moduleSpecifier.text===e)return!0;return!1}function tr(t,e){let r=N.createSourceFile(e,t,N.ScriptTarget.Latest,!0,N.ScriptKind.TS),n;for(let s of r.statements)if(N.isVariableStatement(s)){for(let i of s.declarationList.declarations)if(N.isIdentifier(i.name)&&i.name.text==="config"&&i.initializer){let a=Jo(i.initializer);N.isObjectLiteralExpression(a)&&(n=a)}if(n)break}let o={};if(!n)return o;for(let s of n.properties){if(!N.isPropertyAssignment(s)||!(N.isIdentifier(s.name)||N.isStringLiteral(s.name)))continue;let i=s.name.text;N.isStringLiteralLike(s.initializer)&&(i==="name"?o.name=s.initializer.text:i==="category"?o.category=s.initializer.text:i==="version"&&(o.version=s.initializer.text))}return o}function Vo(t){let e=it(t,"config.ts");if(!ot(e))return{};let r=st(e,"utf8"),n=N.createSourceFile("config.ts",r,N.ScriptTarget.Latest,!0,N.ScriptKind.TS),o=it(t,"_config.ts");return qo(n,"./_config")&&ot(o)?tr(st(o,"utf8"),"_config.ts"):tr(r,"config.ts")}function Bo(t){return t.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Zo(t,e){let r=it(t.root,Lo);if(ot(r))try{let o=JSON.parse(st(r,"utf8")).components?.[e]?.ejectedFrom;return typeof o=="string"&&o.length>0?o:void 0}catch{return}}var nt="none \u2014 params are unvalidated server-side";async function rr(t,e,r){let n=We(t,e),o=it(n,"index.tsx");if(!ot(o))throw Object.assign(new Error(`Component "${e}" has no index.tsx at ${n}. Scaffold it first (cueframe eject / new component).`),{code:"no_component_source"});let s=st(o,"utf8"),i=Vo(n),a=i.name??Bo(e),d=Wo(i.category),l=Zo(t,e),c=`Custom component "${e}" pushed from the local CueFrame workspace.`,u={type:"object",properties:{}};g(r,"push_component",{id:e,name:a,category:d,version:i.version,ejectedFrom:l,propSchema:nt});let k=!1;try{await Be.getComponent(e),k=!0}catch(P){if(P instanceof J&&P.status===404)k=!1;else throw P}return k?(await Be.updateComponent(e,{tsxSource:s,name:a,description:c,category:d,propSchema:u,origin:"repo-owned",...l?{ejectedFrom:l}:{}}),g(r,"pushed",{id:e,action:"updated"}),{id:e,action:"updated",name:a,category:d,propSchema:nt}):(await Be.createComponent({componentId:e,tsxSource:s,name:a,description:c,category:d,propSchema:u,origin:"repo-owned",...l?{ejectedFrom:l}:{}}),g(r,"pushed",{id:e,action:"created"}),{id:e,action:"created",name:a,category:d,propSchema:nt})}async function nr(t,e){t||(x(e,"push",new Error("Pass a component id (cueframe push <id>), or use `cueframe sync` to push all."),f.UserError),m(f.UserError)),R(t,"id",e),j(e.target);let r=Me(process.cwd());r||(x(e,"push",new Error("No CueFrame workspace found (no cueframe.json up-tree). Run `cueframe init` first."),f.UserError),m(f.UserError)),g(e,"push_prepare",{id:t,target:e.target});try{let n=await rr(r,t,e);T(e,{ok:!0,target:e.target,...n},()=>{console.log(`\u2713 ${n.action} component ${n.id} (${n.name}) on CueFrame`),console.log(` propSchema: ${n.propSchema}`)})}catch(n){let o=n.code==="no_component_source"?f.UserError:v(n);x(e,"push",n,o),m(o)}}async function or(t){j(t.target);let e=Me(process.cwd());e||(x(t,"sync",new Error("No CueFrame workspace found (no cueframe.json up-tree). Run `cueframe init` first."),f.UserError),m(f.UserError));let r=Yt(e);g(t,"sync_prepare",{target:t.target,count:r.length,ids:r});let n=[],o=[];for(let s of r)try{n.push(await rr(e,s,t))}catch(i){let a=i.code==="no_component_source"?f.UserError:v(i);O(t,"sync",i,a),o.push({id:s,error:i})}T(t,{ok:o.length===0,target:t.target,pushed:n,failed:o.map(s=>({id:s.id,error:I(s.error)}))},()=>{if(n.length===0&&o.length===0){console.log("No components to sync. Scaffold one with `cueframe eject` or `cueframe new component`.");return}for(let s of n)console.log(`\u2713 ${s.action} ${s.id} (${s.name})`);n.length>0&&console.log(` propSchema: ${nt}`);for(let s of o)console.error(`\u2716 ${s.id}: ${I(s.error)}`);console.log(`Synced ${n.length}/${r.length} component(s) to CueFrame.`)}),o.length>0&&m(v(o[0].error))}var at=["media","sessions","projects","renders","webhooks"],sr={readonly:Object.fromEntries(at.map(t=>[t,["read"]])),editall:Object.fromEntries(at.map(t=>[t,["read","write"]]))};function Go(t){if(t.preset){let e=sr[t.preset];return e||(console.error(`Unknown --preset "${t.preset}". Valid: ${Object.keys(sr).join(", ")}.`),m(f.UserError)),e}if(t.scope)return Ko(t.scope);console.error("Provide --scope or --preset (e.g. --preset readonly | editall)."),m(f.UserError)}function Ko(t){let e={};for(let r of t.split(",").map(n=>n.trim()).filter(Boolean)){let[n,o]=r.split(":");(!n||!o)&&(console.error(`Invalid --scope "${r}". Use resource:rw (e.g. renders:rw,media:r).`),m(f.UserError)),at.includes(n)||(console.error(`--scope "${r}": unknown resource "${n}". Valid: ${at.join(", ")}.`),m(f.UserError));let s=[];/r/i.test(o)&&s.push("read"),/w/i.test(o)&&s.push("write"),s.length===0&&(console.error(`--scope "${r}": actions must include r and/or w.`),m(f.UserError)),e[n]=s}return Object.keys(e).length===0&&(console.error("--scope is required, e.g. --scope media:rw,projects:rw,renders:rw"),m(f.UserError)),e}async function ir(t){j(t.target);let e=Go(t),r={name:t.name,permissions:e};if(t.expires){let n=Number(t.expires);(!Number.isFinite(n)||n<=0)&&(console.error("--expires must be a positive number of days."),m(f.UserError)),r.expiresIn=Math.round(n*86400)}try{let n=await mt("/v1/api-keys",{method:"POST",body:JSON.stringify(r),headers:{"content-type":"application/json"}});T(t,{ok:!0,id:n.id,prefix:n.prefix,start:n.start,key:n.key},()=>{let o=Object.entries(e).map(([s,i])=>`${s}:${i.map(a=>a[0]).join("")}`).join(" ");console.log(`\u2713 API key "${t.name}" created \u2014 scopes: ${o}`),console.log(`
|
|
38
|
+
${n.key}
|
|
39
|
+
`),console.log(" Shown ONCE \u2014 store it now (paste it into your integration; not saved here).")})}catch(n){x(t,"keys_create",n,v(n)),m(v(n))}}async function ar(t){j(t.target);let e;try{e=await L("/api/auth/api-key/list",{method:"GET"})}catch(n){x(t,"keys_list",n,v(n)),m(v(n))}e.status>=400&&(x(t,"keys_list",new Error(`list failed (${e.status})`),F(e.status)),m(F(e.status)));let r=Array.isArray(e.body)?e.body:[];T(t,{ok:!0,keys:r},()=>{if(r.length===0){console.log("No API keys.");return}for(let n of r)console.log(` ${n.id} ${n.name??"(unnamed)"} ${n.start??""}\u2026`)})}async function cr(t,e){j(e.target);let r;try{r=await L("/api/auth/api-key/delete",{method:"POST",body:JSON.stringify({keyId:t}),headers:{"content-type":"application/json"}})}catch(n){x(e,"keys_revoke",n,v(n)),m(v(n))}r.status>=400&&(x(e,"keys_revoke",new Error(`revoke failed (${r.status})`),F(r.status)),m(F(r.status))),T(e,{ok:!0,revoked:t},()=>console.log(`\u2713 Revoked ${t}`))}async function dr(t){j(t.target),g(t,"list_prepare",{target:t.target});try{let e=await Se.listProjects(),r=t.limit,n=typeof r=="number"&&Number.isFinite(r)&&r>0?e.data.slice(0,r):e.data;if(g(t,"list_complete",{count:n.length,total:e.data.length,truncated:n.length<e.data.length,projects:n}),!t.json){if(e.data.length===0){console.log("No projects found.");return}for(let o of n){let s=new Date(o.createdAt).toLocaleDateString();console.log(` ${o.id} ${o.name} (${s})`)}n.length<e.data.length&&console.log(` \u2026 ${e.data.length-n.length} more (raise --limit to see all)`)}}catch(e){x(t,"list",e,v(e)),m(v(e))}}import{readFile as Ho,stat as Yo}from"fs/promises";import{existsSync as Xo}from"fs";import{basename as Qo,extname as es}from"path";var ts=4e3,lr=1800*1e3,ur=5,mr={".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".mkv":"video/x-matroska",".wav":"audio/wav",".mp3":"audio/mpeg",".m4a":"audio/mp4",".aac":"audio/aac",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml"};function rs(t,e){let r=es(t).toLowerCase(),n=mr[r];if(!n){let o=new Error(`Unsupported file extension "${r||"(none)"}" for ${t}. Supported: ${Object.keys(mr).join(", ")}.`);x(e,"preflight",o,f.UserError),m(f.UserError)}return n}var pr=["vo","music","sfx","ambience"];async function fr(t,e){Xo(t)||(x(e,"preflight",new Error(`File not found: ${t}`),f.UserError),m(f.UserError));let r=Qo(t),n=(await Yo(t)).size,o=rs(r,e);if(e.audioRole&&!pr.includes(e.audioRole)){let C=new Error(`--audio-role must be one of ${pr.join("|")} (got "${e.audioRole}")`);x(e,"preflight",C,f.UserError),m(f.UserError)}let s=e.audioRole;if(e.dryRun){g(e,"upload_dry_run",{file:r,sizeBytes:n,contentType:o,target:e.target,analyzeAfter:!!e.analyze,wouldCall:"POST /v1/media \u2192 presigned PUT \u2192 POST /v1/media/:id/finalize \u2192 poll processing"}),e.json||console.log(`[dry-run] Would upload ${r} (${(n/1024/1024).toFixed(1)} MB, ${o}) to ${e.target}.`);return}j(e.target),g(e,"upload_prepare",{file:r,sizeBytes:n,contentType:o,target:e.target});let i=A("Preparing upload\u2026",e.json),a,d;try{let C=await oe.createMediaUpload({filename:r,contentType:o,size:n});a=C.id,d=C.uploadUrl,i.succeed("Ready"),g(e,"upload_ready",{mediaItemId:a})}catch(C){i.fail(`Failed: ${I(C)}`),O(e,"upload_prepare",C,v(C)),m(v(C))}let l=Date.now(),c=A(`Uploading ${r} (${(n/1024/1024).toFixed(1)} MB)\u2026`,e.json);try{let C=await Ho(t),X=await fetch(d,{method:"PUT",headers:{"Content-Type":o},body:C});if(!X.ok)throw new Error(`presigned PUT failed: ${X.status} ${X.statusText}`);await oe.finalizeMedia(a,s?{audioRole:s}:{}),c.succeed(`Uploaded: ${r}`),g(e,"upload_complete",{mediaItemId:a,bytesUploaded:n,...s?{audioRole:s}:{},durationMs:Date.now()-l})}catch(C){c.fail(`Upload failed: ${I(C)}`),O(e,"upload",C,f.NetworkError),m(f.NetworkError)}let u=A("Processing (transcription)\u2026",e.json),k=Date.now(),P=null,ne=0;for(;;){if(await new Promise(C=>setTimeout(C,ts)),Date.now()-k>lr){let C=`Processing did not complete within ${Math.round(lr/6e4)}m. Media item ID: ${a}.`;u.fail(C),O(e,"process",new Error(C),f.ApiServerError),m(f.ApiServerError)}try{let C=await oe.getMedia(a);ne=0;let X=C?.processingStatus?.phase??"unknown",ut=C?.processingStatus?.percent??null,St=Math.round((Date.now()-k)/1e3),Br=ut!=null?` \xB7 ${Math.round(ut*100)}%`:"";if(u.text=`Processing\u2026 ${X}${Br} (${St}s)`,g(e,"process_progress",{phase:X,percent:ut,elapsedSec:St}),X==="complete"||X==="completed"){u.succeed(`Ready: ${a}`),P=C,g(e,"process_complete",{mediaItemId:a,durationMs:Date.now()-k,item:C});break}if(X==="error"){let jt=C?.processingStatus?.error??"unknown error";u.fail(`Processing failed: ${jt}`),O(e,"process",new Error(jt),f.ApiServerError),m(f.ApiServerError)}}catch(C){C instanceof J&&[401,403,404].includes(C.status)&&(u.fail(`Processing check failed: ${I(C)}`),O(e,"process",C,v(C)),m(v(C))),ne++,ne>=ur&&(u.fail(`Processing check failed: ${I(C)}`),O(e,"process",new Error(`Processing status unreadable after ${ur} consecutive failures: ${I(C)}`),v(C)),m(v(C)))}}if(e.analyze){Z(`
|
|
40
|
+
Media item ID: ${a}`,e);let{analyzeCommand:C}=await import("./analyze-6QSD7KHH.js");await C(a,{target:e.target,wait:!0,json:e.json});return}e.json||T(e,{mediaItemId:a,item:P},()=>{console.log(`
|
|
53
41
|
Media item ID: ${a}`),console.log(`
|
|
54
|
-
Run \`cueframe analyze ${a} --target ${e.target}\` to generate clip suggestions.`)})}function
|
|
55
|
-
`),
|
|
56
|
-
`))}function
|
|
57
|
-
|
|
58
|
-
`);
|
|
59
|
-
|
|
60
|
-
`)}}}
|
|
61
|
-
|
|
62
|
-
`))}catch{return null}return{event:e,data:r}}async function sr(t,e,o={}){let r=Date.now()+(o.timeoutMs??rr);for(;Date.now()<r;){let n=null;try{for await(let i of nr(t,e)){if(o.onTypedEvent?.(i.data),i.data.event==="checkpoint_reached"){let s=i.data.data;n={kind:"checkpoint",...s.checkpointId?{checkpointId:s.checkpointId}:{},stage:String(s.stage??""),version:Number(s.version??0),...s.artifactSummary?{artifactSummary:s.artifactSummary}:{}};break}if(i.data.event==="job_completed"){let s=i.data.data;n={kind:"complete",compositionId:s.compositionId??null,etag:s.etag??null};break}if(i.data.event==="job_failed"){let a=i.data.data.reason??"compose_failed";a==="cancelled"||a.startsWith("cancelled")?n={kind:"cancelled",reason:a}:n={kind:"error",message:a};break}}}catch(i){if(i instanceof I)throw i;await new Promise(s=>setTimeout(s,ht));continue}if(n)return n;await new Promise(i=>setTimeout(i,ht))}return{kind:"error",message:`Timed out waiting for compose to reach terminal state. ComposeJob: ${e}, Project: ${t}.`}}async function yt(t,e){E(t,"suggestionId",e),E(e.project,"projectId",e),w(e.target),p(e,"compose_prepare",{suggestionId:t,projectId:e.project,target:e.target});let o=e.idempotencyKey??await de("compose",[e.project,t,e.seed??"auto"]);p(e,"idempotency_key",{scope:"compose",key:o,overridden:!!e.idempotencyKey,seed:e.seed??null});let r=C(`Starting compose for ${t}\u2026`,e.json),n,i=!1;try{let u={suggestionId:t};if(e.critique!==void 0&&(u.critique=e.critique),e.clientNonce!==void 0&&(u.clientNonce=e.clientNonce),e.baseline!==void 0&&(u.parentJobId=e.baseline),e.maxCandidates!==void 0&&(u.maxCandidates=e.maxCandidates),e.holdAt!==void 0&&e.holdAt.length>0&&(u.holdAt=e.holdAt),e.seed!==void 0){let d=Number(e.seed);Number.isInteger(d)&&(u.seed=d)}let c=await k(`/v1/projects/${e.project}/compose`,{method:"POST",headers:{"content-type":"application/json","idempotency-key":o},body:JSON.stringify(u)});if(c.status>=400){let d=c.body?.error,h=d?.message??c.statusText;throw new I(c.status,{code:d?.code??"unknown",message:h})}n=c.body,i=c.headers["idempotency-replay"]==="true"}catch(u){r.fail(`Failed to start compose: ${v(u)}`),g(e,"compose_create",u,y(u)),l(y(u))}i?(p(e,"compose_idempotent_replay",{composeJobId:n.composeJobId,projectId:n.projectId,workflowId:n.workflowId,idempotencyKey:o}),r.text=`Compose already in flight or complete (job ${n.composeJobId})\u2026`):(p(e,"compose_started",{composeJobId:n.composeJobId,projectId:n.projectId,workflowId:n.workflowId}),r.text=`Composing (job ${n.composeJobId})\u2026`);let s,a,f=Date.now();try{s=await sr(e.project,n.composeJobId,{onTypedEvent:u=>{if(p(e,`compose:${u.event}`,{composeJobId:n.composeJobId,...u.data,timestamp:u.timestamp}),e.json)return;let c=Math.round((Date.now()-f)/1e3),d=u.data;if(u.event==="job_started")r.text=`Composing\u2026 ${d.candidateCount??"?"} candidates (${c}s)`;else if(u.event==="candidate_phase_started")r.text=`Candidate ${d.candidateIndex} starting (${c}s)`;else if(u.event==="candidate_phase_evaluated"){let h=d.perCriterion,x=h?`E${(h.editorial?.score??0).toFixed(1)} S${(h.spatial?.score??0).toFixed(1)} B${(h.brand?.score??0).toFixed(1)} C${(h.caption?.score??0).toFixed(1)}`:"";r.text=`Candidate ${d.candidateIndex} evaluated \xB7 ${x} (${c}s)`}else if(u.event==="critique_retry_started")r.text=`Candidate ${d.candidateIndex} retry ${d.attemptNumber} (${c}s)`;else if(u.event==="candidate_completed"){let h=typeof d.composite=="number"?d.composite.toFixed(2):"?";r.text=`Candidate ${d.candidateIndex} done \xB7 composite ${h} (${c}s)`}else if(u.event==="winner_selected"){let h=typeof d.composite=="number"?d.composite.toFixed(2):"?";(d.route==="publish"||d.route==="handoff")&&(a=d.route);let x=a==="handoff"?" \xB7 \u2691 handoff":a==="publish"?" \xB7 \u2713 publish":"";r.text=`Picked candidate ${d.candidateIndex} \xB7 composite ${h}${x} (${c}s)`}}})}catch(u){r.fail(`Compose watch failed: ${v(u)}`),g(e,"compose_watch",u,y(u)),l(y(u))}if(s.kind==="checkpoint"){r.warn(`Compose paused at the "${s.stage}" checkpoint (version ${s.version}) \u2014 awaiting your review.`),p(e,"compose_checkpoint",{composeJobId:n.composeJobId,projectId:e.project,...s.checkpointId?{checkpointId:s.checkpointId}:{},stage:s.stage,version:s.version,...s.artifactSummary?{artifactSummary:s.artifactSummary}:{}}),e.json||(console.log(`
|
|
63
|
-
Stage "${s.stage}" (version ${s.version}) is ready for review.`),s.artifactSummary&&console.log(` ${s.artifactSummary}`),s.checkpointId?(console.log(`
|
|
64
|
-
Review the packet (artifact, stills, verdicts, quote):`),console.log(` GET /v1/checkpoints/${s.checkpointId}`),console.log(" Then answer it:"),console.log(` cueframe compose resume ${s.checkpointId} --approve -t ${e.target} (or --revise --comments @notes.json [--edits @edits.json] / --abandon)`)):(console.log(`
|
|
65
|
-
Inspect it:`),console.log(` cueframe compose inspect ${n.composeJobId} --project ${e.project} -t ${e.target}`)));return}if(s.kind==="complete"){r.succeed(`Compose complete (job ${n.composeJobId})`),p(e,"compose_complete",{composeJobId:n.composeJobId,projectId:e.project,compositionId:s.compositionId,etag:s.etag}),e.json||(console.log(`
|
|
66
|
-
Project: ${e.project}`),s.compositionId&&console.log(` Composition: ${s.compositionId}`),s.etag&&console.log(` ETag: ${s.etag}`),a==="publish"?console.log(" Verdict: \u2713 publish \u2014 clears the quality bar, ships autonomously"):a==="handoff"&&console.log(" Verdict: \u2691 handoff \u2014 below bar / floor violation; review in your NLE before publishing"),console.log(`
|
|
67
|
-
\u2192 Render with: cueframe render ${e.project} -t ${e.target}`));return}s.kind==="cancelled"&&(r.warn(`Compose cancelled: ${s.reason}`),p(e,"compose_cancelled",{composeJobId:n.composeJobId,reason:s.reason}),l(m.UserError)),r.fail(`Compose failed: ${s.message}`),g(e,"compose_run",new Error(s.message),m.ApiServerError),l(m.ApiServerError)}async function wt(t){let e=t.aspect?{aspectRatio:t.aspect,fps:t.fps??30,resolution:t.resolution??"fhd"}:void 0;if(t.dryRun){if(p(t,"project_create_dry_run",{name:t.name,target:t.target,format:e??null,fromSuggestion:t.fromSuggestion??null,cheap:t.cheap??!1,wouldCall:t.fromSuggestion?t.cheap?"POST /v1/projects \u2192 POST /v1/projects/:id/composition/from-suggestion (sync translator)":"POST /v1/projects \u2192 POST /v1/projects/:id/compose (async) \u2192 SSE watch":"POST /v1/projects"}),!t.json){let n=t.cheap?" (--cheap: deterministic translator)":"";console.log(`[dry-run] Would create project "${t.name}" on ${t.target}`+(t.fromSuggestion?` from suggestion ${t.fromSuggestion}${n}.`:"."))}return}w(t.target),p(t,"project_create_prepare",{name:t.name,target:t.target,fromSuggestion:t.fromSuggestion??null,cheap:t.cheap??!1});let o=C(`Creating project "${t.name}"\u2026`,t.json),r;try{r=await L.createProject({name:t.name,format:e}),o.succeed(`Created: ${r.id}`)}catch(n){o.fail(`Failed: ${v(n)}`),g(t,"project_create",n,y(n)),l(y(n))}if(p(t,"project_create_complete",{project:r}),!t.json&&!t.fromSuggestion&&console.log(`
|
|
68
|
-
${r.id} ${r.name}`),t.fromSuggestion&&(t.cheap?await ce(r.id,{target:t.target,suggestionId:t.fromSuggestion,json:t.json,force:!0}):await yt(t.fromSuggestion,{target:t.target,project:r.id,json:t.json}),!t.json)){let n=t.cheap?"(--cheap)":"(composed)";console.log(`
|
|
69
|
-
${r.id} ${r.name} \u2190 composed from ${t.fromSuggestion} ${n}`)}}async function bt(t,e){E(t,"projectId",e),w(e.target),p(e,"project_delete_prepare",{projectId:t});try{await L.deleteProject(t),p(e,"project_delete_complete",{projectId:t}),j(e,{ok:!0,projectId:t},()=>{console.log(`Project ${t} deleted.`)})}catch(o){g(e,"project_delete",o,y(o)),e.json||console.error(`\u2716 project delete: ${v(o)}`),l(y(o))}}async function vt(t,e){E(t,"mediaId",e),w(e.target),p(e,"media_delete_prepare",{mediaId:t});try{await F.deleteMedia(t),p(e,"media_delete_complete",{mediaId:t}),j(e,{ok:!0,mediaId:t},()=>{console.log(`Media ${t} deleted.`)})}catch(o){g(e,"media_delete",o,y(o)),e.json||console.error(`\u2716 media delete: ${v(o)}`),l(y(o))}}import{writeFileSync as ar}from"fs";import{resolve as cr}from"path";var jt=1500,dr=4e3,mr=1800*1e3;async function me(t,e,o={}){let r=Date.now()+(o.timeoutMs??mr),n=Date.now();for(;Date.now()<r;){let i=null,s=!1;try{for await(let a of Oe(t,e)){if(a.event==="progress"){let f=Math.round((Date.now()-n)/1e3);if(o.spinner){let u=Math.round(a.data.percent*100);o.spinner.text=`Rendering\u2026 ${a.data.phase}${u>0?` \xB7 ${u}%`:""} (${f}s)`}o.onProgress?.({phase:a.data.phase,percent:a.data.percent,elapsedSec:f});continue}a.event==="complete"?i={kind:"complete",outputUrl:a.data.outputUrl,outputExpiresAt:a.data.outputExpiresAt,duration:a.data.duration}:i={kind:"failed",message:a.data.message};break}}catch(a){if(a instanceof I)s=!0;else{await new Promise(f=>setTimeout(f,jt));continue}}if(i)return i;if(s){let a=await lr(t,e);if(a)return a;await new Promise(f=>setTimeout(f,dr));continue}await new Promise(a=>setTimeout(a,jt))}return{kind:"failed",message:`Timed out waiting for render to reach a terminal state. Render ID: ${e}, Project ID: ${t}.`}}async function lr(t,e){let o=await Pe.getRender(t,e);return o.status==="complete"?{kind:"complete",outputUrl:o.outputUrl??null,outputExpiresAt:null,duration:null}:o.status==="error"||o.status==="cancelled"?{kind:"failed",message:o.error??`Render ${o.status}`}:null}async function Et(t,e){E(t,"renderId",e),E(e.project,"projectId",e),w(e.target),p(e,"render_watch_prepare",{renderId:t,projectId:e.project,target:e.target});let o=C(`Watching render ${t}\u2026`,e.json),r;try{r=await me(e.project,t,{spinner:o,onProgress:i=>p(e,"render_progress",{renderId:t,...i})})}catch(i){o.fail(`Failed to watch render: ${v(i)}`),g(e,"render_watch",i,y(i)),l(y(i))}r.kind==="failed"&&(o.fail(r.message),g(e,"render_watch",new Error(r.message),m.ApiServerError),l(m.ApiServerError)),o.succeed(`Render complete (${t})`);let n=null;e.download&&r.outputUrl?n=await le(r.outputUrl,e.out??`./reel-${t.slice(0,8)}.mp4`,e.json):r.outputUrl||(g(e,"render_watch",new Error("Render reported complete but no outputUrl was returned."),m.ApiServerError),e.json||console.error(`Render reported complete but no outputUrl was returned.
|
|
70
|
-
Re-fetch via GET /v1/projects/${e.project}/renders/${t}.`),l(m.ApiServerError)),p(e,"render_complete",{renderId:t,projectId:e.project,outputUrl:r.outputUrl,outputExpiresAt:r.outputExpiresAt,duration:r.duration,outputPath:n}),e.json||(r.outputUrl&&console.log(`MP4 URL: ${r.outputUrl}`),r.outputExpiresAt&&console.log(`Expires: ${r.outputExpiresAt}`),r.duration!=null&&console.log(`Duration: ${r.duration}s`))}async function le(t,e,o){let r=cr(e),n=C(`Downloading \u2192 ${r}\u2026`,o);try{let i=await fetch(t);if(!i.ok)throw new Error(`HTTP ${i.status}`);let s=Buffer.from(await i.arrayBuffer());return ar(r,s),n.succeed(`Saved: ${r} (${(s.length/1024/1024).toFixed(1)} MB)`),r}catch(i){n.fail(`Download failed: ${v(i)}`),console.error(`
|
|
71
|
-
MP4 URL (1-hour TTL): ${t}`),l(m.NetworkError)}}async function ur(t){let e=await k(`/v1/projects/${t}/composition`,{method:"GET"});return e.status===404?"no-composition":e.status>=400?"unknown-composition":e.headers.etag??"no-etag"}async function xt(t,e){if(E(t,"projectId",e),e.dryRun){p(e,"render_dry_run",{projectId:t,target:e.target,wouldCall:"POST /v1/projects/:id/renders \u2192 SSE watch \u2192 download MP4"}),e.json||console.log(`[dry-run] Would render project ${t} on ${e.target}.`);return}w(e.target),p(e,"render_prepare",{projectId:t,target:e.target});let o;try{o=e.idempotencyKey??await de("render",[t,await ur(t)]),p(e,"idempotency_key",{scope:"render",key:o,overridden:!!e.idempotencyKey})}catch(c){o="",p(e,"idempotency_key",{scope:"render",key:null,skipped:!0,reason:c instanceof Error?c.message:String(c)})}let r=C("Queuing render\u2026",e.json),n,i,s=!1;try{let c=e.aspect?{format:{aspectRatio:e.aspect,fps:e.fps??30,resolution:e.resolution??"fhd"}}:{};e.priority&&(c.priority=e.priority),e.intent&&(c.intent=e.intent);let d={"content-type":"application/json"};o&&(d["idempotency-key"]=o);let h=await k(`/v1/projects/${t}/renders`,{method:"POST",headers:d,body:JSON.stringify(c)});if(h.status>=400){let b=h.body?.error;throw new I(h.status,{code:b?.code??"unknown",message:b?.message??h.statusText})}let x=h.body;n=x.id,i=x.status,s=h.headers["idempotency-replay"]==="true",r.succeed(s?`Render replayed: ${n} (status: ${i})`:`Render queued: ${n}`)}catch(c){r.fail(`Failed: ${v(c)}`),g(e,"render_prepare",c,y(c)),l(y(c))}s?p(e,"render_idempotent_replay",{renderId:n,projectId:t,status:i,idempotencyKey:o}):p(e,"render_queued",{renderId:n,projectId:t});let a=C("Rendering\u2026",e.json),f;try{f=await me(t,n,{spinner:a,onProgress:c=>p(e,"render_progress",{renderId:n,...c})})}catch(c){a.fail(`Failed to watch render: ${v(c)}`),g(e,"render_progress",c,y(c)),l(y(c))}f.kind==="failed"&&(a.fail(f.message),g(e,"render_progress",new Error(f.message),m.ApiServerError),l(m.ApiServerError)),a.succeed("Render complete"),f.outputUrl||(g(e,"render_complete",new Error("Render reported complete but no outputUrl was returned."),m.ApiServerError),e.json||console.error(`Render reported complete but no outputUrl was returned.
|
|
72
|
-
Render ID: ${n}
|
|
42
|
+
Run \`cueframe analyze ${a} --target ${e.target}\` to generate clip suggestions.`)})}function wt(t){let e=Math.floor(t/60),r=Math.floor(t%60);return`${e}:${String(r).padStart(2,"0")}`}async function gr(t,e){t!==void 0&&R(t,"mediaItemId",e),j(e.target),g(e,"clips_prepare",{target:e.target,mode:t?"suggestions":"media-list",...t?{mediaItemId:t}:{}});try{if(!t){let n=await oe.listMedia();if(g(e,"clips_complete",{mode:"media-list",count:n.data.length,media:n.data}),!e.json){if(n.data.length===0){console.log("No media items found. Import a video first.");return}console.log("Media items (pass the ID to `cueframe clips <id>`):"),console.log("");for(let o of n.data){let s=o.duration?`${wt(o.duration)} `:"",i=o.processingStatus?.phase??"unknown",a=i==="complete"?"":` [${i}]`;console.log(` ${o.id} ${o.name} ${s}${a}`)}}return}let r=await It.listMediaSuggestions(t);if(g(e,"clips_complete",{mode:"suggestions",mediaItemId:t,count:r.suggestions.length,suggestions:r.suggestions}),!e.json){if(r.suggestions.length===0){console.log("No clip suggestions found for this media item."),console.log("If analysis is still running, try again shortly. Otherwise the video may not have suitable clips.");return}console.log(`${r.suggestions.length} clip suggestion${r.suggestions.length!==1?"s":""}:`),console.log("");for(let n of r.suggestions){let o=`${wt(n.trim.start)} \u2192 ${wt(n.trim.end)}`,s=(n.trim.end-n.trim.start).toFixed(1);console.log(` ${n.id}`),console.log(` ${n.title}`),console.log(` ${o} (${s}s) ${n.format} score: ${n.score}`),n.reason&&console.log(` ${n.reason}`),console.log("")}}}catch(r){x(e,"clips",r,v(r)),m(v(r))}}import{readFileSync as ns}from"fs";async function hr(t,e){R(t,"projectId",e),j(e.target),g(e,"composition_get_prepare",{projectId:t});let r=await Je(`/v1/projects/${t}/composition`,{method:"GET"},e,"composition_get");r.status>=400&&(qe(r,e,"composition_get"),m(F(r.status)));let n=r.headers.etag,o=n&&_r(n);g(e,"composition_get_complete",{projectId:t,etag:o,status:r.status}),T(e,{etag:o,composition:r.body},()=>{o&&console.log(`# ETag: ${o}`),console.log(JSON.stringify(r.body,null,2))})}async function yr(t,e){R(t,"projectId",e),e.body||(console.error("--body is required (inline JSON, @file.json, or @- for stdin)"),m(f.UserError)),j(e.target);let r=await bt(t,e),n=await xr(e.body);g(e,"composition_put_prepare",{projectId:t,ifMatch:r});let o=new Headers({"content-type":"application/json","if-match":r}),s=await Je(`/v1/projects/${t}/composition`,{method:"PUT",headers:o,body:n},e,"composition_put");s.status>=400&&(qe(s,e,"composition_put"),m(F(s.status)));let i=s.headers.etag;g(e,"composition_put_complete",{projectId:t,etag:i,status:s.status,response:s.body}),T(e,{etag:i,response:s.body},()=>{console.log(`Composition saved (ETag: ${i??"unknown"}).`),s.body&&typeof s.body=="object"&&console.log(JSON.stringify(s.body,null,2))})}async function ct(t,e){R(t,"projectId",e),e.suggestionId||(console.error("--suggestion <suggestionId> is required"),m(f.UserError)),j(e.target);let r=await bt(t,e),n;if(e.format)try{n=JSON.parse(e.format)}catch{console.error(`--format must be JSON, e.g. '{"aspectRatio":"9:16","fps":30,"resolution":"fhd"}'`),m(f.UserError)}let o=JSON.stringify({suggestionId:e.suggestionId,...n?{format:n}:{}});g(e,"composition_from_suggestion_prepare",{projectId:t,suggestionId:e.suggestionId,ifMatch:r});let s,i=r,a=0,d=3;for(;;){a++;let c=new Headers({"content-type":"application/json","if-match":i});if(s=await Je(`/v1/projects/${t}/composition/from-suggestion`,{method:"POST",headers:c,body:o},e,"composition_from_suggestion"),!(s.status===409&&s.body?.error?.code==="stale_etag"))break;if(a>d){g(e,"composition_from_suggestion_etag_retries_exhausted",{projectId:t,attempts:d});break}g(e,"composition_from_suggestion_etag_retry",{projectId:t,attempt:a,reason:"stale_etag"}),i=await bt(t,e)}s.status>=400&&(qe(s,e,"composition_from_suggestion"),m(F(s.status)));let l=s.headers.etag;g(e,"composition_from_suggestion_complete",{projectId:t,suggestionId:e.suggestionId,etag:l,status:s.status,response:s.body,attempts:a}),T(e,{etag:l,response:s.body},()=>{console.log(`Composition built from suggestion ${e.suggestionId} (ETag: ${l??"unknown"}).`),s.body&&typeof s.body=="object"&&console.log(JSON.stringify(s.body,null,2))})}async function vr(t){t.body||(console.error("--body is required (inline JSON, @file.json, or @- for stdin)"),m(f.UserError)),j(t.target);let e=await xr(t.body);g(t,"composition_validate_prepare",{});let r=new Headers({"content-type":"application/json"}),n=await Je("/v1/composition/validate",{method:"POST",headers:r,body:e},t,"composition_validate");n.status>=400&&(qe(n,t,"composition_validate"),m(F(n.status))),g(t,"composition_validate_complete",{status:n.status}),T(t,{valid:!0},()=>{console.log("\u2713 Composition is valid.")})}function _r(t){return t.replace(/^W\//,"").replace(/-gzip(?=("?)$)/,"")}async function bt(t,e){if(e.force)return"*";if(e.ifMatch)return e.ifMatch;let r=await Je(`/v1/projects/${t}/composition`,{method:"GET"},e,"composition_etag_fetch");if(r.status===404)return Z("No existing composition; treating as create (If-Match: *).",e),"*";r.status>=400&&(qe(r,e,"composition_etag_fetch"),m(F(r.status)));let n=r.headers.etag;return n||(x(e,"composition_etag_fetch",new Error("Server returned no ETag on composition GET; cannot safely thread If-Match. Pass --force to overwrite anyway."),f.ApiServerError),m(f.ApiServerError)),_r(n)}async function xr(t){if(t.startsWith("@")){let e=t.slice(1);if(e==="-"){let r=[];for await(let n of process.stdin)r.push(Buffer.isBuffer(n)?n:Buffer.from(n));return Buffer.concat(r).toString("utf-8")}return ns(e,"utf-8")}return t}async function Je(t,e,r,n){try{return await L(t,e)}catch(o){x(r,n,o,f.NetworkError),m(f.NetworkError)}}function qe(t,e,r){let n=t.body?.error,o=n?.code??"unknown",s=n?.message??t.statusText,i=os(o,t.status,n?.details),a=F(t.status);e.json?x(e,r,Object.assign(new Error(s),{code:o,status:t.status,details:n?.details,advice:i}),a):(process.stderr.write(`\u2716 ${r}: ${s} (${o}, ${t.status})
|
|
43
|
+
`),i&&process.stderr.write(` \u2192 ${i}
|
|
44
|
+
`))}function os(t,e,r){let n=new J(e,{code:t,message:"",details:r&&typeof r=="object"?r:void 0}),o=$t(n);return o||(e===404?"Project or composition not found. Run `cueframe list` to confirm the project ID; the composition may not yet exist.":null)}async function wr(t){let e=t.aspect?{aspectRatio:t.aspect,fps:t.fps??30,resolution:t.resolution??"fhd"}:void 0;if(t.dryRun){if(g(t,"project_create_dry_run",{name:t.name,target:t.target,format:e??null,fromSuggestion:t.fromSuggestion??null,cheap:t.cheap??!1,wouldCall:t.fromSuggestion?t.cheap?"POST /v1/projects \u2192 POST /v1/projects/:id/composition/from-suggestion (sync translator)":"POST /v1/projects \u2192 POST /v1/projects/:id/compose (async) \u2192 SSE watch":"POST /v1/projects"}),!t.json){let o=t.cheap?" (--cheap: deterministic translator)":"";console.log(`[dry-run] Would create project "${t.name}" on ${t.target}`+(t.fromSuggestion?` from suggestion ${t.fromSuggestion}${o}.`:"."))}return}j(t.target),g(t,"project_create_prepare",{name:t.name,target:t.target,fromSuggestion:t.fromSuggestion??null,cheap:t.cheap??!1});let r=A(`Creating project "${t.name}"\u2026`,t.json),n;try{n=await Se.createProject({name:t.name,format:e}),r.succeed(`Created: ${n.id}`)}catch(o){r.fail(`Failed: ${I(o)}`),O(t,"project_create",o,v(o)),m(v(o))}if(g(t,"project_create_complete",{project:n}),!t.json&&!t.fromSuggestion&&console.log(`
|
|
45
|
+
${n.id} ${n.name}`),t.fromSuggestion){let o=!1;if(o||await ct(n.id,{target:t.target,suggestionId:t.fromSuggestion,json:t.json,force:!0}),!t.json){let s=o?"(composed)":"(translated)";console.log(`
|
|
46
|
+
${n.id} ${n.name} \u2190 composed from ${t.fromSuggestion} ${s}`)}}}async function br(t,e){R(t,"projectId",e),j(e.target),g(e,"project_delete_prepare",{projectId:t});try{await Se.deleteProject(t),g(e,"project_delete_complete",{projectId:t}),T(e,{ok:!0,projectId:t},()=>{console.log(`Project ${t} deleted.`)})}catch(r){x(e,"project_delete",r,v(r)),m(v(r))}}async function kr(t,e){R(t,"mediaId",e),j(e.target),g(e,"media_delete_prepare",{mediaId:t});try{await oe.deleteMedia(t),g(e,"media_delete_complete",{mediaId:t}),T(e,{ok:!0,mediaId:t},()=>{console.log(`Media ${t} deleted.`)})}catch(r){x(e,"media_delete",r,v(r)),m(v(r))}}import{writeFileSync as ss}from"fs";import{resolve as is}from"path";var Er=1500,as=4e3,cs=1800*1e3,Sr=5;async function dt(t,e,r={}){let n=Date.now()+(r.timeoutMs??cs),o=Date.now(),s=0;for(;Date.now()<n;){let i=null,a=!1;try{for await(let d of Tt(t,e)){if(s=0,d.event==="progress"){let l=Math.round((Date.now()-o)/1e3);if(r.spinner){let c=Math.round(d.data.percent*100);r.spinner.text=`Rendering\u2026 ${d.data.phase}${c>0?` \xB7 ${c}%`:""} (${l}s)`}r.onProgress?.({phase:d.data.phase,percent:d.data.percent,elapsedSec:l});continue}d.event==="complete"?i={kind:"complete",outputUrl:d.data.outputUrl,outputExpiresAt:d.data.outputExpiresAt,duration:d.data.duration}:i={kind:"failed",message:d.data.message};break}}catch(d){if(d instanceof J)a=!0;else{if(s++,s>=Sr)throw Object.assign(new Error(`Render stream unreachable after ${Sr} consecutive transport failures: ${d instanceof Error?d.message:String(d)}`),{cause:d});await new Promise(l=>setTimeout(l,Er));continue}}if(i)return i;if(a){let d=await ds(t,e);if(d)return d;await new Promise(l=>setTimeout(l,as));continue}await new Promise(d=>setTimeout(d,Er))}return{kind:"failed",message:`Timed out waiting for render to reach a terminal state. Render ID: ${e}, Project ID: ${t}.`}}async function ds(t,e){let r=await Rt.getRender(t,e);return r.status==="complete"?{kind:"complete",outputUrl:r.outputUrl??null,outputExpiresAt:null,duration:null}:r.status==="error"||r.status==="cancelled"?{kind:"failed",message:r.error??`Render ${r.status}`}:null}async function jr(t,e){R(t,"renderId",e),R(e.project,"projectId",e),j(e.target),g(e,"render_watch_prepare",{renderId:t,projectId:e.project,target:e.target});let r=A(`Watching render ${t}\u2026`,e.json),n;try{n=await dt(e.project,t,{spinner:r,onProgress:s=>g(e,"render_progress",{renderId:t,...s})})}catch(s){r.fail(`Failed to watch render: ${I(s)}`),O(e,"render_watch",s,v(s)),m(v(s))}n.kind==="failed"&&(r.fail(n.message),O(e,"render_watch",new Error(n.message),f.ApiServerError),m(f.ApiServerError)),r.succeed(`Render complete (${t})`);let o=null;e.download&&n.outputUrl?o=await lt(n.outputUrl,e.out??`./reel-${t.slice(0,8)}.mp4`,e.json):n.outputUrl||(x(e,"render_watch",new Error("Render reported complete but no outputUrl was returned."),f.ApiServerError),e.json||console.error(`Render reported complete but no outputUrl was returned.
|
|
47
|
+
Re-fetch via GET /v1/projects/${e.project}/renders/${t}.`),m(f.ApiServerError)),g(e,"render_complete",{renderId:t,projectId:e.project,outputUrl:n.outputUrl,outputExpiresAt:n.outputExpiresAt,duration:n.duration,outputPath:o}),e.json||(n.outputUrl&&console.log(`MP4 URL: ${n.outputUrl}`),n.outputExpiresAt&&console.log(`Expires: ${n.outputExpiresAt}`),n.duration!=null&&console.log(`Duration: ${n.duration}s`))}async function lt(t,e,r){let n=is(e),o=A(`Downloading \u2192 ${n}\u2026`,r);try{let s=await fetch(t);if(!s.ok)throw new Error(`HTTP ${s.status}`);let i=Buffer.from(await s.arrayBuffer());return ss(n,i),o.succeed(`Saved: ${n} (${(i.length/1024/1024).toFixed(1)} MB)`),n}catch(s){o.fail(`Download failed: ${I(s)}`),console.error(`
|
|
48
|
+
MP4 URL (1-hour TTL): ${t}`),m(f.NetworkError)}}async function kt(t,e){let r=e.map(i=>i==null?"null":String(i)).join(":"),n=`${t}:${r}`,o=new TextEncoder().encode(n),s=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(s),i=>i.toString(16).padStart(2,"0")).join("")}async function ls(t){let e=await L(`/v1/projects/${t}/composition`,{method:"GET"});return e.status===404?"no-composition":e.status>=400?"unknown-composition":e.headers.etag??"no-etag"}async function Cr(t,e){if(R(t,"projectId",e),e.dryRun){g(e,"render_dry_run",{projectId:t,target:e.target,wouldCall:"POST /v1/projects/:id/renders \u2192 SSE watch \u2192 download MP4"}),e.json||console.log(`[dry-run] Would render project ${t} on ${e.target}.`);return}j(e.target),g(e,"render_prepare",{projectId:t,target:e.target});let r;try{r=e.idempotencyKey??await kt("render",[t,await ls(t)]),g(e,"idempotency_key",{scope:"render",key:r,overridden:!!e.idempotencyKey})}catch(c){r="",g(e,"idempotency_key",{scope:"render",key:null,skipped:!0,reason:c instanceof Error?c.message:String(c)})}let n=A("Queuing render\u2026",e.json),o,s,i=!1;try{let c=e.aspect?{format:{aspectRatio:e.aspect,fps:e.fps??30,resolution:e.resolution??"fhd"}}:{};e.priority&&(c.priority=e.priority),e.intent&&(c.intent=e.intent);let u={"content-type":"application/json"};r&&(u["idempotency-key"]=r);let k=await L(`/v1/projects/${t}/renders`,{method:"POST",headers:u,body:JSON.stringify(c)});if(k.status>=400){let ne=k.body?.error;throw new J(k.status,{code:ne?.code??"unknown",message:ne?.message??k.statusText})}let P=k.body;o=P.id,s=P.status,i=k.headers["idempotency-replay"]==="true",n.succeed(i?`Render replayed: ${o} (status: ${s})`:`Render queued: ${o}`)}catch(c){n.fail(`Failed: ${I(c)}`),O(e,"render_prepare",c,v(c)),m(v(c))}i?g(e,"render_idempotent_replay",{renderId:o,projectId:t,status:s,idempotencyKey:r}):g(e,"render_queued",{renderId:o,projectId:t});let a=A("Rendering\u2026",e.json),d;try{d=await dt(t,o,{spinner:a,onProgress:c=>g(e,"render_progress",{renderId:o,...c})})}catch(c){a.fail(`Failed to watch render: ${I(c)}`),O(e,"render_progress",c,v(c)),m(v(c))}d.kind==="failed"&&(a.fail(d.message),O(e,"render_progress",new Error(d.message),f.ApiServerError),m(f.ApiServerError)),a.succeed("Render complete"),d.outputUrl||(x(e,"render_complete",new Error("Render reported complete but no outputUrl was returned."),f.ApiServerError),e.json||console.error(`Render reported complete but no outputUrl was returned.
|
|
49
|
+
Render ID: ${o}
|
|
73
50
|
Project ID: ${t}
|
|
74
|
-
Re-fetch via GET /v1/projects/${t}/renders/${
|
|
75
|
-
`);for(let[i
|
|
51
|
+
Re-fetch via GET /v1/projects/${t}/renders/${o} once the URL is signed.`),m(f.ApiServerError));let l=await lt(d.outputUrl,e.out??`./reel-${o.slice(0,8)}.mp4`,e.json);g(e,"render_complete",{renderId:o,projectId:t,outputUrl:d.outputUrl,outputExpiresAt:d.outputExpiresAt,duration:d.duration,outputPath:l})}import us from"open";import{createAuthClient as ms}from"better-auth/client";import{deviceAuthorizationClient as ps}from"better-auth/client/plugins";async function $r(t){let e=je(t.target),r=ms({baseURL:e,plugins:[ps()]}),n=A("Requesting device code\u2026",t.json),o;try{let{data:l,error:c}=await r.device.code({client_id:"cueframe-cli",scope:"openid profile email"});(c||!l)&&(n.fail(`Could not start login: ${c?.message??"unknown error"}`),m(f.NetworkError)),o=l}catch(l){n.fail(`Could not start login: ${l instanceof Error?l.message:String(l)}`),m(f.NetworkError)}n.succeed("Device code issued");let s=o.verification_uri_complete??o.verification_uri;Z("",t),Z(` Visit: ${s}`,t),Z(` Code: ${o.user_code}`,t),Z("",t);try{await us(s)}catch{}let i=A("Waiting for approval in browser\u2026",t.json),a=Date.now()+o.expires_in*1e3,d=o.interval*1e3;for(;Date.now()<a;){await new Promise(l=>setTimeout(l,d));try{let{data:l,error:c}=await r.device.token({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:o.device_code,client_id:"cueframe-cli"});if(l?.access_token){let P=l.access_token;Ze(P,t.target,t.url),i.succeed(`Logged in. Token saved for target "${t.target}".`),T(t,{ok:!0,target:t.target,apiUrl:e},()=>{});return}let u=l??c,k=u?.error;k==="authorization_pending"||(k==="slow_down"?d+=5e3:k==="access_denied"?(i.fail("Access denied in the browser."),m(f.UserError)):k==="expired_token"?(i.fail("Device code expired before approval. Run `cueframe login` again."),m(f.UserError)):k&&(i.fail(`Login failed: ${u?.error_description??k}`),m(f.ApiClientError)))}catch{}}i.fail("Timed out waiting for approval. Run `cueframe login` again."),m(f.UserError)}import{readFileSync as fs}from"fs";var Tr=new Set(["GET","POST","PUT","PATCH","DELETE"]);async function Or(t,e,r){let n=t.toUpperCase();Tr.has(n)||(x(r,"api",new Error(`Unsupported method: ${t}. Allowed: ${[...Tr].join(", ")}.`),f.UserError),m(f.UserError)),e.startsWith("/")||(x(r,"api",new Error(`Path must start with '/'. Got: ${e}`),f.UserError),m(f.UserError)),j(r.target);let o=hs(r.header??[]),s=await ys(r.body,n);s!==void 0&&!o.has("content-type")&&o.set("content-type","application/json");let i;try{i=await L(e,{method:n,headers:o,body:s})}catch(d){x(r,"api",d,v(d)),m(v(d))}gs(i,{include:!!r.include,json:!!r.json,method:n,path:e});let a=F(i.status);a!==f.Success&&x(r,"api",Object.assign(new Error(`${n} ${e} \u2192 ${i.status} ${i.statusText}`),{code:i.body?.error?.code,status:i.status}),a),process.exitCode=a}function gs(t,{include:e,json:r,method:n,path:o}){if(r){console.log(JSON.stringify({status:t.status,statusText:t.statusText,headers:t.headers,body:t.body}));return}if(e){process.stdout.write(`HTTP/1.1 ${t.status} ${t.statusText}
|
|
52
|
+
`);for(let[s,i]of Object.entries(t.headers))process.stdout.write(`${s}: ${i}
|
|
76
53
|
`);process.stdout.write(`
|
|
77
|
-
`)
|
|
54
|
+
`),Rr(t.body,t.status>=400);return}if(t.status===204||t.body===null){console.error(`${n} ${o} \u2192 ${t.status} (no content)`);return}Rr(t.body,t.status>=400)}function Rr(t,e){let r=e?process.stderr:process.stdout;t!=null&&(typeof t=="string"?r.write(t.endsWith(`
|
|
78
55
|
`)?t:t+`
|
|
79
|
-
`):
|
|
80
|
-
`))}function
|
|
81
|
-
Export ID: ${
|
|
82
|
-
Re-fetch via GET /v1/projects/${e.projectId}/exports/${
|
|
83
|
-
Export URL (7-day TTL): ${t}`),
|
|
84
|
-
${r.name} \u2014 ${r.description}`);for(let n of r.subcommands??[])console.log(` ${r.name} ${n.name} \u2014 ${n.description}`)}}function Nt(t){if(!t)return;let e=parseInt(t,10);if(e===24||e===30||e===60)return e;console.error(`Invalid --fps ${t}. Allowed: 24, 30, 60.`),l(m.UserError)}function Lt(){let t=new _r;t.name("cueframe").description("AI-assisted video editing and rendering").version("0.1.2").option("--json","Emit a structured JSON document on stdout instead of human-formatted output. Spinners are silenced.").option("--dry-run","Validate inputs and report what would happen \u2014 no API calls, no mutations. Applies to upload, analyze, project create, render.");let e=()=>t.opts();t.command("install").description('One-line setup: wire the CueFrame MCP server into every installed agent (Claude Code / Cursor / Codex / Claude Desktop) and install the agent skills. No API key \u2014 auth is a browser "Allow" on first call.').option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>Ne({json:e().json,target:c.target,dryRun:e().dryRun})),t.command("init").description("Scaffold a CueFrame component workspace (cueframe.json + components dir) in the current repo, so `eject` / `new component` have a home and the render harness can discover them.").action(()=>ze({json:e().json,dryRun:e().dryRun})),t.command("eject").description("Fork a built-in CueFrame primitive into cueframe/components/<id> as owned, editable source (renders on CueFrame).").argument("<primitive>","Primitive id (e.g. cinematic-title, heroText)").option("-f, --force","Overwrite an existing ejected component dir").action((c,d)=>Ve(c,{json:e().json,dryRun:e().dryRun,force:d.force})),t.command("new").description("Scaffold new owned source in the component workspace").command("component").description("Scaffold a blank custom component in cueframe/components/<name>").argument("<name>","Component id (e.g. my-badge)").option("-f, --force","Overwrite an existing non-empty component dir").action((c,d)=>Ye(c,{json:e().json,dryRun:e().dryRun,force:d.force})),t.command("push").description("Publish a locally-authored component (cueframe/components/<id>/index.tsx) to CueFrame so it renders server-side. Upserts by id.").argument("[id]","Component id to push (omit and use `cueframe sync` to push all)").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,d)=>tt(c,{target:d.target,json:e().json})),t.command("sync").description("Publish EVERY component in the workspace (cueframe/components/*) to CueFrame. Upserts each by id.").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>ot({target:c.target,json:e().json}));let r=t.command("keys").description("Manage API keys. `keys create` mints a scoped key \u2014 run `cueframe login` first (keys cannot mint keys).");r.command("create").description("Mint a scoped API key (cf_*). Requires a logged-in session.").requiredOption("-n, --name <name>","Key name, e.g. vaaya-staging").option("-s, --scope <scope>","Comma-separated resource:actions, e.g. media:rw,projects:rw,renders:rw (resources: media,sessions,projects,renders,webhooks; actions r/w)").option("--preset <preset>","Scope preset instead of --scope: readonly (read all) | editall (read+write all)").option("--expires <days>","Expire after N days (default: never)").action(c=>nt({...c,json:e().json})),r.command("list").description("List your API keys.").action(()=>it({json:e().json})),r.command("revoke").description("Revoke an API key by id.").argument("<keyId>","Key id (from `cueframe keys list`)").action(c=>st(c,{json:e().json})),t.command("login").description("Browser-mediated sign-in (OAuth device flow). Recommended for laptops.").option("-t, --target <target>","Target environment: prod (default), dev, local").option("--url <url>","Override the API base URL (advanced)").action(c=>St({...c,json:e().json})),t.command("auth").description("Save a static API key (cf_live_\u2026 / cf_test_\u2026). Use for CI / headless environments.").argument("<api-key>","Your CueFrame API key").option("-t, --target <target>","Target environment: prod (default), dev, local").option("--url <url>","Override the API base URL (advanced)").action((c,d)=>{Z(c,d.target,d.url),e().json?console.log(JSON.stringify({ok:!0,target:d.target},null,2)):console.log(`API key saved for target "${d.target}"`)}),t.command("list").description("List projects").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-n, --limit <n>","Max projects to show","10").action(c=>at({target:c.target,limit:parseInt(c.limit),json:e().json}));let n=t.command("project").description("Project commands");n.command("create").description("Create a new project. With --from-suggestion, atomically build the composition from a clip suggestion in one round-trip \u2014 the project is then immediately renderable via `cueframe render <projectId>`.").requiredOption("-n, --name <name>","Project name").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-a, --aspect <ratio>","Aspect ratio: 9:16, 1:1, 16:9","9:16").option("--fps <n>","Frame rate","30").option("--resolution <r>","Resolution: hd, fhd, 2k, 4k","fhd").option("--from-suggestion <sug>","Clip suggestion publicId (sug_\u2026) \u2014 atomically builds the composition after project creation so render needs no further args").option("--cheap","With --from-suggestion: use the deterministic translator (no LLM, ~100ms) instead of the AI authoring pass. Useful for tests / programmatic flows.").action(c=>wt({name:c.name,target:c.target,aspect:c.aspect,fps:Nt(c.fps),resolution:c.resolution,fromSuggestion:c.fromSuggestion,cheap:c.cheap,json:e().json,dryRun:e().dryRun})),n.command("delete").description("Permanently delete a project (irreversible cleanup \u2014 removes the composition and render history).").argument("<projectId>","Project ID (from `cueframe list` or `project create`)").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,d)=>bt(c,{target:d.target,json:e().json})),t.command("media").description("Media library cleanup commands").command("delete").description("Permanently delete a media item (irreversible cleanup \u2014 removes the source and its derived assets).").argument("<mediaId>","Media item ID (from `cueframe clips`)").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,d)=>vt(c,{target:d.target,json:e().json})),t.command("upload").description("Upload a video file and process it").argument("<file>","Path to video file").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-a, --analyze","Run clip analysis after processing completes").option("-r, --audio-role <role>","Declare the audio role (vo|music|sfx|ambience) \u2014 routes ingest enrichment: vo\u2192transcript, music\u2192beat grid, sfx/ambience\u2192envelope").action((c,d)=>dt(c,{target:d.target,analyze:d.analyze,audioRole:d.audioRole,json:e().json,dryRun:e().dryRun})),t.command("analyze").description("Trigger AI clip suggestion analysis for a media item").argument("<mediaItemId>","Media item ID (from `cueframe clips`)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-w, --wait","Wait for analysis to complete and show results").action((c,d)=>Fe(c,{target:d.target,wait:d.wait,json:e().json,dryRun:e().dryRun})),t.command("clips").description("List AI-generated clip suggestions for a media item").argument("[mediaItemId]","Media item ID (omit to list your media library)").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,d)=>mt(c,{target:d.target,json:e().json}));let s=t.command("render").description("Render a project to MP4 (queues, watches via SSE, downloads). Renders whatever composition is saved on the project \u2014 build it first via `project create --from-suggestion` or `composition from-suggestion`.").allowExcessArguments(!1).argument("<projectId>","Project ID (from `cueframe list` or `project create`)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-a, --aspect <ratio>","Aspect ratio: 9:16, 1:1, 16:9 (defaults to project format)").option("--fps <n>","Frame rate","30").option("--resolution <r>","Resolution: hd, fhd, 2k, 4k","fhd").option("-o, --out <path>","Output file path (default: ./reel-<id>.mp4)").option("--idempotency-key <key>",'Override the auto-derived Idempotency-Key. Default: sha256("render:<projectId>:<currentCompositionETag>"). Pass a fresh UUID to force a new render row.').option("--priority <p>","Routing intent: interactive (low-latency, access-gated), standard (default), background (lowest queue weight).").option("--intent <i>","Encode-quality hint: preview (fast / low-bitrate, for editor scrubbing) or final (default, full Format).").action((c,d)=>xt(c,{target:d.target,aspect:d.aspect,fps:Nt(d.fps),resolution:d.resolution,out:d.out,json:e().json,dryRun:e().dryRun,...d.idempotencyKey?{idempotencyKey:d.idempotencyKey}:{},...d.priority?{priority:d.priority}:{},...d.intent?{intent:d.intent}:{}}));t.command("api").description("Raw API call against the v1 surface (escape hatch \u2014 like `gh api`).").argument("<method>","HTTP method: GET, POST, PUT, PATCH, DELETE").argument("<path>","API path starting with /v1, e.g. /v1/projects").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-b, --body <body>","Request body (inline JSON, @file.json to read from disk, @- for stdin)").option("-H, --header <header...>",'Additional header (repeatable), e.g. -H "If-Match: \\"abc\\""').option("-i, --include","Include response status line + headers in stdout (curl-style). Lets agents read ETag etc.").action((c,d,h)=>_t(c,d,{target:h.target,body:h.body,header:h.header,include:h.include,json:e().json})),t.command("schema").description("Print the live composition wire schema from the server (/v1/openapi.json) \u2014 discover the contract instead of guessing.").argument("[resource]","Schema to print (currently: composition)","composition").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,d)=>Rt(c,{target:d.target,json:e().json}));let a=t.command("composition").description("Read/write a project's composition. ETag is threaded automatically.");a.command("validate").description("Validate a composition body against the live schema WITHOUT saving or rendering. Returns per-field errors \u2014 author safely before paying for a render.").requiredOption("-b, --body <body>","Composition JSON (inline, @file.json, or @- for stdin)").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>pt({target:c.target,body:c.body,json:e().json})),a.command("get").description("Fetch the project's composition and ETag").argument("<projectId>","Project ID").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,d)=>lt(c,{target:d.target,json:e().json})),a.command("put").description("Replace the composition. GETs ETag first for safe concurrent writes.").argument("<projectId>","Project ID").option("-t, --target <target>","Target environment: prod (default), dev, local").requiredOption("-b, --body <body>","Composition JSON (inline, @file.json, or @- for stdin)").option("--if-match <etag>","Use this ETag (skip the GET round-trip)").option("--force","Use If-Match: * (unconditional overwrite \u2014 may clobber concurrent edits)").action((c,d)=>ut(c,{target:d.target,body:d.body,ifMatch:d.ifMatch,force:d.force,json:e().json})),a.command("from-suggestion").description("Build the composition from an existing clip suggestion").argument("<projectId>","Project ID").requiredOption("-s, --suggestion <suggestionId>","Clip suggestion publicId (sug_\u2026)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("--format <json>",`Optional format override, e.g. '{"aspectRatio":"9:16","fps":30,"resolution":"fhd"}'`).option("--if-match <etag>","Use this ETag (skip the GET round-trip)").option("--force","Use If-Match: * (unconditional overwrite)").action((c,d)=>ce(c,{target:d.target,suggestionId:d.suggestion,format:d.format,ifMatch:d.ifMatch,force:d.force,json:e().json})),s.command("watch").description("Reattach to an existing render and stream progress to terminal state").argument("<renderId>","Render ID (from `cueframe render` output)").requiredOption("-p, --project <projectId>","Project the render belongs to").option("-t, --target <target>","Target environment: prod (default), dev, local").option("--no-download","Print the MP4 URL but skip downloading the file").option("-o, --out <path>","Output file path when downloading (default: ./reel-<id>.mp4)").action((c,d,h)=>{let x=h?.parent?.opts?.()?.target??d.target;return Et(c,{target:x,project:d.project,out:d.out,download:d.download!==!1,json:e().json})});let f=t.command("export").description("Hand the timeline off to a real NLE (Final Cut Pro / Premiere Pro)");f.command("fcpxml").description("Build a Final Cut Pro export zip and (optionally) wait to download it").argument("<projectId>","Project ID").requiredOption("-s, --suggestion <suggestionId>","Clip suggestion publicId (sug_\u2026)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-o, --out <path>","Output zip path (default: ./export-<id>.zip)").option("--wait","Block until the export finishes, then download the artifact").action((c,d)=>$e("fcpxml",{target:d.target,projectId:c,suggestionId:d.suggestion,out:d.out,wait:d.wait,json:e().json})),f.command("premiere").description("Build a Premiere Pro export zip and (optionally) wait to download it").argument("<projectId>","Project ID").requiredOption("-s, --suggestion <suggestionId>","Clip suggestion publicId (sug_\u2026)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-o, --out <path>","Output zip path (default: ./export-<id>.zip)").option("--wait","Block until the export finishes, then download the artifact").action((c,d)=>$e("premiere",{target:d.target,projectId:c,suggestionId:d.suggestion,out:d.out,wait:d.wait,json:e().json}));let u=t.command("sessions").description("Multi-file ingest sessions (camera A/B/screen \u2192 muxed composition)");u.command("list").description("List sessions in this org").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>Pt({target:c.target,json:e().json})),u.command("get").description("Get a single session by ID").argument("<sessionId>","Session ID").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,d)=>At(c,{target:d.target,json:e().json})),u.command("create").description("Create a session from one or more media files").requiredOption("-n, --name <name>","Session name").requiredOption("-f, --file <entry...>","Each entry is <mediaId>:<role> (repeatable)").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>Ft({target:c.target,name:c.name,files:c.file,json:e().json})),u.command("delete").description("Delete a session (server checks for compositions referencing it)").argument("<sessionId>","Session ID").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,d)=>Mt(c,{target:d.target,json:e().json})),t.command("describe").description("Print the CLI command tree as structured JSON (agent introspection)").action(()=>Dt(t,{json:e().json})),t.parse()}Lt();
|
|
56
|
+
`):r.write(JSON.stringify(t,null,2)+`
|
|
57
|
+
`))}function hs(t){let e=new Headers;for(let r of t){let n=r.indexOf(":");n===-1&&(console.error(`Invalid --header (expected "Name: value"): ${r}`),m(f.UserError));let o=r.slice(0,n).trim(),s=r.slice(n+1).trim();e.set(o,s)}return e}async function ys(t,e){if(t){if(t.startsWith("@")){let r=t.slice(1);return r==="-"?Ir():fs(r,"utf-8")}return t}if(!(e==="GET"||e==="DELETE")&&!process.stdin.isTTY)return Ir()}async function Ir(){let t=[];for await(let e of process.stdin)t.push(Buffer.isBuffer(e)?e:Buffer.from(e));return Buffer.concat(t).toString("utf-8")}var Ar=/#\/components\/schemas\/([A-Za-z0-9_]+)/g;function vs(t,e){let r=new Set,n=[e];for(;n.length;){let o=n.pop();if(r.has(o)||!(o in t))continue;r.add(o);let s=JSON.stringify(t[o]),i;for(Ar.lastIndex=0;i=Ar.exec(s);)n.push(i[1])}return r}function _s(t){let e=t?.paths??{};for(let r of Object.values(e))if(r?.put?.operationId==="putComposition"){let n=r.put?.requestBody?.content?.["application/json"]?.schema?.$ref,o=typeof n=="string"?n.match(/#\/components\/schemas\/(.+)$/):null;if(o)return o[1]}return null}async function Pr(t,e){t!=="composition"&&(console.error(`Unknown schema '${t}'. Supported: composition.`),m(f.UserError)),Ct({baseUrl:je(e.target)});let r;try{r=await L("/v1/openapi.json",{method:"GET"})}catch(l){x(e,"schema",l,f.NetworkError),m(f.NetworkError)}if(r.status>=400){let l=F(r.status);x(e,"schema",new Error(`Failed to fetch /v1/openapi.json (${r.status})`),l),m(l)}let n=r.body,o=n?.components?.schemas??{},s=_s(n);(!s||!(s in o))&&(x(e,"schema",new Error("Could not locate the composition schema in openapi.json (putComposition body ref not found)."),f.ApiServerError),m(f.ApiServerError));let i=vs(o,s);i.delete(s);let a={};for(let l of[...i].sort())a[l]=o[l];let d={name:s,schema:o[s],referenced:a};T(e,d,()=>{console.log(JSON.stringify(d,null,2))})}import{writeFileSync as xs}from"fs";import{resolve as ws}from"path";var Nr=1800*1e3,bs=5e3;async function Et(t,e){R(e.projectId,"projectId",e),R(e.suggestionId,"suggestionId",e),j(e.target),g(e,"export_prepare",{projectId:e.projectId,suggestionId:e.suggestionId,format:t,target:e.target});let r=A(`Queuing ${t} export\u2026`,e.json),n;try{n=(await(t==="fcpxml"?Ve.createFcpxmlExport:Ve.createPremiereExport)(e.projectId,{clipSuggestionId:e.suggestionId})).id,r.succeed(`Export queued: ${n}`)}catch(d){r.fail(`Failed: ${I(d)}`),O(e,"export_prepare",d,v(d)),m(v(d))}if(g(e,"export_queued",{exportId:n,projectId:e.projectId,format:t}),!e.wait){Z(`Poll status with: cueframe api GET /v1/projects/${e.projectId}/exports/${n}`,e);return}let o=await ks(e.projectId,n,e);o.kind==="failed"&&(x(e,"export_progress",Object.assign(new Error(o.message),o.error?{details:o.error}:{}),f.ApiServerError),e.json||console.error(`Export failed: ${o.message}`),m(f.ApiServerError)),o.outputUrl||(x(e,"export_complete",new Error("Export reported complete but no outputUrl was returned."),f.ApiServerError),e.json||console.error(`Export reported complete but no outputUrl was returned.
|
|
58
|
+
Export ID: ${n}
|
|
59
|
+
Re-fetch via GET /v1/projects/${e.projectId}/exports/${n}.`),m(f.ApiServerError));let i=e.out??`./export-${n.slice(0,8)}.zip`,a=await Es(o.outputUrl,i,e.json);g(e,"export_complete",{exportId:n,projectId:e.projectId,format:t,outputUrl:o.outputUrl,outputExpiresAt:o.outputExpiresAt,outputSizeBytes:o.outputSizeBytes,trimCacheHit:o.trimCacheHit,outputPath:a})}async function ks(t,e,r){let n=Date.now()+(r.timeoutMs??Nr),o=r.pollIntervalMs??bs,s=Date.now(),i=A("Exporting\u2026",r.json);try{for(;Date.now()<n;){let a;try{a=await Ve.getExport(t,e)}catch(c){if(c instanceof J&&c.status>=500){await Mr(o);continue}throw i.fail(`Failed to poll: ${I(c)}`),c}let d=Math.round((Date.now()-s)/1e3),l=Math.round((a.progress??0)*100);if(i.text=`Exporting\u2026 ${a.status}${l>0?` \xB7 ${l}%`:""} (${d}s)`,g(r,"export_progress",{exportId:e,status:a.status,progress:a.progress,elapsedSec:d}),a.status==="complete")return i.succeed(`Export complete (${d}s)`),{kind:"complete",outputUrl:a.outputUrl??null,outputExpiresAt:a.outputExpiresAt??null,outputSizeBytes:a.outputSizeBytes??null,trimCacheHit:a.trimCacheHit??null};if(a.status==="error"||a.status==="cancelled"){let c=a.error?.message??`Export ${a.status}`;return i.fail(c),{kind:"failed",message:c,error:a.error?{phase:a.error.phase,retryable:!!a.error.retryable}:null}}await Mr(o)}return i.fail(`Timed out waiting for export (${Math.round((Date.now()-s)/1e3)}s)`),{kind:"failed",message:`Timed out after ${Math.round((r.timeoutMs??Nr)/1e3)}s`,error:null}}catch(a){x(r,"export_progress",a,v(a)),m(v(a))}}async function Es(t,e,r){let n=ws(e),o=A(`Downloading \u2192 ${n}\u2026`,r);try{let s=await fetch(t);if(!s.ok)throw new Error(`HTTP ${s.status}`);let i=Buffer.from(await s.arrayBuffer());return xs(n,i),o.succeed(`Saved: ${n} (${(i.length/1024/1024).toFixed(1)} MB)`),n}catch(s){o.fail(`Download failed: ${I(s)}`),r||console.error(`
|
|
60
|
+
Export URL (7-day TTL): ${t}`),m(f.NetworkError)}}function Mr(t){return new Promise(e=>setTimeout(e,t))}async function Fr(t){j(t.target),g(t,"sessions_list_prepare",{});try{let e=await Fe.listSessions();g(t,"sessions_list_complete",{count:e.data.length}),T(t,e,()=>{if(e.data.length===0){console.log("No sessions yet. Create one with `cueframe sessions create --name <n> --files <mediaId:role> \u2026`");return}for(let r of e.data){let n=r.muxStatus??"pending";console.log(`${r.id} ${r.fileCount} files mux:${n} ${r.name}`)}e.pagination.hasMore&&console.log(`# more \u2014 pass --after ${e.pagination.nextCursor} (raw via \`cueframe api\`)`)})}catch(e){x(t,"sessions_list",e,v(e)),m(v(e))}}async function Ur(t,e){R(t,"sessionId",e),j(e.target),g(e,"sessions_get_prepare",{sessionId:t});try{let r=await Fe.getSession(t);g(e,"sessions_get_complete",{sessionId:t}),T(e,r,()=>{console.log(JSON.stringify(r,null,2))})}catch(r){x(e,"sessions_get",r,v(r)),m(v(r))}}async function Dr(t){t.name||(console.error("--name is required"),m(f.UserError)),(!t.files||t.files.length===0)&&(console.error("At least one --file <mediaId:role> is required"),m(f.UserError));let e=t.files.map((r,n)=>{let o=r.indexOf(":");return o===-1&&(console.error(`--file[${n}] must be <mediaId>:<role>. Got: ${r}`),m(f.UserError)),{mediaId:r.slice(0,o).trim(),role:r.slice(o+1).trim()}});j(t.target),g(t,"sessions_create_prepare",{name:t.name,fileCount:e.length});try{let r=await Fe.createSession({name:t.name,files:e});g(t,"sessions_create_complete",{sessionId:r.id}),T(t,r,()=>{console.log(`Session created: ${r.id}`),console.log(JSON.stringify(r,null,2))})}catch(r){x(t,"sessions_create",r,v(r)),m(v(r))}}async function Lr(t,e){R(t,"sessionId",e),j(e.target),g(e,"sessions_delete_prepare",{sessionId:t});try{await Fe.deleteSession(t),g(e,"sessions_delete_complete",{sessionId:t}),T(e,{ok:!0,sessionId:t},()=>{console.log(`Session ${t} deleted.`)})}catch(r){x(e,"sessions_delete",r,v(r)),m(v(r))}}function zr(t){let e=t.commands.map(zr);return{name:t.name(),description:t.description(),arguments:t.registeredArguments.map(r=>({name:r.name(),required:r.required,description:r.description})),options:t.options.map(r=>({flags:r.flags,description:r.description,...r.defaultValue!==void 0?{default:r.defaultValue}:{}})),...e.length>0?{subcommands:e}:{}}}function Wr(t,e){let r=t.commands.map(zr);if(e.json){g(e,"describe_complete",{name:t.name(),version:t.version()??null,commands:r});return}console.log(`${t.name()} ${t.version()??""}`.trim());for(let n of r){console.log(`
|
|
61
|
+
${n.name} \u2014 ${n.description}`);for(let o of n.subcommands??[])console.log(` ${n.name} ${o.name} \u2014 ${o.description}`)}}import{existsSync as kc,mkdirSync as Ec,readFileSync as Sc,readdirSync as jc,statSync as Cc,writeFileSync as $c}from"fs";import{dirname as Rc,join as Ic}from"path";import{fileURLToPath as Ac}from"url";import Nc from"typescript";import _c from"typescript";import{readFile as qc}from"fs/promises";var Yc=1800*1e3;var Jr=["prod","dev","local"];function D(t){if(t===void 0)return"prod";if(Jr.includes(t))return t;console.error(`Invalid --target ${t}. Allowed: ${Jr.join(", ")}.`),m(f.UserError)}function qr(t){if(!t)return;let e=parseInt(t,10);if(e===24||e===30||e===60)return e;console.error(`Invalid --fps ${t}. Allowed: 24, 30, 60.`),m(f.UserError)}async function Vr(){let t=new Ss;t.name("cueframe").description("AI-assisted video editing and rendering").version("0.4.2").option("--json","Emit a structured JSON document on stdout instead of human-formatted output. Spinners are silenced.").option("--dry-run","Validate inputs and report what would happen \u2014 no API calls, no mutations. Applies to upload, analyze, project create, render.");let e=()=>t.opts();t.command("install").description('One-line setup: wire the CueFrame MCP server into every installed agent (Claude Code / Cursor / Codex) and install the agent skills. No API key \u2014 auth is a browser "Allow" on first call.').option("-t, --target <target>","Target environment: prod (default), dev, local").option("-f, --force","Overwrite skills that are already installed in ~/.claude/skills").action(c=>Nt({json:e().json,target:D(c.target),dryRun:e().dryRun,force:c.force})),t.command("init").description("Scaffold a CueFrame component workspace (cueframe.json + components dir) in the current repo, so `new component` has a home and the render harness can discover it.").action(()=>Ut({json:e().json,dryRun:e().dryRun})),t.command("new").description("Scaffold new owned source in the component workspace").command("component").description("Scaffold a blank custom component in cueframe/components/<name>").argument("<name>","Component id (e.g. my-badge)").option("-f, --force","Overwrite an existing non-empty component dir").action((c,u)=>er(c,{json:e().json,dryRun:e().dryRun,force:u.force})),t.command("push").description("Publish a locally-authored component (cueframe/components/<id>/index.tsx) to CueFrame so it renders server-side. Upserts by id.").argument("[id]","Component id to push (omit and use `cueframe sync` to push all)").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,u)=>nr(c,{target:D(u.target),json:e().json})),t.command("sync").description("Publish EVERY component in the workspace (cueframe/components/*) to CueFrame. Upserts each by id.").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>or({target:D(c.target),json:e().json}));let n=t.command("keys").description("Manage API keys. `keys create` mints a scoped key \u2014 run `cueframe login` first (keys cannot mint keys).");n.command("create").description("Mint a scoped API key (cf_*). Requires a logged-in session.").requiredOption("-n, --name <name>","Key name, e.g. ci-runner").option("-s, --scope <scope>","Comma-separated resource:actions, e.g. media:rw,projects:rw,renders:rw (resources: media,sessions,projects,renders,webhooks; actions r/w)").option("--preset <preset>","Scope preset instead of --scope: readonly (read all) | editall (read+write all)").option("--expires <days>","Expire after N days (default: never)").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>ir({...c,target:D(c.target),json:e().json})),n.command("list").description("List your API keys.").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>ar({target:D(c.target),json:e().json})),n.command("revoke").description("Revoke an API key by id.").argument("<keyId>","Key id (from `cueframe keys list`)").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,u)=>cr(c,{target:D(u.target),json:e().json})),t.command("login").description("Browser-mediated sign-in (OAuth device flow). Recommended for laptops.").option("-t, --target <target>","Target environment: prod (default), dev, local").option("--url <url>","Override the API base URL (advanced)").action(c=>$r({...c,target:D(c.target),json:e().json})),t.command("auth").description("Save a static API key (cf_live_\u2026 / cf_test_\u2026). Use for CI / headless environments.").argument("<api-key>","Your CueFrame API key").option("-t, --target <target>","Target environment: prod (default), dev, local").option("--url <url>","Override the API base URL (advanced)").action((c,u)=>{let k=D(u.target);Ze(c,k,u.url),e().json?console.log(JSON.stringify({ok:!0,target:k},null,2)):console.log(`API key saved for target "${k}"`)}),t.command("list").description("List projects").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-n, --limit <n>","Max projects to show","10").action(c=>dr({target:D(c.target),limit:parseInt(c.limit),json:e().json}));let o=t.command("project").description("Project commands");o.command("create").description("Create a new project. With --from-suggestion, atomically build the composition from a clip suggestion in one round-trip \u2014 the project is then immediately renderable via `cueframe render <projectId>`.").requiredOption("-n, --name <name>","Project name").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-a, --aspect <ratio>","Aspect ratio: 9:16, 1:1, 16:9","9:16").option("--fps <n>","Frame rate","30").option("--resolution <r>","Resolution: hd, fhd, 2k, 4k","fhd").option("--from-suggestion <sug>","Clip suggestion publicId (sug_\u2026) \u2014 atomically builds the composition after project creation so render needs no further args").option("--cheap","With --from-suggestion: use the deterministic translator (no LLM, ~100ms) instead of the AI authoring pass. Useful for tests / programmatic flows.").action(c=>wr({name:c.name,target:D(c.target),aspect:c.aspect,fps:qr(c.fps),resolution:c.resolution,fromSuggestion:c.fromSuggestion,cheap:c.cheap,json:e().json,dryRun:e().dryRun})),o.command("delete").description("Permanently delete a project (irreversible cleanup \u2014 removes the composition and render history).").argument("<projectId>","Project ID (from `cueframe list` or `project create`)").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,u)=>br(c,{target:D(u.target),json:e().json})),t.command("media").description("Media library cleanup commands").command("delete").description("Permanently delete a media item (irreversible cleanup \u2014 removes the source and its derived assets).").argument("<mediaId>","Media item ID (from `cueframe clips`)").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,u)=>kr(c,{target:D(u.target),json:e().json})),t.command("upload").description("Upload a video file and process it").argument("<file>","Path to video file").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-a, --analyze","Run clip analysis after processing completes").option("-r, --audio-role <role>","Declare the audio role (vo|music|sfx|ambience) \u2014 routes ingest enrichment: vo\u2192transcript, music\u2192beat grid, sfx/ambience\u2192envelope").action((c,u)=>fr(c,{target:D(u.target),analyze:u.analyze,audioRole:u.audioRole,json:e().json,dryRun:e().dryRun})),t.command("analyze").description("Trigger AI clip suggestion analysis for a media item").argument("<mediaItemId>","Media item ID (from `cueframe clips`)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-w, --wait","Wait for analysis to complete and show results").action((c,u)=>Ot(c,{target:D(u.target),wait:u.wait,json:e().json,dryRun:e().dryRun})),t.command("clips").description("List AI-generated clip suggestions for a media item").argument("[mediaItemId]","Media item ID (omit to list your media library)").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,u)=>gr(c,{target:D(u.target),json:e().json}));let i=t.command("render").description("Render a project to MP4 (queues, watches via SSE, downloads). Renders whatever composition is saved on the project \u2014 build it first via `project create --from-suggestion` or `composition from-suggestion`.").allowExcessArguments(!1).argument("<projectId>","Project ID (from `cueframe list` or `project create`)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-a, --aspect <ratio>","Aspect ratio: 9:16, 1:1, 16:9 (defaults to project format)").option("--fps <n>","Frame rate","30").option("--resolution <r>","Resolution: hd, fhd, 2k, 4k","fhd").option("-o, --out <path>","Output file path (default: ./reel-<id>.mp4)").option("--idempotency-key <key>",'Override the auto-derived Idempotency-Key. Default: sha256("render:<projectId>:<currentCompositionETag>"). Pass a fresh UUID to force a new render row.').option("--priority <p>","Routing intent: interactive (low-latency, access-gated), standard (default), background (lowest queue weight).").option("--intent <i>","Encode-quality hint: preview (fast / low-bitrate, for editor scrubbing) or final (default, full Format).").action((c,u)=>Cr(c,{target:u.target,aspect:u.aspect,fps:qr(u.fps),resolution:u.resolution,out:u.out,json:e().json,dryRun:e().dryRun,...u.idempotencyKey?{idempotencyKey:u.idempotencyKey}:{},...u.priority?{priority:u.priority}:{},...u.intent?{intent:u.intent}:{}}));t.command("api").description("Raw API call against the v1 surface (escape hatch \u2014 like `gh api`).").argument("<method>","HTTP method: GET, POST, PUT, PATCH, DELETE").argument("<path>","API path starting with /v1, e.g. /v1/projects").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-b, --body <body>","Request body (inline JSON, @file.json to read from disk, @- for stdin)").option("-H, --header <header...>",'Additional header (repeatable), e.g. -H "If-Match: \\"abc\\""').option("-i, --include","Include response status line + headers in stdout (curl-style). Lets agents read ETag etc.").action((c,u,k)=>Or(c,u,{target:k.target,body:k.body,header:k.header,include:k.include,json:e().json})),t.command("schema").description("Print the live composition wire schema from the server (/v1/openapi.json) \u2014 discover the contract instead of guessing.").argument("[resource]","Schema to print (currently: composition)","composition").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,u)=>Pr(c,{target:u.target,json:e().json}));let a=t.command("composition").description("Read/write a project's composition. ETag is threaded automatically.");a.command("validate").description("Validate a composition body against the live schema WITHOUT saving or rendering. Returns per-field errors \u2014 author safely before paying for a render.").requiredOption("-b, --body <body>","Composition JSON (inline, @file.json, or @- for stdin)").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>vr({target:c.target,body:c.body,json:e().json})),a.command("get").description("Fetch the project's composition and ETag").argument("<projectId>","Project ID").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,u)=>hr(c,{target:u.target,json:e().json})),a.command("put").description("Replace the composition. GETs ETag first for safe concurrent writes.").argument("<projectId>","Project ID").option("-t, --target <target>","Target environment: prod (default), dev, local").requiredOption("-b, --body <body>","Composition JSON (inline, @file.json, or @- for stdin)").option("--if-match <etag>","Use this ETag (skip the GET round-trip)").option("--force","Use If-Match: * (unconditional overwrite \u2014 may clobber concurrent edits)").action((c,u)=>yr(c,{target:u.target,body:u.body,ifMatch:u.ifMatch,force:u.force,json:e().json})),a.command("from-suggestion").description("Build the composition from an existing clip suggestion").argument("<projectId>","Project ID").requiredOption("-s, --suggestion <suggestionId>","Clip suggestion publicId (sug_\u2026)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("--format <json>",`Optional format override, e.g. '{"aspectRatio":"9:16","fps":30,"resolution":"fhd"}'`).option("--if-match <etag>","Use this ETag (skip the GET round-trip)").option("--force","Use If-Match: * (unconditional overwrite)").action((c,u)=>ct(c,{target:u.target,suggestionId:u.suggestion,format:u.format,ifMatch:u.ifMatch,force:u.force,json:e().json})),i.command("watch").description("Reattach to an existing render and stream progress to terminal state").argument("<renderId>","Render ID (from `cueframe render` output)").requiredOption("-p, --project <projectId>","Project the render belongs to").option("-t, --target <target>","Target environment: prod (default), dev, local").option("--no-download","Print the MP4 URL but skip downloading the file").option("-o, --out <path>","Output file path when downloading (default: ./reel-<id>.mp4)").action((c,u,k)=>{let P=k?.parent?.opts?.()?.target??u.target;return jr(c,{target:P,project:u.project,out:u.out,download:u.download!==!1,json:e().json})});let d=t.command("export").description("Hand the timeline off to a real NLE (Final Cut Pro / Premiere Pro)");d.command("fcpxml").description("Build a Final Cut Pro export zip and (optionally) wait to download it").argument("<projectId>","Project ID").requiredOption("-s, --suggestion <suggestionId>","Clip suggestion publicId (sug_\u2026)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-o, --out <path>","Output zip path (default: ./export-<id>.zip)").option("--wait","Block until the export finishes, then download the artifact").action((c,u)=>Et("fcpxml",{target:u.target,projectId:c,suggestionId:u.suggestion,out:u.out,wait:u.wait,json:e().json})),d.command("premiere").description("Build a Premiere Pro export zip and (optionally) wait to download it").argument("<projectId>","Project ID").requiredOption("-s, --suggestion <suggestionId>","Clip suggestion publicId (sug_\u2026)").option("-t, --target <target>","Target environment: prod (default), dev, local").option("-o, --out <path>","Output zip path (default: ./export-<id>.zip)").option("--wait","Block until the export finishes, then download the artifact").action((c,u)=>Et("premiere",{target:u.target,projectId:c,suggestionId:u.suggestion,out:u.out,wait:u.wait,json:e().json}));let l=t.command("sessions").description("Multi-file ingest sessions (camera A/B/screen \u2192 muxed composition)");l.command("list").description("List sessions in this org").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>Fr({target:c.target,json:e().json})),l.command("get").description("Get a single session by ID").argument("<sessionId>","Session ID").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,u)=>Ur(c,{target:u.target,json:e().json})),l.command("create").description("Create a session from one or more media files").requiredOption("-n, --name <name>","Session name").requiredOption("-f, --file <entry...>","Each entry is <mediaId>:<role> (repeatable)").option("-t, --target <target>","Target environment: prod (default), dev, local").action(c=>Dr({target:c.target,name:c.name,files:c.file,json:e().json})),l.command("delete").description("Delete a session (server checks for compositions referencing it)").argument("<sessionId>","Session ID").option("-t, --target <target>","Target environment: prod (default), dev, local").action((c,u)=>Lr(c,{target:u.target,json:e().json})),t.command("describe").description("Print the CLI command tree as structured JSON (agent introspection)").action(()=>Wr(t,{json:e().json}));try{await t.parseAsync()}catch(c){let u=v(c);x(e(),"cli",Object.assign(new Error(I(c)),{code:c?.code,status:c?.status}),u),m(u)}}await Vr();
|