magicpath-ai 2.4.0 → 2.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.
Files changed (2) hide show
  1. package/dist/cli.js +56 -56
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{readFileSync as Br}from"fs";import{dirname as Kr,join as qr}from"path";import{fileURLToPath as Xr}from"url";import{program as T}from"commander";import Ze from"axios";var p=class extends Error{code;suggestion;constructor(n,t){super(n),this.code=t==null?void 0:t.code,this.suggestion=t==null?void 0:t.suggestion}};function Ot(e){if(!(!e||typeof e!="object"))return e}function M(e){var n,t,o;if(e instanceof p)return e;if(Ze.isAxiosError(e)){let r=Ot((n=e.response)==null?void 0:n.data),s=typeof(r==null?void 0:r.message)=="string"?r.message:e.response?`API error: ${e.response.status} ${e.response.statusText}`:e.message,i=typeof(r==null?void 0:r.code)=="string"?r.code:void 0,c=typeof((t=r==null?void 0:r.details)==null?void 0:t.billing_url)=="string"?r.details.billing_url:typeof((o=r==null?void 0:r.details)==null?void 0:o.billingUrl)=="string"?r.details.billingUrl:void 0,a=typeof(r==null?void 0:r.suggestion)=="string"?r.suggestion:i==="GUEST_FORBIDDEN"?"Guest sessions are scoped to one project. Sign up at https://magicpath.ai to unlock this.":c?"Upgrade to Pro from billing to keep using external agents.":void 0;return new p(s,{code:i,...a?{suggestion:a}:{}})}return e instanceof Error?new p(e.message):new p(String(e))}function Ut(){Ze.interceptors.response.use(e=>e,e=>{var n;if(Ze.isAxiosError(e)){let t=Ot((n=e.response)==null?void 0:n.data);if(typeof(t==null?void 0:t.code)=="string")return Promise.reject(M(e))}return Promise.reject(e)})}var Ft=!1;function Mt(e){Ft=e}function x(){return Ft}function b(e){console.log(JSON.stringify(e,null,2)),process.exit(0)}function E(e){let t={error:e instanceof Error?e.message:String(e)};e instanceof p&&(e.code&&(t.code=e.code),e.suggestion&&(t.suggestion=e.suggestion)),console.error(JSON.stringify(t,null,2)),process.exit(1)}var B="0.0.0-dev";function Dt(e){B=e}import ie from"chalk";import ye from"fs-extra";import sn from"path";import To from"os";import an from"axios";var A=process.env.MAGICPATH_API_URL??"https://api.magicpath.ai";function ke(e,n){return`${A}/${e}/${n}`}function _t(e){return`${A}/v1/registry/${e}`}var ko=process.env.MAGICPATH_WEB_URL??"https://www.magicpath.ai";function Qe(e){return`${ko}${e}`}function Lt(e){return Qe(`/files/${e}`)}function Pe(e){return`${A}/auth/${e}`}function et(){return`${A}/v1/external-agent/components`}function tt(e){return`${A}/v1/external-agent/components/${e}/context`}function Wt(e){return`${A}/v1/external-agent/components/${e}/start`}function Ht(e){return`${A}/v1/external-agent/components/${e}/revisions`}function nt(e,n){return`${A}/v1/external-agent/components/${e}/revisions/${n}/files`}function ot(e){return`${A}/v1/external-agent/jobs/${e}`}function Q(){return`${A}/users/me`}function rt(){return`${A}/users/me/projects`}function st(){return`${A}/users/me/skills`}function Gt(){return`${A}/users/me/skills/import`}function Vt(){return`${A}/users/me/assets/upload-url`}function zt(){return`${A}/projects`}function Ae(e){return`${A}/projects/${e}`}function Jt(e){return`${A}/projects/${e}/components`}function it(e){return`${A}/projects/${e}/images`}function Te(){return`${A}/users/me/design-systems`}function Bt(e){return`${A}/design-systems/${e}`}function oe(){return`${A}/users/me/socket-rooms`}function Kt(){return`${A}/liveblocks/auth`}function qt(e){return`${A}/components/${e}`}function Xt(){return`${A}/components/search`}function Yt(e){return`${A}/organizations/${e}`}function at(e){return`${A}/organizations/${e}/projects`}function ct(e){return`${A}/organizations/${e}/skills`}function Zt(e){return`${A}/organizations/${e}/skills/import`}function Ne(e){return`${A}/organizations/${e}/design-systems`}function lt(e){return`${A}/skills/${e}`}function Qt(e){return`${A}/skills/${e}/files`}function en(e,n){return`${A}/skills/${e}/files/content?path=${encodeURIComponent(n)}`}var Po=[{type:"claude-code",envVar:"CLAUDECODE"},{type:"cursor",envVar:"CURSOR_TRACE_ID"},{type:"cursor",envVar:"CURSOR_AGENT"},{type:"codex",envVar:"CODEX_SANDBOX"},{type:"codex",envVar:"CODEX_THREAD_ID"},{type:"codex",envVar:"CODEX_CI"},{type:"gemini",envVar:"GEMINI_CLI"},{type:"antigravity",envVar:"ANTIGRAVITY_AGENT"},{type:"augment",envVar:"AUGMENT_AGENT"},{type:"opencode",envVar:"OPENCODE_CLIENT"},{type:"copilot",envVar:"COPILOT_MODEL"},{type:"cline",envVar:"CLINE_ACTIVE"},{type:"replit",envVar:"REPL_ID"},{type:"goose",envVar:"GOOSE_TERMINAL"}],Re={"claude-code":"claude-code",claude:"claude-code",cursor:"cursor","cursor-agent":"cursor",codex:"codex","codex-cli":"codex",gemini:"gemini","gemini-cli":"gemini",antigravity:"antigravity",augment:"augment",opencode:"opencode",copilot:"copilot","github-copilot":"copilot","github-copilot-cli":"copilot",cline:"cline",replit:"replit",v0:"v0",devin:"devin",aider:"aider",goose:"goose",amp:"amp"};function tn(e){let n=e.trim();if(!n)return null;let t=n.indexOf("@");if(t===-1)return{slug:n.toLowerCase()};let o=n.slice(0,t).trim().toLowerCase(),r=n.slice(t+1).trim()||void 0;return o?{slug:o,version:r}:null}function nn(e){if(e in Re)return Re[e];for(let n of Object.keys(Re))if(e.startsWith(`${n}_`)||e.startsWith(`${n}-`))return Re[n];return e}var Oe;function on(){return Oe||(Oe=Ao(),Oe)}function Ao(){let e=process.env.MAGICPATH_AGENT;if(e){let t=tn(e);if(t)return{kind:"known-agent",slug:nn(t.slug),version:t.version}}for(let t of Po){let o=process.env[t.envVar];if(o&&o!=="0"&&o.toLowerCase()!=="false")return{kind:"known-agent",slug:t.type}}let n=process.env.AI_AGENT;if(n){let t=tn(n);if(t)return{kind:"known-agent",slug:nn(t.slug),version:t.version}}return process.stdin.isTTY?{kind:"interactive-human"}:{kind:"unknown-agent"}}function rn(e){switch(e.kind){case"known-agent":return{type:e.slug,version:e.version};case"interactive-human":return{type:"interactive"};case"unknown-agent":return{}}}var cn=sn.join(To.homedir(),".magicpath"),Ue=sn.join(cn,"session.json");function re(){try{if(!ye.existsSync(Ue))return null;let e=ye.readJsonSync(Ue);return e.accessToken&&(e.refreshToken||e.guest)?e:null}catch{return null}}function mt(e){ye.ensureDirSync(cn),ye.writeJsonSync(Ue,e)}function dt(e,n){let t=re();mt({accessToken:e,refreshToken:n,user:t==null?void 0:t.user})}function ln(e,n){mt({accessToken:e,guest:n})}function se(){let e=re();return e?{accessToken:e.accessToken,refreshToken:e.refreshToken}:null}function Fe(){let e=re();return(e==null?void 0:e.guest)??null}function mn(){try{ye.removeSync(Ue)}catch{}}function No(e){try{let n=re();n&&(n.user=e,mt(n))}catch{}}function dn(){let e=re();return(e==null?void 0:e.user)??null}function j(){let{type:e,version:n}=rn(on()),t={"X-Client-Type":"cli","X-Client-Version":B};e&&(t["X-Agent-Type"]=e),n&&(t["X-Agent-Version"]=n);let o=process.env.MAGICPATH_TOKEN;if(o)return t.Authorization=`Bearer ${o}`,t;let r=re();if(!r)throw new Error("Not logged in. Run `magicpath-ai login` first.");if(r.guest&&Date.parse(r.guest.expiresAt)<Date.now())throw new p("Your guest session has expired. Sign up at https://magicpath.ai to keep building.",{code:"GUEST_EXPIRED",suggestion:"Sign up at https://magicpath.ai or start a new guest project from the MagicPath site."});return t.Authorization=`Bearer ${r.accessToken}`,t}function Ie(e){var o,r;let n=(o=e.subscription)!=null&&o.active?(r=e.subscription.type)!=null&&r.startsWith("PRO")?"Pro":"Creator":"Free",t={name:e.name||e.firstName||e.displayName,email:e.email,plan:n};return No(t),t}async function pt(){let e=j(),n=await an.get(Q(),{headers:e}),t=n.data.user??n.data;return Ie(t)}async function be(e){let n=await an.get(Q(),{headers:e});return((n.data.user??n.data).organizationUsers??[]).map(r=>({id:String(r.organization.id),name:r.organization.name,role:r.role}))}async function _(e,n){let t=await be(n),o=t.find(i=>i.id===e);if(o)return{id:o.id,name:o.name};let r=e.toLowerCase(),s=t.find(i=>i.name.toLowerCase()===r);if(s)return{id:s.id,name:s.name};throw new p(`Team "${e}" not found.`,{code:"TEAM_NOT_FOUND",suggestion:"Run `magicpath-ai list-teams` to see your teams."})}var pn=["#95D5B2","#74C69D","#52B788","#40916C","#2D6A4F","#1B4332"];function Ro(e){return ie.hex(pn[Math.min(e,pn.length-1)])}var gt=ie.hex("#2D6A4F"),Oo=ie.hex("#1B4332"),Uo=ie.hex("#E8F5E9"),ut=ie.hex("#888888"),Fo=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2551 ","\u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 ","\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D"],Mo=["\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551","\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551","\u2588\u2588\u2554\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551","\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D"],Do=Fo.map((e,n)=>e+" "+Mo[n]);function _o(e){return e.map((n,t)=>{let o=Ro(t),r="";for(let s of n)r+=s===" "?s:o(s);return r})}function gn(e){let n=!!se(),t=n?dn():null;console.log();for(let s of _o(Do))console.log(s);if(console.log(),n&&t){let s=t.plan?` \xB7 ${t.plan}`:"";console.log(" "+gt("\u25CF")+" "+ie.bold(Uo(t.name??"MagicPath User"))+Oo(" "+(t.email??"")+s))}else console.log(" "+ut("\u25CB Not logged in \xB7 run")+" "+gt("magicpath-ai login"));console.log();let o=20,r=[["search <query>","Search components"],["add <name>","Add to project"],["list-projects","Your projects"],["setup-skills","Set up AI agents"]];for(let[s,i]of r)console.log(" "+gt(s.padEnd(o))+ut(i));console.log(),console.log(" "+ut(`v${e} \u2500 magicpath-ai --help`)),console.log()}import De from"prompts";import En from"ora";import{z as le}from"zod";import me from"path";import qo from"os";import wt from"fs-extra";import{pino as un}from"pino";var ae=un();function ce(){ae=un({level:"debug"}),ae.debug({message:"DEBUG logger enabled. "})}var R={info:e=>{ae.info(e)},debug:e=>{ae.debug(e)},warn:e=>{ae.warn(e)},error:e=>{ae.error(e)}};import fn from"axios";import Me from"path";import Wo from"os";import{Readable as Ho}from"stream";import $e from"fs-extra";import Go from"adm-zip";import{v4 as Vo}from"uuid";async function zo(e){if(!(e instanceof Ho))return;let n=[];return new Promise((t,o)=>{e.on("data",r=>{n.push(Buffer.isBuffer(r)?r:Buffer.from(r))}),e.on("error",o),e.on("end",()=>t(Buffer.concat(n).toString("utf8")))})}async function Jo(e){var n;if(e instanceof p)return e;if(fn.isAxiosError(e)){let t=await zo((n=e.response)==null?void 0:n.data);if(t)try{let o=JSON.parse(t);return M({...e,response:{...e.response,data:o},isAxiosError:!0})}catch{}return M(e)}return new p("Failed to download project. Make sure your key is valid.")}async function hn(e){let n=ke("v1","components/repository"),t=`${Vo()}.zip`,o=Me.join(Wo.tmpdir(),t);try{let r=await fn({url:n,params:{key:e},method:"GET",responseType:"stream"});return await $e.ensureDir(Me.dirname(o)),await new Promise(async(s,i)=>{try{r.data.pipe($e.createWriteStream(o)).on("error",i).once("close",()=>s(o))}catch(c){i(c)}}),o}catch(r){throw await Jo(r)}}function ft(e){try{$e.removeSync(e)}catch{}}function wn(e,n,t){try{let o=Me.join(t,n),r=1;for(;$e.existsSync(o);)r++,o=Me.join(t,`${n}-${r}`);return $e.mkdirSync(o,{recursive:!0}),new Go(e).extractAllTo(o,!0),ft(e),o}catch{throw new p("Failed to extract project. Please try again.")}}import{execSync as ht}from"child_process";import In from"ora";import yn from"fs-extra";import Bo from"path";function bn(){try{return ht("yarn --version",{stdio:"ignore"}),"yarn"}catch{return"npm"}}function $n(e){let n=bn(),t=In(`\u{1F4E6} Installing dependencies using ${n}...`).start();try{ht(n==="yarn"?"yarn install":"npm install",{cwd:e,stdio:"ignore"}),t.succeed("Dependencies installed successfully!")}catch{throw t.fail("Failed to install dependencies"),new p("Failed to install dependencies. Please check your internet connection and try again.")}}function Ko(e){let n=Bo.join(e,"package.json");if(!yn.existsSync(n))return new Set;try{let t=yn.readJsonSync(n),o=new Set;return t.dependencies&&Object.keys(t.dependencies).forEach(r=>o.add(r)),t.devDependencies&&Object.keys(t.devDependencies).forEach(r=>o.add(r)),o}catch{return new Set}}function xn(e,n){if(e.length===0)return{installed:[],skipped:[]};let t=Ko(n),o=e.filter(c=>!t.has(c)),r=e.filter(c=>t.has(c));if(o.length===0)return R.debug("All dependencies already installed"),{installed:[],skipped:r};let s=bn(),i=In(`\u{1F4E6} Installing ${o.length} package${o.length>1?"s":""} using ${s}...`).start();try{let c=o.join(" "),a=s==="yarn"?`yarn add ${c}`:`npm install ${c}`;return R.debug({command:a}),ht(a,{cwd:n,stdio:"ignore"}),i.succeed(`Installed ${o.length} package${o.length>1?"s":""}`),{installed:o,skipped:r}}catch{throw i.fail("Failed to install packages"),new p(`Failed to install packages: ${o.join(", ")}. Please install them manually.`)}}import{execSync as Sn}from"child_process";import vn from"ora";function Cn(e,n){let t={cursor:"Cursor",antigravity:"Antigravity",vscode:"VS Code",webstorm:"WebStorm"},o={cursor:["cursor","code"],antigravity:["agy","antigravity"],vscode:["code"],webstorm:["webstorm","web"]},r=vn(`\u{1F680} Opening project in ${t[n]}...`).start(),s=!1;try{for(let i of o[n]){if(s)break;try{Sn(`${i} .`,{cwd:e,stdio:"ignore"}),s=!0}catch{s=!1}}if(!s)throw new Error("Failed to open with command.");r.succeed(`Project opened in ${t[n]}!`)}catch{r.fail(`Failed to open ${t[n]}`);let i={cursor:`\u274C Cursor command not found!
2
+ import{readFileSync as qr}from"fs";import{dirname as Xr,join as Yr}from"path";import{fileURLToPath as Zr}from"url";import{program as T}from"commander";import et from"axios";var p=class extends Error{code;suggestion;constructor(n,t){super(n),this.code=t==null?void 0:t.code,this.suggestion=t==null?void 0:t.suggestion}};function Ut(e){if(!(!e||typeof e!="object"))return e}function M(e){var n,t,o;if(e instanceof p)return e;if(et.isAxiosError(e)){let r=Ut((n=e.response)==null?void 0:n.data),s=typeof(r==null?void 0:r.message)=="string"?r.message:e.response?`API error: ${e.response.status} ${e.response.statusText}`:e.message,i=typeof(r==null?void 0:r.code)=="string"?r.code:void 0,c=typeof((t=r==null?void 0:r.details)==null?void 0:t.billing_url)=="string"?r.details.billing_url:typeof((o=r==null?void 0:r.details)==null?void 0:o.billingUrl)=="string"?r.details.billingUrl:void 0,a=typeof(r==null?void 0:r.suggestion)=="string"?r.suggestion:i==="GUEST_FORBIDDEN"?"Guest sessions are scoped to one project. Sign up at https://magicpath.ai to unlock this.":i==="GUEST_BUILD_LIMIT_REACHED"?"You have used all your free guest builds. Sign up at https://magicpath.ai to keep building and save this project.":c?"Upgrade to Pro from billing to keep using external agents.":void 0;return new p(s,{code:i,...a?{suggestion:a}:{}})}return e instanceof Error?new p(e.message):new p(String(e))}function Ft(){et.interceptors.response.use(e=>e,e=>{var n;if(et.isAxiosError(e)){let t=Ut((n=e.response)==null?void 0:n.data);if(typeof(t==null?void 0:t.code)=="string")return Promise.reject(M(e))}return Promise.reject(e)})}var Mt=!1;function Dt(e){Mt=e}function x(){return Mt}function b(e){console.log(JSON.stringify(e,null,2)),process.exit(0)}function E(e){let t={error:e instanceof Error?e.message:String(e)};e instanceof p&&(e.code&&(t.code=e.code),e.suggestion&&(t.suggestion=e.suggestion)),console.error(JSON.stringify(t,null,2)),process.exit(1)}var B="0.0.0-dev";function _t(e){B=e}import ie from"chalk";import ye from"fs-extra";import an from"path";import Ro from"os";import cn from"axios";var A=process.env.MAGICPATH_API_URL??"https://api.magicpath.ai";function ke(e,n){return`${A}/${e}/${n}`}function Lt(e){return`${A}/v1/registry/${e}`}var Ao=process.env.MAGICPATH_WEB_URL??"https://www.magicpath.ai";function Pe(e){return`${Ao}${e}`}function Wt(e){return Pe(`/files/${e}`)}function Ae(e,n){return Pe(`/projects/${e}?guest=${encodeURIComponent(n)}`)}function Te(e){return`${A}/auth/${e}`}function tt(){return`${A}/v1/external-agent/components`}function nt(e){return`${A}/v1/external-agent/components/${e}/context`}function Ht(e){return`${A}/v1/external-agent/components/${e}/start`}function Gt(e){return`${A}/v1/external-agent/components/${e}/revisions`}function ot(e,n){return`${A}/v1/external-agent/components/${e}/revisions/${n}/files`}function rt(e){return`${A}/v1/external-agent/jobs/${e}`}function Q(){return`${A}/users/me`}function st(){return`${A}/users/me/projects`}function it(){return`${A}/users/me/skills`}function Vt(){return`${A}/users/me/skills/import`}function zt(){return`${A}/users/me/assets/upload-url`}function Jt(){return`${A}/projects`}function Ne(e){return`${A}/projects/${e}`}function Bt(e){return`${A}/projects/${e}/components`}function at(e){return`${A}/projects/${e}/images`}function Re(){return`${A}/users/me/design-systems`}function Kt(e){return`${A}/design-systems/${e}`}function re(){return`${A}/users/me/socket-rooms`}function qt(){return`${A}/liveblocks/auth`}function Xt(e){return`${A}/components/${e}`}function Yt(){return`${A}/components/search`}function Zt(e){return`${A}/organizations/${e}`}function ct(e){return`${A}/organizations/${e}/projects`}function lt(e){return`${A}/organizations/${e}/skills`}function Qt(e){return`${A}/organizations/${e}/skills/import`}function Oe(e){return`${A}/organizations/${e}/design-systems`}function mt(e){return`${A}/skills/${e}`}function en(e){return`${A}/skills/${e}/files`}function tn(e,n){return`${A}/skills/${e}/files/content?path=${encodeURIComponent(n)}`}var To=[{type:"claude-code",envVar:"CLAUDECODE"},{type:"cursor",envVar:"CURSOR_TRACE_ID"},{type:"cursor",envVar:"CURSOR_AGENT"},{type:"codex",envVar:"CODEX_SANDBOX"},{type:"codex",envVar:"CODEX_THREAD_ID"},{type:"codex",envVar:"CODEX_CI"},{type:"gemini",envVar:"GEMINI_CLI"},{type:"antigravity",envVar:"ANTIGRAVITY_AGENT"},{type:"augment",envVar:"AUGMENT_AGENT"},{type:"opencode",envVar:"OPENCODE_CLIENT"},{type:"copilot",envVar:"COPILOT_MODEL"},{type:"cline",envVar:"CLINE_ACTIVE"},{type:"replit",envVar:"REPL_ID"},{type:"goose",envVar:"GOOSE_TERMINAL"}],Ue={"claude-code":"claude-code",claude:"claude-code",cursor:"cursor","cursor-agent":"cursor",codex:"codex","codex-cli":"codex",gemini:"gemini","gemini-cli":"gemini",antigravity:"antigravity",augment:"augment",opencode:"opencode",copilot:"copilot","github-copilot":"copilot","github-copilot-cli":"copilot",cline:"cline",replit:"replit",v0:"v0",devin:"devin",aider:"aider",goose:"goose",amp:"amp"};function nn(e){let n=e.trim();if(!n)return null;let t=n.indexOf("@");if(t===-1)return{slug:n.toLowerCase()};let o=n.slice(0,t).trim().toLowerCase(),r=n.slice(t+1).trim()||void 0;return o?{slug:o,version:r}:null}function on(e){if(e in Ue)return Ue[e];for(let n of Object.keys(Ue))if(e.startsWith(`${n}_`)||e.startsWith(`${n}-`))return Ue[n];return e}var Fe;function rn(){return Fe||(Fe=No(),Fe)}function No(){let e=process.env.MAGICPATH_AGENT;if(e){let t=nn(e);if(t)return{kind:"known-agent",slug:on(t.slug),version:t.version}}for(let t of To){let o=process.env[t.envVar];if(o&&o!=="0"&&o.toLowerCase()!=="false")return{kind:"known-agent",slug:t.type}}let n=process.env.AI_AGENT;if(n){let t=nn(n);if(t)return{kind:"known-agent",slug:on(t.slug),version:t.version}}return process.stdin.isTTY?{kind:"interactive-human"}:{kind:"unknown-agent"}}function sn(e){switch(e.kind){case"known-agent":return{type:e.slug,version:e.version};case"interactive-human":return{type:"interactive"};case"unknown-agent":return{}}}var ln=an.join(Ro.homedir(),".magicpath"),Me=an.join(ln,"session.json");function ee(){try{if(!ye.existsSync(Me))return null;let e=ye.readJsonSync(Me);return e.accessToken&&(e.refreshToken||e.guest)?e:null}catch{return null}}function dt(e){ye.ensureDirSync(ln),ye.writeJsonSync(Me,e)}function pt(e,n){let t=ee();dt({accessToken:e,refreshToken:n,user:t==null?void 0:t.user})}function mn(e,n){dt({accessToken:e,guest:n})}function se(){let e=ee();return e?{accessToken:e.accessToken,refreshToken:e.refreshToken}:null}function De(){let e=ee();return(e==null?void 0:e.guest)??null}function dn(){let e=ee();return e!=null&&e.guest?Ae(e.guest.projectId,e.accessToken):null}function pn(){try{ye.removeSync(Me)}catch{}}function Oo(e){try{let n=ee();n&&(n.user=e,dt(n))}catch{}}function gn(){let e=ee();return(e==null?void 0:e.user)??null}function j(){let{type:e,version:n}=sn(rn()),t={"X-Client-Type":"cli","X-Client-Version":B};e&&(t["X-Agent-Type"]=e),n&&(t["X-Agent-Version"]=n);let o=process.env.MAGICPATH_TOKEN;if(o)return t.Authorization=`Bearer ${o}`,t;let r=ee();if(!r)throw new Error("Not logged in. Run `magicpath-ai login` first.");if(r.guest&&Date.parse(r.guest.expiresAt)<Date.now())throw new p("Your guest session has expired. Sign up at https://magicpath.ai to keep building.",{code:"GUEST_EXPIRED",suggestion:"Sign up at https://magicpath.ai or start a new guest project from the MagicPath site."});return t.Authorization=`Bearer ${r.accessToken}`,t}function Ie(e){var o,r;let n=(o=e.subscription)!=null&&o.active?(r=e.subscription.type)!=null&&r.startsWith("PRO")?"Pro":"Creator":"Free",t={name:e.name||e.firstName||e.displayName,email:e.email,plan:n};return Oo(t),t}async function gt(){let e=j(),n=await cn.get(Q(),{headers:e}),t=n.data.user??n.data;return Ie(t)}async function be(e){let n=await cn.get(Q(),{headers:e});return((n.data.user??n.data).organizationUsers??[]).map(r=>({id:String(r.organization.id),name:r.organization.name,role:r.role}))}async function _(e,n){let t=await be(n),o=t.find(i=>i.id===e);if(o)return{id:o.id,name:o.name};let r=e.toLowerCase(),s=t.find(i=>i.name.toLowerCase()===r);if(s)return{id:s.id,name:s.name};throw new p(`Team "${e}" not found.`,{code:"TEAM_NOT_FOUND",suggestion:"Run `magicpath-ai list-teams` to see your teams."})}var un=["#95D5B2","#74C69D","#52B788","#40916C","#2D6A4F","#1B4332"];function Uo(e){return ie.hex(un[Math.min(e,un.length-1)])}var ut=ie.hex("#2D6A4F"),Fo=ie.hex("#1B4332"),Mo=ie.hex("#E8F5E9"),ft=ie.hex("#888888"),Do=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2551 ","\u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 ","\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D"],_o=["\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551","\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551","\u2588\u2588\u2554\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551","\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D"],Lo=Do.map((e,n)=>e+" "+_o[n]);function Wo(e){return e.map((n,t)=>{let o=Uo(t),r="";for(let s of n)r+=s===" "?s:o(s);return r})}function fn(e){let n=!!se(),t=n?gn():null;console.log();for(let s of Wo(Lo))console.log(s);if(console.log(),n&&t){let s=t.plan?` \xB7 ${t.plan}`:"";console.log(" "+ut("\u25CF")+" "+ie.bold(Mo(t.name??"MagicPath User"))+Fo(" "+(t.email??"")+s))}else console.log(" "+ft("\u25CB Not logged in \xB7 run")+" "+ut("magicpath-ai login"));console.log();let o=20,r=[["search <query>","Search components"],["add <name>","Add to project"],["list-projects","Your projects"],["setup-skills","Set up AI agents"]];for(let[s,i]of r)console.log(" "+ut(s.padEnd(o))+ft(i));console.log(),console.log(" "+ft(`v${e} \u2500 magicpath-ai --help`)),console.log()}import Le from"prompts";import Pn from"ora";import{z as le}from"zod";import me from"path";import Yo from"os";import yt from"fs-extra";import{pino as hn}from"pino";var ae=hn();function ce(){ae=hn({level:"debug"}),ae.debug({message:"DEBUG logger enabled. "})}var R={info:e=>{ae.info(e)},debug:e=>{ae.debug(e)},warn:e=>{ae.warn(e)},error:e=>{ae.error(e)}};import wn from"axios";import _e from"path";import Go from"os";import{Readable as Vo}from"stream";import $e from"fs-extra";import zo from"adm-zip";import{v4 as Jo}from"uuid";async function Bo(e){if(!(e instanceof Vo))return;let n=[];return new Promise((t,o)=>{e.on("data",r=>{n.push(Buffer.isBuffer(r)?r:Buffer.from(r))}),e.on("error",o),e.on("end",()=>t(Buffer.concat(n).toString("utf8")))})}async function Ko(e){var n;if(e instanceof p)return e;if(wn.isAxiosError(e)){let t=await Bo((n=e.response)==null?void 0:n.data);if(t)try{let o=JSON.parse(t);return M({...e,response:{...e.response,data:o},isAxiosError:!0})}catch{}return M(e)}return new p("Failed to download project. Make sure your key is valid.")}async function yn(e){let n=ke("v1","components/repository"),t=`${Jo()}.zip`,o=_e.join(Go.tmpdir(),t);try{let r=await wn({url:n,params:{key:e},method:"GET",responseType:"stream"});return await $e.ensureDir(_e.dirname(o)),await new Promise(async(s,i)=>{try{r.data.pipe($e.createWriteStream(o)).on("error",i).once("close",()=>s(o))}catch(c){i(c)}}),o}catch(r){throw await Ko(r)}}function ht(e){try{$e.removeSync(e)}catch{}}function In(e,n,t){try{let o=_e.join(t,n),r=1;for(;$e.existsSync(o);)r++,o=_e.join(t,`${n}-${r}`);return $e.mkdirSync(o,{recursive:!0}),new zo(e).extractAllTo(o,!0),ht(e),o}catch{throw new p("Failed to extract project. Please try again.")}}import{execSync as wt}from"child_process";import $n from"ora";import bn from"fs-extra";import qo from"path";function xn(){try{return wt("yarn --version",{stdio:"ignore"}),"yarn"}catch{return"npm"}}function vn(e){let n=xn(),t=$n(`\u{1F4E6} Installing dependencies using ${n}...`).start();try{wt(n==="yarn"?"yarn install":"npm install",{cwd:e,stdio:"ignore"}),t.succeed("Dependencies installed successfully!")}catch{throw t.fail("Failed to install dependencies"),new p("Failed to install dependencies. Please check your internet connection and try again.")}}function Xo(e){let n=qo.join(e,"package.json");if(!bn.existsSync(n))return new Set;try{let t=bn.readJsonSync(n),o=new Set;return t.dependencies&&Object.keys(t.dependencies).forEach(r=>o.add(r)),t.devDependencies&&Object.keys(t.devDependencies).forEach(r=>o.add(r)),o}catch{return new Set}}function Sn(e,n){if(e.length===0)return{installed:[],skipped:[]};let t=Xo(n),o=e.filter(c=>!t.has(c)),r=e.filter(c=>t.has(c));if(o.length===0)return R.debug("All dependencies already installed"),{installed:[],skipped:r};let s=xn(),i=$n(`\u{1F4E6} Installing ${o.length} package${o.length>1?"s":""} using ${s}...`).start();try{let c=o.join(" "),a=s==="yarn"?`yarn add ${c}`:`npm install ${c}`;return R.debug({command:a}),wt(a,{cwd:n,stdio:"ignore"}),i.succeed(`Installed ${o.length} package${o.length>1?"s":""}`),{installed:o,skipped:r}}catch{throw i.fail("Failed to install packages"),new p(`Failed to install packages: ${o.join(", ")}. Please install them manually.`)}}import{execSync as Cn}from"child_process";import jn from"ora";function En(e,n){let t={cursor:"Cursor",antigravity:"Antigravity",vscode:"VS Code",webstorm:"WebStorm"},o={cursor:["cursor","code"],antigravity:["agy","antigravity"],vscode:["code"],webstorm:["webstorm","web"]},r=jn(`\u{1F680} Opening project in ${t[n]}...`).start(),s=!1;try{for(let i of o[n]){if(s)break;try{Cn(`${i} .`,{cwd:e,stdio:"ignore"}),s=!0}catch{s=!1}}if(!s)throw new Error("Failed to open with command.");r.succeed(`Project opened in ${t[n]}!`)}catch{r.fail(`Failed to open ${t[n]}`);let i={cursor:`\u274C Cursor command not found!
3
3
 
4
4
  \u{1F527} To fix this, you need to install the Cursor command line tools:
5
5
 
@@ -62,10 +62,10 @@ import{readFileSync as Br}from"fs";import{dirname as Kr,join as qr}from"path";im
62
62
  export PATH="/Applications/WebStorm.app/Contents/MacOS:$PATH"
63
63
  - Or create an alias: alias webstorm="open -na 'WebStorm.app'"
64
64
 
65
- \u{1F4D6} More help: https://www.jetbrains.com/help/webstorm/working-with-the-ide-features-from-command-line.html`};throw new p(i[n])}}function jn(e){let n=process.platform,t;switch(n){case"darwin":t="open";break;case"win32":t="explorer";break;default:t="xdg-open";break}let r={darwin:"Finder",win32:"File Explorer",linux:"File Manager"}[n]||"File Manager",s=vn(`\u{1F4C1} Opening project in ${r}...`).start();try{Sn(`${t} "${e}"`,{stdio:"ignore"}),s.succeed(`Project opened in ${r}!`)}catch{throw s.fail(`Failed to open ${r}`),new p(`Failed to open project in ${r}. The file manager may not be available.`)}}var Xo=le.object({key:le.string(),debug:le.boolean().default(!1),ide:le.enum(["cursor","antigravity","vscode","webstorm"]).optional(),dir:le.string().optional(),name:le.string().optional()});function Yo(e){let n=M(e);x()&&E(n),console.error(`
66
- ${n.message}`),process.exit(1)}function kn(e){e.command("clone").description("\u2728 Instantly bring your MagicPath project to your local playground. Edit, remix, and create in your own vibe.").requiredOption("-k, --key <accessKey>","\u{1F511} One-time magic access key to unlock and download your project").option("-d, --debug","Get verbose debug logs in the CLI").option("-i, --ide <ide>","Pre-select IDE to open project in (cursor, antigravity, vscode, webstorm)").option("--dir <directory>","Target directory for non-interactive use").option("--name <projectName>","Project name for non-interactive use").action(async n=>{try{let t;try{t=Xo.parse(n)}catch{throw new p("Invalid CLI options for clone command.")}t.debug&&ce();let o=x();o&&(!t.dir||!t.name)&&E(new Error("In JSON mode, --dir and --name are required for clone.")),R.debug({options:n}),R.debug({options:t});let r,s;if(t.dir&&t.name)r=me.resolve(t.dir),s=t.name,await wt.ensureDir(r);else{let g=qo.homedir(),$=[{name:"Documents",path:me.join(g,"Documents")},{name:"Desktop",path:me.join(g,"Desktop")},{name:"Downloads",path:me.join(g,"Downloads")}],S=(await Promise.all($.map(async I=>{try{return await wt.pathExists(I.path)?I:null}catch{return null}}))).filter(I=>I!==null),h=[{title:`Right here (current folder: ${process.cwd()})`,value:process.cwd()},{title:`Home directory (${g})`,value:g}];S.forEach(I=>{h.push({title:I.name,value:I.path})}),h.push({title:"Other (specify custom path)",value:"custom"});let{targetDir:u}=await De({type:"select",name:"targetDir",message:"Where should we put your code?",choices:h,initial:0});if(r=u,u==="custom"){let{customPath:I}=await De({type:"text",name:"customPath",message:"Enter the full path where you want to create your project:",initial:g,validate:P=>{if(!P)return"Please enter a path";try{return me.resolve(P),!0}catch{return"Please enter a valid path"}}});if(!I)throw new p("Project creation cancelled");r=me.resolve(I);try{await wt.ensureDir(r)}catch{throw new p(`Failed to create or access directory: ${r}`)}}if(!r)throw new p("Download cancelled");if(s=(await De({type:"text",name:"projectName",message:"What would you like to name your project?",initial:"magicpath-project"})).projectName,!s)throw new p("Project creation cancelled")}let i,c=o?null:En("\u{1F4E5} Downloading project...").start();try{i=await hn(t.key),R.debug({filename:i}),c==null||c.succeed("Project downloaded")}catch(g){throw c==null||c.fail("Download failed"),g instanceof p?g:new p("Something went wrong!")}let a=o?null:En("\u{1F4E6} Unpacking project...").start(),l;try{l=wn(i,s,r),a==null||a.succeed(`Project unpacked to ${s}`)}catch(g){throw a==null||a.fail("Failed to unpack project"),ft(i),g instanceof p?g:new p("Something went wrong!")}try{$n(l)}catch(g){throw g instanceof p?g:new p("Something went wrong!")}o&&b({projectDir:l});let m=[{title:"Cursor",value:"cursor"},{title:"Antigravity",value:"antigravity"},{title:"VS Code",value:"vscode"},{title:"WebStorm",value:"webstorm"},{title:"Open in file manager",value:"filemanager"},{title:"None (just finish)",value:"none"}],d=0;if(t.ide){let g=m.findIndex($=>$.value===t.ide);g!==-1&&(d=g)}let f=await De({type:"select",name:"ide",message:"Which IDE would you like to open the project in?",choices:m,initial:d});if(f.ide&&f.ide!=="none")try{f.ide==="filemanager"?jn(l):Cn(l,f.ide)}catch(g){R.debug({err:g}),g instanceof p?console.log(g.message):console.log("\u26A0\uFE0F Opening failed, but your project is ready!")}console.log(`
67
- \u{1F389} Done! Your project is ready to go at: ${l}`)}catch(t){Yo(t)}})}import It from"prompts";import{z as D}from"zod";import X from"path";import gr from"fs-extra";var K=class extends p{constructor(){super("You must be logged in to install components.")}};import Zo from"ora";var Pn="\x1B[38;2;32;140;80m",Qo="\x1B[0m",er=`${Pn}\u2714${Qo}`;function k(e){let n=Zo(e),t=n.stopAndPersist.bind(n);return n.succeed=o=>t({symbol:er,text:o}),n}function An(){let e=process.stdout.write.bind(process.stdout),n=((t,...o)=>(typeof t=="string"&&(t=t.replace(/\x1b\[36m/g,Pn)),e(t,...o)));return process.stdout.write=n,()=>{process.stdout.write=e}}import Tn from"axios";import q from"fs-extra";import Y from"path";import{z as G}from"zod";var tr=G.object({name:G.string(),path:G.string(),content:G.string()}),nr=G.object({data:G.object({name:G.string(),generatedName:G.string(),files:G.array(tr),utils:G.object({content:G.string()}),dependencies:G.array(G.string())})});function ee(e){let n=e.match(/export\s+default\s+function\s+([A-Z][a-zA-Z0-9]*)/),t=e.match(/export\s+default\s+([A-Z][a-zA-Z0-9]*)\s*[;\n]/),o=e.match(/export\s+function\s+([A-Z][a-zA-Z0-9]*)/),r=e.match(/export\s+const\s+([A-Z][a-zA-Z0-9]*)\s*[=:]/),s=null,i=!1;if(n?(s=n[1],i=!0):t?(s=t[1],i=!0):o?s=o[1]:r&&(s=r[1]),!s)return null;let c=`${s}Props`,a=new RegExp(`(?:interface|type)\\s+${c}\\s*(?:=\\s*)?\\{([^}]*)\\}`,"s"),l=e.match(a),m=[],d=[];if(l){let g=l[1].split(/[;\n]/).filter($=>$.trim());for(let $ of g){let y=$.trim();if(!y||y.startsWith("//")||y.startsWith("/*"))continue;let S=y.match(/^(\w+)(\?)?:/);if(S){let h=S[1],u=!!S[2];if(h==="children")continue;u?d.push(h):m.push(h)}}}return{name:s,isDefault:i,propsType:l?c:void 0,requiredProps:m,optionalProps:d}}function de(e,n){return e.isDefault?`import ${e.name} from '${n}';`:`import { ${e.name} } from '${n}';`}function pe(e){let{name:n,requiredProps:t,optionalProps:o}=e;if(t.length===0&&o.length===0)return`<${n} />`;let r=t.map(s=>`${s}={/* TODO */}`).join(" ");return r?`<${n} ${r} />`:`<${n} />`}function or(e){let{componentName:n,importPath:t,exportInfo:o,fileName:r}=e,s=[`# ${n}`,"","## Import","","```tsx"];if(o){if(s.push(de(o,t)),s.push("```"),s.push(""),s.push("## Usage"),s.push(""),s.push("```tsx"),s.push(pe(o)),s.push("```"),o.requiredProps.length>0){s.push(""),s.push("## Required Props"),s.push("");for(let i of o.requiredProps)s.push(`- \`${i}\``)}if(o.optionalProps.length>0){s.push(""),s.push("## Optional Props"),s.push("");for(let i of o.optionalProps)s.push(`- \`${i}\``)}}else s.push(`import { ${r} } from '${t}';`),s.push("```");return s.push(""),s.join(`
68
- `)}function Nn(e,n){let t=or(n),o=Y.join(e,"usage.md");q.writeFileSync(o,t,"utf8"),R.debug({message:"Wrote usage file",usagePath:o})}async function xe(e){var o,r,s;let n=_t(e);R.debug({message:"Fetching component from registry",url:n});let t;try{t=j()}catch{throw new K}try{let i=await Tn.get(n,{headers:t});return nr.parse(i.data).data}catch(i){throw i instanceof p?i:Tn.isAxiosError(i)?((o=i.response)==null?void 0:o.status)===401?new K:((r=i.response)==null?void 0:r.status)===403?new p("A Pro subscription is required to install components. Visit https://www.magicpath.ai/documentation/help/plans to see the plans available.",{code:"FORBIDDEN",suggestion:"Upgrade to a Pro subscription at https://www.magicpath.ai/documentation/help/plans"}):((s=i.response)==null?void 0:s.status)===404?new p(`Component "${e}" not found. Please check the name and try again.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai search <query>` to find available components."}):M(i):new p("Failed to fetch component. Please check your internet connection and try again.")}}function Rn(e,n){let t=[];for(let o of e){let r=Y.join(n,o.path);q.existsSync(r)&&t.push(o.path)}return t}function rr(e,n=1){let t="../".repeat(n),o=e;return o=o.replace(/((?:import|export)(?:\s+type)?\s+(?:(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)(?:\s*,\s*(?:\{[^}]*\}|\*\s+as\s+\w+|\w+))*\s+from\s+)?['"])(\.\.\/)([^'"]+['"])/g,(r,s,i,c)=>`${s}${t}${i}${c}`),o=o.replace(/(import\s*\(\s*['"])(\.\.\/)([^'"]+['"]\s*\))/g,(r,s,i,c)=>`${s}${t}${i}${c}`),o=o.replace(/(require\s*\(\s*['"])(\.\.\/)([^'"]+['"]\s*\))/g,(r,s,i,c)=>`${s}${t}${i}${c}`),o}function On(e,n,t=!1){q.ensureDirSync(n);for(let o of e){let r=Y.join(n,o.path),s=Y.dirname(r);q.ensureDirSync(s);let i=t?rr(o.content):o.content;q.writeFileSync(r,i,"utf8"),R.debug({message:"Wrote file",filePath:r})}}function Un(e){let n=Y.join(e,"utils.ts");if(!q.existsSync(n))return!1;try{return q.readFileSync(n,"utf8").includes("export function cn")}catch{return!1}}function Fn(e,n){q.ensureDirSync(n);let t=Y.join(n,"utils.ts");q.writeFileSync(t,e,"utf8"),R.debug({message:"Wrote utils file",utilsPath:t})}var Se="src/components/magicpath",sr="src/lib";function _e(e){return e.trim().replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"component"}function Le(e,n=process.cwd()){let t=e||Se;return Y.join(n,t)}function Mn(e=process.cwd()){return Y.join(e,sr)}import ir from"http";import ar from"ora";import We from"axios";import{exec as cr}from"child_process";var lr=12e4,_n=`
65
+ \u{1F4D6} More help: https://www.jetbrains.com/help/webstorm/working-with-the-ide-features-from-command-line.html`};throw new p(i[n])}}function kn(e){let n=process.platform,t;switch(n){case"darwin":t="open";break;case"win32":t="explorer";break;default:t="xdg-open";break}let r={darwin:"Finder",win32:"File Explorer",linux:"File Manager"}[n]||"File Manager",s=jn(`\u{1F4C1} Opening project in ${r}...`).start();try{Cn(`${t} "${e}"`,{stdio:"ignore"}),s.succeed(`Project opened in ${r}!`)}catch{throw s.fail(`Failed to open ${r}`),new p(`Failed to open project in ${r}. The file manager may not be available.`)}}var Zo=le.object({key:le.string(),debug:le.boolean().default(!1),ide:le.enum(["cursor","antigravity","vscode","webstorm"]).optional(),dir:le.string().optional(),name:le.string().optional()});function Qo(e){let n=M(e);x()&&E(n),console.error(`
66
+ ${n.message}`),process.exit(1)}function An(e){e.command("clone").description("\u2728 Instantly bring your MagicPath project to your local playground. Edit, remix, and create in your own vibe.").requiredOption("-k, --key <accessKey>","\u{1F511} One-time magic access key to unlock and download your project").option("-d, --debug","Get verbose debug logs in the CLI").option("-i, --ide <ide>","Pre-select IDE to open project in (cursor, antigravity, vscode, webstorm)").option("--dir <directory>","Target directory for non-interactive use").option("--name <projectName>","Project name for non-interactive use").action(async n=>{try{let t;try{t=Zo.parse(n)}catch{throw new p("Invalid CLI options for clone command.")}t.debug&&ce();let o=x();o&&(!t.dir||!t.name)&&E(new Error("In JSON mode, --dir and --name are required for clone.")),R.debug({options:n}),R.debug({options:t});let r,s;if(t.dir&&t.name)r=me.resolve(t.dir),s=t.name,await yt.ensureDir(r);else{let g=Yo.homedir(),$=[{name:"Documents",path:me.join(g,"Documents")},{name:"Desktop",path:me.join(g,"Desktop")},{name:"Downloads",path:me.join(g,"Downloads")}],v=(await Promise.all($.map(async I=>{try{return await yt.pathExists(I.path)?I:null}catch{return null}}))).filter(I=>I!==null),h=[{title:`Right here (current folder: ${process.cwd()})`,value:process.cwd()},{title:`Home directory (${g})`,value:g}];v.forEach(I=>{h.push({title:I.name,value:I.path})}),h.push({title:"Other (specify custom path)",value:"custom"});let{targetDir:u}=await Le({type:"select",name:"targetDir",message:"Where should we put your code?",choices:h,initial:0});if(r=u,u==="custom"){let{customPath:I}=await Le({type:"text",name:"customPath",message:"Enter the full path where you want to create your project:",initial:g,validate:P=>{if(!P)return"Please enter a path";try{return me.resolve(P),!0}catch{return"Please enter a valid path"}}});if(!I)throw new p("Project creation cancelled");r=me.resolve(I);try{await yt.ensureDir(r)}catch{throw new p(`Failed to create or access directory: ${r}`)}}if(!r)throw new p("Download cancelled");if(s=(await Le({type:"text",name:"projectName",message:"What would you like to name your project?",initial:"magicpath-project"})).projectName,!s)throw new p("Project creation cancelled")}let i,c=o?null:Pn("\u{1F4E5} Downloading project...").start();try{i=await yn(t.key),R.debug({filename:i}),c==null||c.succeed("Project downloaded")}catch(g){throw c==null||c.fail("Download failed"),g instanceof p?g:new p("Something went wrong!")}let a=o?null:Pn("\u{1F4E6} Unpacking project...").start(),l;try{l=In(i,s,r),a==null||a.succeed(`Project unpacked to ${s}`)}catch(g){throw a==null||a.fail("Failed to unpack project"),ht(i),g instanceof p?g:new p("Something went wrong!")}try{vn(l)}catch(g){throw g instanceof p?g:new p("Something went wrong!")}o&&b({projectDir:l});let m=[{title:"Cursor",value:"cursor"},{title:"Antigravity",value:"antigravity"},{title:"VS Code",value:"vscode"},{title:"WebStorm",value:"webstorm"},{title:"Open in file manager",value:"filemanager"},{title:"None (just finish)",value:"none"}],d=0;if(t.ide){let g=m.findIndex($=>$.value===t.ide);g!==-1&&(d=g)}let f=await Le({type:"select",name:"ide",message:"Which IDE would you like to open the project in?",choices:m,initial:d});if(f.ide&&f.ide!=="none")try{f.ide==="filemanager"?kn(l):En(l,f.ide)}catch(g){R.debug({err:g}),g instanceof p?console.log(g.message):console.log("\u26A0\uFE0F Opening failed, but your project is ready!")}console.log(`
67
+ \u{1F389} Done! Your project is ready to go at: ${l}`)}catch(t){Qo(t)}})}import bt from"prompts";import{z as D}from"zod";import X from"path";import fr from"fs-extra";var K=class extends p{constructor(){super("You must be logged in to install components.")}};import er from"ora";var Tn="\x1B[38;2;32;140;80m",tr="\x1B[0m",nr=`${Tn}\u2714${tr}`;function k(e){let n=er(e),t=n.stopAndPersist.bind(n);return n.succeed=o=>t({symbol:nr,text:o}),n}function Nn(){let e=process.stdout.write.bind(process.stdout),n=((t,...o)=>(typeof t=="string"&&(t=t.replace(/\x1b\[36m/g,Tn)),e(t,...o)));return process.stdout.write=n,()=>{process.stdout.write=e}}import Rn from"axios";import q from"fs-extra";import Y from"path";import{z as G}from"zod";var or=G.object({name:G.string(),path:G.string(),content:G.string()}),rr=G.object({data:G.object({name:G.string(),generatedName:G.string(),files:G.array(or),utils:G.object({content:G.string()}),dependencies:G.array(G.string())})});function te(e){let n=e.match(/export\s+default\s+function\s+([A-Z][a-zA-Z0-9]*)/),t=e.match(/export\s+default\s+([A-Z][a-zA-Z0-9]*)\s*[;\n]/),o=e.match(/export\s+function\s+([A-Z][a-zA-Z0-9]*)/),r=e.match(/export\s+const\s+([A-Z][a-zA-Z0-9]*)\s*[=:]/),s=null,i=!1;if(n?(s=n[1],i=!0):t?(s=t[1],i=!0):o?s=o[1]:r&&(s=r[1]),!s)return null;let c=`${s}Props`,a=new RegExp(`(?:interface|type)\\s+${c}\\s*(?:=\\s*)?\\{([^}]*)\\}`,"s"),l=e.match(a),m=[],d=[];if(l){let g=l[1].split(/[;\n]/).filter($=>$.trim());for(let $ of g){let y=$.trim();if(!y||y.startsWith("//")||y.startsWith("/*"))continue;let v=y.match(/^(\w+)(\?)?:/);if(v){let h=v[1],u=!!v[2];if(h==="children")continue;u?d.push(h):m.push(h)}}}return{name:s,isDefault:i,propsType:l?c:void 0,requiredProps:m,optionalProps:d}}function de(e,n){return e.isDefault?`import ${e.name} from '${n}';`:`import { ${e.name} } from '${n}';`}function pe(e){let{name:n,requiredProps:t,optionalProps:o}=e;if(t.length===0&&o.length===0)return`<${n} />`;let r=t.map(s=>`${s}={/* TODO */}`).join(" ");return r?`<${n} ${r} />`:`<${n} />`}function sr(e){let{componentName:n,importPath:t,exportInfo:o,fileName:r}=e,s=[`# ${n}`,"","## Import","","```tsx"];if(o){if(s.push(de(o,t)),s.push("```"),s.push(""),s.push("## Usage"),s.push(""),s.push("```tsx"),s.push(pe(o)),s.push("```"),o.requiredProps.length>0){s.push(""),s.push("## Required Props"),s.push("");for(let i of o.requiredProps)s.push(`- \`${i}\``)}if(o.optionalProps.length>0){s.push(""),s.push("## Optional Props"),s.push("");for(let i of o.optionalProps)s.push(`- \`${i}\``)}}else s.push(`import { ${r} } from '${t}';`),s.push("```");return s.push(""),s.join(`
68
+ `)}function On(e,n){let t=sr(n),o=Y.join(e,"usage.md");q.writeFileSync(o,t,"utf8"),R.debug({message:"Wrote usage file",usagePath:o})}async function xe(e){var o,r,s;let n=Lt(e);R.debug({message:"Fetching component from registry",url:n});let t;try{t=j()}catch{throw new K}try{let i=await Rn.get(n,{headers:t});return rr.parse(i.data).data}catch(i){throw i instanceof p?i:Rn.isAxiosError(i)?((o=i.response)==null?void 0:o.status)===401?new K:((r=i.response)==null?void 0:r.status)===403?new p("A Pro subscription is required to install components. Visit https://www.magicpath.ai/documentation/help/plans to see the plans available.",{code:"FORBIDDEN",suggestion:"Upgrade to a Pro subscription at https://www.magicpath.ai/documentation/help/plans"}):((s=i.response)==null?void 0:s.status)===404?new p(`Component "${e}" not found. Please check the name and try again.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai search <query>` to find available components."}):M(i):new p("Failed to fetch component. Please check your internet connection and try again.")}}function Un(e,n){let t=[];for(let o of e){let r=Y.join(n,o.path);q.existsSync(r)&&t.push(o.path)}return t}function ir(e,n=1){let t="../".repeat(n),o=e;return o=o.replace(/((?:import|export)(?:\s+type)?\s+(?:(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)(?:\s*,\s*(?:\{[^}]*\}|\*\s+as\s+\w+|\w+))*\s+from\s+)?['"])(\.\.\/)([^'"]+['"])/g,(r,s,i,c)=>`${s}${t}${i}${c}`),o=o.replace(/(import\s*\(\s*['"])(\.\.\/)([^'"]+['"]\s*\))/g,(r,s,i,c)=>`${s}${t}${i}${c}`),o=o.replace(/(require\s*\(\s*['"])(\.\.\/)([^'"]+['"]\s*\))/g,(r,s,i,c)=>`${s}${t}${i}${c}`),o}function Fn(e,n,t=!1){q.ensureDirSync(n);for(let o of e){let r=Y.join(n,o.path),s=Y.dirname(r);q.ensureDirSync(s);let i=t?ir(o.content):o.content;q.writeFileSync(r,i,"utf8"),R.debug({message:"Wrote file",filePath:r})}}function Mn(e){let n=Y.join(e,"utils.ts");if(!q.existsSync(n))return!1;try{return q.readFileSync(n,"utf8").includes("export function cn")}catch{return!1}}function Dn(e,n){q.ensureDirSync(n);let t=Y.join(n,"utils.ts");q.writeFileSync(t,e,"utf8"),R.debug({message:"Wrote utils file",utilsPath:t})}var ve="src/components/magicpath",ar="src/lib";function We(e){return e.trim().replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"component"}function He(e,n=process.cwd()){let t=e||ve;return Y.join(n,t)}function _n(e=process.cwd()){return Y.join(e,ar)}import cr from"http";import lr from"ora";import Ge from"axios";import{exec as mr}from"child_process";var dr=12e4,Wn=`
69
69
  *{margin:0;padding:0;box-sizing:border-box}
70
70
  body{font-family:Geist,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;background:#fff;color:#1a1a1a;padding:1rem}
71
71
  .card{position:relative;width:100%;max-width:32rem;background:#fff;border-radius:1.5rem;box-shadow:0 1px 3px rgba(0,0,0,.1),0 8px 10px -1px rgba(0,0,0,.1);overflow:hidden}
@@ -75,80 +75,80 @@ body{font-family:Geist,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;di
75
75
  .icon-box svg{width:2rem;height:2rem}
76
76
  h1{font-size:1.5rem;font-weight:600;margin-bottom:.5rem;text-align:center}
77
77
  p{color:#999;font-size:.9rem;text-align:center;max-width:24rem;line-height:1.5}
78
- `,mr='<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#085C34"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"/></svg>',dr='<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#dc2626"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m9-.75a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 3.75h.008v.008H12v-.008Z"/></svg>',pr=`<!DOCTYPE html>
78
+ `,pr='<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#085C34"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"/></svg>',gr='<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#dc2626"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m9-.75a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 3.75h.008v.008H12v-.008Z"/></svg>',ur=`<!DOCTYPE html>
79
79
  <html><head><meta charset="utf-8"><title>MagicPath CLI</title>
80
- <style>${_n}</style>
80
+ <style>${Wn}</style>
81
81
  </head><body><div class="card"><div class="gradient"></div><div class="content">
82
- <div class="icon-box">${mr}</div>
82
+ <div class="icon-box">${pr}</div>
83
83
  <h1>Logged in!</h1>
84
84
  <p>You can close this tab and return to your terminal.</p>
85
- </div></div></body></html>`,Dn=e=>`<!DOCTYPE html>
85
+ </div></div></body></html>`,Ln=e=>`<!DOCTYPE html>
86
86
  <html><head><meta charset="utf-8"><title>MagicPath CLI</title>
87
- <style>${_n}</style>
87
+ <style>${Wn}</style>
88
88
  </head><body><div class="card"><div class="gradient"></div><div class="content">
89
- <div class="icon-box">${dr}</div>
89
+ <div class="icon-box">${gr}</div>
90
90
  <h1>Login failed</h1>
91
91
  <p>${e}</p>
92
- </div></div></body></html>`;async function yt(){return new Promise((e,n)=>{let t=!1,o,r=ir.createServer(async(c,a)=>{var d;let l=new URL(c.url||"/","http://localhost");if(l.pathname!=="/callback"){a.writeHead(404,{"Content-Type":"text/plain"}),a.end("Not found");return}let m=l.searchParams.get("code");if(!m){a.writeHead(400,{"Content-Type":"text/html"}),a.end(Dn("No authorization code received."));return}try{let f=await We.post(Pe("extension/tokens"),{token:m}),{access_token:g,refresh_token:$}=f.data;dt(g,$);try{await pt()}catch{}a.writeHead(200,{"Content-Type":"text/html"}),a.end(pr),s(),i.succeed("Logged in successfully!"),t=!0,e(!0)}catch(f){console.error(f);let g=We.isAxiosError(f)&&((d=f.response)==null?void 0:d.status)===400?"Invalid or expired authorization code. Please try again.":"Failed to exchange code. Please try again.";a.writeHead(400,{"Content-Type":"text/html"}),a.end(Dn(g)),s(),i.fail("Login failed"),t=!0,n(new p(g))}});function s(){clearTimeout(o),r.close()}r.listen(0,"127.0.0.1",()=>{let c=r.address();if(!c||typeof c=="string"){t=!0,n(new p("Failed to start local auth server."));return}let a=c.port,l=Qe(`/auth/cli?port=${a}`);console.log(`
92
+ </div></div></body></html>`;async function It(){return new Promise((e,n)=>{let t=!1,o,r=cr.createServer(async(c,a)=>{var d;let l=new URL(c.url||"/","http://localhost");if(l.pathname!=="/callback"){a.writeHead(404,{"Content-Type":"text/plain"}),a.end("Not found");return}let m=l.searchParams.get("code");if(!m){a.writeHead(400,{"Content-Type":"text/html"}),a.end(Ln("No authorization code received."));return}try{let f=await Ge.post(Te("extension/tokens"),{token:m}),{access_token:g,refresh_token:$}=f.data;pt(g,$);try{await gt()}catch{}a.writeHead(200,{"Content-Type":"text/html"}),a.end(ur),s(),i.succeed("Logged in successfully!"),t=!0,e(!0)}catch(f){console.error(f);let g=Ge.isAxiosError(f)&&((d=f.response)==null?void 0:d.status)===400?"Invalid or expired authorization code. Please try again.":"Failed to exchange code. Please try again.";a.writeHead(400,{"Content-Type":"text/html"}),a.end(Ln(g)),s(),i.fail("Login failed"),t=!0,n(new p(g))}});function s(){clearTimeout(o),r.close()}r.listen(0,"127.0.0.1",()=>{let c=r.address();if(!c||typeof c=="string"){t=!0,n(new p("Failed to start local auth server."));return}let a=c.port,l=Pe(`/auth/cli?port=${a}`);console.log(`
93
93
  Opening your browser to log in...
94
94
  `),console.log(`If the browser doesn't open, visit: ${l}
95
- `);let m=process.platform;cr(`${m==="darwin"?"open":m==="win32"?"start":"xdg-open"} "${l}"`)});let i=ar("Waiting for browser login...").start();o=setTimeout(()=>{t||(s(),i.fail("Login timed out"),console.log("\nTip: You can also log in with `magicpath-ai login --code <code>`."),t=!0,e(!1))},lr)})}function Ln(e){e.command("login").description("Log in to your MagicPath account").option("--code <code>","Exchange an authorization code non-interactively").option("--guest-code <code>","Connect to a guest project using a one-time pairing code (no account needed)").action(async n=>{try{if(n.guestCode){let o;try{o=await We.post(Pe("guest/tokens"),{code:n.guestCode})}catch(a){throw M(a)}let{access_token:r,session_id:s,project_id:i,expires_at:c}=o.data;ln(r,{sessionId:String(s),projectId:String(i),expiresAt:String(c)}),x()&&b({authenticated:!0,guest:!0,projectId:String(i),expiresAt:String(c)}),console.log("Connected to your guest project!"),console.log(` Project ID: ${i}`),console.log(" Changes you make will appear live on the canvas.");return}if(n.code){let o=await We.post(Pe("extension/tokens"),{token:n.code}),{access_token:r,refresh_token:s}=o.data;dt(r,s);try{await pt()}catch{}x()&&b({authenticated:!0,method:"code"}),console.log("Logged in successfully!");return}x()&&(process.env.MAGICPATH_TOKEN&&b({authenticated:!0,method:"environment"}),se()&&b({authenticated:!0,method:"stored"}),E(new Error("Not authenticated. Set MAGICPATH_TOKEN environment variable or run login interactively."))),await yt()||console.log("Login cancelled.")}catch(t){throw x()&&E(t),t instanceof p&&(console.error(`
96
- ${t.message}`),process.exit(1)),t}}),e.command("logout").description("Log out of your MagicPath account").action(()=>{mn(),x()&&b({loggedOut:!0}),console.log("Logged out successfully.")})}var ur=D.object({yes:D.boolean().default(!1),overwrite:D.boolean().default(!1),path:D.string().optional(),debug:D.boolean().default(!1),dryRun:D.boolean().default(!1)}),Fi=D.object({component:D.string(),generatedName:D.string(),filesWritten:D.array(D.string()),dependenciesInstalled:D.array(D.string()),importStatement:D.string().optional(),usage:D.string().optional(),dryRun:D.boolean()});function Wn(e){e.command("add").description("Add a MagicPath component to your project").argument("<generatedNames...>","One or more generated names of components (e.g., wispy-river-5234 bold-moon-2031)").option("-y, --yes","Skip confirmation prompts",!1).option("--overwrite","Overwrite existing files",!1).option("-p, --path <path>",`Custom path for components (default: ${Se})`).option("-d, --debug","Enable debug logging",!1).option("--dry-run","Show what would happen without writing files",!1).action(async(n,t)=>{try{let o;try{o=ur.parse(t)}catch{throw new Error("Invalid CLI options for add command.")}o.debug&&ce();let r=x();r&&(o.yes=!0);let s=n.length>1;s&&(o.yes=!0),R.debug({generatedNames:n,options:o});let i=process.cwd(),c=X.join(i,"package.json");if(!gr.existsSync(c))throw new p("No package.json found. Please run this command from the root of your React project.",{code:"MISSING_PACKAGE_JSON",suggestion:"Run this command from the root of your project where package.json is located."});let a=[];s&&!r&&console.log(`
95
+ `);let m=process.platform;mr(`${m==="darwin"?"open":m==="win32"?"start":"xdg-open"} "${l}"`)});let i=lr("Waiting for browser login...").start();o=setTimeout(()=>{t||(s(),i.fail("Login timed out"),console.log("\nTip: You can also log in with `magicpath-ai login --code <code>`."),t=!0,e(!1))},dr)})}function Hn(e){e.command("login").description("Log in to your MagicPath account").option("--code <code>","Exchange an authorization code non-interactively").option("--guest-code <code>","Connect to a guest project using a one-time pairing code (no account needed)").action(async n=>{try{if(n.guestCode){let o;try{o=await Ge.post(Te("guest/tokens"),{code:n.guestCode})}catch(l){throw M(l)}let{access_token:r,session_id:s,project_id:i,expires_at:c}=o.data;mn(r,{sessionId:String(s),projectId:String(i),expiresAt:String(c)});let a=Ae(String(i),r);x()&&b({authenticated:!0,guest:!0,projectId:String(i),expiresAt:String(c),canvasUrl:a}),console.log("Connected to your guest project!"),console.log(` Project ID: ${i}`),console.log(` Canvas: ${a}`),console.log(" Changes you make will appear live on the canvas.");return}if(n.code){let o=await Ge.post(Te("extension/tokens"),{token:n.code}),{access_token:r,refresh_token:s}=o.data;pt(r,s);try{await gt()}catch{}x()&&b({authenticated:!0,method:"code"}),console.log("Logged in successfully!");return}x()&&(process.env.MAGICPATH_TOKEN&&b({authenticated:!0,method:"environment"}),se()&&b({authenticated:!0,method:"stored"}),E(new Error("Not authenticated. Set MAGICPATH_TOKEN environment variable or run login interactively."))),await It()||console.log("Login cancelled.")}catch(t){throw x()&&E(t),t instanceof p&&(console.error(`
96
+ ${t.message}`),process.exit(1)),t}}),e.command("logout").description("Log out of your MagicPath account").action(()=>{pn(),x()&&b({loggedOut:!0}),console.log("Logged out successfully.")})}var hr=D.object({yes:D.boolean().default(!1),overwrite:D.boolean().default(!1),path:D.string().optional(),debug:D.boolean().default(!1),dryRun:D.boolean().default(!1)}),Di=D.object({component:D.string(),generatedName:D.string(),filesWritten:D.array(D.string()),dependenciesInstalled:D.array(D.string()),importStatement:D.string().optional(),usage:D.string().optional(),dryRun:D.boolean()});function Gn(e){e.command("add").description("Add a MagicPath component to your project").argument("<generatedNames...>","One or more generated names of components (e.g., wispy-river-5234 bold-moon-2031)").option("-y, --yes","Skip confirmation prompts",!1).option("--overwrite","Overwrite existing files",!1).option("-p, --path <path>",`Custom path for components (default: ${ve})`).option("-d, --debug","Enable debug logging",!1).option("--dry-run","Show what would happen without writing files",!1).action(async(n,t)=>{try{let o;try{o=hr.parse(t)}catch{throw new Error("Invalid CLI options for add command.")}o.debug&&ce();let r=x();r&&(o.yes=!0);let s=n.length>1;s&&(o.yes=!0),R.debug({generatedNames:n,options:o});let i=process.cwd(),c=X.join(i,"package.json");if(!fr.existsSync(c))throw new p("No package.json found. Please run this command from the root of your React project.",{code:"MISSING_PACKAGE_JSON",suggestion:"Run this command from the root of your project where package.json is located."});let a=[];s&&!r&&console.log(`
97
97
  Adding ${n.length} components...
98
- `);for(let l of n)try{let m=r?null:k(`Fetching component "${l}"...`).start(),d;try{d=await xe(l),m==null||m.succeed(`Found component: ${d.name}`)}catch(v){if(v instanceof K){if(m==null||m.fail("Not logged in"),r||s)throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."});let{shouldLogin:C}=await It({type:"confirm",name:"shouldLogin",message:"You need to be logged in to install components. Log in now?",initial:!0});if(!C){console.log("Installation cancelled.");return}if(!await yt()){console.log("Installation cancelled.");return}let H=k(`Fetching component "${l}"...`).start();try{d=await xe(l),H.succeed(`Found component: ${d.name}`)}catch(Rt){throw H.fail("Failed to fetch component"),Rt instanceof p?Rt:new p("Something went wrong!")}}else{if(m==null||m.fail("Failed to fetch component"),s){let C=v instanceof p?v.message:"Something went wrong!";a.push({component:l,generatedName:l,filesWritten:[],dependenciesInstalled:[],dryRun:o.dryRun,error:C}),r||console.log(` \u26A0\uFE0F Skipping "${l}": ${C}`);continue}throw v instanceof p?v:new p("Something went wrong!")}}let f=Le(o.path,i),g=_e(d.name),$=X.join(f,g),y=Mn(i);R.debug({basePath:f,componentFolderName:g,componentsPath:$,utilsPath:y});let S=Rn(d.files,$);if(S.length>0&&!o.overwrite)if(r||(console.log(`
99
- The following files already exist:`),S.forEach(v=>console.log(` - ${v}`))),o.yes){if(s){r||console.log(` \u26A0\uFE0F Skipping "${d.name}": files already exist. Use --overwrite.`),a.push({component:d.name,generatedName:d.generatedName,filesWritten:[],dependenciesInstalled:[],dryRun:o.dryRun,error:"Files already exist. Use --overwrite to replace."});continue}if(r)throw new p(`Files already exist: ${S.join(", ")}. Use --overwrite to replace.`,{code:"FILES_EXIST",suggestion:"Pass `--overwrite` to replace existing files."});console.log("Use --overwrite to replace existing files.");return}else{let{shouldOverwrite:v}=await It({type:"confirm",name:"shouldOverwrite",message:"Do you want to overwrite these files?",initial:!1});if(!v){console.log("Installation cancelled.");return}}if(!o.yes&&S.length===0){console.log(`
100
- This will install:`),console.log(` Component: ${d.name}`),console.log(` Files: ${d.files.length} file(s) to ${X.relative(i,$)||"."}`),console.log(` Dependencies: ${d.dependencies.length} package(s)`);let{shouldProceed:v}=await It({type:"confirm",name:"shouldProceed",message:"Proceed with installation?",initial:!0});if(!v){console.log("Installation cancelled.");return}}let h=d.files.map(v=>X.relative(i,X.join($,v.path))),u=d.files[0],w,I;if(u){let v=u.name.replace(/\.tsx?$/,""),C=o.path?`@/${o.path}/${g}/${v}`:`@/components/magicpath/${g}/${v}`,N=ee(u.content);N?(w=de(N,C),I=pe(N)):w=`import { ${v} } from '${C}';`}if(o.dryRun){let v=r?d.files.map(C=>({path:C.path,name:C.name,content:C.content})):void 0;!s&&r&&b({component:d.name,generatedName:d.generatedName,filesWritten:h,files:v,dependenciesInstalled:d.dependencies,importStatement:w,usage:I,dryRun:!0}),a.push({component:d.name,generatedName:d.generatedName,filesWritten:h,dependenciesInstalled:d.dependencies,importStatement:w,usage:I,dryRun:!0}),r||(console.log(`
101
- [Dry run] Would install:`),console.log(` Component: ${d.name}`),console.log(` Files: ${h.join(", ")}`),console.log(` Dependencies: ${d.dependencies.join(", ")||"none"}`),w&&console.log(` Import: ${w}`));continue}let P=r?null:k("Writing component files...").start();try{On(d.files,$,!0),P==null||P.succeed(`Wrote ${d.files.length} file(s) to ${X.relative(i,$)||"."}`)}catch{if(P==null||P.fail("Failed to write component files"),s){a.push({component:d.name,generatedName:d.generatedName,filesWritten:[],dependenciesInstalled:[],dryRun:!1,error:"Failed to write component files."});continue}throw new p("Failed to write component files. Please check permissions and try again.")}if(!Un(y)&&d.utils.content){let v=r?null:k("Installing utilities...").start();try{Fn(d.utils.content,y),v==null||v.succeed(`Wrote utils.ts to ${X.relative(i,y)||"."}`)}catch(C){v==null||v.fail("Failed to write utils file"),R.debug({err:C}),r||console.log(" Warning: Could not write utils.ts. You may need to create it manually.")}}let W=[];if(d.dependencies.length>0)try{let{installed:v,skipped:C}=xn(d.dependencies,i);W.push(...v),C.length>0&&R.debug({message:"Skipped already installed packages",skipped:C})}catch(v){v instanceof p&&(r||console.log(`
102
- \u26A0\uFE0F ${v.message}`))}if(a.push({component:d.name,generatedName:d.generatedName,filesWritten:h,dependenciesInstalled:W,importStatement:w,usage:I,dryRun:!1}),!s&&r&&b({component:d.name,generatedName:d.generatedName,filesWritten:h,dependenciesInstalled:W,importStatement:w,usage:I,dryRun:!1}),r||(console.log(`
98
+ `);for(let l of n)try{let m=r?null:k(`Fetching component "${l}"...`).start(),d;try{d=await xe(l),m==null||m.succeed(`Found component: ${d.name}`)}catch(S){if(S instanceof K){if(m==null||m.fail("Not logged in"),r||s)throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."});let{shouldLogin:C}=await bt({type:"confirm",name:"shouldLogin",message:"You need to be logged in to install components. Log in now?",initial:!0});if(!C){console.log("Installation cancelled.");return}if(!await It()){console.log("Installation cancelled.");return}let H=k(`Fetching component "${l}"...`).start();try{d=await xe(l),H.succeed(`Found component: ${d.name}`)}catch(Ot){throw H.fail("Failed to fetch component"),Ot instanceof p?Ot:new p("Something went wrong!")}}else{if(m==null||m.fail("Failed to fetch component"),s){let C=S instanceof p?S.message:"Something went wrong!";a.push({component:l,generatedName:l,filesWritten:[],dependenciesInstalled:[],dryRun:o.dryRun,error:C}),r||console.log(` \u26A0\uFE0F Skipping "${l}": ${C}`);continue}throw S instanceof p?S:new p("Something went wrong!")}}let f=He(o.path,i),g=We(d.name),$=X.join(f,g),y=_n(i);R.debug({basePath:f,componentFolderName:g,componentsPath:$,utilsPath:y});let v=Un(d.files,$);if(v.length>0&&!o.overwrite)if(r||(console.log(`
99
+ The following files already exist:`),v.forEach(S=>console.log(` - ${S}`))),o.yes){if(s){r||console.log(` \u26A0\uFE0F Skipping "${d.name}": files already exist. Use --overwrite.`),a.push({component:d.name,generatedName:d.generatedName,filesWritten:[],dependenciesInstalled:[],dryRun:o.dryRun,error:"Files already exist. Use --overwrite to replace."});continue}if(r)throw new p(`Files already exist: ${v.join(", ")}. Use --overwrite to replace.`,{code:"FILES_EXIST",suggestion:"Pass `--overwrite` to replace existing files."});console.log("Use --overwrite to replace existing files.");return}else{let{shouldOverwrite:S}=await bt({type:"confirm",name:"shouldOverwrite",message:"Do you want to overwrite these files?",initial:!1});if(!S){console.log("Installation cancelled.");return}}if(!o.yes&&v.length===0){console.log(`
100
+ This will install:`),console.log(` Component: ${d.name}`),console.log(` Files: ${d.files.length} file(s) to ${X.relative(i,$)||"."}`),console.log(` Dependencies: ${d.dependencies.length} package(s)`);let{shouldProceed:S}=await bt({type:"confirm",name:"shouldProceed",message:"Proceed with installation?",initial:!0});if(!S){console.log("Installation cancelled.");return}}let h=d.files.map(S=>X.relative(i,X.join($,S.path))),u=d.files[0],w,I;if(u){let S=u.name.replace(/\.tsx?$/,""),C=o.path?`@/${o.path}/${g}/${S}`:`@/components/magicpath/${g}/${S}`,N=te(u.content);N?(w=de(N,C),I=pe(N)):w=`import { ${S} } from '${C}';`}if(o.dryRun){let S=r?d.files.map(C=>({path:C.path,name:C.name,content:C.content})):void 0;!s&&r&&b({component:d.name,generatedName:d.generatedName,filesWritten:h,files:S,dependenciesInstalled:d.dependencies,importStatement:w,usage:I,dryRun:!0}),a.push({component:d.name,generatedName:d.generatedName,filesWritten:h,dependenciesInstalled:d.dependencies,importStatement:w,usage:I,dryRun:!0}),r||(console.log(`
101
+ [Dry run] Would install:`),console.log(` Component: ${d.name}`),console.log(` Files: ${h.join(", ")}`),console.log(` Dependencies: ${d.dependencies.join(", ")||"none"}`),w&&console.log(` Import: ${w}`));continue}let P=r?null:k("Writing component files...").start();try{Fn(d.files,$,!0),P==null||P.succeed(`Wrote ${d.files.length} file(s) to ${X.relative(i,$)||"."}`)}catch{if(P==null||P.fail("Failed to write component files"),s){a.push({component:d.name,generatedName:d.generatedName,filesWritten:[],dependenciesInstalled:[],dryRun:!1,error:"Failed to write component files."});continue}throw new p("Failed to write component files. Please check permissions and try again.")}if(!Mn(y)&&d.utils.content){let S=r?null:k("Installing utilities...").start();try{Dn(d.utils.content,y),S==null||S.succeed(`Wrote utils.ts to ${X.relative(i,y)||"."}`)}catch(C){S==null||S.fail("Failed to write utils file"),R.debug({err:C}),r||console.log(" Warning: Could not write utils.ts. You may need to create it manually.")}}let W=[];if(d.dependencies.length>0)try{let{installed:S,skipped:C}=Sn(d.dependencies,i);W.push(...S),C.length>0&&R.debug({message:"Skipped already installed packages",skipped:C})}catch(S){S instanceof p&&(r||console.log(`
102
+ \u26A0\uFE0F ${S.message}`))}if(a.push({component:d.name,generatedName:d.generatedName,filesWritten:h,dependenciesInstalled:W,importStatement:w,usage:I,dryRun:!1}),!s&&r&&b({component:d.name,generatedName:d.generatedName,filesWritten:h,dependenciesInstalled:W,importStatement:w,usage:I,dryRun:!1}),r||(console.log(`
103
103
  \u2705 Successfully added "${d.name}" to your project!`),s||console.log(`
104
- Usage:`)),u){let v=u.name.replace(/\.tsx?$/,""),C=o.path?`@/${o.path}/${g}/${v}`:`@/components/magicpath/${g}/${v}`,N=ee(u.content);!s&&!r&&(N?(console.log(` ${de(N,C)}`),console.log(""),console.log(` ${pe(N)}`),N.requiredProps.length>0&&(console.log(""),console.log(` Required props: ${N.requiredProps.join(", ")}`))):console.log(` import { ${v} } from '${C}';`));try{Nn($,{componentName:d.name,importPath:C,exportInfo:N,fileName:v}),!s&&!r&&console.log(`
104
+ Usage:`)),u){let S=u.name.replace(/\.tsx?$/,""),C=o.path?`@/${o.path}/${g}/${S}`:`@/components/magicpath/${g}/${S}`,N=te(u.content);!s&&!r&&(N?(console.log(` ${de(N,C)}`),console.log(""),console.log(` ${pe(N)}`),N.requiredProps.length>0&&(console.log(""),console.log(` Required props: ${N.requiredProps.join(", ")}`))):console.log(` import { ${S} } from '${C}';`));try{On($,{componentName:d.name,importPath:C,exportInfo:N,fileName:S}),!s&&!r&&console.log(`
105
105
  \u{1F4C4} Usage documentation written to ${X.relative(i,X.join($,"usage.md"))}`)}catch(H){R.debug({err:H})}}}catch(m){if(s){let d=m instanceof Error?m.message:String(m);a.push({component:l,generatedName:l,filesWritten:[],dependenciesInstalled:[],dryRun:o.dryRun,error:d}),r||console.log(` \u26A0\uFE0F Failed "${l}": ${d}`);continue}throw m}if(s){r&&b({results:a,total:a.length,succeeded:a.filter(d=>!d.error).length,failed:a.filter(d=>d.error).length});let l=a.filter(d=>!d.error),m=a.filter(d=>d.error);console.log(`
106
106
  ${l.length} of ${a.length} component(s) added successfully.`),m.length>0&&console.log(` ${m.length} failed: ${m.map(d=>d.generatedName).join(", ")}`)}}catch(o){throw x()&&E(o),o instanceof p&&(console.error(`
107
- ${o.message}`),process.exit(1)),o}})}import Hn from"axios";function Gn(e){e.command("whoami").description("Show the currently authenticated user").action(async()=>{var t;let n=x();try{let o=Fe();if(o){n&&b({authenticated:!0,guest:!0,projectId:o.projectId,expiresAt:o.expiresAt}),console.log(`
108
- Guest session (no account)`),console.log(` Project ID: ${o.projectId}`),console.log(` Expires: ${o.expiresAt}`),console.log(`
109
- Sign up at https://magicpath.ai to keep this project.`);return}let r;try{r=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let s=n?null:k("Fetching user info...").start();try{let i=await Hn.get(Q(),{headers:r}),c=i.data.user??i.data;s==null||s.succeed("Authenticated");let a=Ie(c);n&&b(c),console.log(`
110
- Name: ${a.name||"N/A"}`),console.log(` Email: ${a.email||"N/A"}`),c.id&&console.log(` ID: ${c.id}`),console.log(` Plan: ${a.plan}`)}catch(i){throw s==null||s.fail("Failed to fetch user info"),Hn.isAxiosError(i)?((t=i.response)==null?void 0:t.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login` to re-authenticate.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):M(i):i}}catch(o){throw n&&E(o),o instanceof p&&(console.error(`
111
- ${o.message}`),process.exit(1)),o}})}import bt from"axios";import He from"axios";function Ge(e){var t;let n=((t=e.data.data)==null?void 0:t.projects)??e.data.projects??e.data;return Array.isArray(n)?n:[]}async function Z(e,n){if(n!=null&&n.personal){let c=await He.get(`${rt()}`,{headers:e});return Ge(c).map(a=>{var l;return{...a,ownerType:"personal",ownerName:((l=a.owner)==null?void 0:l.email)??""}})}if(n!=null&&n.orgId){let c=await He.get(`${at(n.orgId)}`,{headers:{...e,"X-Organization-ID":n.orgId}});return Ge(c).map(a=>({...a,ownerType:"team",ownerName:n.orgName??""}))}let t=await be(e),o=[He.get(`${rt()}`,{headers:e}).then(c=>Ge(c).map(a=>{var l;return{...a,ownerType:"personal",ownerName:((l=a.owner)==null?void 0:l.email)??""}})),...t.map(c=>He.get(`${at(c.id)}`,{headers:{...e,"X-Organization-ID":c.id}}).then(a=>Ge(a).map(l=>({...l,ownerType:"team",ownerName:c.name}))).catch(()=>[]))],s=(await Promise.all(o)).flat(),i=new Set;return s.filter(c=>{let a=String(c.id);return i.has(a)?!1:(i.add(a),!0)})}function Vn(e){e.command("list-projects").description("List all projects (personal and team)").option("--limit <n>","Maximum number of results").option("--offset <n>","Number of results to skip","0").option("--team <nameOrId>","Filter to a specific team").option("--personal","Show only personal projects").action(async n=>{var s,i,c;let t=x(),o=n.limit?parseInt(n.limit,10):void 0,r=parseInt(n.offset,10)||0;try{if(n.team&&n.personal)throw new p("Cannot use --team and --personal together.",{code:"INVALID_OPTIONS",suggestion:"Use --team to filter by team, or --personal for personal projects only."});let a;try{a=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let l=t?null:k("Fetching projects...").start();try{let m;if(n.personal)m={personal:!0};else if(n.team){let w=await _(n.team,a);m={orgId:w.id,orgName:w.name}}let d=await Z(a,m),f=d.length,g=d;if(r>0&&(g=g.slice(r)),o!==void 0&&(g=g.slice(0,o)),l==null||l.succeed(`Found ${f} project(s)`),t&&b({projects:g,pagination:{total:f,limit:o??f,offset:r,hasMore:r+g.length<f}}),g.length===0){console.log(`
112
- No projects found.`);return}console.log("");let $=Math.max(4,...g.map(w=>(w.name||"").length)),y=Math.max(9,...g.map(w=>w.ownerType==="personal"?8:(w.ownerName||"").length)),S=7,h=10,u=10;console.log(` ${"Name".padEnd($)} ${"Type".padEnd(S)} ${"Components".padEnd(h)} ${"Workspace".padEnd(y)} Updated`),console.log(` ${"\u2500".repeat($)} ${"\u2500".repeat(S)} ${"\u2500".repeat(h)} ${"\u2500".repeat(y)} ${"\u2500".repeat(u)}`);for(let w of g){let I=(w.name||"").padEnd($),P=(w.isLibrary?"library":"project").padEnd(S),F=String(w.componentCount??((s=w._count)==null?void 0:s.components)??"?").padEnd(h),W=(w.ownerType==="personal"?"Personal":w.ownerName||"").padEnd(y),v=w.updatedAt?new Date(w.updatedAt).toISOString().slice(0,10):"";console.log(` ${I} ${P} ${F} ${W} ${v}`)}o!==void 0&&r+g.length<f&&console.log(`
113
- Showing ${g.length} of ${f}. Use --offset ${r+g.length} to see more.`)}catch(m){throw l==null||l.fail("Failed to fetch projects"),m instanceof p?m:bt.isAxiosError(m)?((i=m.response)==null?void 0:i.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(c=m.response)==null?void 0:c.status}`):m}}catch(a){throw t&&E(a),a instanceof p&&(console.error(`
114
- ${a.message}`),process.exit(1)),a}}),e.command("list-components").description("List components in a project").argument("<projectId>","The project ID").option("--limit <n>","Maximum number of results","100").option("--after <id>","Cursor: fetch components after this ID (for pagination)").option("--sort-by <field>","Sort by field (name, createdAt)","name").option("--order <dir>","Sort direction (asc, desc)","asc").option("--created-by <userId>","Filter to components created or edited by this user ID").action(async(n,t)=>{var s,i,c,a,l;let o=x(),r=parseInt(t.limit,10)||100;try{let m;try{m=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let d=o?null:k("Fetching components...").start();try{let f=new URLSearchParams({limit:String(r),revisionStatus:"COMPLETED",sortBy:t.sortBy,order:t.order});t.after&&f.set("after",t.after),t.createdBy&&f.set("createdBy",t.createdBy);let g=`${Jt(n)}?${f}`,$=await bt.get(g,{headers:m}),y=((s=$.data.data)==null?void 0:s.components)??$.data.components??$.data,S=((i=$.data.data)==null?void 0:i.pagination)??$.data.pagination,h=Array.isArray(y)?y.length:0;if(d==null||d.succeed(`Found ${h} component(s)`),o&&b({components:y,pagination:S??{limit:r,hasNext:!1,lastId:null}}),!Array.isArray(y)||y.length===0){console.log(`
115
- No components found.`);return}console.log("");let u=Math.max(4,...y.map(I=>(I.name||"").length)),w=Math.max(14,...y.map(I=>(I.generatedName||"").length));console.log(` ${"Name".padEnd(u)} ${"Generated Name".padEnd(w)} ${"Rev".padEnd(4)} ${"Views".padEnd(6)} ${"Likes".padEnd(6)} ${"Remixes".padEnd(7)} ${"Updated".padEnd(10)} ID`),console.log(` ${"\u2500".repeat(u)} ${"\u2500".repeat(w)} ${"\u2500".repeat(4)} ${"\u2500".repeat(6)} ${"\u2500".repeat(6)} ${"\u2500".repeat(7)} ${"\u2500".repeat(10)} ${"\u2500".repeat(20)}`);for(let I of y){let P=(I.name||"").padEnd(u),F=(I.generatedName||"").padEnd(w),W=String(I.revisionCount??"?").padEnd(4),v=String(I.viewCount??0).padEnd(6),C=String(I.likeCount??0).padEnd(6),N=String(I.remixCount??0).padEnd(7),H=I.updatedAt?new Date(I.updatedAt).toISOString().slice(0,10):"";console.log(` ${P} ${F} ${W} ${v} ${C} ${N} ${H.padEnd(10)} ${I.id||""}`)}S!=null&&S.hasNext&&console.log(`
116
- More results available. Use --after ${S.lastId} to see the next page.`)}catch(f){throw d==null||d.fail("Failed to fetch components"),bt.isAxiosError(f)?((c=f.response)==null?void 0:c.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):((a=f.response)==null?void 0:a.status)===404?new p(`Project "${n}" not found.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai list-projects` to see available projects."}):new p(`API error: ${(l=f.response)==null?void 0:l.status}`):f}}catch(m){throw o&&E(m),m instanceof p&&(console.error(`
117
- ${m.message}`),process.exit(1)),m}})}import{execSync as fr}from"child_process";function zn(e){e.command("setup-skills").description("Set up MagicPath for AI agents").action(async()=>{console.log("Installing MagicPath skills..."),fr("npx skills add https://github.com/MagicPathAI/agent-skills --skill magicpath -y",{stdio:"inherit"})})}import{exec as hr}from"child_process";function Ve(e){return/^\d+$/.test(e)?{type:"project",url:Lt(e),projectId:e}:{type:"component",url:ke("v1",e),generatedName:e}}function Jn(e){e.command("view").alias("view-component").description("Open a component preview or a project in the browser").argument("<identifier>","A component generatedName (e.g., wispy-river-5234) or a project id").action(n=>{let t=Ve(n);x()&&b(t);let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";hr(`${o} ${t.url}`),console.log(`Opening ${t.url}`)})}function Bn(e){e.command("share").description("Get a shareable URL for a component or a project").argument("<identifier>","A component generatedName (e.g., wispy-river-5234) or a project id").action(n=>{let t=Ve(n);if(x()){b(t);return}console.log(t.url)})}import wr from"axios";function Kn(e){e.command("info").description("Show project and auth status (useful for agent context injection)").action(async()=>{let n=x();try{let t=null,o=!1,r=null;process.env.MAGICPATH_TOKEN?(t="environment",o=!0,r=j()):se()&&(t="stored",o=!0,r=j());let s=null,i=null;if(o&&r)try{let l=await wr.get(Q(),{headers:r}),m=l.data.user??l.data,d=Ie(m);s={id:m.id,name:d.name??"Unknown",email:d.email??""},i=(m.organizationUsers??[]).map(g=>({id:String(g.organization.id),name:g.organization.name,role:g.role}))}catch{}let c=null;if(o&&r)try{c=(await Z(r)).map(m=>{var d;return{id:m.id,name:m.name,componentCount:m.componentCount??((d=m._count)==null?void 0:d.components)??0,ownerType:m.ownerType,ownerName:m.ownerName}})}catch{}if(n&&b({auth:{authenticated:o,method:t,user:s},teams:i,projects:c,cli:{version:B,commands:["add","view","share","search","inspect","list-projects","list-components","list-teams","list-members","list-themes","get-theme","list-installed","selection","active-project","code","image","login","logout","whoami","info","clone","setup-skills"]}}),console.log(""),console.log(` MagicPath CLI v${B}`),console.log(""),o&&s?(console.log(` Authenticated: yes (${t})`),console.log(` User: ${s.name} <${s.email}>`)):o?(console.log(` Authenticated: yes (${t})`),console.log(" User: (could not fetch)")):(console.log(" Authenticated: no"),console.log(" Run `magicpath-ai login` to authenticate.")),i&&i.length>0){console.log(""),console.log(` Teams: ${i.length}`);for(let l of i)console.log(` - ${l.name} (${l.role.toLowerCase()})`)}if(console.log(""),c&&c.length>0){console.log(` Projects: ${c.length}`);for(let l of c){let m=l.ownerType==="personal"?"":` [${l.ownerName}]`;console.log(` - ${l.name} (${l.componentCount} components)${m}`)}}else o&&console.log(" Projects: none");console.log("")}catch(t){n&&E(t),console.error(`Error: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}})}import qn from"axios";function Xn(e){e.command("search").description("Search component names across all projects").argument("<query>","Search query (case-insensitive substring match)").option("--limit <n>","Maximum number of results","20").option("--team <nameOrId>","Search only within a specific team").option("--personal","Search only personal projects").action(async(n,t)=>{var s,i;let o=x(),r=parseInt(t.limit,10)||20;try{if(t.team&&t.personal)throw new p("Cannot use --team and --personal together.",{code:"INVALID_OPTIONS",suggestion:"Use --team to filter by team, or --personal for personal projects only."});let c;try{c=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let a=o?null:k("Searching components...").start();try{let l=new URLSearchParams({q:n,limit:String(Math.min(Math.max(r,1),50))});if(t.personal)l.set("personal","true");else if(t.team){let u=await _(t.team,c);l.set("organizationId",u.id)}let m=await qn.get(`${Xt()}?${l.toString()}`,{headers:c}),d=m.data.data??m.data,g=(Array.isArray(d==null?void 0:d.components)?d.components:[]).map(u=>{var w,I,P,F;return{name:u.name,generatedName:u.generatedName,id:String(u.id),projectName:((w=u.project)==null?void 0:w.name)??"",projectId:String(((I=u.project)==null?void 0:I.id)??""),previewImageUrl:u.previewImageUrl??null,ownerType:((P=u.project)==null?void 0:P.ownerType)==="team"?"team":"personal",ownerName:((F=u.project)==null?void 0:F.ownerName)??""}});if(a==null||a.succeed(`Found ${g.length} match(es) for "${n}"`),o&&b(g),g.length===0){console.log(`
118
- No components matching "${n}".`);return}console.log("");let $=Math.max(4,...g.map(u=>u.name.length)),y=Math.max(13,...g.map(u=>u.generatedName.length)),S=Math.max(7,...g.map(u=>u.projectName.length)),h=Math.max(9,...g.map(u=>u.ownerType==="personal"?8:u.ownerName.length));console.log(` ${"Name".padEnd($)} ${"Generated Name".padEnd(y)} ${"Project".padEnd(S)} ${"Workspace".padEnd(h)}`),console.log(` ${"\u2500".repeat($)} ${"\u2500".repeat(y)} ${"\u2500".repeat(S)} ${"\u2500".repeat(h)}`);for(let u of g){let w=u.ownerType==="personal"?"Personal":u.ownerName;console.log(` ${u.name.padEnd($)} ${u.generatedName.padEnd(y)} ${u.projectName.padEnd(S)} ${w.padEnd(h)}`)}}catch(l){throw a==null||a.fail("Search failed"),l instanceof p?l:qn.isAxiosError(l)?((s=l.response)==null?void 0:s.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`."):new p(`API error: ${(i=l.response)==null?void 0:i.status}`):l}}catch(c){throw o&&E(c),c instanceof p&&(console.error(`
119
- ${c.message}`),process.exit(1)),c}})}import{z as L}from"zod";var Ua=L.object({generatedName:L.string().describe("The generated name of the component (e.g., wispy-river-5234)")}),Fa=L.object({component:L.string().describe("Component display name"),generatedName:L.string().describe("Component generated name"),files:L.array(L.object({path:L.string(),name:L.string(),content:L.string()})).describe("Component source files"),dependencies:L.array(L.string()).describe("Required packages"),importStatement:L.string().optional().describe("Import statement for the component"),usage:L.string().optional().describe("JSX usage example")});function Yn(e){e.command("inspect").description("Inspect a MagicPath component's source code without installing").argument("<generatedName>","Generated name of the component (e.g., wispy-river-5234)").option("-d, --debug","Enable debug logging",!1).action(async(n,t)=>{try{t.debug&&ce();let o=x();R.debug({generatedName:n,options:t});let r=o?null:k(`Fetching component "${n}"...`).start(),s;try{s=await xe(n),r==null||r.succeed(`Found component: ${s.name}`)}catch(d){throw r==null||r.fail("Failed to fetch component"),d instanceof K?new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."}):d instanceof p?d:new p("Something went wrong!")}let i=_e(s.name),c=s.files[0],a,l;if(c){let d=c.name.replace(/\.tsx?$/,""),f=`@/components/magicpath/${i}/${d}`,g=ee(c.content);g?(a=de(g,f),l=pe(g)):a=`import { ${d} } from '${f}';`}let m=s.files.map(d=>({path:d.path,name:d.name,content:d.content}));if(o){b({component:s.name,generatedName:s.generatedName,files:m,dependencies:s.dependencies,importStatement:a,usage:l});return}console.log(`
107
+ ${o.message}`),process.exit(1)),o}})}import Vn from"axios";function zn(e){e.command("whoami").description("Show the currently authenticated user").action(async()=>{var t;let n=x();try{let o=De();if(o){let i=dn();n&&b({authenticated:!0,guest:!0,projectId:o.projectId,expiresAt:o.expiresAt,canvasUrl:i}),console.log(`
108
+ Guest session (no account)`),console.log(` Project ID: ${o.projectId}`),i&&console.log(` Canvas: ${i}`),console.log(` Expires: ${o.expiresAt}`),console.log(`
109
+ Sign up at https://magicpath.ai to keep this project.`);return}let r;try{r=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let s=n?null:k("Fetching user info...").start();try{let i=await Vn.get(Q(),{headers:r}),c=i.data.user??i.data;s==null||s.succeed("Authenticated");let a=Ie(c);n&&b(c),console.log(`
110
+ Name: ${a.name||"N/A"}`),console.log(` Email: ${a.email||"N/A"}`),c.id&&console.log(` ID: ${c.id}`),console.log(` Plan: ${a.plan}`)}catch(i){throw s==null||s.fail("Failed to fetch user info"),Vn.isAxiosError(i)?((t=i.response)==null?void 0:t.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login` to re-authenticate.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):M(i):i}}catch(o){throw n&&E(o),o instanceof p&&(console.error(`
111
+ ${o.message}`),process.exit(1)),o}})}import $t from"axios";import Ve from"axios";function ze(e){var t;let n=((t=e.data.data)==null?void 0:t.projects)??e.data.projects??e.data;return Array.isArray(n)?n:[]}async function Z(e,n){if(n!=null&&n.personal){let c=await Ve.get(`${st()}`,{headers:e});return ze(c).map(a=>{var l;return{...a,ownerType:"personal",ownerName:((l=a.owner)==null?void 0:l.email)??""}})}if(n!=null&&n.orgId){let c=await Ve.get(`${ct(n.orgId)}`,{headers:{...e,"X-Organization-ID":n.orgId}});return ze(c).map(a=>({...a,ownerType:"team",ownerName:n.orgName??""}))}let t=await be(e),o=[Ve.get(`${st()}`,{headers:e}).then(c=>ze(c).map(a=>{var l;return{...a,ownerType:"personal",ownerName:((l=a.owner)==null?void 0:l.email)??""}})),...t.map(c=>Ve.get(`${ct(c.id)}`,{headers:{...e,"X-Organization-ID":c.id}}).then(a=>ze(a).map(l=>({...l,ownerType:"team",ownerName:c.name}))).catch(()=>[]))],s=(await Promise.all(o)).flat(),i=new Set;return s.filter(c=>{let a=String(c.id);return i.has(a)?!1:(i.add(a),!0)})}function Jn(e){e.command("list-projects").description("List all projects (personal and team)").option("--limit <n>","Maximum number of results").option("--offset <n>","Number of results to skip","0").option("--team <nameOrId>","Filter to a specific team").option("--personal","Show only personal projects").action(async n=>{var s,i,c;let t=x(),o=n.limit?parseInt(n.limit,10):void 0,r=parseInt(n.offset,10)||0;try{if(n.team&&n.personal)throw new p("Cannot use --team and --personal together.",{code:"INVALID_OPTIONS",suggestion:"Use --team to filter by team, or --personal for personal projects only."});let a;try{a=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let l=t?null:k("Fetching projects...").start();try{let m;if(n.personal)m={personal:!0};else if(n.team){let w=await _(n.team,a);m={orgId:w.id,orgName:w.name}}let d=await Z(a,m),f=d.length,g=d;if(r>0&&(g=g.slice(r)),o!==void 0&&(g=g.slice(0,o)),l==null||l.succeed(`Found ${f} project(s)`),t&&b({projects:g,pagination:{total:f,limit:o??f,offset:r,hasMore:r+g.length<f}}),g.length===0){console.log(`
112
+ No projects found.`);return}console.log("");let $=Math.max(4,...g.map(w=>(w.name||"").length)),y=Math.max(9,...g.map(w=>w.ownerType==="personal"?8:(w.ownerName||"").length)),v=7,h=10,u=10;console.log(` ${"Name".padEnd($)} ${"Type".padEnd(v)} ${"Components".padEnd(h)} ${"Workspace".padEnd(y)} Updated`),console.log(` ${"\u2500".repeat($)} ${"\u2500".repeat(v)} ${"\u2500".repeat(h)} ${"\u2500".repeat(y)} ${"\u2500".repeat(u)}`);for(let w of g){let I=(w.name||"").padEnd($),P=(w.isLibrary?"library":"project").padEnd(v),F=String(w.componentCount??((s=w._count)==null?void 0:s.components)??"?").padEnd(h),W=(w.ownerType==="personal"?"Personal":w.ownerName||"").padEnd(y),S=w.updatedAt?new Date(w.updatedAt).toISOString().slice(0,10):"";console.log(` ${I} ${P} ${F} ${W} ${S}`)}o!==void 0&&r+g.length<f&&console.log(`
113
+ Showing ${g.length} of ${f}. Use --offset ${r+g.length} to see more.`)}catch(m){throw l==null||l.fail("Failed to fetch projects"),m instanceof p?m:$t.isAxiosError(m)?((i=m.response)==null?void 0:i.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(c=m.response)==null?void 0:c.status}`):m}}catch(a){throw t&&E(a),a instanceof p&&(console.error(`
114
+ ${a.message}`),process.exit(1)),a}}),e.command("list-components").description("List components in a project").argument("<projectId>","The project ID").option("--limit <n>","Maximum number of results","100").option("--after <id>","Cursor: fetch components after this ID (for pagination)").option("--sort-by <field>","Sort by field (name, createdAt)","name").option("--order <dir>","Sort direction (asc, desc)","asc").option("--created-by <userId>","Filter to components created or edited by this user ID").action(async(n,t)=>{var s,i,c,a,l;let o=x(),r=parseInt(t.limit,10)||100;try{let m;try{m=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let d=o?null:k("Fetching components...").start();try{let f=new URLSearchParams({limit:String(r),revisionStatus:"COMPLETED",sortBy:t.sortBy,order:t.order});t.after&&f.set("after",t.after),t.createdBy&&f.set("createdBy",t.createdBy);let g=`${Bt(n)}?${f}`,$=await $t.get(g,{headers:m}),y=((s=$.data.data)==null?void 0:s.components)??$.data.components??$.data,v=((i=$.data.data)==null?void 0:i.pagination)??$.data.pagination,h=Array.isArray(y)?y.length:0;if(d==null||d.succeed(`Found ${h} component(s)`),o&&b({components:y,pagination:v??{limit:r,hasNext:!1,lastId:null}}),!Array.isArray(y)||y.length===0){console.log(`
115
+ No components found.`);return}console.log("");let u=Math.max(4,...y.map(I=>(I.name||"").length)),w=Math.max(14,...y.map(I=>(I.generatedName||"").length));console.log(` ${"Name".padEnd(u)} ${"Generated Name".padEnd(w)} ${"Rev".padEnd(4)} ${"Views".padEnd(6)} ${"Likes".padEnd(6)} ${"Remixes".padEnd(7)} ${"Updated".padEnd(10)} ID`),console.log(` ${"\u2500".repeat(u)} ${"\u2500".repeat(w)} ${"\u2500".repeat(4)} ${"\u2500".repeat(6)} ${"\u2500".repeat(6)} ${"\u2500".repeat(7)} ${"\u2500".repeat(10)} ${"\u2500".repeat(20)}`);for(let I of y){let P=(I.name||"").padEnd(u),F=(I.generatedName||"").padEnd(w),W=String(I.revisionCount??"?").padEnd(4),S=String(I.viewCount??0).padEnd(6),C=String(I.likeCount??0).padEnd(6),N=String(I.remixCount??0).padEnd(7),H=I.updatedAt?new Date(I.updatedAt).toISOString().slice(0,10):"";console.log(` ${P} ${F} ${W} ${S} ${C} ${N} ${H.padEnd(10)} ${I.id||""}`)}v!=null&&v.hasNext&&console.log(`
116
+ More results available. Use --after ${v.lastId} to see the next page.`)}catch(f){throw d==null||d.fail("Failed to fetch components"),$t.isAxiosError(f)?((c=f.response)==null?void 0:c.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):((a=f.response)==null?void 0:a.status)===404?new p(`Project "${n}" not found.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai list-projects` to see available projects."}):new p(`API error: ${(l=f.response)==null?void 0:l.status}`):f}}catch(m){throw o&&E(m),m instanceof p&&(console.error(`
117
+ ${m.message}`),process.exit(1)),m}})}import{execSync as wr}from"child_process";function Bn(e){e.command("setup-skills").description("Set up MagicPath for AI agents").action(async()=>{console.log("Installing MagicPath skills..."),wr("npx skills add https://github.com/MagicPathAI/agent-skills --skill magicpath -y",{stdio:"inherit"})})}import{exec as yr}from"child_process";function Je(e){return/^\d+$/.test(e)?{type:"project",url:Wt(e),projectId:e}:{type:"component",url:ke("v1",e),generatedName:e}}function Kn(e){e.command("view").alias("view-component").description("Open a component preview or a project in the browser").argument("<identifier>","A component generatedName (e.g., wispy-river-5234) or a project id").action(n=>{let t=Je(n);x()&&b(t);let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";yr(`${o} ${t.url}`),console.log(`Opening ${t.url}`)})}function qn(e){e.command("share").description("Get a shareable URL for a component or a project").argument("<identifier>","A component generatedName (e.g., wispy-river-5234) or a project id").action(n=>{let t=Je(n);if(x()){b(t);return}console.log(t.url)})}import Ir from"axios";function Xn(e){e.command("info").description("Show project and auth status (useful for agent context injection)").action(async()=>{let n=x();try{let t=null,o=!1,r=null;process.env.MAGICPATH_TOKEN?(t="environment",o=!0,r=j()):se()&&(t="stored",o=!0,r=j());let s=null,i=null;if(o&&r)try{let l=await Ir.get(Q(),{headers:r}),m=l.data.user??l.data,d=Ie(m);s={id:m.id,name:d.name??"Unknown",email:d.email??""},i=(m.organizationUsers??[]).map(g=>({id:String(g.organization.id),name:g.organization.name,role:g.role}))}catch{}let c=null;if(o&&r)try{c=(await Z(r)).map(m=>{var d;return{id:m.id,name:m.name,componentCount:m.componentCount??((d=m._count)==null?void 0:d.components)??0,ownerType:m.ownerType,ownerName:m.ownerName}})}catch{}if(n&&b({auth:{authenticated:o,method:t,user:s},teams:i,projects:c,cli:{version:B,commands:["add","view","share","search","inspect","list-projects","list-components","list-teams","list-members","list-themes","get-theme","list-installed","selection","active-project","code","image","login","logout","whoami","info","clone","setup-skills"]}}),console.log(""),console.log(` MagicPath CLI v${B}`),console.log(""),o&&s?(console.log(` Authenticated: yes (${t})`),console.log(` User: ${s.name} <${s.email}>`)):o?(console.log(` Authenticated: yes (${t})`),console.log(" User: (could not fetch)")):(console.log(" Authenticated: no"),console.log(" Run `magicpath-ai login` to authenticate.")),i&&i.length>0){console.log(""),console.log(` Teams: ${i.length}`);for(let l of i)console.log(` - ${l.name} (${l.role.toLowerCase()})`)}if(console.log(""),c&&c.length>0){console.log(` Projects: ${c.length}`);for(let l of c){let m=l.ownerType==="personal"?"":` [${l.ownerName}]`;console.log(` - ${l.name} (${l.componentCount} components)${m}`)}}else o&&console.log(" Projects: none");console.log("")}catch(t){n&&E(t),console.error(`Error: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}})}import Yn from"axios";function Zn(e){e.command("search").description("Search component names across all projects").argument("<query>","Search query (case-insensitive substring match)").option("--limit <n>","Maximum number of results","20").option("--team <nameOrId>","Search only within a specific team").option("--personal","Search only personal projects").action(async(n,t)=>{var s,i;let o=x(),r=parseInt(t.limit,10)||20;try{if(t.team&&t.personal)throw new p("Cannot use --team and --personal together.",{code:"INVALID_OPTIONS",suggestion:"Use --team to filter by team, or --personal for personal projects only."});let c;try{c=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let a=o?null:k("Searching components...").start();try{let l=new URLSearchParams({q:n,limit:String(Math.min(Math.max(r,1),50))});if(t.personal)l.set("personal","true");else if(t.team){let u=await _(t.team,c);l.set("organizationId",u.id)}let m=await Yn.get(`${Yt()}?${l.toString()}`,{headers:c}),d=m.data.data??m.data,g=(Array.isArray(d==null?void 0:d.components)?d.components:[]).map(u=>{var w,I,P,F;return{name:u.name,generatedName:u.generatedName,id:String(u.id),projectName:((w=u.project)==null?void 0:w.name)??"",projectId:String(((I=u.project)==null?void 0:I.id)??""),previewImageUrl:u.previewImageUrl??null,ownerType:((P=u.project)==null?void 0:P.ownerType)==="team"?"team":"personal",ownerName:((F=u.project)==null?void 0:F.ownerName)??""}});if(a==null||a.succeed(`Found ${g.length} match(es) for "${n}"`),o&&b(g),g.length===0){console.log(`
118
+ No components matching "${n}".`);return}console.log("");let $=Math.max(4,...g.map(u=>u.name.length)),y=Math.max(13,...g.map(u=>u.generatedName.length)),v=Math.max(7,...g.map(u=>u.projectName.length)),h=Math.max(9,...g.map(u=>u.ownerType==="personal"?8:u.ownerName.length));console.log(` ${"Name".padEnd($)} ${"Generated Name".padEnd(y)} ${"Project".padEnd(v)} ${"Workspace".padEnd(h)}`),console.log(` ${"\u2500".repeat($)} ${"\u2500".repeat(y)} ${"\u2500".repeat(v)} ${"\u2500".repeat(h)}`);for(let u of g){let w=u.ownerType==="personal"?"Personal":u.ownerName;console.log(` ${u.name.padEnd($)} ${u.generatedName.padEnd(y)} ${u.projectName.padEnd(v)} ${w.padEnd(h)}`)}}catch(l){throw a==null||a.fail("Search failed"),l instanceof p?l:Yn.isAxiosError(l)?((s=l.response)==null?void 0:s.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`."):new p(`API error: ${(i=l.response)==null?void 0:i.status}`):l}}catch(c){throw o&&E(c),c instanceof p&&(console.error(`
119
+ ${c.message}`),process.exit(1)),c}})}import{z as L}from"zod";var Ma=L.object({generatedName:L.string().describe("The generated name of the component (e.g., wispy-river-5234)")}),Da=L.object({component:L.string().describe("Component display name"),generatedName:L.string().describe("Component generated name"),files:L.array(L.object({path:L.string(),name:L.string(),content:L.string()})).describe("Component source files"),dependencies:L.array(L.string()).describe("Required packages"),importStatement:L.string().optional().describe("Import statement for the component"),usage:L.string().optional().describe("JSX usage example")});function Qn(e){e.command("inspect").description("Inspect a MagicPath component's source code without installing").argument("<generatedName>","Generated name of the component (e.g., wispy-river-5234)").option("-d, --debug","Enable debug logging",!1).action(async(n,t)=>{try{t.debug&&ce();let o=x();R.debug({generatedName:n,options:t});let r=o?null:k(`Fetching component "${n}"...`).start(),s;try{s=await xe(n),r==null||r.succeed(`Found component: ${s.name}`)}catch(d){throw r==null||r.fail("Failed to fetch component"),d instanceof K?new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."}):d instanceof p?d:new p("Something went wrong!")}let i=We(s.name),c=s.files[0],a,l;if(c){let d=c.name.replace(/\.tsx?$/,""),f=`@/components/magicpath/${i}/${d}`,g=te(c.content);g?(a=de(g,f),l=pe(g)):a=`import { ${d} } from '${f}';`}let m=s.files.map(d=>({path:d.path,name:d.name,content:d.content}));if(o){b({component:s.name,generatedName:s.generatedName,files:m,dependencies:s.dependencies,importStatement:a,usage:l});return}console.log(`
120
120
  Component: ${s.name}`),console.log(` Files: ${s.files.map(d=>d.path).join(", ")}`),console.log(` Dependencies: ${s.dependencies.join(", ")||"none"}`),a&&console.log(` Import: ${a}`);for(let d of s.files)console.log(`
121
121
  ${"\u2500".repeat(60)}`),console.log(` ${d.path}`),console.log(`${"\u2500".repeat(60)}`),console.log(d.content)}catch(o){throw x()&&E(o),o instanceof p&&(console.error(`
122
- ${o.message}`),process.exit(1)),o}})}import te from"path";import ge from"fs-extra";function yr(e,n){if(!ge.existsSync(e))return[];let t=ge.readdirSync(e,{withFileTypes:!0}),o=[];for(let r of t){if(!r.isDirectory())continue;let s=te.join(e,r.name),i=ge.readdirSync(s).filter(m=>!ge.statSync(te.join(s,m)).isDirectory()),c=i.find(m=>(m.endsWith(".tsx")||m.endsWith(".ts"))&&m!=="usage.md"&&!m.includes(".test.")&&!m.includes(".spec.")),a=null,l=null;if(c)try{let m=ge.readFileSync(te.join(s,c),"utf8"),d=ee(m);if(d){a=d.name;let f=c.replace(/\.tsx?$/,""),g=`@/components/magicpath/${r.name}/${f}`;d.isDefault?l=`import ${d.name} from '${g}';`:l=`import { ${d.name} } from '${g}';`}}catch{}o.push({name:a||r.name,folder:r.name,path:te.relative(n,s),files:i.filter(m=>m!=="usage.md"),exportName:a,importStatement:l})}return o}function Zn(e){e.command("list-installed").description("List MagicPath components installed in the current project").option("-p, --path <path>",`Custom components path (default: ${Se})`).action(async n=>{let t=x();try{let o=process.cwd(),r=Le(n.path,o);if(!ge.existsSync(r)){t&&b({components:[],total:0}),console.log(`
123
- No MagicPath components found at ${te.relative(o,r)||r}`);return}let s=yr(r,o);if(t&&b({components:s,total:s.length,componentsPath:te.relative(o,r)}),s.length===0){console.log(`
122
+ ${o.message}`),process.exit(1)),o}})}import ne from"path";import ge from"fs-extra";function br(e,n){if(!ge.existsSync(e))return[];let t=ge.readdirSync(e,{withFileTypes:!0}),o=[];for(let r of t){if(!r.isDirectory())continue;let s=ne.join(e,r.name),i=ge.readdirSync(s).filter(m=>!ge.statSync(ne.join(s,m)).isDirectory()),c=i.find(m=>(m.endsWith(".tsx")||m.endsWith(".ts"))&&m!=="usage.md"&&!m.includes(".test.")&&!m.includes(".spec.")),a=null,l=null;if(c)try{let m=ge.readFileSync(ne.join(s,c),"utf8"),d=te(m);if(d){a=d.name;let f=c.replace(/\.tsx?$/,""),g=`@/components/magicpath/${r.name}/${f}`;d.isDefault?l=`import ${d.name} from '${g}';`:l=`import { ${d.name} } from '${g}';`}}catch{}o.push({name:a||r.name,folder:r.name,path:ne.relative(n,s),files:i.filter(m=>m!=="usage.md"),exportName:a,importStatement:l})}return o}function eo(e){e.command("list-installed").description("List MagicPath components installed in the current project").option("-p, --path <path>",`Custom components path (default: ${ve})`).action(async n=>{let t=x();try{let o=process.cwd(),r=He(n.path,o);if(!ge.existsSync(r)){t&&b({components:[],total:0}),console.log(`
123
+ No MagicPath components found at ${ne.relative(o,r)||r}`);return}let s=br(r,o);if(t&&b({components:s,total:s.length,componentsPath:ne.relative(o,r)}),s.length===0){console.log(`
124
124
  No MagicPath components installed.`);return}console.log(`
125
- ${s.length} component(s) installed in ${te.relative(o,r)}:
125
+ ${s.length} component(s) installed in ${ne.relative(o,r)}:
126
126
  `);let i=Math.max(9,...s.map(l=>l.name.length)),c=Math.max(6,...s.map(l=>l.folder.length)),a=5;console.log(` ${"Component".padEnd(i)} ${"Folder".padEnd(c)} ${"Files".padEnd(a)}`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(c)} ${"\u2500".repeat(a)}`);for(let l of s)console.log(` ${l.name.padEnd(i)} ${l.folder.padEnd(c)} ${String(l.files.length).padEnd(a)}`)}catch(o){throw t&&E(o),o instanceof p&&(console.error(`
127
- ${o.message}`),process.exit(1)),o}})}import Qn from"axios";function eo(e){e.command("list-themes").description("List all themes (design systems)").option("--team <nameOrId>","List themes for a specific team").action(async n=>{var o,r,s;let t=x();try{let i;try{i=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let c=t?null:k("Fetching themes...").start();try{let a=Te(),l=i;if(n.team){let h=await _(n.team,i);a=Ne(h.id),l={...i,"X-Organization-ID":h.id}}let m=await Qn.get(a,{headers:l}),d=((o=m.data.data)==null?void 0:o.design_systems)??m.data.design_systems??m.data,f=Array.isArray(d)?d:[];if(c==null||c.succeed(`Found ${f.length} theme(s)`),t&&b({themes:f.map(h=>({id:String(h.id),name:h.name,isPublic:h.isPublic,createdAt:h.createdAt,updatedAt:h.updatedAt}))}),f.length===0){console.log(`
128
- No themes found.`);return}console.log("");let g=Math.max(4,...f.map(h=>(h.name||"").length)),$=Math.max(2,...f.map(h=>String(h.id).length)),y=6,S=10;console.log(` ${"Name".padEnd(g)} ${"ID".padEnd($)} ${"Public".padEnd(y)} Updated`),console.log(` ${"\u2500".repeat(g)} ${"\u2500".repeat($)} ${"\u2500".repeat(y)} ${"\u2500".repeat(S)}`);for(let h of f){let u=(h.name||"").padEnd(g),w=String(h.id).padEnd($),I=(h.isPublic?"yes":"no").padEnd(y),P=h.updatedAt?new Date(h.updatedAt).toISOString().slice(0,10):"";console.log(` ${u} ${w} ${I} ${P}`)}}catch(a){throw c==null||c.fail("Failed to fetch themes"),Qn.isAxiosError(a)?((r=a.response)==null?void 0:r.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(s=a.response)==null?void 0:s.status}`):a}}catch(i){throw t&&E(i),i instanceof p&&(console.error(`
129
- ${i.message}`),process.exit(1)),i}})}import $t from"axios";function to(e){e.command("get-theme").description("Get a theme definition (CSS variables, fonts, styling prompt)").argument("<themeIdOrName>","Theme ID (numeric) or name (case-insensitive match)").option("--team <nameOrId>","Look up theme within a specific team").action(async(n,t)=>{var r,s,i,c,a,l,m;let o=x();try{let d;try{d=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let f=o?null:k("Fetching theme...").start();try{let g=n,$;if(!/^\d+$/.test(n)){let w=Te(),I=d;if(t.team){let N=await _(t.team,d);w=Ne(N.id),I={...d,"X-Organization-ID":N.id}}let P=await $t.get(w,{headers:I}),F=((r=P.data.data)==null?void 0:r.design_systems)??P.data.design_systems??P.data,W=Array.isArray(F)?F:[],v=n.toLowerCase(),C=W.find(N=>(N.name||"").toLowerCase()===v);if(!C)throw new p(`Theme "${n}" not found.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai list-themes` to see available themes."});g=String(C.id),$=C.name}let y=await $t.get(Bt(g),{headers:d}),S=((s=y.data.data)==null?void 0:s.design_system)??y.data.design_system,h=S.name??$??g,u=S.data;f==null||f.succeed(`Theme: ${h}`),o&&b({id:String(S.id??g),name:h,theme:u.theme,defaultTheme:u.defaultTheme,prompt:u.prompt,fonts:u.fonts,version:u.version}),console.log(""),console.log(` Name: ${h}`),console.log(` ID: ${S.id??g}`),console.log(` Default Theme: ${u.defaultTheme??"light"}`),u.prompt&&console.log(` Prompt: ${u.prompt}`);for(let w of["light","dark"]){let I=(i=u.theme)==null?void 0:i[w];if(I&&Object.keys(I).length>0){console.log(`
127
+ ${o.message}`),process.exit(1)),o}})}import to from"axios";function no(e){e.command("list-themes").description("List all themes (design systems)").option("--team <nameOrId>","List themes for a specific team").action(async n=>{var o,r,s;let t=x();try{let i;try{i=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let c=t?null:k("Fetching themes...").start();try{let a=Re(),l=i;if(n.team){let h=await _(n.team,i);a=Oe(h.id),l={...i,"X-Organization-ID":h.id}}let m=await to.get(a,{headers:l}),d=((o=m.data.data)==null?void 0:o.design_systems)??m.data.design_systems??m.data,f=Array.isArray(d)?d:[];if(c==null||c.succeed(`Found ${f.length} theme(s)`),t&&b({themes:f.map(h=>({id:String(h.id),name:h.name,isPublic:h.isPublic,createdAt:h.createdAt,updatedAt:h.updatedAt}))}),f.length===0){console.log(`
128
+ No themes found.`);return}console.log("");let g=Math.max(4,...f.map(h=>(h.name||"").length)),$=Math.max(2,...f.map(h=>String(h.id).length)),y=6,v=10;console.log(` ${"Name".padEnd(g)} ${"ID".padEnd($)} ${"Public".padEnd(y)} Updated`),console.log(` ${"\u2500".repeat(g)} ${"\u2500".repeat($)} ${"\u2500".repeat(y)} ${"\u2500".repeat(v)}`);for(let h of f){let u=(h.name||"").padEnd(g),w=String(h.id).padEnd($),I=(h.isPublic?"yes":"no").padEnd(y),P=h.updatedAt?new Date(h.updatedAt).toISOString().slice(0,10):"";console.log(` ${u} ${w} ${I} ${P}`)}}catch(a){throw c==null||c.fail("Failed to fetch themes"),to.isAxiosError(a)?((r=a.response)==null?void 0:r.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(s=a.response)==null?void 0:s.status}`):a}}catch(i){throw t&&E(i),i instanceof p&&(console.error(`
129
+ ${i.message}`),process.exit(1)),i}})}import xt from"axios";function oo(e){e.command("get-theme").description("Get a theme definition (CSS variables, fonts, styling prompt)").argument("<themeIdOrName>","Theme ID (numeric) or name (case-insensitive match)").option("--team <nameOrId>","Look up theme within a specific team").action(async(n,t)=>{var r,s,i,c,a,l,m;let o=x();try{let d;try{d=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let f=o?null:k("Fetching theme...").start();try{let g=n,$;if(!/^\d+$/.test(n)){let w=Re(),I=d;if(t.team){let N=await _(t.team,d);w=Oe(N.id),I={...d,"X-Organization-ID":N.id}}let P=await xt.get(w,{headers:I}),F=((r=P.data.data)==null?void 0:r.design_systems)??P.data.design_systems??P.data,W=Array.isArray(F)?F:[],S=n.toLowerCase(),C=W.find(N=>(N.name||"").toLowerCase()===S);if(!C)throw new p(`Theme "${n}" not found.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai list-themes` to see available themes."});g=String(C.id),$=C.name}let y=await xt.get(Kt(g),{headers:d}),v=((s=y.data.data)==null?void 0:s.design_system)??y.data.design_system,h=v.name??$??g,u=v.data;f==null||f.succeed(`Theme: ${h}`),o&&b({id:String(v.id??g),name:h,theme:u.theme,defaultTheme:u.defaultTheme,prompt:u.prompt,fonts:u.fonts,version:u.version}),console.log(""),console.log(` Name: ${h}`),console.log(` ID: ${v.id??g}`),console.log(` Default Theme: ${u.defaultTheme??"light"}`),u.prompt&&console.log(` Prompt: ${u.prompt}`);for(let w of["light","dark"]){let I=(i=u.theme)==null?void 0:i[w];if(I&&Object.keys(I).length>0){console.log(`
130
130
  ${w.charAt(0).toUpperCase()+w.slice(1)} Theme Variables:`);let P=Math.max(8,...Object.keys(I).map(F=>F.length));console.log(` ${"Variable".padEnd(P)} Value`),console.log(` ${"\u2500".repeat(P)} ${"\u2500".repeat(30)}`);for(let[F,W]of Object.entries(I))console.log(` ${F.padEnd(P)} ${W}`)}}if(u.fonts&&Object.keys(u.fonts).length>0){console.log(`
131
- Fonts:`);for(let[w,I]of Object.entries(u.fonts)){let P=I.weights?Object.keys(I.weights).join(", "):"default";console.log(` ${w} (${I.source}, weights: ${P})`)}}}catch(g){throw f==null||f.fail("Failed to fetch theme"),$t.isAxiosError(g)?((c=g.response)==null?void 0:c.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):((a=g.response)==null?void 0:a.status)===404||((l=g.response)==null?void 0:l.status)===403?new p(`Theme "${n}" not found or not accessible.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai list-themes` to see available themes."}):new p(`API error: ${(m=g.response)==null?void 0:m.status}`):(g instanceof p,g)}}catch(d){throw o&&E(d),d instanceof p&&(console.error(`
132
- ${d.message}`),process.exit(1)),d}})}import xt from"axios";import{createClient as Ir}from"@liveblocks/client";import br from"ws";function ze(e){let n=Kt();return Ir({polyfills:{fetch,WebSocket:br},authEndpoint:async t=>await(await fetch(n,{method:"POST",headers:{...e,"Content-Type":"application/json"},body:JSON.stringify({room:t})})).json()})}async function Je(e,n,t=1e4){let{room:o,leave:r}=e.enterRoom(n,{initialPresence:{}});return await new Promise((s,i)=>{let c=setTimeout(()=>{i(new Error(`Timed out connecting to room ${n}`))},t),a=o.subscribe("status",l=>{l==="connected"&&(clearTimeout(c),a(),s())});o.getStatus()==="connected"&&(clearTimeout(c),a(),s())}),await new Promise(s=>{if(o.getOthers().length>0){s();return}let c=setTimeout(()=>{a(),s()},3e3),a=o.subscribe("others",l=>{l.length>0&&(clearTimeout(c),a(),s())})}),{room:o,leave:r}}function Be(e){var o,r;let n=e.getOthers(),t=[];for(let s of n){let i=(o=s.presence)==null?void 0:o.presence;(r=i==null?void 0:i.selectedShapeIds)!=null&&r.length&&t.push(...i.selectedShapeIds)}return[...new Set(t)]}async function no(e,n){let{root:t}=await e.getStorage(),o=t.get("records");if(!o)return[];let r=[];for(let s of n){let i=o.get(s);if(!i)continue;let c=typeof i.toObject=="function"?i.toObject():i;if(c.type==="mp-component"&&c.props){let a=typeof c.props.toObject=="function"?c.props.toObject():c.props;a.serverId&&r.push({serverId:a.serverId,clientId:a.clientId??s.replace("shape:",""),name:a.name??"Unknown",selectedRevisionId:typeof a.selectedRevisionId=="string"&&a.selectedRevisionId.length>0?a.selectedRevisionId:null})}}return r}function ue(e){return e&&typeof e.toObject=="function"?e.toObject():e}function z(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function $r(e,n){let t=ue(n),o=ue(t==null?void 0:t.meta);return z(o==null?void 0:o.imageId)??(e.startsWith("asset:")?e.slice(6):void 0)}function xr(e){return e.startsWith("shape:")?e.slice(6):e}async function Ke(e,n){let{root:t}=await e.getStorage(),o=t.get("records");if(!o)return[];let r=[];for(let s of n){let i=o.get(s);if(!i)continue;let c=ue(i);if(c.type!=="image"&&c.type!=="mp-image")continue;let a=ue(c.props)??{},l=z(a.assetId),m=l?o.get(l):null,d=ue(m),f=ue(d==null?void 0:d.props)??{},g=(l?$r(l,m):void 0)??z(a.imageId)??z(a.serverId)??(s.startsWith("shape:")?s.slice(6):s);g&&r.push({imageId:g,shapeId:xr(s),...z(f.name)||z(a.name)||z(a.altText)?{name:z(f.name)??z(a.name)??z(a.altText)}:{},...typeof a.w=="number"?{width:a.w}:{},...typeof a.h=="number"?{height:a.h}:{}})}return r}function oo(e){e.command("selection").description("Get the currently selected component(s) from the web app canvas").action(async()=>{var t,o,r,s;let n=x();try{let i;try{i=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let c=n?null:k("Checking canvas selection...").start();try{let a=await xt.get(oe(),{headers:i}),l=((t=a.data.data)==null?void 0:t.socket_rooms)??a.data.socket_rooms,m=(l==null?void 0:l.projectRooms)??[];if(m.length===0){c==null||c.succeed("No active canvas session"),n&&b({projects:[],components:[],images:[]}),console.log(`
133
- No active canvas session found.`);return}let d=new Map;try{let u=await Z(i);d=new Map(u.map(w=>[String(w.id),{name:w.name??"",ownerType:w.ownerType,ownerName:w.ownerName}]))}catch{}let f=m.map(u=>{let w=d.get(String(u.id));return w?{id:String(u.id),name:w.name,ownerType:w.ownerType,ownerName:w.ownerName}:{id:String(u.id),name:null,ownerType:null,ownerName:null}}),g=m.map(u=>{var w;return{projectId:u.id,projectName:((w=d.get(String(u.id)))==null?void 0:w.name)??"",roomId:u.room}}),$=ze(i),y=[],S=[];for(let u of g){let w=null;try{let I=await Je($,u.roomId);w=I.leave;let P=I.room,F=Be(P);if(F.length===0)continue;let[W,v]=await Promise.all([no(P,F),Ke(P,F)]);S.push(...v.map(C=>({id:C.imageId,shapeId:C.shapeId,name:C.name??null,projectId:u.projectId,projectName:u.projectName,...C.width?{width:C.width}:{},...C.height?{height:C.height}:{}})));for(let C of W)try{let N=await xt.get(qt(C.serverId),{headers:i}),H=((o=N.data.data)==null?void 0:o.component)??N.data.component;y.push({id:C.serverId,name:(H==null?void 0:H.name)??C.name,generatedName:(H==null?void 0:H.generatedName)??null,clientId:C.clientId,projectId:u.projectId,projectName:u.projectName,selectedRevisionId:C.selectedRevisionId})}catch{y.push({id:C.serverId,name:C.name,generatedName:null,clientId:C.clientId,projectId:u.projectId,projectName:u.projectName,selectedRevisionId:C.selectedRevisionId})}}catch{}finally{w&&w()}}if(y.length===0){if(c==null||c.succeed(S.length>0?`Found ${S.length} selected image(s)`:"No components selected"),n&&b({projects:f,components:[],images:S}),S.length>0){console.log(`
134
- Selected image(s):`);for(let u of S)console.log(` ${u.name??"Image"} (${u.id})`)}else console.log(`
135
- No active selection.`);if(f.length>0){console.log(" Active project(s):");for(let u of f){let w=u.ownerType==="team"&&u.ownerName?` [${u.ownerName}]`:"",I=u.name??`(unresolved project ${u.id})`;console.log(` ${I}${w}`)}}return}c==null||c.succeed(`Found ${y.length} selected component(s)`),n&&b({projects:f,components:y,images:S});let h=new Map;for(let u of y){let w=u.projectId;h.has(w)||h.set(w,[]),h.get(w).push(u)}console.log("");for(let[,u]of h){console.log(` Selected in "${u[0].projectName}":`);for(let w of u){let I=w.generatedName?` (${w.generatedName})`:"";console.log(` ${w.name}${I}`)}}if(S.length>0){console.log(`
136
- Selected image(s):`);for(let u of S)console.log(` ${u.name??"Image"} (${u.id})`)}}catch(a){throw c==null||c.fail("Failed to check selection"),xt.isAxiosError(a)?((r=a.response)==null?void 0:r.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(s=a.response)==null?void 0:s.status}`):a}}catch(i){throw n&&E(i),i instanceof p&&(console.error(`
137
- ${i.message}`),process.exit(1)),i}})}import St from"axios";function ro(e){e.command("active-project").description("Get the project(s) the user currently has open in the MagicPath web app").action(async()=>{var t,o,r,s;let n=x();try{let i;try{i=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let c=Fe();if(c){let l=n?null:k("Resolving guest project...").start(),m=null;try{let f=await St.get(Ae(c.projectId),{headers:i}),g=((t=f.data.data)==null?void 0:t.project)??f.data.project??f.data;m=(g==null?void 0:g.name)??null}catch{}let d=[{id:c.projectId,name:m,ownerType:null,ownerName:null}];l==null||l.succeed("Guest project"),n&&b({projects:d,guest:!0}),console.log(`
138
- ${m??`(guest project ${c.projectId})`}`);return}let a=n?null:k("Checking active project...").start();try{let l=await St.get(oe(),{headers:i}),m=((o=l.data.data)==null?void 0:o.socket_rooms)??l.data.socket_rooms,d=(m==null?void 0:m.projectRooms)??[];if(d.length===0){a==null||a.succeed("No active canvas session"),n&&b({projects:[]}),console.log(`
139
- No active canvas session found.`);return}let f=await Z(i),g=new Map;for(let y of f)g.set(String(y.id),y);let $=[];for(let y of d){let S=String(y.id),h=g.get(S);h?$.push({id:S,name:h.name??null,ownerType:h.ownerType,ownerName:h.ownerName}):$.push({id:S,name:null,ownerType:null,ownerName:null})}a==null||a.succeed(`Found ${$.length} active project${$.length===1?"":"s"}`),n&&b({projects:$}),console.log("");for(let y of $){let S=y.ownerType==="team"&&y.ownerName?` [${y.ownerName}]`:"",h=y.name??`(unresolved project ${y.id})`;console.log(` ${h}${S}`)}}catch(l){throw a==null||a.fail("Failed to check active project"),St.isAxiosError(l)?((r=l.response)==null?void 0:r.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(s=l.response)==null?void 0:s.status}`):l}}catch(i){throw n&&E(i),i instanceof p&&(console.error(`
140
- ${i.message}`),process.exit(1)),i}})}function so(e){e.command("list-teams").description("List teams you belong to").action(async()=>{let n=x();try{let t;try{t=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let o=n?null:k("Fetching teams...").start();try{let r=await be(t);if(o==null||o.succeed(`Found ${r.length} team(s)`),n&&b({teams:r}),r.length===0){console.log(`
131
+ Fonts:`);for(let[w,I]of Object.entries(u.fonts)){let P=I.weights?Object.keys(I.weights).join(", "):"default";console.log(` ${w} (${I.source}, weights: ${P})`)}}}catch(g){throw f==null||f.fail("Failed to fetch theme"),xt.isAxiosError(g)?((c=g.response)==null?void 0:c.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):((a=g.response)==null?void 0:a.status)===404||((l=g.response)==null?void 0:l.status)===403?new p(`Theme "${n}" not found or not accessible.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai list-themes` to see available themes."}):new p(`API error: ${(m=g.response)==null?void 0:m.status}`):(g instanceof p,g)}}catch(d){throw o&&E(d),d instanceof p&&(console.error(`
132
+ ${d.message}`),process.exit(1)),d}})}import vt from"axios";import{createClient as $r}from"@liveblocks/client";import xr from"ws";function Be(e){let n=qt();return $r({polyfills:{fetch,WebSocket:xr},authEndpoint:async t=>await(await fetch(n,{method:"POST",headers:{...e,"Content-Type":"application/json"},body:JSON.stringify({room:t})})).json()})}async function Ke(e,n,t=1e4){let{room:o,leave:r}=e.enterRoom(n,{initialPresence:{}});return await new Promise((s,i)=>{let c=setTimeout(()=>{i(new Error(`Timed out connecting to room ${n}`))},t),a=o.subscribe("status",l=>{l==="connected"&&(clearTimeout(c),a(),s())});o.getStatus()==="connected"&&(clearTimeout(c),a(),s())}),await new Promise(s=>{if(o.getOthers().length>0){s();return}let c=setTimeout(()=>{a(),s()},3e3),a=o.subscribe("others",l=>{l.length>0&&(clearTimeout(c),a(),s())})}),{room:o,leave:r}}function qe(e){var o,r;let n=e.getOthers(),t=[];for(let s of n){let i=(o=s.presence)==null?void 0:o.presence;(r=i==null?void 0:i.selectedShapeIds)!=null&&r.length&&t.push(...i.selectedShapeIds)}return[...new Set(t)]}async function ro(e,n){let{root:t}=await e.getStorage(),o=t.get("records");if(!o)return[];let r=[];for(let s of n){let i=o.get(s);if(!i)continue;let c=typeof i.toObject=="function"?i.toObject():i;if(c.type==="mp-component"&&c.props){let a=typeof c.props.toObject=="function"?c.props.toObject():c.props;a.serverId&&r.push({serverId:a.serverId,clientId:a.clientId??s.replace("shape:",""),name:a.name??"Unknown",selectedRevisionId:typeof a.selectedRevisionId=="string"&&a.selectedRevisionId.length>0?a.selectedRevisionId:null})}}return r}function ue(e){return e&&typeof e.toObject=="function"?e.toObject():e}function z(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function vr(e,n){let t=ue(n),o=ue(t==null?void 0:t.meta);return z(o==null?void 0:o.imageId)??(e.startsWith("asset:")?e.slice(6):void 0)}function Sr(e){return e.startsWith("shape:")?e.slice(6):e}async function Xe(e,n){let{root:t}=await e.getStorage(),o=t.get("records");if(!o)return[];let r=[];for(let s of n){let i=o.get(s);if(!i)continue;let c=ue(i);if(c.type!=="image"&&c.type!=="mp-image")continue;let a=ue(c.props)??{},l=z(a.assetId),m=l?o.get(l):null,d=ue(m),f=ue(d==null?void 0:d.props)??{},g=(l?vr(l,m):void 0)??z(a.imageId)??z(a.serverId)??(s.startsWith("shape:")?s.slice(6):s);g&&r.push({imageId:g,shapeId:Sr(s),...z(f.name)||z(a.name)||z(a.altText)?{name:z(f.name)??z(a.name)??z(a.altText)}:{},...typeof a.w=="number"?{width:a.w}:{},...typeof a.h=="number"?{height:a.h}:{}})}return r}function so(e){e.command("selection").description("Get the currently selected component(s) from the web app canvas").action(async()=>{var t,o,r,s;let n=x();try{let i;try{i=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let c=n?null:k("Checking canvas selection...").start();try{let a=await vt.get(re(),{headers:i}),l=((t=a.data.data)==null?void 0:t.socket_rooms)??a.data.socket_rooms,m=(l==null?void 0:l.projectRooms)??[];if(m.length===0){c==null||c.succeed("No active canvas session"),n&&b({projects:[],components:[],images:[]}),console.log(`
133
+ No active canvas session found.`);return}let d=new Map;try{let u=await Z(i);d=new Map(u.map(w=>[String(w.id),{name:w.name??"",ownerType:w.ownerType,ownerName:w.ownerName}]))}catch{}let f=m.map(u=>{let w=d.get(String(u.id));return w?{id:String(u.id),name:w.name,ownerType:w.ownerType,ownerName:w.ownerName}:{id:String(u.id),name:null,ownerType:null,ownerName:null}}),g=m.map(u=>{var w;return{projectId:u.id,projectName:((w=d.get(String(u.id)))==null?void 0:w.name)??"",roomId:u.room}}),$=Be(i),y=[],v=[];for(let u of g){let w=null;try{let I=await Ke($,u.roomId);w=I.leave;let P=I.room,F=qe(P);if(F.length===0)continue;let[W,S]=await Promise.all([ro(P,F),Xe(P,F)]);v.push(...S.map(C=>({id:C.imageId,shapeId:C.shapeId,name:C.name??null,projectId:u.projectId,projectName:u.projectName,...C.width?{width:C.width}:{},...C.height?{height:C.height}:{}})));for(let C of W)try{let N=await vt.get(Xt(C.serverId),{headers:i}),H=((o=N.data.data)==null?void 0:o.component)??N.data.component;y.push({id:C.serverId,name:(H==null?void 0:H.name)??C.name,generatedName:(H==null?void 0:H.generatedName)??null,clientId:C.clientId,projectId:u.projectId,projectName:u.projectName,selectedRevisionId:C.selectedRevisionId})}catch{y.push({id:C.serverId,name:C.name,generatedName:null,clientId:C.clientId,projectId:u.projectId,projectName:u.projectName,selectedRevisionId:C.selectedRevisionId})}}catch{}finally{w&&w()}}if(y.length===0){if(c==null||c.succeed(v.length>0?`Found ${v.length} selected image(s)`:"No components selected"),n&&b({projects:f,components:[],images:v}),v.length>0){console.log(`
134
+ Selected image(s):`);for(let u of v)console.log(` ${u.name??"Image"} (${u.id})`)}else console.log(`
135
+ No active selection.`);if(f.length>0){console.log(" Active project(s):");for(let u of f){let w=u.ownerType==="team"&&u.ownerName?` [${u.ownerName}]`:"",I=u.name??`(unresolved project ${u.id})`;console.log(` ${I}${w}`)}}return}c==null||c.succeed(`Found ${y.length} selected component(s)`),n&&b({projects:f,components:y,images:v});let h=new Map;for(let u of y){let w=u.projectId;h.has(w)||h.set(w,[]),h.get(w).push(u)}console.log("");for(let[,u]of h){console.log(` Selected in "${u[0].projectName}":`);for(let w of u){let I=w.generatedName?` (${w.generatedName})`:"";console.log(` ${w.name}${I}`)}}if(v.length>0){console.log(`
136
+ Selected image(s):`);for(let u of v)console.log(` ${u.name??"Image"} (${u.id})`)}}catch(a){throw c==null||c.fail("Failed to check selection"),vt.isAxiosError(a)?((r=a.response)==null?void 0:r.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(s=a.response)==null?void 0:s.status}`):a}}catch(i){throw n&&E(i),i instanceof p&&(console.error(`
137
+ ${i.message}`),process.exit(1)),i}})}import St from"axios";function io(e){e.command("active-project").description("Get the project(s) the user currently has open in the MagicPath web app").action(async()=>{var t,o,r,s;let n=x();try{let i;try{i=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let c=De();if(c){let l=n?null:k("Resolving guest project...").start(),m=null;try{let f=await St.get(Ne(c.projectId),{headers:i}),g=((t=f.data.data)==null?void 0:t.project)??f.data.project??f.data;m=(g==null?void 0:g.name)??null}catch{}let d=[{id:c.projectId,name:m,ownerType:null,ownerName:null}];l==null||l.succeed("Guest project"),n&&b({projects:d,guest:!0}),console.log(`
138
+ ${m??`(guest project ${c.projectId})`}`);return}let a=n?null:k("Checking active project...").start();try{let l=await St.get(re(),{headers:i}),m=((o=l.data.data)==null?void 0:o.socket_rooms)??l.data.socket_rooms,d=(m==null?void 0:m.projectRooms)??[];if(d.length===0){a==null||a.succeed("No active canvas session"),n&&b({projects:[]}),console.log(`
139
+ No active canvas session found.`);return}let f=await Z(i),g=new Map;for(let y of f)g.set(String(y.id),y);let $=[];for(let y of d){let v=String(y.id),h=g.get(v);h?$.push({id:v,name:h.name??null,ownerType:h.ownerType,ownerName:h.ownerName}):$.push({id:v,name:null,ownerType:null,ownerName:null})}a==null||a.succeed(`Found ${$.length} active project${$.length===1?"":"s"}`),n&&b({projects:$}),console.log("");for(let y of $){let v=y.ownerType==="team"&&y.ownerName?` [${y.ownerName}]`:"",h=y.name??`(unresolved project ${y.id})`;console.log(` ${h}${v}`)}}catch(l){throw a==null||a.fail("Failed to check active project"),St.isAxiosError(l)?((r=l.response)==null?void 0:r.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(s=l.response)==null?void 0:s.status}`):l}}catch(i){throw n&&E(i),i instanceof p&&(console.error(`
140
+ ${i.message}`),process.exit(1)),i}})}function ao(e){e.command("list-teams").description("List teams you belong to").action(async()=>{let n=x();try{let t;try{t=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let o=n?null:k("Fetching teams...").start();try{let r=await be(t);if(o==null||o.succeed(`Found ${r.length} team(s)`),n&&b({teams:r}),r.length===0){console.log(`
141
141
  No teams found.`);return}console.log("");let s=Math.max(4,...r.map(a=>a.name.length)),i=Math.max(2,...r.map(a=>a.id.length)),c=Math.max(4,...r.map(a=>a.role.length));console.log(` ${"Name".padEnd(s)} ${"ID".padEnd(i)} Role`),console.log(` ${"\u2500".repeat(s)} ${"\u2500".repeat(i)} ${"\u2500".repeat(c)}`);for(let a of r)console.log(` ${a.name.padEnd(s)} ${a.id.padEnd(i)} ${a.role}`)}catch(r){throw o==null||o.fail("Failed to fetch teams"),r instanceof p,r}}catch(t){throw n&&E(t),t instanceof p&&(console.error(`
142
- ${t.message}`),process.exit(1)),t}})}import io from"axios";function ao(e){e.command("list-members").description("List members of a team").requiredOption("--team <nameOrId>","Team name or ID").action(async n=>{var o,r,s;let t=x();try{let i;try{i=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let c=t?null:k("Fetching members...").start();try{let a=await _(n.team,i),l=await io.get(Yt(a.id),{headers:{...i,"X-Organization-ID":a.id}}),f=((((o=l.data.data)==null?void 0:o.organization)??l.data.organization??l.data).users??[]).map(h=>{var u,w,I;return{id:String(((u=h.user)==null?void 0:u.id)??h.userId),displayName:((w=h.user)==null?void 0:w.displayName)??null,email:((I=h.user)==null?void 0:I.email)??null,role:h.role}});if(c==null||c.succeed(`${a.name}: ${f.length} member(s)`),t&&b({team:{id:a.id,name:a.name},members:f}),f.length===0){console.log(`
143
- No members found.`);return}console.log("");let g=Math.max(4,...f.map(h=>(h.displayName||"").length)),$=Math.max(5,...f.map(h=>(h.email||"").length)),y=Math.max(2,...f.map(h=>h.id.length)),S=Math.max(4,...f.map(h=>h.role.length));console.log(` ${"Name".padEnd(g)} ${"Email".padEnd($)} ${"ID".padEnd(y)} Role`),console.log(` ${"\u2500".repeat(g)} ${"\u2500".repeat($)} ${"\u2500".repeat(y)} ${"\u2500".repeat(S)}`);for(let h of f)console.log(` ${(h.displayName||"").padEnd(g)} ${(h.email||"").padEnd($)} ${h.id.padEnd(y)} ${h.role}`)}catch(a){throw c==null||c.fail("Failed to fetch members"),a instanceof p?a:io.isAxiosError(a)?((r=a.response)==null?void 0:r.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(s=a.response)==null?void 0:s.status}`):a}}catch(i){throw t&&E(i),i instanceof p&&(console.error(`
144
- ${i.message}`),process.exit(1)),i}})}import V from"axios";import fo from"crypto";import O from"fs-extra";import U from"path";var ho="magicpath-code.json",Sr=new Set(["src/App.tsx","src/index.css"]),co="This component uses Tailwind v4. Replace @tailwind base/components/utilities; with @import 'tailwindcss';. Preserve the existing src/index.css Tailwind setup and append custom CSS below it.",vr=/@tailwind\s+(base|components|utilities)\s*;/i,Cr=/@import\s+(?:url\(\s*)?['"]tailwindcss['"]\s*\)?\s*;/i;function fe(e){return fo.createHash("sha256").update(e).digest("hex")}function jr(e){return fo.createHash("sha256").update(e).digest("hex")}function Et(e){return Sr.has(e)||e.startsWith("src/components/generated/")&&!e.endsWith("/")||e.startsWith("assets/")&&!e.endsWith("/")}function kt(e){return e.startsWith("assets/")&&!e.endsWith("/")}function Er(e){let n=U.extname(e).toLowerCase();return{".avif":"image/avif",".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".svg":"image/svg+xml",".webp":"image/webp"}[n]}function qe(e){return U.join(e,ho)}function kr(e){let n=qe(e);if(!O.existsSync(n))throw new p(`No ${ho} found. Run \`magicpath-ai code context <componentId>\` or \`magicpath-ai code start --project <projectId>\` first.`);return O.readJsonSync(n)}function ve(e,n){O.ensureDirSync(e),O.writeJsonSync(qe(e),n,{spaces:2})}function vt(e,n){if(!Et(n.path))throw new p(`Refusing to write disallowed path from API: ${n.path}`);let t=U.join(e,n.path);O.ensureDirSync(U.dirname(t)),n.encoding==="base64"?O.writeFileSync(t,Buffer.from(n.content.replace(/\s/g,""),"base64")):O.writeFileSync(t,n.content,"utf8")}function je(e){let n=[],t=["src/App.tsx","src/index.css"],o=U.join(e,"src/components/generated");if(O.existsSync(o))for(let s of jt(o))t.push(U.relative(e,s).split(U.sep).join("/"));let r=U.join(e,"assets");if(O.existsSync(r))for(let s of jt(r))t.push(U.relative(e,s).split(U.sep).join("/"));for(let s of Array.from(new Set(t)).sort()){if(!Et(s))continue;let i=U.join(e,s);if(!(!O.existsSync(i)||!O.statSync(i).isFile()))if(kt(s)){let c=O.readFileSync(i);n.push({path:s,content:c.toString("base64"),encoding:"base64",mimeType:Er(s),sha256:jr(c)})}else{let c=O.readFileSync(i,"utf8");n.push({path:s,content:c,encoding:"utf8",sha256:fe(c)})}}return n}function lo(e){let n=U.join(e,"src/index.css");if(!O.existsSync(n))throw new p(co);let t=O.readFileSync(n,"utf8");if(vr.test(t)||!Cr.test(t))throw new p(co)}function jt(e){let n=[];for(let t of O.readdirSync(e,{withFileTypes:!0})){let o=U.join(e,t.name);t.isDirectory()?n.push(...jt(o)):t.isFile()&&n.push(o)}return n}function Pr(e,n){if(n.mode==="create")return je(e);let t=new Map(n.editableFiles.map(o=>[o.path,o.sha256]));return je(e).map(o=>({...o,baseSha256:t.get(o.path)})).filter(o=>o.sha256!==o.baseSha256)}function Ar(e,n){if(n.mode==="create")return[];let t=new Set(je(e).map(o=>o.path));return n.editableFiles.map(o=>o.path).filter(o=>!kt(o)).filter(o=>!t.has(o))}async function mo(e,n){let t=j();for(;;){let r=(await V.get(ot(e),{headers:t})).data.data;if(r.status==="completed"||r.status==="failed"||r.status==="cancelled")return r;await new Promise(s=>setTimeout(s,n))}}function Ce(e){let n=M(e);throw x()&&E(n),n}function po(e,n){if(e===void 0)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new p(`${n} must be a positive number.`);return t}function Ct(e){let n=po(e.width,"--width"),t=po(e.height,"--height");if(n===void 0!=(t===void 0))throw new p("Pass both --width and --height, or neither.");return n===void 0||t===void 0?void 0:{width:n,height:t}}function Tr(e){let n=new Map;for(let t of e)n.has(t.imageId)||n.set(t.imageId,t);return Array.from(n.values())}async function go(e){var t;let n;try{n=j()}catch{return[]}try{let o=await V.get(oe(),{headers:n}),r=((t=o.data.data)==null?void 0:t.socket_rooms)??o.data.socket_rooms,s=(r==null?void 0:r.projectRooms)??[],i=e?s.filter(l=>String(l.id)===String(e)):s;if(i.length===0)return[];let c=ze(n),a=[];for(let l of i){let m=null;try{let d=await Je(c,l.room);m=d.leave;let f=Be(d.room);if(f.length===0)continue;let g=await Ke(d.room,f);a.push(...g.filter($=>/^\d+$/.test($.imageId)).map($=>({imageId:$.imageId,...$.shapeId?{shapeId:$.shapeId}:{}})))}catch{}finally{m&&m()}}return Tr(a)}catch{return[]}}async function uo(e,n){if(!(n!=null&&n.length))return[];let t=[];for(let o of n){if(!Et(o.assetPath)||!kt(o.assetPath))throw new p(`Refusing to download selected image outside assets/: ${o.assetPath}`);let r=await V.get(o.accessUrl,{responseType:"arraybuffer"}),s=U.join(e,o.assetPath);O.ensureDirSync(U.dirname(s)),O.writeFileSync(s,Buffer.from(r.data)),t.push({...o,downloadedPath:s})}return t}function wo(e){let n=e.command("code").description("Create and edit canvas components from local code").addHelpText("after",`
142
+ ${t.message}`),process.exit(1)),t}})}import co from"axios";function lo(e){e.command("list-members").description("List members of a team").requiredOption("--team <nameOrId>","Team name or ID").action(async n=>{var o,r,s;let t=x();try{let i;try{i=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let c=t?null:k("Fetching members...").start();try{let a=await _(n.team,i),l=await co.get(Zt(a.id),{headers:{...i,"X-Organization-ID":a.id}}),f=((((o=l.data.data)==null?void 0:o.organization)??l.data.organization??l.data).users??[]).map(h=>{var u,w,I;return{id:String(((u=h.user)==null?void 0:u.id)??h.userId),displayName:((w=h.user)==null?void 0:w.displayName)??null,email:((I=h.user)==null?void 0:I.email)??null,role:h.role}});if(c==null||c.succeed(`${a.name}: ${f.length} member(s)`),t&&b({team:{id:a.id,name:a.name},members:f}),f.length===0){console.log(`
143
+ No members found.`);return}console.log("");let g=Math.max(4,...f.map(h=>(h.displayName||"").length)),$=Math.max(5,...f.map(h=>(h.email||"").length)),y=Math.max(2,...f.map(h=>h.id.length)),v=Math.max(4,...f.map(h=>h.role.length));console.log(` ${"Name".padEnd(g)} ${"Email".padEnd($)} ${"ID".padEnd(y)} Role`),console.log(` ${"\u2500".repeat(g)} ${"\u2500".repeat($)} ${"\u2500".repeat(y)} ${"\u2500".repeat(v)}`);for(let h of f)console.log(` ${(h.displayName||"").padEnd(g)} ${(h.email||"").padEnd($)} ${h.id.padEnd(y)} ${h.role}`)}catch(a){throw c==null||c.fail("Failed to fetch members"),a instanceof p?a:co.isAxiosError(a)?((r=a.response)==null?void 0:r.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(s=a.response)==null?void 0:s.status}`):a}}catch(i){throw t&&E(i),i instanceof p&&(console.error(`
144
+ ${i.message}`),process.exit(1)),i}})}import V from"axios";import wo from"crypto";import O from"fs-extra";import U from"path";var yo="magicpath-code.json",Cr=new Set(["src/App.tsx","src/index.css"]),mo="This component uses Tailwind v4. Replace @tailwind base/components/utilities; with @import 'tailwindcss';. Preserve the existing src/index.css Tailwind setup and append custom CSS below it.",jr=/@tailwind\s+(base|components|utilities)\s*;/i,Er=/@import\s+(?:url\(\s*)?['"]tailwindcss['"]\s*\)?\s*;/i;function fe(e){return wo.createHash("sha256").update(e).digest("hex")}function kr(e){return wo.createHash("sha256").update(e).digest("hex")}function kt(e){return Cr.has(e)||e.startsWith("src/components/generated/")&&!e.endsWith("/")||e.startsWith("assets/")&&!e.endsWith("/")}function Pt(e){return e.startsWith("assets/")&&!e.endsWith("/")}function Pr(e){let n=U.extname(e).toLowerCase();return{".avif":"image/avif",".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".png":"image/png",".svg":"image/svg+xml",".webp":"image/webp"}[n]}function Ye(e){return U.join(e,yo)}function Ar(e){let n=Ye(e);if(!O.existsSync(n))throw new p(`No ${yo} found. Run \`magicpath-ai code context <componentId>\` or \`magicpath-ai code start --project <projectId>\` first.`);return O.readJsonSync(n)}function Se(e,n){O.ensureDirSync(e),O.writeJsonSync(Ye(e),n,{spaces:2})}function Ct(e,n){if(!kt(n.path))throw new p(`Refusing to write disallowed path from API: ${n.path}`);let t=U.join(e,n.path);O.ensureDirSync(U.dirname(t)),n.encoding==="base64"?O.writeFileSync(t,Buffer.from(n.content.replace(/\s/g,""),"base64")):O.writeFileSync(t,n.content,"utf8")}function je(e){let n=[],t=["src/App.tsx","src/index.css"],o=U.join(e,"src/components/generated");if(O.existsSync(o))for(let s of Et(o))t.push(U.relative(e,s).split(U.sep).join("/"));let r=U.join(e,"assets");if(O.existsSync(r))for(let s of Et(r))t.push(U.relative(e,s).split(U.sep).join("/"));for(let s of Array.from(new Set(t)).sort()){if(!kt(s))continue;let i=U.join(e,s);if(!(!O.existsSync(i)||!O.statSync(i).isFile()))if(Pt(s)){let c=O.readFileSync(i);n.push({path:s,content:c.toString("base64"),encoding:"base64",mimeType:Pr(s),sha256:kr(c)})}else{let c=O.readFileSync(i,"utf8");n.push({path:s,content:c,encoding:"utf8",sha256:fe(c)})}}return n}function po(e){let n=U.join(e,"src/index.css");if(!O.existsSync(n))throw new p(mo);let t=O.readFileSync(n,"utf8");if(jr.test(t)||!Er.test(t))throw new p(mo)}function Et(e){let n=[];for(let t of O.readdirSync(e,{withFileTypes:!0})){let o=U.join(e,t.name);t.isDirectory()?n.push(...Et(o)):t.isFile()&&n.push(o)}return n}function Tr(e,n){if(n.mode==="create")return je(e);let t=new Map(n.editableFiles.map(o=>[o.path,o.sha256]));return je(e).map(o=>({...o,baseSha256:t.get(o.path)})).filter(o=>o.sha256!==o.baseSha256)}function Nr(e,n){if(n.mode==="create")return[];let t=new Set(je(e).map(o=>o.path));return n.editableFiles.map(o=>o.path).filter(o=>!Pt(o)).filter(o=>!t.has(o))}async function go(e,n){let t=j();for(;;){let r=(await V.get(rt(e),{headers:t})).data.data;if(r.status==="completed"||r.status==="failed"||r.status==="cancelled")return r;await new Promise(s=>setTimeout(s,n))}}function Ce(e){let n=M(e);throw x()&&E(n),n}function uo(e,n){if(e===void 0)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new p(`${n} must be a positive number.`);return t}function jt(e){let n=uo(e.width,"--width"),t=uo(e.height,"--height");if(n===void 0!=(t===void 0))throw new p("Pass both --width and --height, or neither.");return n===void 0||t===void 0?void 0:{width:n,height:t}}function Rr(e){let n=new Map;for(let t of e)n.has(t.imageId)||n.set(t.imageId,t);return Array.from(n.values())}async function fo(e){var t;let n;try{n=j()}catch{return[]}try{let o=await V.get(re(),{headers:n}),r=((t=o.data.data)==null?void 0:t.socket_rooms)??o.data.socket_rooms,s=(r==null?void 0:r.projectRooms)??[],i=e?s.filter(l=>String(l.id)===String(e)):s;if(i.length===0)return[];let c=Be(n),a=[];for(let l of i){let m=null;try{let d=await Ke(c,l.room);m=d.leave;let f=qe(d.room);if(f.length===0)continue;let g=await Xe(d.room,f);a.push(...g.filter($=>/^\d+$/.test($.imageId)).map($=>({imageId:$.imageId,...$.shapeId?{shapeId:$.shapeId}:{}})))}catch{}finally{m&&m()}}return Rr(a)}catch{return[]}}async function ho(e,n){if(!(n!=null&&n.length))return[];let t=[];for(let o of n){if(!kt(o.assetPath)||!Pt(o.assetPath))throw new p(`Refusing to download selected image outside assets/: ${o.assetPath}`);let r=await V.get(o.accessUrl,{responseType:"arraybuffer"}),s=U.join(e,o.assetPath);O.ensureDirSync(U.dirname(s)),O.writeFileSync(s,Buffer.from(r.data)),t.push({...o,downloadedPath:s})}return t}function Io(e){let n=e.command("code").description("Create and edit canvas components from local code").addHelpText("after",`
145
145
  Tailwind v4:
146
146
  src/index.css must keep @import 'tailwindcss';.
147
147
  Do not use @tailwind base/components/utilities; and do not replace the
148
148
  template @theme inline, :root, or .dark token blocks. Append custom CSS below
149
149
  the existing setup.
150
- `);n.command("start").description("Start a pending create or edit session before writing code").option("--project <projectId>","Target MagicPath project ID for create").option("--component <componentId>","Existing MagicPath component ID for edit").option("--revision <revisionId>","Start editing this revision. Defaults to the component's currently selected revision.").option("--dir <dir>","Working directory to initialize",".").option("--name <name>","Component name").option("--width <px>","Canvas component width for create").option("--height <px>","Canvas component height for create").action(async t=>{try{let o=U.resolve(t.dir),r=Ct(t);if(!!t.project==!!t.component)throw new p("Run code start with exactly one of --project for create or --component for edit.");if(t.component){if(r)throw new p("Use --width and --height with code submit when resizing an existing component.");let g=await go(),y=(await V.post(Wt(t.component),{...t.revision?{revisionId:t.revision}:{},...g.length>0?{selectedImages:g}:{}},{headers:j()})).data.data;O.ensureDirSync(o);for(let w of y.editableFiles)vt(o,w);let S=await uo(o,y.selectedImages),h={mode:"edit",componentId:y.component.id,projectId:y.component.projectId,selectedRevisionId:y.component.selectedRevisionId,baseRevisionId:y.component.baseRevisionId,jobId:y.jobId,generatedName:y.component.generatedName,name:y.component.name,selectedImages:S,editableFiles:y.editableFiles.map(w=>({path:w.path,sha256:fe(w.content)}))};ve(o,h);let u={dir:o,manifestPath:qe(o),...h,status:"pending",scaffoldedPaths:y.editableFiles.map(w=>w.path),selectedImages:S};x()&&b(u),console.log(`Started pending edit ${h.selectedRevisionId} for component ${h.componentId} in ${o}`);return}let s=t.project;if(!s)throw new p("Create sessions require --project.");let i=await go(s),a=(await V.post(et(),{projectId:s,...t.name?{name:t.name}:{},...r?{dimensions:r}:{},...i.length>0?{selectedImages:i}:{}},{headers:j()})).data.data,l=a.editableFiles??[];O.ensureDirSync(o);for(let g of l)vt(o,g);let m=await uo(o,a.selectedImages),d={mode:"create",componentId:a.componentId,projectId:s,selectedRevisionId:a.revisionId,jobId:a.jobId,generatedName:a.generatedName,name:t.name,dimensions:r,selectedImages:m,editableFiles:l.map(g=>({path:g.path,sha256:fe(g.content)}))};ve(o,d);let f={dir:o,manifestPath:qe(o),...d,status:"pending",scaffoldedPaths:l.map(g=>g.path),selectedImages:m};x()&&b(f),console.log(`Started pending component ${d.componentId} in ${o}`+(l.length>0?` (scaffolded ${l.length} file${l.length===1?"":"s"})`:""))}catch(o){Ce(o)}}),n.command("context").description("Fetch editable files for an existing MagicPath component").argument("<componentId>","MagicPath component ID").option("--dir <dir>","Working directory to write",".").option("--revision <revisionId>","Pull this revision of the component. Defaults to the component's currently selected revision.").action(async(t,o)=>{try{let r=U.resolve(o.dir);O.ensureDirSync(r);let s=o.revision?`${tt(t)}?revisionId=${encodeURIComponent(o.revision)}`:tt(t),c=(await V.get(s,{headers:j()})).data.data;for(let l of c.editableFiles)vt(r,l);let a={dir:r,readOnly:!0,component:c.component,editableFiles:c.editableFiles.map(l=>({path:l.path,sha256:fe(l.content)}))};x()&&b(a),console.log(`Fetched ${c.editableFiles.length} read-only editable file(s) into ${r}. Run \`magicpath-ai code start --component ${t} --dir ${r}\` before submitting edits.`)}catch(r){Ce(r)}}),n.command("submit").description("Submit changed editable files for the component in this working directory").option("--dir <dir>","Working directory containing magicpath-code.json",".").option("--wait","Wait for the build job to finish",!1).option("--interval <ms>","Polling interval when --wait is set","2000").option("--width <px>","Updated canvas component width").option("--height <px>","Updated canvas component height").action(async t=>{try{let o=U.resolve(t.dir),r=kr(o),s=Ct(t);lo(o);let i=Pr(o,r),c=Ar(o,r);if(r.mode==="create"&&!i.some(d=>d.path==="src/App.tsx"))throw new p("Create submit requires src/App.tsx in the working directory.");if(i.length===0&&c.length===0&&!s){let d={status:"unchanged",componentId:r.componentId,revisionId:r.selectedRevisionId};x()&&b(d),console.log("No editable file changes to submit.");return}let l=r.mode==="create"||!!r.baseRevisionId&&r.selectedRevisionId!==r.baseRevisionId?await V.post(nt(r.componentId,r.selectedRevisionId),{files:i.map(d=>({path:d.path,content:d.content,encoding:d.encoding,mimeType:d.mimeType})),contextJobId:r.jobId,...s?{dimensions:s}:{},...r.mode==="edit"?{deletedPaths:c}:{}},{headers:j()}):await V.post(Ht(r.componentId),{baseRevisionId:r.baseRevisionId??r.selectedRevisionId,files:i.map(d=>({path:d.path,content:d.content,encoding:d.encoding,mimeType:d.mimeType,baseSha256:d.baseSha256})),deletedPaths:c,...s?{dimensions:s}:{}},{headers:j()}),m=l.data.data;if(t.wait&&(m=await mo(l.data.data.jobId,Number(t.interval))),m.status==="completed"){let d=je(o),f={...r,mode:"edit",jobId:l.data.data.jobId,selectedRevisionId:m.revisionId,baseRevisionId:m.revisionId,...s?{dimensions:s}:{},editableFiles:d.map(g=>({path:g.path,sha256:g.sha256??fe(g.content)}))};ve(o,f)}x()&&b({...m,jobId:l.data.data.jobId,deletedPaths:c,...s?{dimensions:s}:{}}),console.log(`Submitted ${i.length} file(s)`+(c.length>0?` and ${c.length} deletion(s)`:"")+`. Job ${l.data.data.jobId}: ${m.status}`)}catch(o){Ce(o)}}),n.command("create").description("Create a new MagicPath component from local editable files").requiredOption("--project <projectId>","Target MagicPath project ID").option("--dir <dir>","Working directory containing src/App.tsx",".").option("--name <name>","Component name").option("--wait","Wait for the build job to finish",!1).option("--width <px>","Canvas component width").option("--height <px>","Canvas component height").action(async t=>{try{let o=U.resolve(t.dir),r=Ct(t);lo(o);let s=je(o);if(!s.some(m=>m.path==="src/App.tsx"))throw new p("Create requires src/App.tsx in the working directory.");let i=await V.post(et(),{projectId:t.project,...t.name?{name:t.name}:{},...r?{dimensions:r}:{}},{headers:j()}),c={mode:"create",componentId:i.data.data.componentId,projectId:t.project,selectedRevisionId:i.data.data.revisionId,jobId:i.data.data.jobId,generatedName:i.data.data.generatedName,name:t.name,dimensions:r,editableFiles:[]};ve(o,c);let a=await V.post(nt(c.componentId,c.selectedRevisionId),{files:s.map(m=>({path:m.path,content:m.content,encoding:m.encoding,mimeType:m.mimeType})),contextJobId:c.jobId,...r?{dimensions:r}:{}},{headers:j()}),l=a.data.data;t.wait&&(l=await mo(a.data.data.jobId,2e3)),l.status==="completed"&&ve(o,{...c,mode:"edit",jobId:a.data.data.jobId,selectedRevisionId:l.revisionId,...r?{dimensions:r}:{},editableFiles:s.map(m=>({path:m.path,sha256:m.sha256??fe(m.content)}))}),x()&&b({...l,jobId:a.data.data.jobId,...r?{dimensions:r}:{}}),console.log(`Created component ${a.data.data.componentId}. Job ${a.data.data.jobId}: ${l.status}`)}catch(o){Ce(o)}}),n.command("status").description("Fetch external-agent build job status").argument("<jobId>","External agent job ID").action(async t=>{try{let o=await V.get(ot(t),{headers:j()});x()&&b(o.data.data),console.log(`${t}: ${o.data.data.status}`)}catch(o){Ce(o)}})}import Ee from"axios";import yo from"fs";import Pt from"path";import{imageSize as Nr}from"image-size";var Io=512;async function Rr(e){if(/^https?:\/\//i.test(e)){let t=await Ee.get(e,{responseType:"arraybuffer"}),o=Pt.basename(new URL(e).pathname)||"image";return{buffer:Buffer.from(t.data),fileName:o}}let n=Pt.resolve(e);if(!yo.existsSync(n))throw new Error(`Image file not found: ${n}`);return{buffer:yo.readFileSync(n),fileName:Pt.basename(n)}}function Xe(e){if(e===void 0)return;let n=Number(e);if(!Number.isFinite(n))throw new Error(`Invalid number: ${e}`);return n}function bo(e){let n=e.command("image").description("Add and list images on a project canvas");n.command("add").description("Add an image to a project canvas from a local file path or a URL").argument("<projectId>","The id of the project to add the image to").argument("<pathOrUrl>","A local image file path or an http(s) URL").option("--name <name>","Display name for the image (defaults to the file name)").option("--x <x>","Canvas x position (default 0)").option("--y <y>","Canvas y position (default 0)").option("--width <width>","Width in canvas units (defaults to the intrinsic width)").option("--height <height>","Height in canvas units (defaults to the intrinsic height)").action(async(t,o,r)=>{var c,a;let s=x(),i=s?null:k("Adding image to project...").start();try{let l=j(),{buffer:m,fileName:d}=await Rr(o),f=Xe(r.width),g=Xe(r.height);if(f===void 0||g===void 0)try{let P=Nr(m);f=f??P.width,g=g??P.height}catch{}f=f??Io,g=g??Io;let $={x:Xe(r.x)??0,y:Xe(r.y)??0,z:0,width:f,height:g},y=r.name??(d.replace(/\.[^/.]+$/,"")||d),S=await Ee.get(Vt(),{headers:l,params:{filename:d,content_type:"image/*",make_public:"true"}}),{upload_url:h,upload_token:u}=S.data;await Ee.put(h,m,{headers:{"Content-Type":"image/*","x-goog-acl":"public-read"}});let I=(a=(c=(await Ee.post(it(t),{name:y,position:$,upload_token:u},{headers:l})).data)==null?void 0:c.data)==null?void 0:a.image;i==null||i.succeed("Image added to project"),s&&b({image:I}),console.log(`Added "${(I==null?void 0:I.name)??y}" (${(I==null?void 0:I.id)??"unknown id"})`),I!=null&&I.url&&console.log(I.url)}catch(l){i==null||i.fail("Failed to add image"),s&&E(l),console.error(l instanceof Error?l.message:String(l)),process.exit(1)}}),n.command("list").description("List the images on a project canvas").argument("<projectId>","The id of the project").action(async t=>{var s,i;let o=x(),r=o?null:k("Fetching images...").start();try{let c=j(),l=((i=(s=(await Ee.get(it(t),{headers:c})).data)==null?void 0:s.data)==null?void 0:i.images)??[];if(r==null||r.succeed(`Found ${l.length} image(s)`),o&&b({images:l}),l.length===0){console.log("No images in this project.");return}for(let m of l)console.log(`- ${m.name} (${m.id})${m.url?` \u2014 ${m.url}`:""}`)}catch(c){r==null||r.fail("Failed to list images"),o&&E(c),console.error(c instanceof Error?c.message:String(c)),process.exit(1)}})}import At from"axios";function $o(e){var n;return((n=e==null?void 0:e.data)==null?void 0:n.project)??(e==null?void 0:e.project)??e}function xo(e){e.command("create-project").description("Create a new project (personal or in a team)").option("--name <name>","Project name (defaults to an auto-generated name)").option("--team <nameOrId>","Create the project in this team").action(async n=>{var o,r,s,i;let t=x();try{let c;try{c=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let a=t?null:k("Creating project...").start();try{let l={...c},m=null;n.team&&(m=await _(n.team,c),l["X-Organization-ID"]=m.id);let d=await At.post(zt(),{},{headers:l}),f=$o(d.data);if(n.name){let $=await At.patch(Ae(String(f.id)),{data:{name:n.name}},{headers:l});f=$o($.data)}let g=m?{...f,ownerType:"team",ownerName:m.name}:{...f,ownerType:"personal",ownerName:((o=f.owner)==null?void 0:o.email)??""};a==null||a.succeed(`Created project "${g.name}"${m?` in ${m.name}`:""}`),t&&b({project:g}),console.log(""),console.log(` ID: ${g.id}`),console.log(` Name: ${g.name}`),console.log(` Workspace: ${m?m.name+" (team)":"personal"}`)}catch(l){throw a==null||a.fail("Failed to create project"),l instanceof p?l:At.isAxiosError(l)?((r=l.response)==null?void 0:r.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):((s=l.response)==null?void 0:s.status)===403?new p("Not allowed to create a project in this workspace.",{code:"FORBIDDEN",suggestion:"Verify you are a member of the team and have permission to create projects."}):new p(`API error: ${(i=l.response)==null?void 0:i.status}`):l}}catch(c){throw t&&E(c),c instanceof p&&(console.error(`
151
- ${c.message}`),process.exit(1)),c}})}import So from"fs-extra";import vo from"path";import ne from"axios";import Or from"prompts";function Ur(e){var t;let n=((t=e==null?void 0:e.data)==null?void 0:t.skills)??(e==null?void 0:e.skills)??e;if(!Array.isArray(n))throw new p("Unexpected skills response from MagicPath.",{code:"INVALID_RESPONSE"});return n}function Ye(e){var t;let n=((t=e==null?void 0:e.data)==null?void 0:t.skill)??(e==null?void 0:e.skill)??e;if(!n||typeof n!="object")throw new p("Unexpected skill response from MagicPath.",{code:"INVALID_RESPONSE"});return n}function Fr(e){var t;let n=((t=e==null?void 0:e.data)==null?void 0:t.files)??(e==null?void 0:e.files)??e;if(!Array.isArray(n))throw new p("Unexpected skill files response from MagicPath.",{code:"INVALID_RESPONSE"});return n}function Mr(e){var t;let n=((t=e==null?void 0:e.data)==null?void 0:t.file)??(e==null?void 0:e.file)??e;if(!n||typeof n!="object")throw new p("Unexpected skill file response from MagicPath.",{code:"INVALID_RESPONSE"});return n}function J(e){return String(e.id)}function Nt(e){return e.isPublic?"Public":e.organizationId?"Team":"Personal"}function Dr(){try{return j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}}async function he(e){let n=Dr();if(!e.team)return{headers:n,label:"personal",listUrl:st(),createUrl:st(),importUrl:Gt()};let t=await _(e.team,n);return{headers:{...n,"X-Organization-ID":t.id},label:`${t.name} (team)`,listUrl:ct(t.id),createUrl:ct(t.id),importUrl:Zt(t.id)}}async function Co(e){let n=await ne.get(e.listUrl,{headers:e.headers});return Ur(n.data)}function _r(e){return e.trim().toLowerCase()}function Lr(e,n){let t=_r(n);return J(e)===n||e.slug.toLowerCase()===t||e.name.toLowerCase()===t}async function Tt(e,n,t){let r=(await Co(e)).filter(i=>Lr(i,n)),s=t!=null&&t.writable?r.filter(i=>!i.isPublic):r;if(s.length===1)return s[0];throw s.length>1?new p(`Multiple skills matched "${n}".`,{code:"AMBIGUOUS_SKILL",suggestion:"Use the skill ID instead of the name or slash command."}):new p(`Skill "${n}" not found.`,{code:"SKILL_NOT_FOUND",suggestion:t!=null&&t.writable?"Run `magicpath-ai skills list --owned-only` to see editable skills.":"Run `magicpath-ai skills list` to see available skills."})}function jo(e){if(e.instructions&&e.instructionsFile)throw new p("Use either --instructions or --instructions-file, not both.",{code:"INVALID_OPTIONS"});return e.instructionsFile?So.readFileSync(vo.resolve(e.instructionsFile),"utf8"):e.instructions}function Wr(e){let n=jo(e);if(!e.name||!e.description||!n)throw new p("Creating a skill requires --name, --description, and --instructions or --instructions-file.",{code:"MISSING_FIELDS"});return{name:e.name,description:e.description,instructions:n}}function Hr(e){if(e.enable&&e.disable)throw new p("Use either --enable or --disable, not both.",{code:"INVALID_OPTIONS"});let n={},t=jo(e);if(e.name&&(n.name=e.name),e.description&&(n.description=e.description),t&&(n.instructions=t),e.enable&&(n.enabled=!0),e.disable&&(n.enabled=!1),Object.keys(n).length===0)throw new p("Updating a skill requires at least one field.",{code:"MISSING_FIELDS",suggestion:"Pass --name, --description, --instructions, --instructions-file, --enable, or --disable."});return n}function Gr(e){return e.toLowerCase().endsWith(".skill")?"application/octet-stream":"application/zip"}function Vr(e){if(e.length===0){console.log(`
152
- No skills found.`);return}console.log("");let n=Math.max(4,...e.map(s=>s.name.length)),t=Math.max(5,...e.map(s=>s.slug.length)),o=Math.max(6,...e.map(s=>Nt(s).length)),r=Math.max(6,...e.map(s=>(s.sourceFormat??"EDITOR").length));console.log(` ${"Name".padEnd(n)} ${"Slash".padEnd(t)} ${"Source".padEnd(o)} ${"Format".padEnd(r)} Enabled ID`),console.log(` ${"-".repeat(n)} ${"-".repeat(t)} ${"-".repeat(o)} ${"-".repeat(r)} ------- --`);for(let s of e){let i=s.enabled===!1?"no":"yes";console.log(` ${s.name.padEnd(n)} ${s.slug.padEnd(t)} ${Nt(s).padEnd(o)} ${(s.sourceFormat??"EDITOR").padEnd(r)} ${i.padEnd(7)} ${J(s)}`)}}function zr(e){console.log(""),console.log(` Name: ${e.name}`),console.log(` ID: ${J(e)}`),console.log(` Slash: /${e.slug}`),console.log(` Source: ${Nt(e)}`),console.log(` Format: ${e.sourceFormat??"EDITOR"}`),console.log(` Enabled: ${e.enabled===!1?"no":"yes"}`),console.log(""),console.log(" Description:"),console.log(` ${e.description}`),console.log(""),console.log(" Instructions:"),console.log(e.instructions)}function Jr(e){if(e.length===0){console.log(`
150
+ `);n.command("start").description("Start a pending create or edit session before writing code").option("--project <projectId>","Target MagicPath project ID for create").option("--component <componentId>","Existing MagicPath component ID for edit").option("--revision <revisionId>","Start editing this revision. Defaults to the component's currently selected revision.").option("--dir <dir>","Working directory to initialize",".").option("--name <name>","Component name").option("--width <px>","Canvas component width for create").option("--height <px>","Canvas component height for create").action(async t=>{try{let o=U.resolve(t.dir),r=jt(t);if(!!t.project==!!t.component)throw new p("Run code start with exactly one of --project for create or --component for edit.");if(t.component){if(r)throw new p("Use --width and --height with code submit when resizing an existing component.");let g=await fo(),y=(await V.post(Ht(t.component),{...t.revision?{revisionId:t.revision}:{},...g.length>0?{selectedImages:g}:{}},{headers:j()})).data.data;O.ensureDirSync(o);for(let w of y.editableFiles)Ct(o,w);let v=await ho(o,y.selectedImages),h={mode:"edit",componentId:y.component.id,projectId:y.component.projectId,selectedRevisionId:y.component.selectedRevisionId,baseRevisionId:y.component.baseRevisionId,jobId:y.jobId,generatedName:y.component.generatedName,name:y.component.name,selectedImages:v,editableFiles:y.editableFiles.map(w=>({path:w.path,sha256:fe(w.content)}))};Se(o,h);let u={dir:o,manifestPath:Ye(o),...h,status:"pending",scaffoldedPaths:y.editableFiles.map(w=>w.path),selectedImages:v};x()&&b(u),console.log(`Started pending edit ${h.selectedRevisionId} for component ${h.componentId} in ${o}`);return}let s=t.project;if(!s)throw new p("Create sessions require --project.");let i=await fo(s),a=(await V.post(tt(),{projectId:s,...t.name?{name:t.name}:{},...r?{dimensions:r}:{},...i.length>0?{selectedImages:i}:{}},{headers:j()})).data.data,l=a.editableFiles??[];O.ensureDirSync(o);for(let g of l)Ct(o,g);let m=await ho(o,a.selectedImages),d={mode:"create",componentId:a.componentId,projectId:s,selectedRevisionId:a.revisionId,jobId:a.jobId,generatedName:a.generatedName,name:t.name,dimensions:r,selectedImages:m,editableFiles:l.map(g=>({path:g.path,sha256:fe(g.content)}))};Se(o,d);let f={dir:o,manifestPath:Ye(o),...d,status:"pending",scaffoldedPaths:l.map(g=>g.path),selectedImages:m};x()&&b(f),console.log(`Started pending component ${d.componentId} in ${o}`+(l.length>0?` (scaffolded ${l.length} file${l.length===1?"":"s"})`:""))}catch(o){Ce(o)}}),n.command("context").description("Fetch editable files for an existing MagicPath component").argument("<componentId>","MagicPath component ID").option("--dir <dir>","Working directory to write",".").option("--revision <revisionId>","Pull this revision of the component. Defaults to the component's currently selected revision.").action(async(t,o)=>{try{let r=U.resolve(o.dir);O.ensureDirSync(r);let s=o.revision?`${nt(t)}?revisionId=${encodeURIComponent(o.revision)}`:nt(t),c=(await V.get(s,{headers:j()})).data.data;for(let l of c.editableFiles)Ct(r,l);let a={dir:r,readOnly:!0,component:c.component,editableFiles:c.editableFiles.map(l=>({path:l.path,sha256:fe(l.content)}))};x()&&b(a),console.log(`Fetched ${c.editableFiles.length} read-only editable file(s) into ${r}. Run \`magicpath-ai code start --component ${t} --dir ${r}\` before submitting edits.`)}catch(r){Ce(r)}}),n.command("submit").description("Submit changed editable files for the component in this working directory").option("--dir <dir>","Working directory containing magicpath-code.json",".").option("--wait","Wait for the build job to finish",!1).option("--interval <ms>","Polling interval when --wait is set","2000").option("--width <px>","Updated canvas component width").option("--height <px>","Updated canvas component height").action(async t=>{try{let o=U.resolve(t.dir),r=Ar(o),s=jt(t);po(o);let i=Tr(o,r),c=Nr(o,r);if(r.mode==="create"&&!i.some(d=>d.path==="src/App.tsx"))throw new p("Create submit requires src/App.tsx in the working directory.");if(i.length===0&&c.length===0&&!s){let d={status:"unchanged",componentId:r.componentId,revisionId:r.selectedRevisionId};x()&&b(d),console.log("No editable file changes to submit.");return}let l=r.mode==="create"||!!r.baseRevisionId&&r.selectedRevisionId!==r.baseRevisionId?await V.post(ot(r.componentId,r.selectedRevisionId),{files:i.map(d=>({path:d.path,content:d.content,encoding:d.encoding,mimeType:d.mimeType})),contextJobId:r.jobId,...s?{dimensions:s}:{},...r.mode==="edit"?{deletedPaths:c}:{}},{headers:j()}):await V.post(Gt(r.componentId),{baseRevisionId:r.baseRevisionId??r.selectedRevisionId,files:i.map(d=>({path:d.path,content:d.content,encoding:d.encoding,mimeType:d.mimeType,baseSha256:d.baseSha256})),deletedPaths:c,...s?{dimensions:s}:{}},{headers:j()}),m=l.data.data;if(t.wait&&(m=await go(l.data.data.jobId,Number(t.interval))),m.status==="completed"){let d=je(o),f={...r,mode:"edit",jobId:l.data.data.jobId,selectedRevisionId:m.revisionId,baseRevisionId:m.revisionId,...s?{dimensions:s}:{},editableFiles:d.map(g=>({path:g.path,sha256:g.sha256??fe(g.content)}))};Se(o,f)}x()&&b({...m,jobId:l.data.data.jobId,deletedPaths:c,...s?{dimensions:s}:{}}),console.log(`Submitted ${i.length} file(s)`+(c.length>0?` and ${c.length} deletion(s)`:"")+`. Job ${l.data.data.jobId}: ${m.status}`)}catch(o){Ce(o)}}),n.command("create").description("Create a new MagicPath component from local editable files").requiredOption("--project <projectId>","Target MagicPath project ID").option("--dir <dir>","Working directory containing src/App.tsx",".").option("--name <name>","Component name").option("--wait","Wait for the build job to finish",!1).option("--width <px>","Canvas component width").option("--height <px>","Canvas component height").action(async t=>{try{let o=U.resolve(t.dir),r=jt(t);po(o);let s=je(o);if(!s.some(m=>m.path==="src/App.tsx"))throw new p("Create requires src/App.tsx in the working directory.");let i=await V.post(tt(),{projectId:t.project,...t.name?{name:t.name}:{},...r?{dimensions:r}:{}},{headers:j()}),c={mode:"create",componentId:i.data.data.componentId,projectId:t.project,selectedRevisionId:i.data.data.revisionId,jobId:i.data.data.jobId,generatedName:i.data.data.generatedName,name:t.name,dimensions:r,editableFiles:[]};Se(o,c);let a=await V.post(ot(c.componentId,c.selectedRevisionId),{files:s.map(m=>({path:m.path,content:m.content,encoding:m.encoding,mimeType:m.mimeType})),contextJobId:c.jobId,...r?{dimensions:r}:{}},{headers:j()}),l=a.data.data;t.wait&&(l=await go(a.data.data.jobId,2e3)),l.status==="completed"&&Se(o,{...c,mode:"edit",jobId:a.data.data.jobId,selectedRevisionId:l.revisionId,...r?{dimensions:r}:{},editableFiles:s.map(m=>({path:m.path,sha256:m.sha256??fe(m.content)}))}),x()&&b({...l,jobId:a.data.data.jobId,...r?{dimensions:r}:{}}),console.log(`Created component ${a.data.data.componentId}. Job ${a.data.data.jobId}: ${l.status}`)}catch(o){Ce(o)}}),n.command("status").description("Fetch external-agent build job status").argument("<jobId>","External agent job ID").action(async t=>{try{let o=await V.get(rt(t),{headers:j()});x()&&b(o.data.data),console.log(`${t}: ${o.data.data.status}`)}catch(o){Ce(o)}})}import Ee from"axios";import bo from"fs";import At from"path";import{imageSize as Or}from"image-size";var $o=512;async function Ur(e){if(/^https?:\/\//i.test(e)){let t=await Ee.get(e,{responseType:"arraybuffer"}),o=At.basename(new URL(e).pathname)||"image";return{buffer:Buffer.from(t.data),fileName:o}}let n=At.resolve(e);if(!bo.existsSync(n))throw new Error(`Image file not found: ${n}`);return{buffer:bo.readFileSync(n),fileName:At.basename(n)}}function Ze(e){if(e===void 0)return;let n=Number(e);if(!Number.isFinite(n))throw new Error(`Invalid number: ${e}`);return n}function xo(e){let n=e.command("image").description("Add and list images on a project canvas");n.command("add").description("Add an image to a project canvas from a local file path or a URL").argument("<projectId>","The id of the project to add the image to").argument("<pathOrUrl>","A local image file path or an http(s) URL").option("--name <name>","Display name for the image (defaults to the file name)").option("--x <x>","Canvas x position (default 0)").option("--y <y>","Canvas y position (default 0)").option("--width <width>","Width in canvas units (defaults to the intrinsic width)").option("--height <height>","Height in canvas units (defaults to the intrinsic height)").action(async(t,o,r)=>{var c,a;let s=x(),i=s?null:k("Adding image to project...").start();try{let l=j(),{buffer:m,fileName:d}=await Ur(o),f=Ze(r.width),g=Ze(r.height);if(f===void 0||g===void 0)try{let P=Or(m);f=f??P.width,g=g??P.height}catch{}f=f??$o,g=g??$o;let $={x:Ze(r.x)??0,y:Ze(r.y)??0,z:0,width:f,height:g},y=r.name??(d.replace(/\.[^/.]+$/,"")||d),v=await Ee.get(zt(),{headers:l,params:{filename:d,content_type:"image/*",make_public:"true"}}),{upload_url:h,upload_token:u}=v.data;await Ee.put(h,m,{headers:{"Content-Type":"image/*","x-goog-acl":"public-read"}});let I=(a=(c=(await Ee.post(at(t),{name:y,position:$,upload_token:u},{headers:l})).data)==null?void 0:c.data)==null?void 0:a.image;i==null||i.succeed("Image added to project"),s&&b({image:I}),console.log(`Added "${(I==null?void 0:I.name)??y}" (${(I==null?void 0:I.id)??"unknown id"})`),I!=null&&I.url&&console.log(I.url)}catch(l){i==null||i.fail("Failed to add image"),s&&E(l),console.error(l instanceof Error?l.message:String(l)),process.exit(1)}}),n.command("list").description("List the images on a project canvas").argument("<projectId>","The id of the project").action(async t=>{var s,i;let o=x(),r=o?null:k("Fetching images...").start();try{let c=j(),l=((i=(s=(await Ee.get(at(t),{headers:c})).data)==null?void 0:s.data)==null?void 0:i.images)??[];if(r==null||r.succeed(`Found ${l.length} image(s)`),o&&b({images:l}),l.length===0){console.log("No images in this project.");return}for(let m of l)console.log(`- ${m.name} (${m.id})${m.url?` \u2014 ${m.url}`:""}`)}catch(c){r==null||r.fail("Failed to list images"),o&&E(c),console.error(c instanceof Error?c.message:String(c)),process.exit(1)}})}import Tt from"axios";function vo(e){var n;return((n=e==null?void 0:e.data)==null?void 0:n.project)??(e==null?void 0:e.project)??e}function So(e){e.command("create-project").description("Create a new project (personal or in a team)").option("--name <name>","Project name (defaults to an auto-generated name)").option("--team <nameOrId>","Create the project in this team").action(async n=>{var o,r,s,i;let t=x();try{let c;try{c=j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}let a=t?null:k("Creating project...").start();try{let l={...c},m=null;n.team&&(m=await _(n.team,c),l["X-Organization-ID"]=m.id);let d=await Tt.post(Jt(),{},{headers:l}),f=vo(d.data);if(n.name){let $=await Tt.patch(Ne(String(f.id)),{data:{name:n.name}},{headers:l});f=vo($.data)}let g=m?{...f,ownerType:"team",ownerName:m.name}:{...f,ownerType:"personal",ownerName:((o=f.owner)==null?void 0:o.email)??""};a==null||a.succeed(`Created project "${g.name}"${m?` in ${m.name}`:""}`),t&&b({project:g}),console.log(""),console.log(` ID: ${g.id}`),console.log(` Name: ${g.name}`),console.log(` Workspace: ${m?m.name+" (team)":"personal"}`)}catch(l){throw a==null||a.fail("Failed to create project"),l instanceof p?l:Tt.isAxiosError(l)?((r=l.response)==null?void 0:r.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):((s=l.response)==null?void 0:s.status)===403?new p("Not allowed to create a project in this workspace.",{code:"FORBIDDEN",suggestion:"Verify you are a member of the team and have permission to create projects."}):new p(`API error: ${(i=l.response)==null?void 0:i.status}`):l}}catch(c){throw t&&E(c),c instanceof p&&(console.error(`
151
+ ${c.message}`),process.exit(1)),c}})}import Co from"fs-extra";import jo from"path";import oe from"axios";import Fr from"prompts";function Mr(e){var t;let n=((t=e==null?void 0:e.data)==null?void 0:t.skills)??(e==null?void 0:e.skills)??e;if(!Array.isArray(n))throw new p("Unexpected skills response from MagicPath.",{code:"INVALID_RESPONSE"});return n}function Qe(e){var t;let n=((t=e==null?void 0:e.data)==null?void 0:t.skill)??(e==null?void 0:e.skill)??e;if(!n||typeof n!="object")throw new p("Unexpected skill response from MagicPath.",{code:"INVALID_RESPONSE"});return n}function Dr(e){var t;let n=((t=e==null?void 0:e.data)==null?void 0:t.files)??(e==null?void 0:e.files)??e;if(!Array.isArray(n))throw new p("Unexpected skill files response from MagicPath.",{code:"INVALID_RESPONSE"});return n}function _r(e){var t;let n=((t=e==null?void 0:e.data)==null?void 0:t.file)??(e==null?void 0:e.file)??e;if(!n||typeof n!="object")throw new p("Unexpected skill file response from MagicPath.",{code:"INVALID_RESPONSE"});return n}function J(e){return String(e.id)}function Rt(e){return e.isPublic?"Public":e.organizationId?"Team":"Personal"}function Lr(){try{return j()}catch{throw new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."})}}async function he(e){let n=Lr();if(!e.team)return{headers:n,label:"personal",listUrl:it(),createUrl:it(),importUrl:Vt()};let t=await _(e.team,n);return{headers:{...n,"X-Organization-ID":t.id},label:`${t.name} (team)`,listUrl:lt(t.id),createUrl:lt(t.id),importUrl:Qt(t.id)}}async function Eo(e){let n=await oe.get(e.listUrl,{headers:e.headers});return Mr(n.data)}function Wr(e){return e.trim().toLowerCase()}function Hr(e,n){let t=Wr(n);return J(e)===n||e.slug.toLowerCase()===t||e.name.toLowerCase()===t}async function Nt(e,n,t){let r=(await Eo(e)).filter(i=>Hr(i,n)),s=t!=null&&t.writable?r.filter(i=>!i.isPublic):r;if(s.length===1)return s[0];throw s.length>1?new p(`Multiple skills matched "${n}".`,{code:"AMBIGUOUS_SKILL",suggestion:"Use the skill ID instead of the name or slash command."}):new p(`Skill "${n}" not found.`,{code:"SKILL_NOT_FOUND",suggestion:t!=null&&t.writable?"Run `magicpath-ai skills list --owned-only` to see editable skills.":"Run `magicpath-ai skills list` to see available skills."})}function ko(e){if(e.instructions&&e.instructionsFile)throw new p("Use either --instructions or --instructions-file, not both.",{code:"INVALID_OPTIONS"});return e.instructionsFile?Co.readFileSync(jo.resolve(e.instructionsFile),"utf8"):e.instructions}function Gr(e){let n=ko(e);if(!e.name||!e.description||!n)throw new p("Creating a skill requires --name, --description, and --instructions or --instructions-file.",{code:"MISSING_FIELDS"});return{name:e.name,description:e.description,instructions:n}}function Vr(e){if(e.enable&&e.disable)throw new p("Use either --enable or --disable, not both.",{code:"INVALID_OPTIONS"});let n={},t=ko(e);if(e.name&&(n.name=e.name),e.description&&(n.description=e.description),t&&(n.instructions=t),e.enable&&(n.enabled=!0),e.disable&&(n.enabled=!1),Object.keys(n).length===0)throw new p("Updating a skill requires at least one field.",{code:"MISSING_FIELDS",suggestion:"Pass --name, --description, --instructions, --instructions-file, --enable, or --disable."});return n}function zr(e){return e.toLowerCase().endsWith(".skill")?"application/octet-stream":"application/zip"}function Jr(e){if(e.length===0){console.log(`
152
+ No skills found.`);return}console.log("");let n=Math.max(4,...e.map(s=>s.name.length)),t=Math.max(5,...e.map(s=>s.slug.length)),o=Math.max(6,...e.map(s=>Rt(s).length)),r=Math.max(6,...e.map(s=>(s.sourceFormat??"EDITOR").length));console.log(` ${"Name".padEnd(n)} ${"Slash".padEnd(t)} ${"Source".padEnd(o)} ${"Format".padEnd(r)} Enabled ID`),console.log(` ${"-".repeat(n)} ${"-".repeat(t)} ${"-".repeat(o)} ${"-".repeat(r)} ------- --`);for(let s of e){let i=s.enabled===!1?"no":"yes";console.log(` ${s.name.padEnd(n)} ${s.slug.padEnd(t)} ${Rt(s).padEnd(o)} ${(s.sourceFormat??"EDITOR").padEnd(r)} ${i.padEnd(7)} ${J(s)}`)}}function Br(e){console.log(""),console.log(` Name: ${e.name}`),console.log(` ID: ${J(e)}`),console.log(` Slash: /${e.slug}`),console.log(` Source: ${Rt(e)}`),console.log(` Format: ${e.sourceFormat??"EDITOR"}`),console.log(` Enabled: ${e.enabled===!1?"no":"yes"}`),console.log(""),console.log(" Description:"),console.log(` ${e.description}`),console.log(""),console.log(" Instructions:"),console.log(e.instructions)}function Kr(e){if(e.length===0){console.log(`
153
153
  No bundled files.`);return}console.log("");let n=Math.max(4,...e.map(t=>t.path.length));console.log(` ${"Path".padEnd(n)} Size`),console.log(` ${"-".repeat(n)} ----`);for(let t of e)console.log(` ${t.path.padEnd(n)} ${t.size}`)}async function we(e,n){try{await n()}catch(t){let o=M(t);e&&E(o),console.error(`
154
- ${o.message}`),o.suggestion&&console.error(o.suggestion),process.exit(1)}}function Eo(e){let n=e.command("skills").description("Manage MagicPath skills");n.command("list").description("List skills in your personal workspace or a team").option("--team <nameOrId>","List skills for this team").option("--owned-only","Hide public MagicPath skills",!1).action(async t=>{let o=x();await we(o,async()=>{let r=await he(t),s=o?null:k("Fetching skills...").start(),i=await Co(r),c=t.ownedOnly?i.filter(a=>!a.isPublic):i;s==null||s.succeed(`Found ${c.length} skill(s)`),o&&b({skills:c,workspace:r.label}),Vr(c)})}),n.command("get").description("Show a skill by ID, slash command, or exact name").argument("<skill>","Skill ID, slash command, or exact name").option("--team <nameOrId>","Look up a team skill").option("--files","Also list bundled files",!1).option("--file <path>","Print a bundled file from the skill").action(async(t,o)=>{let r=x();await we(r,async()=>{let s=await he(o),i=r?null:k("Fetching skill...").start(),c=await Tt(s,t),a,l;if(o.file){let m=await ne.get(en(J(c),o.file),{headers:s.headers});l=Mr(m.data)}else if(o.files){let m=await ne.get(Qt(J(c)),{headers:s.headers});a=Fr(m.data)}if(i==null||i.succeed("Fetched skill"),r&&b({skill:c,...a?{files:a}:{},...l?{file:l}:{}}),l){console.log(l.content);return}zr(c),a&&Jr(a)})}),n.command("create").description("Create an editable skill").requiredOption("--name <name>","Skill name").requiredOption("--description <text>","Skill description").option("--instructions <text>","Skill instructions").option("--instructions-file <path>","Read skill instructions from a file").option("--team <nameOrId>","Create the skill in this team").action(async t=>{let o=x();await we(o,async()=>{let r=Wr(t),s=await he(t),i=o?null:k("Creating skill...").start(),c=await ne.post(s.createUrl,r,{headers:s.headers}),a=Ye(c.data);i==null||i.succeed(`Created skill "${a.name}"`),o&&b({skill:a,workspace:s.label}),console.log(""),console.log(` Created: ${a.name}`),console.log(` ID: ${J(a)}`),console.log(` Slash: /${a.slug}`),console.log(` Workspace: ${s.label}`)})}),n.command("import").description("Import a .zip or .skill package").argument("<archivePath>","Path to the .zip or .skill package").option("--team <nameOrId>","Import the skill into this team").action(async(t,o)=>{let r=x();await we(r,async()=>{let s=await he(o),i=vo.resolve(t),c=So.readFileSync(i),a=r?null:k("Importing skill...").start(),l=await ne.post(s.importUrl,c,{headers:{...s.headers,"Content-Type":Gr(i)}}),m=Ye(l.data);a==null||a.succeed(`Imported skill "${m.name}"`),r&&b({skill:m,workspace:s.label}),console.log(""),console.log(` Imported: ${m.name}`),console.log(` ID: ${J(m)}`),console.log(` Slash: /${m.slug}`),console.log(` Workspace: ${s.label}`)})}),n.command("update").description("Update an editable skill by ID, slash command, or exact name").argument("<skill>","Skill ID, slash command, or exact name").option("--name <name>","New skill name").option("--description <text>","New skill description").option("--instructions <text>","New skill instructions").option("--instructions-file <path>","Read new skill instructions from a file").option("--enable","Enable the skill for chat",!1).option("--disable","Disable the skill for chat",!1).option("--team <nameOrId>","Update a team skill").action(async(t,o)=>{let r=x();await we(r,async()=>{let s=Hr(o),i=await he(o),c=r?null:k("Updating skill...").start(),a=await Tt(i,t,{writable:!0}),l=await ne.patch(lt(J(a)),s,{headers:i.headers}),m=Ye(l.data);c==null||c.succeed(`Updated skill "${m.name}"`),r&&b({skill:m,workspace:i.label}),console.log(""),console.log(` Updated: ${m.name}`),console.log(` ID: ${J(m)}`),console.log(` Slash: /${m.slug}`),console.log(` Enabled: ${m.enabled===!1?"no":"yes"}`)})}),n.command("delete").description("Delete an editable skill by ID, slash command, or exact name").argument("<skill>","Skill ID, slash command, or exact name").option("-y, --yes","Skip confirmation prompt",!1).option("--team <nameOrId>","Delete a team skill").action(async(t,o)=>{let r=x();await we(r,async()=>{let s=await he(o),i=r?null:k("Finding skill...").start(),c=await Tt(s,t,{writable:!0});if(i==null||i.stop(),!r&&!o.yes){let d=An();try{if(!(await Or({type:"confirm",name:"confirmed",message:`Delete "${c.name}"?`,initial:!1})).confirmed){console.log("Cancelled.");return}}finally{d()}}let a=r?null:k("Deleting skill...").start(),l=await ne.delete(lt(J(c)),{headers:s.headers}),m=Ye(l.data);a==null||a.succeed(`Deleted skill "${m.name}"`),r&&b({skill:m,workspace:s.label})})})}var Yr=Kr(Xr(import.meta.url)),Zr=JSON.parse(Br(qr(Yr,"..","package.json"),"utf8"));Dt(Zr.version);Ut();process.argv.length<=2&&(gn(B),process.exit(0));T.name("magicpath").description("").version(B).option("-o, --output <format>","Output format: json").hook("preAction",e=>{e.optsWithGlobals().output==="json"&&Mt(!0)});kn(T);Wn(T);Ln(T);Gn(T);Vn(T);zn(T);Jn(T);Bn(T);Kn(T);Xn(T);Zn(T);Yn(T);eo(T);to(T);oo(T);ro(T);so(T);ao(T);wo(T);bo(T);xo(T);Eo(T);T.parse();
154
+ ${o.message}`),o.suggestion&&console.error(o.suggestion),process.exit(1)}}function Po(e){let n=e.command("skills").description("Manage MagicPath skills");n.command("list").description("List skills in your personal workspace or a team").option("--team <nameOrId>","List skills for this team").option("--owned-only","Hide public MagicPath skills",!1).action(async t=>{let o=x();await we(o,async()=>{let r=await he(t),s=o?null:k("Fetching skills...").start(),i=await Eo(r),c=t.ownedOnly?i.filter(a=>!a.isPublic):i;s==null||s.succeed(`Found ${c.length} skill(s)`),o&&b({skills:c,workspace:r.label}),Jr(c)})}),n.command("get").description("Show a skill by ID, slash command, or exact name").argument("<skill>","Skill ID, slash command, or exact name").option("--team <nameOrId>","Look up a team skill").option("--files","Also list bundled files",!1).option("--file <path>","Print a bundled file from the skill").action(async(t,o)=>{let r=x();await we(r,async()=>{let s=await he(o),i=r?null:k("Fetching skill...").start(),c=await Nt(s,t),a,l;if(o.file){let m=await oe.get(tn(J(c),o.file),{headers:s.headers});l=_r(m.data)}else if(o.files){let m=await oe.get(en(J(c)),{headers:s.headers});a=Dr(m.data)}if(i==null||i.succeed("Fetched skill"),r&&b({skill:c,...a?{files:a}:{},...l?{file:l}:{}}),l){console.log(l.content);return}Br(c),a&&Kr(a)})}),n.command("create").description("Create an editable skill").requiredOption("--name <name>","Skill name").requiredOption("--description <text>","Skill description").option("--instructions <text>","Skill instructions").option("--instructions-file <path>","Read skill instructions from a file").option("--team <nameOrId>","Create the skill in this team").action(async t=>{let o=x();await we(o,async()=>{let r=Gr(t),s=await he(t),i=o?null:k("Creating skill...").start(),c=await oe.post(s.createUrl,r,{headers:s.headers}),a=Qe(c.data);i==null||i.succeed(`Created skill "${a.name}"`),o&&b({skill:a,workspace:s.label}),console.log(""),console.log(` Created: ${a.name}`),console.log(` ID: ${J(a)}`),console.log(` Slash: /${a.slug}`),console.log(` Workspace: ${s.label}`)})}),n.command("import").description("Import a .zip or .skill package").argument("<archivePath>","Path to the .zip or .skill package").option("--team <nameOrId>","Import the skill into this team").action(async(t,o)=>{let r=x();await we(r,async()=>{let s=await he(o),i=jo.resolve(t),c=Co.readFileSync(i),a=r?null:k("Importing skill...").start(),l=await oe.post(s.importUrl,c,{headers:{...s.headers,"Content-Type":zr(i)}}),m=Qe(l.data);a==null||a.succeed(`Imported skill "${m.name}"`),r&&b({skill:m,workspace:s.label}),console.log(""),console.log(` Imported: ${m.name}`),console.log(` ID: ${J(m)}`),console.log(` Slash: /${m.slug}`),console.log(` Workspace: ${s.label}`)})}),n.command("update").description("Update an editable skill by ID, slash command, or exact name").argument("<skill>","Skill ID, slash command, or exact name").option("--name <name>","New skill name").option("--description <text>","New skill description").option("--instructions <text>","New skill instructions").option("--instructions-file <path>","Read new skill instructions from a file").option("--enable","Enable the skill for chat",!1).option("--disable","Disable the skill for chat",!1).option("--team <nameOrId>","Update a team skill").action(async(t,o)=>{let r=x();await we(r,async()=>{let s=Vr(o),i=await he(o),c=r?null:k("Updating skill...").start(),a=await Nt(i,t,{writable:!0}),l=await oe.patch(mt(J(a)),s,{headers:i.headers}),m=Qe(l.data);c==null||c.succeed(`Updated skill "${m.name}"`),r&&b({skill:m,workspace:i.label}),console.log(""),console.log(` Updated: ${m.name}`),console.log(` ID: ${J(m)}`),console.log(` Slash: /${m.slug}`),console.log(` Enabled: ${m.enabled===!1?"no":"yes"}`)})}),n.command("delete").description("Delete an editable skill by ID, slash command, or exact name").argument("<skill>","Skill ID, slash command, or exact name").option("-y, --yes","Skip confirmation prompt",!1).option("--team <nameOrId>","Delete a team skill").action(async(t,o)=>{let r=x();await we(r,async()=>{let s=await he(o),i=r?null:k("Finding skill...").start(),c=await Nt(s,t,{writable:!0});if(i==null||i.stop(),!r&&!o.yes){let d=Nn();try{if(!(await Fr({type:"confirm",name:"confirmed",message:`Delete "${c.name}"?`,initial:!1})).confirmed){console.log("Cancelled.");return}}finally{d()}}let a=r?null:k("Deleting skill...").start(),l=await oe.delete(mt(J(c)),{headers:s.headers}),m=Qe(l.data);a==null||a.succeed(`Deleted skill "${m.name}"`),r&&b({skill:m,workspace:s.label})})})}var Qr=Xr(Zr(import.meta.url)),es=JSON.parse(qr(Yr(Qr,"..","package.json"),"utf8"));_t(es.version);Ft();process.argv.length<=2&&(fn(B),process.exit(0));T.name("magicpath").description("").version(B).option("-o, --output <format>","Output format: json").hook("preAction",e=>{e.optsWithGlobals().output==="json"&&Dt(!0)});An(T);Gn(T);Hn(T);zn(T);Jn(T);Bn(T);Kn(T);qn(T);Xn(T);Zn(T);eo(T);Qn(T);no(T);oo(T);so(T);io(T);ao(T);lo(T);Io(T);xo(T);So(T);Po(T);T.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "magicpath-ai",
3
- "version": "2.4.0",
3
+ "version": "2.4.2",
4
4
  "description": "Node CLI for MagicPath",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",