magicpath-ai 1.5.0-beta.3 → 1.5.0-beta.5

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 +57 -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 Dn}from"fs";import{dirname as _n,join as Ln}from"path";import{fileURLToPath as Wn}from"url";import{program as k}from"commander";var p=class extends Error{code;suggestion;constructor(n,o){super(n),this.code=o==null?void 0:o.code,this.suggestion=o==null?void 0:o.suggestion}};var nt=!1;function rt(t){nt=t}function x(){return nt}function j(t){console.log(JSON.stringify(t,null,2)),process.exit(0)}function A(t){let o={error:t instanceof Error?t.message:String(t)};t instanceof p&&(t.code&&(o.code=t.code),t.suggestion&&(o.suggestion=t.suggestion)),console.error(JSON.stringify(o,null,2)),process.exit(1)}var H="0.0.0-dev";function st(t){H=t}import te from"chalk";import le from"fs-extra";import gt from"path";import Ao from"os";import ut from"axios";var O=process.env.MAGICPATH_API_URL??"https://preview.api.magicpath.ai";function Ie(t,n){return`${O}/${t}/${n}`}function it(t){return`${O}/v1/registry/${t}`}var Co=process.env.MAGICPATH_WEB_URL??"https://preview.magicpath.ai";function at(t){return`${Co}${t}`}function Fe(t){return`${O}/auth/${t}`}function Ue(){return`${O}/v1/external-agent/components`}function De(t){return`${O}/v1/external-agent/components/${t}/context`}function ct(t){return`${O}/v1/external-agent/components/${t}/revisions`}function _e(t,n){return`${O}/v1/external-agent/components/${t}/revisions/${n}/files`}function Le(t){return`${O}/v1/external-agent/jobs/${t}`}function Z(){return`${O}/users/me`}function We(){return`${O}/users/me/projects`}function $e(t){return`${O}/projects/${t}/components`}function je(){return`${O}/users/me/design-systems`}function lt(t){return`${O}/design-systems/${t}`}function xe(){return`${O}/users/me/socket-rooms`}function mt(){return`${O}/liveblocks/auth`}function dt(t){return`${O}/components/${t}`}function pt(t){return`${O}/organizations/${t}`}function He(t){return`${O}/organizations/${t}/projects`}function ve(t){return`${O}/organizations/${t}/design-systems`}var ft=gt.join(Ao.homedir(),".magicpath"),Ce=gt.join(ft,"session.json");function Ae(){try{if(!le.existsSync(Ce))return null;let t=le.readJsonSync(Ce);return t.accessToken&&t.refreshToken?t:null}catch{return null}}function ht(t){le.ensureDirSync(ft),le.writeJsonSync(Ce,t)}function ze(t,n){let o=Ae();ht({accessToken:t,refreshToken:n,user:o==null?void 0:o.user})}function X(){let t=Ae();return t?{accessToken:t.accessToken,refreshToken:t.refreshToken}:null}function yt(){try{le.removeSync(Ce)}catch{}}function So(t){try{let n=Ae();n&&(n.user=t,ht(n))}catch{}}function wt(){let t=Ae();return(t==null?void 0:t.user)??null}function S(){let t=process.env.MAGICPATH_TOKEN;if(t)return{Authorization:`Bearer ${t}`,"X-Client-Type":"cli","X-Client-Version":H};let n=X();if(!n)throw new Error("Not logged in. Run `magicpath-ai login` first.");return{Authorization:`Bearer ${n.accessToken}`,"X-Client-Type":"cli","X-Client-Version":H}}function me(t){var e,r;let n=(e=t.subscription)!=null&&e.active?(r=t.subscription.type)!=null&&r.startsWith("PRO")?"Pro":"Creator":"Free",o={name:t.name||t.firstName||t.displayName,email:t.email,plan:n};return So(o),o}async function Ge(){let t=S(),n=await ut.get(Z(),{headers:t}),o=n.data.user??n.data;return me(o)}async function de(t){let n=await ut.get(Z(),{headers:t});return((n.data.user??n.data).organizationUsers??[]).map(r=>({id:String(r.organization.id),name:r.organization.name,role:r.role}))}async function z(t,n){let o=await de(n),e=o.find(i=>i.id===t);if(e)return{id:e.id,name:e.name};let r=t.toLowerCase(),s=o.find(i=>i.name.toLowerCase()===r);if(s)return{id:s.id,name:s.name};throw new p(`Team "${t}" not found.`,{code:"TEAM_NOT_FOUND",suggestion:"Run `magicpath-ai list-teams` to see your teams."})}var bt=["#95D5B2","#74C69D","#52B788","#40916C","#2D6A4F","#1B4332"];function Po(t){return te.hex(bt[Math.min(t,bt.length-1)])}var Je=te.hex("#2D6A4F"),To=te.hex("#1B4332"),Eo=te.hex("#E8F5E9"),Ve=te.hex("#888888"),No=["\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"],Ro=["\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"],ko=No.map((t,n)=>t+" "+Ro[n]);function Oo(t){return t.map((n,o)=>{let e=Po(o),r="";for(let s of n)r+=s===" "?s:e(s);return r})}function It(t){let n=!!X(),o=n?wt():null;console.log();for(let s of Oo(ko))console.log(s);if(console.log(),n&&o){let s=o.plan?` \xB7 ${o.plan}`:"";console.log(" "+Je("\u25CF")+" "+te.bold(Eo(o.name??"MagicPath User"))+To(" "+(o.email??"")+s))}else console.log(" "+Ve("\u25CB Not logged in \xB7 run")+" "+Je("magicpath-ai login"));console.log();let e=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(" "+Je(s.padEnd(e))+Ve(i));console.log(),console.log(" "+Ve(`v${t} \u2500 magicpath-ai --help`)),console.log()}import Pe from"prompts";import kt from"ora";import{z as re}from"zod";import se from"path";import Ho from"os";import qe from"fs-extra";import{pino as $t}from"pino";var oe=$t();function ne(){oe=$t({level:"debug"}),oe.debug({message:"DEBUG logger enabled. "})}var R={info:t=>{oe.info(t)},debug:t=>{oe.debug(t)},warn:t=>{oe.warn(t)},error:t=>{oe.error(t)}};import Fo from"axios";import Se from"path";import Uo from"os";import pe from"fs-extra";import Do from"adm-zip";import{v4 as _o}from"uuid";async function jt(t){let n=Ie("v1","components/repository"),o=`${_o()}.zip`,e=Se.join(Uo.tmpdir(),o);try{let r=await Fo({url:n,params:{key:t},method:"GET",responseType:"stream"});return await pe.ensureDir(Se.dirname(e)),await new Promise(async(s,i)=>{try{r.data.pipe(pe.createWriteStream(e)).on("error",i).once("close",()=>s(e))}catch(c){i(c)}}),e}catch{throw new p("Failed to download project. Make sure your key is valid.")}}function Ke(t){try{pe.removeSync(t)}catch{}}function xt(t,n,o){try{let e=Se.join(o,n),r=1;for(;pe.existsSync(e);)r++,e=Se.join(o,`${n}-${r}`);return pe.mkdirSync(e,{recursive:!0}),new Do(t).extractAllTo(e,!0),Ke(t),e}catch{throw new p("Failed to extract project. Please try again.")}}import{execSync as Be}from"child_process";import Ct from"ora";import vt from"fs-extra";import Lo from"path";function At(){try{return Be("yarn --version",{stdio:"ignore"}),"yarn"}catch{return"npm"}}function St(t){let n=At(),o=Ct(`\u{1F4E6} Installing dependencies using ${n}...`).start();try{Be(n==="yarn"?"yarn install":"npm install",{cwd:t,stdio:"ignore"}),o.succeed("Dependencies installed successfully!")}catch{throw o.fail("Failed to install dependencies"),new p("Failed to install dependencies. Please check your internet connection and try again.")}}function Wo(t){let n=Lo.join(t,"package.json");if(!vt.existsSync(n))return new Set;try{let o=vt.readJsonSync(n),e=new Set;return o.dependencies&&Object.keys(o.dependencies).forEach(r=>e.add(r)),o.devDependencies&&Object.keys(o.devDependencies).forEach(r=>e.add(r)),e}catch{return new Set}}function Pt(t,n){if(t.length===0)return{installed:[],skipped:[]};let o=Wo(n),e=t.filter(c=>!o.has(c)),r=t.filter(c=>o.has(c));if(e.length===0)return R.debug("All dependencies already installed"),{installed:[],skipped:r};let s=At(),i=Ct(`\u{1F4E6} Installing ${e.length} package${e.length>1?"s":""} using ${s}...`).start();try{let c=e.join(" "),a=s==="yarn"?`yarn add ${c}`:`npm install ${c}`;return R.debug({command:a}),Be(a,{cwd:n,stdio:"ignore"}),i.succeed(`Installed ${e.length} package${e.length>1?"s":""}`),{installed:e,skipped:r}}catch{throw i.fail("Failed to install packages"),new p(`Failed to install packages: ${e.join(", ")}. Please install them manually.`)}}import{execSync as Tt}from"child_process";import Et from"ora";function Nt(t,n){let o={cursor:"Cursor",antigravity:"Antigravity",vscode:"VS Code",webstorm:"WebStorm"},e={cursor:["cursor","code"],antigravity:["agy","antigravity"],vscode:["code"],webstorm:["webstorm","web"]},r=Et(`\u{1F680} Opening project in ${o[n]}...`).start(),s=!1;try{for(let i of e[n]){if(s)break;try{Tt(`${i} .`,{cwd:t,stdio:"ignore"}),s=!0}catch{s=!1}}if(!s)throw new Error("Failed to open with command.");r.succeed(`Project opened in ${o[n]}!`)}catch{r.fail(`Failed to open ${o[n]}`);let i={cursor:`\u274C Cursor command not found!
2
+ import{readFileSync as zn}from"fs";import{dirname as Gn,join as Jn}from"path";import{fileURLToPath as Vn}from"url";import{program as N}from"commander";var p=class extends Error{code;suggestion;constructor(n,o){super(n),this.code=o==null?void 0:o.code,this.suggestion=o==null?void 0:o.suggestion}};var rt=!1;function st(e){rt=e}function x(){return rt}function j(e){console.log(JSON.stringify(e,null,2)),process.exit(0)}function A(e){let o={error:e instanceof Error?e.message:String(e)};e instanceof p&&(e.code&&(o.code=e.code),e.suggestion&&(o.suggestion=e.suggestion)),console.error(JSON.stringify(o,null,2)),process.exit(1)}var z="0.0.0-dev";function it(e){z=e}import te from"chalk";import le from"fs-extra";import ht from"path";import No from"os";import yt from"axios";var O=process.env.MAGICPATH_API_URL??"https://preview.api.magicpath.ai";function Ie(e,n){return`${O}/${e}/${n}`}function at(e){return`${O}/v1/registry/${e}`}var So=process.env.MAGICPATH_WEB_URL??"https://preview.magicpath.ai";function ct(e){return`${So}${e}`}function Fe(e){return`${O}/auth/${e}`}function Ue(){return`${O}/v1/external-agent/components`}function De(e){return`${O}/v1/external-agent/components/${e}/context`}function lt(e){return`${O}/v1/external-agent/components/${e}/revisions`}function _e(e,n){return`${O}/v1/external-agent/components/${e}/revisions/${n}/files`}function Le(e){return`${O}/v1/external-agent/jobs/${e}`}function Z(){return`${O}/users/me`}function We(){return`${O}/users/me/projects`}function mt(){return`${O}/projects`}function dt(e){return`${O}/projects/${e}`}function $e(e){return`${O}/projects/${e}/components`}function je(){return`${O}/users/me/design-systems`}function pt(e){return`${O}/design-systems/${e}`}function xe(){return`${O}/users/me/socket-rooms`}function gt(){return`${O}/liveblocks/auth`}function ut(e){return`${O}/components/${e}`}function ft(e){return`${O}/organizations/${e}`}function He(e){return`${O}/organizations/${e}/projects`}function ve(e){return`${O}/organizations/${e}/design-systems`}var wt=ht.join(No.homedir(),".magicpath"),Ce=ht.join(wt,"session.json");function Ae(){try{if(!le.existsSync(Ce))return null;let e=le.readJsonSync(Ce);return e.accessToken&&e.refreshToken?e:null}catch{return null}}function bt(e){le.ensureDirSync(wt),le.writeJsonSync(Ce,e)}function ze(e,n){let o=Ae();bt({accessToken:e,refreshToken:n,user:o==null?void 0:o.user})}function X(){let e=Ae();return e?{accessToken:e.accessToken,refreshToken:e.refreshToken}:null}function It(){try{le.removeSync(Ce)}catch{}}function Ro(e){try{let n=Ae();n&&(n.user=e,bt(n))}catch{}}function $t(){let e=Ae();return(e==null?void 0:e.user)??null}function P(){let e=process.env.MAGICPATH_TOKEN;if(e)return{Authorization:`Bearer ${e}`,"X-Client-Type":"cli","X-Client-Version":z};let n=X();if(!n)throw new Error("Not logged in. Run `magicpath-ai login` first.");return{Authorization:`Bearer ${n.accessToken}`,"X-Client-Type":"cli","X-Client-Version":z}}function me(e){var t,r;let n=(t=e.subscription)!=null&&t.active?(r=e.subscription.type)!=null&&r.startsWith("PRO")?"Pro":"Creator":"Free",o={name:e.name||e.firstName||e.displayName,email:e.email,plan:n};return Ro(o),o}async function Ge(){let e=P(),n=await yt.get(Z(),{headers:e}),o=n.data.user??n.data;return me(o)}async function de(e){let n=await yt.get(Z(),{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 W(e,n){let o=await de(n),t=o.find(a=>a.id===e);if(t)return{id:t.id,name:t.name};let r=e.toLowerCase(),s=o.find(a=>a.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 jt=["#95D5B2","#74C69D","#52B788","#40916C","#2D6A4F","#1B4332"];function Oo(e){return te.hex(jt[Math.min(e,jt.length-1)])}var Je=te.hex("#2D6A4F"),ko=te.hex("#1B4332"),Mo=te.hex("#E8F5E9"),Ve=te.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"],Uo=["\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+" "+Uo[n]);function _o(e){return e.map((n,o)=>{let t=Oo(o),r="";for(let s of n)r+=s===" "?s:t(s);return r})}function xt(e){let n=!!X(),o=n?$t():null;console.log();for(let s of _o(Do))console.log(s);if(console.log(),n&&o){let s=o.plan?` \xB7 ${o.plan}`:"";console.log(" "+Je("\u25CF")+" "+te.bold(Mo(o.name??"MagicPath User"))+ko(" "+(o.email??"")+s))}else console.log(" "+Ve("\u25CB Not logged in \xB7 run")+" "+Je("magicpath-ai login"));console.log();let t=20,r=[["search <query>","Search components"],["add <name>","Add to project"],["list-projects","Your projects"],["setup-skills","Set up AI agents"]];for(let[s,a]of r)console.log(" "+Je(s.padEnd(t))+Ve(a));console.log(),console.log(" "+Ve(`v${e} \u2500 magicpath-ai --help`)),console.log()}import Te from"prompts";import Ft from"ora";import{z as re}from"zod";import se from"path";import Ko from"os";import qe from"fs-extra";import{pino as vt}from"pino";var oe=vt();function ne(){oe=vt({level:"debug"}),oe.debug({message:"DEBUG logger enabled. "})}var k={info:e=>{oe.info(e)},debug:e=>{oe.debug(e)},warn:e=>{oe.warn(e)},error:e=>{oe.error(e)}};import Wo from"axios";import Pe from"path";import Ho from"os";import pe from"fs-extra";import zo from"adm-zip";import{v4 as Go}from"uuid";async function Ct(e){let n=Ie("v1","components/repository"),o=`${Go()}.zip`,t=Pe.join(Ho.tmpdir(),o);try{let r=await Wo({url:n,params:{key:e},method:"GET",responseType:"stream"});return await pe.ensureDir(Pe.dirname(t)),await new Promise(async(s,a)=>{try{r.data.pipe(pe.createWriteStream(t)).on("error",a).once("close",()=>s(t))}catch(i){a(i)}}),t}catch{throw new p("Failed to download project. Make sure your key is valid.")}}function Ke(e){try{pe.removeSync(e)}catch{}}function At(e,n,o){try{let t=Pe.join(o,n),r=1;for(;pe.existsSync(t);)r++,t=Pe.join(o,`${n}-${r}`);return pe.mkdirSync(t,{recursive:!0}),new zo(e).extractAllTo(t,!0),Ke(e),t}catch{throw new p("Failed to extract project. Please try again.")}}import{execSync as Be}from"child_process";import Tt from"ora";import Pt from"fs-extra";import Jo from"path";function Et(){try{return Be("yarn --version",{stdio:"ignore"}),"yarn"}catch{return"npm"}}function St(e){let n=Et(),o=Tt(`\u{1F4E6} Installing dependencies using ${n}...`).start();try{Be(n==="yarn"?"yarn install":"npm install",{cwd:e,stdio:"ignore"}),o.succeed("Dependencies installed successfully!")}catch{throw o.fail("Failed to install dependencies"),new p("Failed to install dependencies. Please check your internet connection and try again.")}}function Vo(e){let n=Jo.join(e,"package.json");if(!Pt.existsSync(n))return new Set;try{let o=Pt.readJsonSync(n),t=new Set;return o.dependencies&&Object.keys(o.dependencies).forEach(r=>t.add(r)),o.devDependencies&&Object.keys(o.devDependencies).forEach(r=>t.add(r)),t}catch{return new Set}}function Nt(e,n){if(e.length===0)return{installed:[],skipped:[]};let o=Vo(n),t=e.filter(i=>!o.has(i)),r=e.filter(i=>o.has(i));if(t.length===0)return k.debug("All dependencies already installed"),{installed:[],skipped:r};let s=Et(),a=Tt(`\u{1F4E6} Installing ${t.length} package${t.length>1?"s":""} using ${s}...`).start();try{let i=t.join(" "),c=s==="yarn"?`yarn add ${i}`:`npm install ${i}`;return k.debug({command:c}),Be(c,{cwd:n,stdio:"ignore"}),a.succeed(`Installed ${t.length} package${t.length>1?"s":""}`),{installed:t,skipped:r}}catch{throw a.fail("Failed to install packages"),new p(`Failed to install packages: ${t.join(", ")}. Please install them manually.`)}}import{execSync as Rt}from"child_process";import Ot from"ora";function kt(e,n){let o={cursor:"Cursor",antigravity:"Antigravity",vscode:"VS Code",webstorm:"WebStorm"},t={cursor:["cursor","code"],antigravity:["agy","antigravity"],vscode:["code"],webstorm:["webstorm","web"]},r=Ot(`\u{1F680} Opening project in ${o[n]}...`).start(),s=!1;try{for(let a of t[n]){if(s)break;try{Rt(`${a} .`,{cwd:e,stdio:"ignore"}),s=!0}catch{s=!1}}if(!s)throw new Error("Failed to open with command.");r.succeed(`Project opened in ${o[n]}!`)}catch{r.fail(`Failed to open ${o[n]}`);let a={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,9 +62,9 @@ import{readFileSync as Dn}from"fs";import{dirname as _n,join as Ln}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 Rt(t){let n=process.platform,o;switch(n){case"darwin":o="open";break;case"win32":o="explorer";break;default:o="xdg-open";break}let r={darwin:"Finder",win32:"File Explorer",linux:"File Manager"}[n]||"File Manager",s=Et(`\u{1F4C1} Opening project in ${r}...`).start();try{Tt(`${o} "${t}"`,{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=re.object({key:re.string(),debug:re.boolean().default(!1),ide:re.enum(["cursor","antigravity","vscode","webstorm"]).optional(),dir:re.string().optional(),name:re.string().optional()});function Ot(t){t.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=>{let o;try{o=zo.parse(n)}catch{throw new Error("Invalid CLI options for clone command.")}o.debug&&ne();let e=x();e&&(!o.dir||!o.name)&&A(new Error("In JSON mode, --dir and --name are required for clone.")),R.debug({options:n}),R.debug({options:o});let r,s;if(o.dir&&o.name)r=se.resolve(o.dir),s=o.name,await qe.ensureDir(r);else{let g=Ho.homedir(),$=[{name:"Documents",path:se.join(g,"Documents")},{name:"Desktop",path:se.join(g,"Desktop")},{name:"Downloads",path:se.join(g,"Downloads")}],C=(await Promise.all($.map(async w=>{try{return await qe.pathExists(w.path)?w:null}catch{return null}}))).filter(w=>w!==null),f=[{title:`Right here (current folder: ${process.cwd()})`,value:process.cwd()},{title:`Home directory (${g})`,value:g}];C.forEach(w=>{f.push({title:w.name,value:w.path})}),f.push({title:"Other (specify custom path)",value:"custom"});let{targetDir:h}=await Pe({type:"select",name:"targetDir",message:"Where should we put your code?",choices:f,initial:0});if(r=h,h==="custom"){let{customPath:w}=await Pe({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 se.resolve(P),!0}catch{return"Please enter a valid path"}}});if(!w)throw new p("Project creation cancelled");r=se.resolve(w);try{await qe.ensureDir(r)}catch{throw new p(`Failed to create or access directory: ${r}`)}}if(!r)throw new p("Download cancelled");if(s=(await Pe({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=e?null:kt("\u{1F4E5} Downloading project...").start();try{i=await jt(o.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=e?null:kt("\u{1F4E6} Unpacking project...").start(),l;try{l=xt(i,s,r),a==null||a.succeed(`Project unpacked to ${s}`)}catch(g){throw a==null||a.fail("Failed to unpack project"),Ke(i),g instanceof p?g:new p("Something went wrong!")}try{St(l)}catch(g){throw g instanceof p?g:new p("Something went wrong!")}e&&j({projectDir:l});let u=[{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(o.ide){let g=u.findIndex($=>$.value===o.ide);g!==-1&&(d=g)}let y=await Pe({type:"select",name:"ide",message:"Which IDE would you like to open the project in?",choices:u,initial:d});if(y.ide&&y.ide!=="none")try{y.ide==="filemanager"?Rt(l):Nt(l,y.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(`
66
- \u{1F389} Done! Your project is ready to go at: ${l}`)})}import Ye from"prompts";import{z as U}from"zod";import K from"path";import an from"fs-extra";var J=class extends p{constructor(){super("You must be logged in to install components.")}};import Go from"ora";var Jo="\x1B[38;2;32;140;80m",Vo="\x1B[0m",Ko=`${Jo}\u2714${Vo}`;function E(t){let n=Go(t),o=n.stopAndPersist.bind(n);return n.succeed=e=>o({symbol:Ko,text:e}),n}import Mt from"axios";import V from"fs-extra";import q from"path";import{z as _}from"zod";var Bo=_.object({name:_.string(),path:_.string(),content:_.string()}),qo=_.object({data:_.object({name:_.string(),generatedName:_.string(),files:_.array(Bo),utils:_.object({content:_.string()}),dependencies:_.array(_.string())})});function Y(t){let n=t.match(/export\s+default\s+function\s+([A-Z][a-zA-Z0-9]*)/),o=t.match(/export\s+default\s+([A-Z][a-zA-Z0-9]*)\s*[;\n]/),e=t.match(/export\s+function\s+([A-Z][a-zA-Z0-9]*)/),r=t.match(/export\s+const\s+([A-Z][a-zA-Z0-9]*)\s*[=:]/),s=null,i=!1;if(n?(s=n[1],i=!0):o?(s=o[1],i=!0):e?s=e[1]:r&&(s=r[1]),!s)return null;let c=`${s}Props`,a=new RegExp(`(?:interface|type)\\s+${c}\\s*(?:=\\s*)?\\{([^}]*)\\}`,"s"),l=t.match(a),u=[],d=[];if(l){let g=l[1].split(/[;\n]/).filter($=>$.trim());for(let $ of g){let I=$.trim();if(!I||I.startsWith("//")||I.startsWith("/*"))continue;let C=I.match(/^(\w+)(\?)?:/);if(C){let f=C[1],h=!!C[2];if(f==="children")continue;h?d.push(f):u.push(f)}}}return{name:s,isDefault:i,propsType:l?c:void 0,requiredProps:u,optionalProps:d}}function ie(t,n){return t.isDefault?`import ${t.name} from '${n}';`:`import { ${t.name} } from '${n}';`}function ae(t){let{name:n,requiredProps:o,optionalProps:e}=t;if(o.length===0&&e.length===0)return`<${n} />`;let r=o.map(s=>`${s}={/* TODO */}`).join(" ");return r?`<${n} ${r} />`:`<${n} />`}function Zo(t){let{componentName:n,importPath:o,exportInfo:e,fileName:r}=t,s=[`# ${n}`,"","## Import","","```tsx"];if(e){if(s.push(ie(e,o)),s.push("```"),s.push(""),s.push("## Usage"),s.push(""),s.push("```tsx"),s.push(ae(e)),s.push("```"),e.requiredProps.length>0){s.push(""),s.push("## Required Props"),s.push("");for(let i of e.requiredProps)s.push(`- \`${i}\``)}if(e.optionalProps.length>0){s.push(""),s.push("## Optional Props"),s.push("");for(let i of e.optionalProps)s.push(`- \`${i}\``)}}else s.push(`import { ${r} } from '${o}';`),s.push("```");return s.push(""),s.join(`
67
- `)}function Ft(t,n){let o=Zo(n),e=q.join(t,"usage.md");V.writeFileSync(e,o,"utf8"),R.debug({message:"Wrote usage file",usagePath:e})}async function ge(t){var e,r,s;let n=it(t);R.debug({message:"Fetching component from registry",url:n});let o;try{o=S()}catch{throw new J}try{let i=await Mt.get(n,{headers:o});return qo.parse(i.data).data}catch(i){throw Mt.isAxiosError(i)?((e=i.response)==null?void 0:e.status)===401?new J:((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 "${t}" not found. Please check the name and try again.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai search <query>` to find available components."}):new p(`Failed to fetch component: ${i.message}`):new p("Failed to fetch component. Please check your internet connection and try again.")}}function Ut(t,n){let o=[];for(let e of t){let r=q.join(n,e.path);V.existsSync(r)&&o.push(e.path)}return o}function Xo(t,n=1){let o="../".repeat(n),e=t;return e=e.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}${o}${i}${c}`),e=e.replace(/(import\s*\(\s*['"])(\.\.\/)([^'"]+['"]\s*\))/g,(r,s,i,c)=>`${s}${o}${i}${c}`),e=e.replace(/(require\s*\(\s*['"])(\.\.\/)([^'"]+['"]\s*\))/g,(r,s,i,c)=>`${s}${o}${i}${c}`),e}function Dt(t,n,o=!1){V.ensureDirSync(n);for(let e of t){let r=q.join(n,e.path),s=q.dirname(r);V.ensureDirSync(s);let i=o?Xo(e.content):e.content;V.writeFileSync(r,i,"utf8"),R.debug({message:"Wrote file",filePath:r})}}function _t(t){let n=q.join(t,"utils.ts");if(!V.existsSync(n))return!1;try{return V.readFileSync(n,"utf8").includes("export function cn")}catch{return!1}}function Lt(t,n){V.ensureDirSync(n);let o=q.join(n,"utils.ts");V.writeFileSync(o,t,"utf8"),R.debug({message:"Wrote utils file",utilsPath:o})}var ue="src/components/magicpath",Yo="src/lib";function Te(t){return t.trim().replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"component"}function Ee(t,n=process.cwd()){let o=t||ue;return q.join(n,o)}function Wt(t=process.cwd()){return q.join(t,Yo)}import Qo from"http";import en from"ora";import Ze from"axios";import{exec as tn}from"child_process";var on=12e4,zt=`
65
+ \u{1F4D6} More help: https://www.jetbrains.com/help/webstorm/working-with-the-ide-features-from-command-line.html`};throw new p(a[n])}}function Mt(e){let n=process.platform,o;switch(n){case"darwin":o="open";break;case"win32":o="explorer";break;default:o="xdg-open";break}let r={darwin:"Finder",win32:"File Explorer",linux:"File Manager"}[n]||"File Manager",s=Ot(`\u{1F4C1} Opening project in ${r}...`).start();try{Rt(`${o} "${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 Bo=re.object({key:re.string(),debug:re.boolean().default(!1),ide:re.enum(["cursor","antigravity","vscode","webstorm"]).optional(),dir:re.string().optional(),name:re.string().optional()});function Ut(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=>{let o;try{o=Bo.parse(n)}catch{throw new Error("Invalid CLI options for clone command.")}o.debug&&ne();let t=x();t&&(!o.dir||!o.name)&&A(new Error("In JSON mode, --dir and --name are required for clone.")),k.debug({options:n}),k.debug({options:o});let r,s;if(o.dir&&o.name)r=se.resolve(o.dir),s=o.name,await qe.ensureDir(r);else{let g=Ko.homedir(),I=[{name:"Documents",path:se.join(g,"Documents")},{name:"Desktop",path:se.join(g,"Desktop")},{name:"Downloads",path:se.join(g,"Downloads")}],C=(await Promise.all(I.map(async w=>{try{return await qe.pathExists(w.path)?w:null}catch{return null}}))).filter(w=>w!==null),f=[{title:`Right here (current folder: ${process.cwd()})`,value:process.cwd()},{title:`Home directory (${g})`,value:g}];C.forEach(w=>{f.push({title:w.name,value:w.path})}),f.push({title:"Other (specify custom path)",value:"custom"});let{targetDir:h}=await Te({type:"select",name:"targetDir",message:"Where should we put your code?",choices:f,initial:0});if(r=h,h==="custom"){let{customPath:w}=await Te({type:"text",name:"customPath",message:"Enter the full path where you want to create your project:",initial:g,validate:T=>{if(!T)return"Please enter a path";try{return se.resolve(T),!0}catch{return"Please enter a valid path"}}});if(!w)throw new p("Project creation cancelled");r=se.resolve(w);try{await qe.ensureDir(r)}catch{throw new p(`Failed to create or access directory: ${r}`)}}if(!r)throw new p("Download cancelled");if(s=(await Te({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 a,i=t?null:Ft("\u{1F4E5} Downloading project...").start();try{a=await Ct(o.key),k.debug({filename:a}),i==null||i.succeed("Project downloaded")}catch(g){throw i==null||i.fail("Download failed"),g instanceof p?g:new p("Something went wrong!")}let c=t?null:Ft("\u{1F4E6} Unpacking project...").start(),l;try{l=At(a,s,r),c==null||c.succeed(`Project unpacked to ${s}`)}catch(g){throw c==null||c.fail("Failed to unpack project"),Ke(a),g instanceof p?g:new p("Something went wrong!")}try{St(l)}catch(g){throw g instanceof p?g:new p("Something went wrong!")}t&&j({projectDir:l});let u=[{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(o.ide){let g=u.findIndex(I=>I.value===o.ide);g!==-1&&(d=g)}let y=await Te({type:"select",name:"ide",message:"Which IDE would you like to open the project in?",choices:u,initial:d});if(y.ide&&y.ide!=="none")try{y.ide==="filemanager"?Mt(l):kt(l,y.ide)}catch(g){k.debug({err:g}),g instanceof p?console.log(g.message):console.log("\u26A0\uFE0F Opening failed, but your project is ready!")}console.log(`
66
+ \u{1F389} Done! Your project is ready to go at: ${l}`)})}import Ye from"prompts";import{z as U}from"zod";import K from"path";import pn from"fs-extra";var J=class extends p{constructor(){super("You must be logged in to install components.")}};import qo from"ora";var Zo="\x1B[38;2;32;140;80m",Xo="\x1B[0m",Yo=`${Zo}\u2714${Xo}`;function S(e){let n=qo(e),o=n.stopAndPersist.bind(n);return n.succeed=t=>o({symbol:Yo,text:t}),n}import Dt from"axios";import V from"fs-extra";import q from"path";import{z as _}from"zod";var Qo=_.object({name:_.string(),path:_.string(),content:_.string()}),en=_.object({data:_.object({name:_.string(),generatedName:_.string(),files:_.array(Qo),utils:_.object({content:_.string()}),dependencies:_.array(_.string())})});function Y(e){let n=e.match(/export\s+default\s+function\s+([A-Z][a-zA-Z0-9]*)/),o=e.match(/export\s+default\s+([A-Z][a-zA-Z0-9]*)\s*[;\n]/),t=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,a=!1;if(n?(s=n[1],a=!0):o?(s=o[1],a=!0):t?s=t[1]:r&&(s=r[1]),!s)return null;let i=`${s}Props`,c=new RegExp(`(?:interface|type)\\s+${i}\\s*(?:=\\s*)?\\{([^}]*)\\}`,"s"),l=e.match(c),u=[],d=[];if(l){let g=l[1].split(/[;\n]/).filter(I=>I.trim());for(let I of g){let $=I.trim();if(!$||$.startsWith("//")||$.startsWith("/*"))continue;let C=$.match(/^(\w+)(\?)?:/);if(C){let f=C[1],h=!!C[2];if(f==="children")continue;h?d.push(f):u.push(f)}}}return{name:s,isDefault:a,propsType:l?i:void 0,requiredProps:u,optionalProps:d}}function ie(e,n){return e.isDefault?`import ${e.name} from '${n}';`:`import { ${e.name} } from '${n}';`}function ae(e){let{name:n,requiredProps:o,optionalProps:t}=e;if(o.length===0&&t.length===0)return`<${n} />`;let r=o.map(s=>`${s}={/* TODO */}`).join(" ");return r?`<${n} ${r} />`:`<${n} />`}function tn(e){let{componentName:n,importPath:o,exportInfo:t,fileName:r}=e,s=[`# ${n}`,"","## Import","","```tsx"];if(t){if(s.push(ie(t,o)),s.push("```"),s.push(""),s.push("## Usage"),s.push(""),s.push("```tsx"),s.push(ae(t)),s.push("```"),t.requiredProps.length>0){s.push(""),s.push("## Required Props"),s.push("");for(let a of t.requiredProps)s.push(`- \`${a}\``)}if(t.optionalProps.length>0){s.push(""),s.push("## Optional Props"),s.push("");for(let a of t.optionalProps)s.push(`- \`${a}\``)}}else s.push(`import { ${r} } from '${o}';`),s.push("```");return s.push(""),s.join(`
67
+ `)}function _t(e,n){let o=tn(n),t=q.join(e,"usage.md");V.writeFileSync(t,o,"utf8"),k.debug({message:"Wrote usage file",usagePath:t})}async function ge(e){var t,r,s;let n=at(e);k.debug({message:"Fetching component from registry",url:n});let o;try{o=P()}catch{throw new J}try{let a=await Dt.get(n,{headers:o});return en.parse(a.data).data}catch(a){throw Dt.isAxiosError(a)?((t=a.response)==null?void 0:t.status)===401?new J:((r=a.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=a.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."}):new p(`Failed to fetch component: ${a.message}`):new p("Failed to fetch component. Please check your internet connection and try again.")}}function Lt(e,n){let o=[];for(let t of e){let r=q.join(n,t.path);V.existsSync(r)&&o.push(t.path)}return o}function on(e,n=1){let o="../".repeat(n),t=e;return t=t.replace(/((?:import|export)(?:\s+type)?\s+(?:(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)(?:\s*,\s*(?:\{[^}]*\}|\*\s+as\s+\w+|\w+))*\s+from\s+)?['"])(\.\.\/)([^'"]+['"])/g,(r,s,a,i)=>`${s}${o}${a}${i}`),t=t.replace(/(import\s*\(\s*['"])(\.\.\/)([^'"]+['"]\s*\))/g,(r,s,a,i)=>`${s}${o}${a}${i}`),t=t.replace(/(require\s*\(\s*['"])(\.\.\/)([^'"]+['"]\s*\))/g,(r,s,a,i)=>`${s}${o}${a}${i}`),t}function Wt(e,n,o=!1){V.ensureDirSync(n);for(let t of e){let r=q.join(n,t.path),s=q.dirname(r);V.ensureDirSync(s);let a=o?on(t.content):t.content;V.writeFileSync(r,a,"utf8"),k.debug({message:"Wrote file",filePath:r})}}function Ht(e){let n=q.join(e,"utils.ts");if(!V.existsSync(n))return!1;try{return V.readFileSync(n,"utf8").includes("export function cn")}catch{return!1}}function zt(e,n){V.ensureDirSync(n);let o=q.join(n,"utils.ts");V.writeFileSync(o,e,"utf8"),k.debug({message:"Wrote utils file",utilsPath:o})}var ue="src/components/magicpath",nn="src/lib";function Ee(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 Se(e,n=process.cwd()){let o=e||ue;return q.join(n,o)}function Gt(e=process.cwd()){return q.join(e,nn)}import rn from"http";import sn from"ora";import Ze from"axios";import{exec as an}from"child_process";var cn=12e4,Vt=`
68
68
  *{margin:0;padding:0;box-sizing:border-box}
69
69
  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}
70
70
  .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}
@@ -74,67 +74,68 @@ body{font-family:Geist,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;di
74
74
  .icon-box svg{width:2rem;height:2rem}
75
75
  h1{font-size:1.5rem;font-weight:600;margin-bottom:.5rem;text-align:center}
76
76
  p{color:#999;font-size:.9rem;text-align:center;max-width:24rem;line-height:1.5}
77
- `,nn='<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>',rn='<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>',sn=`<!DOCTYPE html>
77
+ `,ln='<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>',mn='<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>',dn=`<!DOCTYPE html>
78
78
  <html><head><meta charset="utf-8"><title>MagicPath CLI</title>
79
- <style>${zt}</style>
79
+ <style>${Vt}</style>
80
80
  </head><body><div class="card"><div class="gradient"></div><div class="content">
81
- <div class="icon-box">${nn}</div>
81
+ <div class="icon-box">${ln}</div>
82
82
  <h1>Logged in!</h1>
83
83
  <p>You can close this tab and return to your terminal.</p>
84
- </div></div></body></html>`,Ht=t=>`<!DOCTYPE html>
84
+ </div></div></body></html>`,Jt=e=>`<!DOCTYPE html>
85
85
  <html><head><meta charset="utf-8"><title>MagicPath CLI</title>
86
- <style>${zt}</style>
86
+ <style>${Vt}</style>
87
87
  </head><body><div class="card"><div class="gradient"></div><div class="content">
88
- <div class="icon-box">${rn}</div>
88
+ <div class="icon-box">${mn}</div>
89
89
  <h1>Login failed</h1>
90
- <p>${t}</p>
91
- </div></div></body></html>`;async function Xe(){return new Promise((t,n)=>{let o=!1,e,r=Qo.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 u=l.searchParams.get("code");if(!u){a.writeHead(400,{"Content-Type":"text/html"}),a.end(Ht("No authorization code received."));return}try{let y=await Ze.post(Fe("extension/tokens"),{token:u}),{access_token:g,refresh_token:$}=y.data;ze(g,$);try{await Ge()}catch{}a.writeHead(200,{"Content-Type":"text/html"}),a.end(sn),s(),i.succeed("Logged in successfully!"),o=!0,t(!0)}catch(y){console.error(y);let g=Ze.isAxiosError(y)&&((d=y.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(Ht(g)),s(),i.fail("Login failed"),o=!0,n(new p(g))}});function s(){clearTimeout(e),r.close()}r.listen(0,"127.0.0.1",()=>{let c=r.address();if(!c||typeof c=="string"){o=!0,n(new p("Failed to start local auth server."));return}let a=c.port,l=at(`/auth/cli?port=${a}`);console.log(`
90
+ <p>${e}</p>
91
+ </div></div></body></html>`;async function Xe(){return new Promise((e,n)=>{let o=!1,t,r=rn.createServer(async(i,c)=>{var d;let l=new URL(i.url||"/","http://localhost");if(l.pathname!=="/callback"){c.writeHead(404,{"Content-Type":"text/plain"}),c.end("Not found");return}let u=l.searchParams.get("code");if(!u){c.writeHead(400,{"Content-Type":"text/html"}),c.end(Jt("No authorization code received."));return}try{let y=await Ze.post(Fe("extension/tokens"),{token:u}),{access_token:g,refresh_token:I}=y.data;ze(g,I);try{await Ge()}catch{}c.writeHead(200,{"Content-Type":"text/html"}),c.end(dn),s(),a.succeed("Logged in successfully!"),o=!0,e(!0)}catch(y){console.error(y);let g=Ze.isAxiosError(y)&&((d=y.response)==null?void 0:d.status)===400?"Invalid or expired authorization code. Please try again.":"Failed to exchange code. Please try again.";c.writeHead(400,{"Content-Type":"text/html"}),c.end(Jt(g)),s(),a.fail("Login failed"),o=!0,n(new p(g))}});function s(){clearTimeout(t),r.close()}r.listen(0,"127.0.0.1",()=>{let i=r.address();if(!i||typeof i=="string"){o=!0,n(new p("Failed to start local auth server."));return}let c=i.port,l=ct(`/auth/cli?port=${c}`);console.log(`
92
92
  Opening your browser to log in...
93
93
  `),console.log(`If the browser doesn't open, visit: ${l}
94
- `);let u=process.platform;tn(`${u==="darwin"?"open":u==="win32"?"start":"xdg-open"} "${l}"`)});let i=en("Waiting for browser login...").start();e=setTimeout(()=>{o||(s(),i.fail("Login timed out"),console.log("\nTip: You can also log in with `magicpath-ai login --code <code>`."),o=!0,t(!1))},on)})}function Gt(t){t.command("login").description("Log in to your MagicPath account").option("--code <code>","Exchange an authorization code non-interactively").action(async n=>{try{if(n.code){let e=await Ze.post(Fe("extension/tokens"),{token:n.code}),{access_token:r,refresh_token:s}=e.data;ze(r,s);try{await Ge()}catch{}x()&&j({authenticated:!0,method:"code"}),console.log("Logged in successfully!");return}x()&&(process.env.MAGICPATH_TOKEN&&j({authenticated:!0,method:"environment"}),X()&&j({authenticated:!0,method:"stored"}),A(new Error("Not authenticated. Set MAGICPATH_TOKEN environment variable or run login interactively."))),await Xe()||console.log("Login cancelled.")}catch(o){throw x()&&A(o),o instanceof p&&(console.error(`
95
- ${o.message}`),process.exit(1)),o}}),t.command("logout").description("Log out of your MagicPath account").action(()=>{yt(),x()&&j({loggedOut:!0}),console.log("Logged out successfully.")})}var cn=U.object({yes:U.boolean().default(!1),overwrite:U.boolean().default(!1),path:U.string().optional(),debug:U.boolean().default(!1),dryRun:U.boolean().default(!1)}),xs=U.object({component:U.string(),generatedName:U.string(),filesWritten:U.array(U.string()),dependenciesInstalled:U.array(U.string()),importStatement:U.string().optional(),usage:U.string().optional(),dryRun:U.boolean()});function Jt(t){t.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: ${ue})`).option("-d, --debug","Enable debug logging",!1).option("--dry-run","Show what would happen without writing files",!1).action(async(n,o)=>{try{let e;try{e=cn.parse(o)}catch{throw new Error("Invalid CLI options for add command.")}e.debug&&ne();let r=x();r&&(e.yes=!0);let s=n.length>1;s&&(e.yes=!0),R.debug({generatedNames:n,options:e});let i=process.cwd(),c=K.join(i,"package.json");if(!an.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(`
94
+ `);let u=process.platform;an(`${u==="darwin"?"open":u==="win32"?"start":"xdg-open"} "${l}"`)});let a=sn("Waiting for browser login...").start();t=setTimeout(()=>{o||(s(),a.fail("Login timed out"),console.log("\nTip: You can also log in with `magicpath-ai login --code <code>`."),o=!0,e(!1))},cn)})}function Kt(e){e.command("login").description("Log in to your MagicPath account").option("--code <code>","Exchange an authorization code non-interactively").action(async n=>{try{if(n.code){let t=await Ze.post(Fe("extension/tokens"),{token:n.code}),{access_token:r,refresh_token:s}=t.data;ze(r,s);try{await Ge()}catch{}x()&&j({authenticated:!0,method:"code"}),console.log("Logged in successfully!");return}x()&&(process.env.MAGICPATH_TOKEN&&j({authenticated:!0,method:"environment"}),X()&&j({authenticated:!0,method:"stored"}),A(new Error("Not authenticated. Set MAGICPATH_TOKEN environment variable or run login interactively."))),await Xe()||console.log("Login cancelled.")}catch(o){throw x()&&A(o),o instanceof p&&(console.error(`
95
+ ${o.message}`),process.exit(1)),o}}),e.command("logout").description("Log out of your MagicPath account").action(()=>{It(),x()&&j({loggedOut:!0}),console.log("Logged out successfully.")})}var gn=U.object({yes:U.boolean().default(!1),overwrite:U.boolean().default(!1),path:U.string().optional(),debug:U.boolean().default(!1),dryRun:U.boolean().default(!1)}),Ts=U.object({component:U.string(),generatedName:U.string(),filesWritten:U.array(U.string()),dependenciesInstalled:U.array(U.string()),importStatement:U.string().optional(),usage:U.string().optional(),dryRun:U.boolean()});function Bt(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: ${ue})`).option("-d, --debug","Enable debug logging",!1).option("--dry-run","Show what would happen without writing files",!1).action(async(n,o)=>{try{let t;try{t=gn.parse(o)}catch{throw new Error("Invalid CLI options for add command.")}t.debug&&ne();let r=x();r&&(t.yes=!0);let s=n.length>1;s&&(t.yes=!0),k.debug({generatedNames:n,options:t});let a=process.cwd(),i=K.join(a,"package.json");if(!pn.existsSync(i))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 c=[];s&&!r&&console.log(`
96
96
  Adding ${n.length} components...
97
- `);for(let l of n)try{let u=r?null:E(`Fetching component "${l}"...`).start(),d;try{d=await ge(l),u==null||u.succeed(`Found component: ${d.name}`)}catch(v){if(v instanceof J){if(u==null||u.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:T}=await Ye({type:"confirm",name:"shouldLogin",message:"You need to be logged in to install components. Log in now?",initial:!0});if(!T){console.log("Installation cancelled.");return}if(!await Xe()){console.log("Installation cancelled.");return}let ee=E(`Fetching component "${l}"...`).start();try{d=await ge(l),ee.succeed(`Found component: ${d.name}`)}catch(ot){throw ee.fail("Failed to fetch component"),ot instanceof p?ot:new p("Something went wrong!")}}else{if(u==null||u.fail("Failed to fetch component"),s){let T=v instanceof p?v.message:"Something went wrong!";a.push({component:l,generatedName:l,filesWritten:[],dependenciesInstalled:[],dryRun:e.dryRun,error:T}),r||console.log(` \u26A0\uFE0F Skipping "${l}": ${T}`);continue}throw v instanceof p?v:new p("Something went wrong!")}}let y=Ee(e.path,i),g=Te(d.name),$=K.join(y,g),I=Wt(i);R.debug({basePath:y,componentFolderName:g,componentsPath:$,utilsPath:I});let C=Ut(d.files,$);if(C.length>0&&!e.overwrite)if(r||(console.log(`
98
- The following files already exist:`),C.forEach(v=>console.log(` - ${v}`))),e.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:e.dryRun,error:"Files already exist. Use --overwrite to replace."});continue}if(r)throw new p(`Files already exist: ${C.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 Ye({type:"confirm",name:"shouldOverwrite",message:"Do you want to overwrite these files?",initial:!1});if(!v){console.log("Installation cancelled.");return}}if(!e.yes&&C.length===0){console.log(`
99
- This will install:`),console.log(` Component: ${d.name}`),console.log(` Files: ${d.files.length} file(s) to ${K.relative(i,$)||"."}`),console.log(` Dependencies: ${d.dependencies.length} package(s)`);let{shouldProceed:v}=await Ye({type:"confirm",name:"shouldProceed",message:"Proceed with installation?",initial:!0});if(!v){console.log("Installation cancelled.");return}}let f=d.files.map(v=>K.relative(i,K.join($,v.path))),h=d.files[0],b,w;if(h){let v=h.name.replace(/\.tsx?$/,""),T=e.path?`@/${e.path}/${g}/${v}`:`@/components/magicpath/${g}/${v}`,M=Y(h.content);M?(b=ie(M,T),w=ae(M)):b=`import { ${v} } from '${T}';`}if(e.dryRun){let v=r?d.files.map(T=>({path:T.path,name:T.name,content:T.content})):void 0;!s&&r&&j({component:d.name,generatedName:d.generatedName,filesWritten:f,files:v,dependenciesInstalled:d.dependencies,importStatement:b,usage:w,dryRun:!0}),a.push({component:d.name,generatedName:d.generatedName,filesWritten:f,dependenciesInstalled:d.dependencies,importStatement:b,usage:w,dryRun:!0}),r||(console.log(`
100
- [Dry run] Would install:`),console.log(` Component: ${d.name}`),console.log(` Files: ${f.join(", ")}`),console.log(` Dependencies: ${d.dependencies.join(", ")||"none"}`),b&&console.log(` Import: ${b}`));continue}let P=r?null:E("Writing component files...").start();try{Dt(d.files,$,!0),P==null||P.succeed(`Wrote ${d.files.length} file(s) to ${K.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(!_t(I)&&d.utils.content){let v=r?null:E("Installing utilities...").start();try{Lt(d.utils.content,I),v==null||v.succeed(`Wrote utils.ts to ${K.relative(i,I)||"."}`)}catch(T){v==null||v.fail("Failed to write utils file"),R.debug({err:T}),r||console.log(" Warning: Could not write utils.ts. You may need to create it manually.")}}let N=[];if(d.dependencies.length>0)try{let{installed:v,skipped:T}=Pt(d.dependencies,i);N.push(...v),T.length>0&&R.debug({message:"Skipped already installed packages",skipped:T})}catch(v){v instanceof p&&(r||console.log(`
101
- \u26A0\uFE0F ${v.message}`))}if(a.push({component:d.name,generatedName:d.generatedName,filesWritten:f,dependenciesInstalled:N,importStatement:b,usage:w,dryRun:!1}),!s&&r&&j({component:d.name,generatedName:d.generatedName,filesWritten:f,dependenciesInstalled:N,importStatement:b,usage:w,dryRun:!1}),r||(console.log(`
97
+ `);for(let l of n)try{let u=r?null:S(`Fetching component "${l}"...`).start(),d;try{d=await ge(l),u==null||u.succeed(`Found component: ${d.name}`)}catch(v){if(v instanceof J){if(u==null||u.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:E}=await Ye({type:"confirm",name:"shouldLogin",message:"You need to be logged in to install components. Log in now?",initial:!0});if(!E){console.log("Installation cancelled.");return}if(!await Xe()){console.log("Installation cancelled.");return}let ee=S(`Fetching component "${l}"...`).start();try{d=await ge(l),ee.succeed(`Found component: ${d.name}`)}catch(nt){throw ee.fail("Failed to fetch component"),nt instanceof p?nt:new p("Something went wrong!")}}else{if(u==null||u.fail("Failed to fetch component"),s){let E=v instanceof p?v.message:"Something went wrong!";c.push({component:l,generatedName:l,filesWritten:[],dependenciesInstalled:[],dryRun:t.dryRun,error:E}),r||console.log(` \u26A0\uFE0F Skipping "${l}": ${E}`);continue}throw v instanceof p?v:new p("Something went wrong!")}}let y=Se(t.path,a),g=Ee(d.name),I=K.join(y,g),$=Gt(a);k.debug({basePath:y,componentFolderName:g,componentsPath:I,utilsPath:$});let C=Lt(d.files,I);if(C.length>0&&!t.overwrite)if(r||(console.log(`
98
+ The following files already exist:`),C.forEach(v=>console.log(` - ${v}`))),t.yes){if(s){r||console.log(` \u26A0\uFE0F Skipping "${d.name}": files already exist. Use --overwrite.`),c.push({component:d.name,generatedName:d.generatedName,filesWritten:[],dependenciesInstalled:[],dryRun:t.dryRun,error:"Files already exist. Use --overwrite to replace."});continue}if(r)throw new p(`Files already exist: ${C.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 Ye({type:"confirm",name:"shouldOverwrite",message:"Do you want to overwrite these files?",initial:!1});if(!v){console.log("Installation cancelled.");return}}if(!t.yes&&C.length===0){console.log(`
99
+ This will install:`),console.log(` Component: ${d.name}`),console.log(` Files: ${d.files.length} file(s) to ${K.relative(a,I)||"."}`),console.log(` Dependencies: ${d.dependencies.length} package(s)`);let{shouldProceed:v}=await Ye({type:"confirm",name:"shouldProceed",message:"Proceed with installation?",initial:!0});if(!v){console.log("Installation cancelled.");return}}let f=d.files.map(v=>K.relative(a,K.join(I,v.path))),h=d.files[0],b,w;if(h){let v=h.name.replace(/\.tsx?$/,""),E=t.path?`@/${t.path}/${g}/${v}`:`@/components/magicpath/${g}/${v}`,M=Y(h.content);M?(b=ie(M,E),w=ae(M)):b=`import { ${v} } from '${E}';`}if(t.dryRun){let v=r?d.files.map(E=>({path:E.path,name:E.name,content:E.content})):void 0;!s&&r&&j({component:d.name,generatedName:d.generatedName,filesWritten:f,files:v,dependenciesInstalled:d.dependencies,importStatement:b,usage:w,dryRun:!0}),c.push({component:d.name,generatedName:d.generatedName,filesWritten:f,dependenciesInstalled:d.dependencies,importStatement:b,usage:w,dryRun:!0}),r||(console.log(`
100
+ [Dry run] Would install:`),console.log(` Component: ${d.name}`),console.log(` Files: ${f.join(", ")}`),console.log(` Dependencies: ${d.dependencies.join(", ")||"none"}`),b&&console.log(` Import: ${b}`));continue}let T=r?null:S("Writing component files...").start();try{Wt(d.files,I,!0),T==null||T.succeed(`Wrote ${d.files.length} file(s) to ${K.relative(a,I)||"."}`)}catch{if(T==null||T.fail("Failed to write component files"),s){c.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(!Ht($)&&d.utils.content){let v=r?null:S("Installing utilities...").start();try{zt(d.utils.content,$),v==null||v.succeed(`Wrote utils.ts to ${K.relative(a,$)||"."}`)}catch(E){v==null||v.fail("Failed to write utils file"),k.debug({err:E}),r||console.log(" Warning: Could not write utils.ts. You may need to create it manually.")}}let R=[];if(d.dependencies.length>0)try{let{installed:v,skipped:E}=Nt(d.dependencies,a);R.push(...v),E.length>0&&k.debug({message:"Skipped already installed packages",skipped:E})}catch(v){v instanceof p&&(r||console.log(`
101
+ \u26A0\uFE0F ${v.message}`))}if(c.push({component:d.name,generatedName:d.generatedName,filesWritten:f,dependenciesInstalled:R,importStatement:b,usage:w,dryRun:!1}),!s&&r&&j({component:d.name,generatedName:d.generatedName,filesWritten:f,dependenciesInstalled:R,importStatement:b,usage:w,dryRun:!1}),r||(console.log(`
102
102
  \u2705 Successfully added "${d.name}" to your project!`),s||console.log(`
103
- Usage:`)),h){let v=h.name.replace(/\.tsx?$/,""),T=e.path?`@/${e.path}/${g}/${v}`:`@/components/magicpath/${g}/${v}`,M=Y(h.content);!s&&!r&&(M?(console.log(` ${ie(M,T)}`),console.log(""),console.log(` ${ae(M)}`),M.requiredProps.length>0&&(console.log(""),console.log(` Required props: ${M.requiredProps.join(", ")}`))):console.log(` import { ${v} } from '${T}';`));try{Ft($,{componentName:d.name,importPath:T,exportInfo:M,fileName:v}),!s&&!r&&console.log(`
104
- \u{1F4C4} Usage documentation written to ${K.relative(i,K.join($,"usage.md"))}`)}catch(ee){R.debug({err:ee})}}}catch(u){if(s){let d=u instanceof Error?u.message:String(u);a.push({component:l,generatedName:l,filesWritten:[],dependenciesInstalled:[],dryRun:e.dryRun,error:d}),r||console.log(` \u26A0\uFE0F Failed "${l}": ${d}`);continue}throw u}if(s){r&&j({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),u=a.filter(d=>d.error);console.log(`
105
- ${l.length} of ${a.length} component(s) added successfully.`),u.length>0&&console.log(` ${u.length} failed: ${u.map(d=>d.generatedName).join(", ")}`)}}catch(e){throw x()&&A(e),e instanceof p&&(console.error(`
106
- ${e.message}`),process.exit(1)),e}})}import Vt from"axios";function Kt(t){t.command("whoami").description("Show the currently authenticated user").action(async()=>{var o,e,r;let n=x();try{let s;try{s=S()}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 i=n?null:E("Fetching user info...").start();try{let c=await Vt.get(Z(),{headers:s}),a=c.data.user??c.data;i==null||i.succeed("Authenticated");let l=me(a);n&&j(a),console.log(`
107
- Name: ${l.name||"N/A"}`),console.log(` Email: ${l.email||"N/A"}`),a.id&&console.log(` ID: ${a.id}`),console.log(` Plan: ${l.plan}`)}catch(c){throw i==null||i.fail("Failed to fetch user info"),Vt.isAxiosError(c)?((o=c.response)==null?void 0:o.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."}):new p(`API error: ${(e=c.response)==null?void 0:e.status} ${(r=c.response)==null?void 0:r.statusText}`):c}}catch(s){throw n&&A(s),s instanceof p&&(console.error(`
108
- ${s.message}`),process.exit(1)),s}})}import Qe from"axios";import Ne from"axios";function Re(t){var o;let n=((o=t.data.data)==null?void 0:o.projects)??t.data.projects??t.data;return Array.isArray(n)?n:[]}async function G(t,n){if(n!=null&&n.personal){let c=await Ne.get(`${We()}`,{headers:t});return Re(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 Ne.get(`${He(n.orgId)}`,{headers:{...t,"X-Organization-ID":n.orgId}});return Re(c).map(a=>({...a,ownerType:"team",ownerName:n.orgName??""}))}let o=await de(t),e=[Ne.get(`${We()}`,{headers:t}).then(c=>Re(c).map(a=>{var l;return{...a,ownerType:"personal",ownerName:((l=a.owner)==null?void 0:l.email)??""}})),...o.map(c=>Ne.get(`${He(c.id)}`,{headers:{...t,"X-Organization-ID":c.id}}).then(a=>Re(a).map(l=>({...l,ownerType:"team",ownerName:c.name}))).catch(()=>[]))],s=(await Promise.all(e)).flat(),i=new Set;return s.filter(c=>{let a=String(c.id);return i.has(a)?!1:(i.add(a),!0)})}function Bt(t){t.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 o=x(),e=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=S()}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=o?null:E("Fetching projects...").start();try{let u;if(n.personal)u={personal:!0};else if(n.team){let b=await z(n.team,a);u={orgId:b.id,orgName:b.name}}let d=await G(a,u),y=d.length,g=d;if(r>0&&(g=g.slice(r)),e!==void 0&&(g=g.slice(0,e)),l==null||l.succeed(`Found ${y} project(s)`),o&&j({projects:g,pagination:{total:y,limit:e??y,offset:r,hasMore:r+g.length<y}}),g.length===0){console.log(`
109
- No projects found.`);return}console.log("");let $=Math.max(4,...g.map(b=>(b.name||"").length)),I=Math.max(9,...g.map(b=>b.ownerType==="personal"?8:(b.ownerName||"").length)),C=7,f=10,h=10;console.log(` ${"Name".padEnd($)} ${"Type".padEnd(C)} ${"Components".padEnd(f)} ${"Workspace".padEnd(I)} Updated`),console.log(` ${"\u2500".repeat($)} ${"\u2500".repeat(C)} ${"\u2500".repeat(f)} ${"\u2500".repeat(I)} ${"\u2500".repeat(h)}`);for(let b of g){let w=(b.name||"").padEnd($),P=(b.isLibrary?"library":"project").padEnd(C),F=String(b.componentCount??((s=b._count)==null?void 0:s.components)??"?").padEnd(f),N=(b.ownerType==="personal"?"Personal":b.ownerName||"").padEnd(I),v=b.updatedAt?new Date(b.updatedAt).toISOString().slice(0,10):"";console.log(` ${w} ${P} ${F} ${N} ${v}`)}e!==void 0&&r+g.length<y&&console.log(`
110
- Showing ${g.length} of ${y}. Use --offset ${r+g.length} to see more.`)}catch(u){throw l==null||l.fail("Failed to fetch projects"),u instanceof p?u:Qe.isAxiosError(u)?((i=u.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=u.response)==null?void 0:c.status}`):u}}catch(a){throw o&&A(a),a instanceof p&&(console.error(`
111
- ${a.message}`),process.exit(1)),a}}),t.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,o)=>{var s,i,c,a,l;let e=x(),r=parseInt(o.limit,10)||100;try{let u;try{u=S()}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=e?null:E("Fetching components...").start();try{let y=new URLSearchParams({limit:String(r),revisionStatus:"COMPLETED",sortBy:o.sortBy,order:o.order});o.after&&y.set("after",o.after),o.createdBy&&y.set("createdBy",o.createdBy);let g=`${$e(n)}?${y}`,$=await Qe.get(g,{headers:u}),I=((s=$.data.data)==null?void 0:s.components)??$.data.components??$.data,C=((i=$.data.data)==null?void 0:i.pagination)??$.data.pagination,f=Array.isArray(I)?I.length:0;if(d==null||d.succeed(`Found ${f} component(s)`),e&&j({components:I,pagination:C??{limit:r,hasNext:!1,lastId:null}}),!Array.isArray(I)||I.length===0){console.log(`
112
- No components found.`);return}console.log("");let h=Math.max(4,...I.map(w=>(w.name||"").length)),b=Math.max(14,...I.map(w=>(w.generatedName||"").length));console.log(` ${"Name".padEnd(h)} ${"Generated Name".padEnd(b)} ${"Rev".padEnd(4)} ${"Views".padEnd(6)} ${"Likes".padEnd(6)} ${"Remixes".padEnd(7)} ${"Updated".padEnd(10)} ID`),console.log(` ${"\u2500".repeat(h)} ${"\u2500".repeat(b)} ${"\u2500".repeat(4)} ${"\u2500".repeat(6)} ${"\u2500".repeat(6)} ${"\u2500".repeat(7)} ${"\u2500".repeat(10)} ${"\u2500".repeat(20)}`);for(let w of I){let P=(w.name||"").padEnd(h),F=(w.generatedName||"").padEnd(b),N=String(w.revisionCount??"?").padEnd(4),v=String(w.viewCount??0).padEnd(6),T=String(w.likeCount??0).padEnd(6),M=String(w.remixCount??0).padEnd(7),ee=w.updatedAt?new Date(w.updatedAt).toISOString().slice(0,10):"";console.log(` ${P} ${F} ${N} ${v} ${T} ${M} ${ee.padEnd(10)} ${w.id||""}`)}C!=null&&C.hasNext&&console.log(`
113
- More results available. Use --after ${C.lastId} to see the next page.`)}catch(y){throw d==null||d.fail("Failed to fetch components"),Qe.isAxiosError(y)?((c=y.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=y.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=y.response)==null?void 0:l.status}`):y}}catch(u){throw e&&A(u),u instanceof p&&(console.error(`
114
- ${u.message}`),process.exit(1)),u}})}import{z as m}from"zod";import{z as D}from"zod";var qt=D.object({generatedName:D.string().describe("The generated name of the component (e.g., wispy-river-5234)")}),Zt=D.object({component:D.string().describe("Component display name"),generatedName:D.string().describe("Component generated name"),files:D.array(D.object({path:D.string(),name:D.string(),content:D.string()})).describe("Component source files"),dependencies:D.array(D.string()).describe("Required packages"),importStatement:D.string().optional().describe("Import statement for the component"),usage:D.string().optional().describe("JSX usage example")});function Xt(t){t.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,o)=>{try{o.debug&&ne();let e=x();R.debug({generatedName:n,options:o});let r=e?null:E(`Fetching component "${n}"...`).start(),s;try{s=await ge(n),r==null||r.succeed(`Found component: ${s.name}`)}catch(d){throw r==null||r.fail("Failed to fetch component"),d instanceof J?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=Te(s.name),c=s.files[0],a,l;if(c){let d=c.name.replace(/\.tsx?$/,""),y=`@/components/magicpath/${i}/${d}`,g=Y(c.content);g?(a=ie(g,y),l=ae(g)):a=`import { ${d} } from '${y}';`}let u=s.files.map(d=>({path:d.path,name:d.name,content:d.content}));if(e){j({component:s.name,generatedName:s.generatedName,files:u,dependencies:s.dependencies,importStatement:a,usage:l});return}console.log(`
115
- 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(`
116
- ${"\u2500".repeat(60)}`),console.log(` ${d.path}`),console.log(`${"\u2500".repeat(60)}`),console.log(d.content)}catch(e){throw x()&&A(e),e instanceof p&&(console.error(`
117
- ${e.message}`),process.exit(1)),e}})}var ln=m.object({generatedName:m.string().describe("The generated name of the component (e.g., wispy-river-5234)"),yes:m.boolean().default(!1).describe("Skip confirmation prompts"),overwrite:m.boolean().default(!1).describe("Overwrite existing files"),path:m.string().optional().describe("Custom path for components (default: src/components/magicpath)"),dryRun:m.boolean().default(!1).describe("Show what would happen without writing files")}),mn=m.object({component:m.string().describe("Component display name"),generatedName:m.string().describe("Component generated name"),filesWritten:m.array(m.string()).describe("Paths of files written"),dependenciesInstalled:m.array(m.string()).describe("Packages installed"),importStatement:m.string().optional().describe("Import statement for the component"),usage:m.string().optional().describe("JSX usage example"),dryRun:m.boolean().describe("Whether this was a dry run")}),dn=m.object({key:m.string().describe("One-time access key"),dir:m.string().describe("Target directory"),name:m.string().describe("Project name")}),pn=m.object({projectDir:m.string().describe("Path to the created project")}),gn=m.object({id:m.string().optional(),displayName:m.string().optional(),email:m.string().optional()}),un=m.object({team:m.string().optional().describe("Team name or ID to filter by"),personal:m.boolean().optional().describe("Show only personal projects")}),fn=m.object({projects:m.array(m.object({id:m.string(),name:m.string(),isLibrary:m.boolean(),isSharingEnabled:m.boolean(),allowPublicListing:m.boolean(),createdAt:m.string(),updatedAt:m.string(),componentCount:m.number(),owner:m.object({displayName:m.string(),email:m.string()}).nullable(),isActive:m.boolean(),isDefaultLibrary:m.boolean(),ownerType:m.string().optional().describe('"personal" or "team"'),ownerName:m.string().optional().describe("User email for personal, team name for team projects")})),pagination:m.object({total:m.number(),limit:m.number(),offset:m.number(),hasMore:m.boolean()})}),hn=m.object({teams:m.array(m.object({id:m.string(),name:m.string(),role:m.string()}))}),yn=m.object({team:m.string().describe("Team name or ID (required)")}),wn=m.object({team:m.object({id:m.string(),name:m.string()}),members:m.array(m.object({id:m.string(),displayName:m.string().nullable(),email:m.string().nullable(),role:m.string()}))}),bn=m.object({projectId:m.string().describe("The project ID"),createdBy:m.string().optional().describe("Filter to components created or edited by this user ID")}),In=m.object({components:m.array(m.object({id:m.string(),name:m.string(),generatedName:m.string(),createdAt:m.string(),updatedAt:m.string(),parentId:m.string().nullable(),revisionCount:m.number(),viewCount:m.number(),likeCount:m.number(),remixCount:m.number(),previewImageUrl:m.string().nullable(),lastEditedBy:m.object({id:m.string(),displayName:m.string()}).nullable().optional().describe("User who last edited this component")})),pagination:m.object({limit:m.number(),hasNext:m.boolean(),lastId:m.string().nullable()})}),$n=m.object({generatedName:m.string().describe("The generated name of the component")}),jn=m.object({url:m.string().describe("Preview URL to open in a browser"),generatedName:m.string()}),xn=m.object({themes:m.array(m.object({id:m.string(),name:m.string(),isPublic:m.boolean(),createdAt:m.string(),updatedAt:m.string()}))}),vn=m.object({themeIdOrName:m.string().describe("Theme ID (numeric) or name (case-insensitive match)")}),Cn=m.object({id:m.string(),name:m.string(),theme:m.object({light:m.record(m.string(),m.string()),dark:m.record(m.string(),m.string())}),defaultTheme:m.string(),prompt:m.string().optional().describe("Styling instructions for AI agents"),fonts:m.record(m.string(),m.object({source:m.string(),weights:m.record(m.string(),m.object({fontId:m.string(),url:m.string(),format:m.string()})).optional()})).optional(),version:m.number()}),ke={view:{description:"Get the preview URL for a MagicPath component",input:$n,output:jn},add:{description:"Add a MagicPath component to your project",input:ln,output:mn},inspect:{description:"Inspect a MagicPath component's source code without installing",input:qt,output:Zt},clone:{description:"Clone/download a MagicPath project",input:dn,output:pn},whoami:{description:"Show the currently authenticated user",output:gn},"list-projects":{description:"List all projects (personal and team)",input:un,output:fn},"list-teams":{description:"List teams you belong to",output:hn},"list-members":{description:"List members of a team",input:yn,output:wn},"list-components":{description:"List components in a project",input:bn,output:In},"list-themes":{description:"List all themes (design systems) for the current user",output:xn},"get-theme":{description:"Get a theme definition with CSS variables, fonts, and styling prompt",input:vn,output:Cn},selection:{description:"Get the currently selected component(s) from the web app canvas",output:m.object({components:m.array(m.object({id:m.string(),name:m.string(),generatedName:m.string().nullable(),clientId:m.string(),projectId:m.string(),projectName:m.string()}))})}};function Oe(t){return fe(t)}function fe(t){let n=t._def;if(!n)return{};let o=n.typeName,e={};switch(n.description&&(e.description=n.description),o){case"ZodString":e.type="string";break;case"ZodNumber":e.type="number";break;case"ZodBoolean":e.type="boolean";break;case"ZodOptional":return fe(n.innerType);case"ZodDefault":return{...fe(n.innerType),default:n.defaultValue()};case"ZodArray":e.type="array",e.items=fe(n.type);break;case"ZodObject":{e.type="object",e.properties={};let r=[],s=n.shape();for(let[i,c]of Object.entries(s)){e.properties[i]=fe(c);let a=c._def;(a==null?void 0:a.typeName)!=="ZodOptional"&&(a==null?void 0:a.typeName)!=="ZodDefault"&&r.push(i)}r.length>0&&(e.required=r);break}default:e.type="string"}return e}function Yt(t){t.command("schema").description("Show JSON Schema for a command's input/output").argument("[command]","Command name (e.g., add, view)").option("--all","Show schemas for all commands").action((n,o)=>{if(o!=null&&o.all){let s={};for(let[i,c]of Object.entries(ke))s[i]={description:c.description,input:c.input?Oe(c.input):void 0,output:c.output?Oe(c.output):void 0};console.log(JSON.stringify(s,null,2));return}if(!n){console.log("Available commands:",Object.keys(ke).join(", ")),console.log(`
118
- Usage: magicpath-ai schema <command>`),console.log(" magicpath-ai schema --all");return}let e=ke[n];e||(console.error(`Unknown command: ${n}`),console.error("Available:",Object.keys(ke).join(", ")),process.exit(1));let r={command:n,description:e.description};e.input&&(r.input=Oe(e.input)),e.output&&(r.output=Oe(e.output)),console.log(JSON.stringify(r,null,2))})}import{execSync as An}from"child_process";function Qt(t){t.command("setup-skills").description("Set up MagicPath for AI agents").action(async()=>{console.log("Installing MagicPath skills..."),An("npx skills add https://github.com/MagicPathAI/agent-skills/tree/beta --skill magicpath -y",{stdio:"inherit"})})}import{exec as Sn}from"child_process";function Pn(t){return Ie("v1",t)}function eo(t){t.command("view").alias("view-component").description("Open a component preview in the browser").argument("<generatedName>","The generated name of the component (e.g., wispy-river-5234)").action(n=>{let o=Pn(n);x()&&j({url:o,generatedName:n});let e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Sn(`${e} ${o}`),console.log(`Opening ${o}`)})}import Tn from"axios";function to(t){t.command("info").description("Show project and auth status (useful for agent context injection)").action(async()=>{let n=x();try{let o=null,e=!1,r=null;process.env.MAGICPATH_TOKEN?(o="environment",e=!0,r=S()):X()&&(o="stored",e=!0,r=S());let s=null,i=null;if(e&&r)try{let l=await Tn.get(Z(),{headers:r}),u=l.data.user??l.data,d=me(u);s={id:u.id,name:d.name??"Unknown",email:d.email??""},i=(u.organizationUsers??[]).map(g=>({id:String(g.organization.id),name:g.organization.name,role:g.role}))}catch{}let c=null;if(e&&r)try{c=(await G(r)).map(u=>{var d;return{id:u.id,name:u.name,componentCount:u.componentCount??((d=u._count)==null?void 0:d.components)??0,ownerType:u.ownerType,ownerName:u.ownerName}})}catch{}if(n&&j({auth:{authenticated:e,method:o,user:s},teams:i,projects:c,cli:{version:H,commands:["add","view","search","inspect","list-projects","list-components","list-teams","list-members","list-themes","get-theme","list-installed","selection","active-project","code","login","logout","whoami","info","clone","setup-skills","schema"]}}),console.log(""),console.log(` MagicPath CLI v${H}`),console.log(""),e&&s?(console.log(` Authenticated: yes (${o})`),console.log(` User: ${s.name} <${s.email}>`)):e?(console.log(` Authenticated: yes (${o})`),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 u=l.ownerType==="personal"?"":` [${l.ownerName}]`;console.log(` - ${l.name} (${l.componentCount} components)${u}`)}}else e&&console.log(" Projects: none");console.log("")}catch(o){n&&A(o),console.error(`Error: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}})}import oo from"axios";function no(t){t.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,o)=>{var s,i;let e=x(),r=parseInt(o.limit,10)||20;try{if(o.team&&o.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=S()}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=e?null:E("Searching components...").start();try{let l;if(o.personal)l={personal:!0};else if(o.team){let h=await z(o.team,c);l={orgId:h.id,orgName:h.name}}let u=await G(c,l);if(u.length===0){a==null||a.succeed("No projects found"),e&&j([]),console.log(`
119
- No projects found.`);return}let d=await Promise.all(u.map(async h=>{var b;try{let w=`${$e(h.id)}?limit=100&revisionStatus=COMPLETED`,P=await oo.get(w,{headers:c}),F=((b=P.data.data)==null?void 0:b.components)??P.data.components??P.data;return{project:h,components:Array.isArray(F)?F:[]}}catch{return{project:h,components:[]}}})),y=n.toLowerCase(),g=[];for(let{project:h,components:b}of d){for(let w of b){if(g.length>=r)break;(w.name||"").toLowerCase().includes(y)&&g.push({name:w.name,generatedName:w.generatedName,id:w.id,projectName:h.name,projectId:h.id,previewImageUrl:w.previewImageUrl??null,ownerType:h.ownerType,ownerName:h.ownerName})}if(g.length>=r)break}if(a==null||a.succeed(`Found ${g.length} match(es) for "${n}"`),e&&j(g),g.length===0){console.log(`
120
- No components matching "${n}".`);return}console.log("");let $=Math.max(4,...g.map(h=>h.name.length)),I=Math.max(13,...g.map(h=>h.generatedName.length)),C=Math.max(7,...g.map(h=>h.projectName.length)),f=Math.max(9,...g.map(h=>h.ownerType==="personal"?8:h.ownerName.length));console.log(` ${"Name".padEnd($)} ${"Generated Name".padEnd(I)} ${"Project".padEnd(C)} ${"Workspace".padEnd(f)}`),console.log(` ${"\u2500".repeat($)} ${"\u2500".repeat(I)} ${"\u2500".repeat(C)} ${"\u2500".repeat(f)}`);for(let h of g){let b=h.ownerType==="personal"?"Personal":h.ownerName;console.log(` ${h.name.padEnd($)} ${h.generatedName.padEnd(I)} ${h.projectName.padEnd(C)} ${b.padEnd(f)}`)}}catch(l){throw a==null||a.fail("Search failed"),l instanceof p?l:oo.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 e&&A(c),c instanceof p&&(console.error(`
121
- ${c.message}`),process.exit(1)),c}})}import Q from"path";import ce from"fs-extra";function En(t,n){if(!ce.existsSync(t))return[];let o=ce.readdirSync(t,{withFileTypes:!0}),e=[];for(let r of o){if(!r.isDirectory())continue;let s=Q.join(t,r.name),i=ce.readdirSync(s).filter(u=>!ce.statSync(Q.join(s,u)).isDirectory()),c=i.find(u=>(u.endsWith(".tsx")||u.endsWith(".ts"))&&u!=="usage.md"&&!u.includes(".test.")&&!u.includes(".spec.")),a=null,l=null;if(c)try{let u=ce.readFileSync(Q.join(s,c),"utf8"),d=Y(u);if(d){a=d.name;let y=c.replace(/\.tsx?$/,""),g=`@/components/magicpath/${r.name}/${y}`;d.isDefault?l=`import ${d.name} from '${g}';`:l=`import { ${d.name} } from '${g}';`}}catch{}e.push({name:a||r.name,folder:r.name,path:Q.relative(n,s),files:i.filter(u=>u!=="usage.md"),exportName:a,importStatement:l})}return e}function ro(t){t.command("list-installed").description("List MagicPath components installed in the current project").option("-p, --path <path>",`Custom components path (default: ${ue})`).action(async n=>{let o=x();try{let e=process.cwd(),r=Ee(n.path,e);if(!ce.existsSync(r)){o&&j({components:[],total:0}),console.log(`
122
- No MagicPath components found at ${Q.relative(e,r)||r}`);return}let s=En(r,e);if(o&&j({components:s,total:s.length,componentsPath:Q.relative(e,r)}),s.length===0){console.log(`
103
+ Usage:`)),h){let v=h.name.replace(/\.tsx?$/,""),E=t.path?`@/${t.path}/${g}/${v}`:`@/components/magicpath/${g}/${v}`,M=Y(h.content);!s&&!r&&(M?(console.log(` ${ie(M,E)}`),console.log(""),console.log(` ${ae(M)}`),M.requiredProps.length>0&&(console.log(""),console.log(` Required props: ${M.requiredProps.join(", ")}`))):console.log(` import { ${v} } from '${E}';`));try{_t(I,{componentName:d.name,importPath:E,exportInfo:M,fileName:v}),!s&&!r&&console.log(`
104
+ \u{1F4C4} Usage documentation written to ${K.relative(a,K.join(I,"usage.md"))}`)}catch(ee){k.debug({err:ee})}}}catch(u){if(s){let d=u instanceof Error?u.message:String(u);c.push({component:l,generatedName:l,filesWritten:[],dependenciesInstalled:[],dryRun:t.dryRun,error:d}),r||console.log(` \u26A0\uFE0F Failed "${l}": ${d}`);continue}throw u}if(s){r&&j({results:c,total:c.length,succeeded:c.filter(d=>!d.error).length,failed:c.filter(d=>d.error).length});let l=c.filter(d=>!d.error),u=c.filter(d=>d.error);console.log(`
105
+ ${l.length} of ${c.length} component(s) added successfully.`),u.length>0&&console.log(` ${u.length} failed: ${u.map(d=>d.generatedName).join(", ")}`)}}catch(t){throw x()&&A(t),t instanceof p&&(console.error(`
106
+ ${t.message}`),process.exit(1)),t}})}import qt from"axios";function Zt(e){e.command("whoami").description("Show the currently authenticated user").action(async()=>{var o,t,r;let n=x();try{let s;try{s=P()}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=n?null:S("Fetching user info...").start();try{let i=await qt.get(Z(),{headers:s}),c=i.data.user??i.data;a==null||a.succeed("Authenticated");let l=me(c);n&&j(c),console.log(`
107
+ Name: ${l.name||"N/A"}`),console.log(` Email: ${l.email||"N/A"}`),c.id&&console.log(` ID: ${c.id}`),console.log(` Plan: ${l.plan}`)}catch(i){throw a==null||a.fail("Failed to fetch user info"),qt.isAxiosError(i)?((o=i.response)==null?void 0:o.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."}):new p(`API error: ${(t=i.response)==null?void 0:t.status} ${(r=i.response)==null?void 0:r.statusText}`):i}}catch(s){throw n&&A(s),s instanceof p&&(console.error(`
108
+ ${s.message}`),process.exit(1)),s}})}import Qe from"axios";import Ne from"axios";function Re(e){var o;let n=((o=e.data.data)==null?void 0:o.projects)??e.data.projects??e.data;return Array.isArray(n)?n:[]}async function G(e,n){if(n!=null&&n.personal){let i=await Ne.get(`${We()}`,{headers:e});return Re(i).map(c=>{var l;return{...c,ownerType:"personal",ownerName:((l=c.owner)==null?void 0:l.email)??""}})}if(n!=null&&n.orgId){let i=await Ne.get(`${He(n.orgId)}`,{headers:{...e,"X-Organization-ID":n.orgId}});return Re(i).map(c=>({...c,ownerType:"team",ownerName:n.orgName??""}))}let o=await de(e),t=[Ne.get(`${We()}`,{headers:e}).then(i=>Re(i).map(c=>{var l;return{...c,ownerType:"personal",ownerName:((l=c.owner)==null?void 0:l.email)??""}})),...o.map(i=>Ne.get(`${He(i.id)}`,{headers:{...e,"X-Organization-ID":i.id}}).then(c=>Re(c).map(l=>({...l,ownerType:"team",ownerName:i.name}))).catch(()=>[]))],s=(await Promise.all(t)).flat(),a=new Set;return s.filter(i=>{let c=String(i.id);return a.has(c)?!1:(a.add(c),!0)})}function Xt(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,a,i;let o=x(),t=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 c;try{c=P()}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=o?null:S("Fetching projects...").start();try{let u;if(n.personal)u={personal:!0};else if(n.team){let b=await W(n.team,c);u={orgId:b.id,orgName:b.name}}let d=await G(c,u),y=d.length,g=d;if(r>0&&(g=g.slice(r)),t!==void 0&&(g=g.slice(0,t)),l==null||l.succeed(`Found ${y} project(s)`),o&&j({projects:g,pagination:{total:y,limit:t??y,offset:r,hasMore:r+g.length<y}}),g.length===0){console.log(`
109
+ No projects found.`);return}console.log("");let I=Math.max(4,...g.map(b=>(b.name||"").length)),$=Math.max(9,...g.map(b=>b.ownerType==="personal"?8:(b.ownerName||"").length)),C=7,f=10,h=10;console.log(` ${"Name".padEnd(I)} ${"Type".padEnd(C)} ${"Components".padEnd(f)} ${"Workspace".padEnd($)} Updated`),console.log(` ${"\u2500".repeat(I)} ${"\u2500".repeat(C)} ${"\u2500".repeat(f)} ${"\u2500".repeat($)} ${"\u2500".repeat(h)}`);for(let b of g){let w=(b.name||"").padEnd(I),T=(b.isLibrary?"library":"project").padEnd(C),F=String(b.componentCount??((s=b._count)==null?void 0:s.components)??"?").padEnd(f),R=(b.ownerType==="personal"?"Personal":b.ownerName||"").padEnd($),v=b.updatedAt?new Date(b.updatedAt).toISOString().slice(0,10):"";console.log(` ${w} ${T} ${F} ${R} ${v}`)}t!==void 0&&r+g.length<y&&console.log(`
110
+ Showing ${g.length} of ${y}. Use --offset ${r+g.length} to see more.`)}catch(u){throw l==null||l.fail("Failed to fetch projects"),u instanceof p?u:Qe.isAxiosError(u)?((a=u.response)==null?void 0:a.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: ${(i=u.response)==null?void 0:i.status}`):u}}catch(c){throw o&&A(c),c instanceof p&&(console.error(`
111
+ ${c.message}`),process.exit(1)),c}}),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,o)=>{var s,a,i,c,l;let t=x(),r=parseInt(o.limit,10)||100;try{let u;try{u=P()}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=t?null:S("Fetching components...").start();try{let y=new URLSearchParams({limit:String(r),revisionStatus:"COMPLETED",sortBy:o.sortBy,order:o.order});o.after&&y.set("after",o.after),o.createdBy&&y.set("createdBy",o.createdBy);let g=`${$e(n)}?${y}`,I=await Qe.get(g,{headers:u}),$=((s=I.data.data)==null?void 0:s.components)??I.data.components??I.data,C=((a=I.data.data)==null?void 0:a.pagination)??I.data.pagination,f=Array.isArray($)?$.length:0;if(d==null||d.succeed(`Found ${f} component(s)`),t&&j({components:$,pagination:C??{limit:r,hasNext:!1,lastId:null}}),!Array.isArray($)||$.length===0){console.log(`
112
+ No components found.`);return}console.log("");let h=Math.max(4,...$.map(w=>(w.name||"").length)),b=Math.max(14,...$.map(w=>(w.generatedName||"").length));console.log(` ${"Name".padEnd(h)} ${"Generated Name".padEnd(b)} ${"Rev".padEnd(4)} ${"Views".padEnd(6)} ${"Likes".padEnd(6)} ${"Remixes".padEnd(7)} ${"Updated".padEnd(10)} ID`),console.log(` ${"\u2500".repeat(h)} ${"\u2500".repeat(b)} ${"\u2500".repeat(4)} ${"\u2500".repeat(6)} ${"\u2500".repeat(6)} ${"\u2500".repeat(7)} ${"\u2500".repeat(10)} ${"\u2500".repeat(20)}`);for(let w of $){let T=(w.name||"").padEnd(h),F=(w.generatedName||"").padEnd(b),R=String(w.revisionCount??"?").padEnd(4),v=String(w.viewCount??0).padEnd(6),E=String(w.likeCount??0).padEnd(6),M=String(w.remixCount??0).padEnd(7),ee=w.updatedAt?new Date(w.updatedAt).toISOString().slice(0,10):"";console.log(` ${T} ${F} ${R} ${v} ${E} ${M} ${ee.padEnd(10)} ${w.id||""}`)}C!=null&&C.hasNext&&console.log(`
113
+ More results available. Use --after ${C.lastId} to see the next page.`)}catch(y){throw d==null||d.fail("Failed to fetch components"),Qe.isAxiosError(y)?((i=y.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."}):((c=y.response)==null?void 0:c.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=y.response)==null?void 0:l.status}`):y}}catch(u){throw t&&A(u),u instanceof p&&(console.error(`
114
+ ${u.message}`),process.exit(1)),u}})}import{z as m}from"zod";import{z as D}from"zod";var Yt=D.object({generatedName:D.string().describe("The generated name of the component (e.g., wispy-river-5234)")}),Qt=D.object({component:D.string().describe("Component display name"),generatedName:D.string().describe("Component generated name"),files:D.array(D.object({path:D.string(),name:D.string(),content:D.string()})).describe("Component source files"),dependencies:D.array(D.string()).describe("Required packages"),importStatement:D.string().optional().describe("Import statement for the component"),usage:D.string().optional().describe("JSX usage example")});function eo(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,o)=>{try{o.debug&&ne();let t=x();k.debug({generatedName:n,options:o});let r=t?null:S(`Fetching component "${n}"...`).start(),s;try{s=await ge(n),r==null||r.succeed(`Found component: ${s.name}`)}catch(d){throw r==null||r.fail("Failed to fetch component"),d instanceof J?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 a=Ee(s.name),i=s.files[0],c,l;if(i){let d=i.name.replace(/\.tsx?$/,""),y=`@/components/magicpath/${a}/${d}`,g=Y(i.content);g?(c=ie(g,y),l=ae(g)):c=`import { ${d} } from '${y}';`}let u=s.files.map(d=>({path:d.path,name:d.name,content:d.content}));if(t){j({component:s.name,generatedName:s.generatedName,files:u,dependencies:s.dependencies,importStatement:c,usage:l});return}console.log(`
115
+ Component: ${s.name}`),console.log(` Files: ${s.files.map(d=>d.path).join(", ")}`),console.log(` Dependencies: ${s.dependencies.join(", ")||"none"}`),c&&console.log(` Import: ${c}`);for(let d of s.files)console.log(`
116
+ ${"\u2500".repeat(60)}`),console.log(` ${d.path}`),console.log(`${"\u2500".repeat(60)}`),console.log(d.content)}catch(t){throw x()&&A(t),t instanceof p&&(console.error(`
117
+ ${t.message}`),process.exit(1)),t}})}var un=m.object({generatedName:m.string().describe("The generated name of the component (e.g., wispy-river-5234)"),yes:m.boolean().default(!1).describe("Skip confirmation prompts"),overwrite:m.boolean().default(!1).describe("Overwrite existing files"),path:m.string().optional().describe("Custom path for components (default: src/components/magicpath)"),dryRun:m.boolean().default(!1).describe("Show what would happen without writing files")}),fn=m.object({component:m.string().describe("Component display name"),generatedName:m.string().describe("Component generated name"),filesWritten:m.array(m.string()).describe("Paths of files written"),dependenciesInstalled:m.array(m.string()).describe("Packages installed"),importStatement:m.string().optional().describe("Import statement for the component"),usage:m.string().optional().describe("JSX usage example"),dryRun:m.boolean().describe("Whether this was a dry run")}),hn=m.object({key:m.string().describe("One-time access key"),dir:m.string().describe("Target directory"),name:m.string().describe("Project name")}),yn=m.object({projectDir:m.string().describe("Path to the created project")}),wn=m.object({id:m.string().optional(),displayName:m.string().optional(),email:m.string().optional()}),bn=m.object({team:m.string().optional().describe("Team name or ID to filter by"),personal:m.boolean().optional().describe("Show only personal projects")}),In=m.object({projects:m.array(m.object({id:m.string(),name:m.string(),isLibrary:m.boolean(),isSharingEnabled:m.boolean(),allowPublicListing:m.boolean(),createdAt:m.string(),updatedAt:m.string(),componentCount:m.number(),owner:m.object({displayName:m.string(),email:m.string()}).nullable(),isActive:m.boolean(),isDefaultLibrary:m.boolean(),ownerType:m.string().optional().describe('"personal" or "team"'),ownerName:m.string().optional().describe("User email for personal, team name for team projects")})),pagination:m.object({total:m.number(),limit:m.number(),offset:m.number(),hasMore:m.boolean()})}),$n=m.object({teams:m.array(m.object({id:m.string(),name:m.string(),role:m.string()}))}),jn=m.object({team:m.string().describe("Team name or ID (required)")}),xn=m.object({team:m.object({id:m.string(),name:m.string()}),members:m.array(m.object({id:m.string(),displayName:m.string().nullable(),email:m.string().nullable(),role:m.string()}))}),vn=m.object({projectId:m.string().describe("The project ID"),createdBy:m.string().optional().describe("Filter to components created or edited by this user ID")}),Cn=m.object({components:m.array(m.object({id:m.string(),name:m.string(),generatedName:m.string(),createdAt:m.string(),updatedAt:m.string(),parentId:m.string().nullable(),revisionCount:m.number(),viewCount:m.number(),likeCount:m.number(),remixCount:m.number(),previewImageUrl:m.string().nullable(),lastEditedBy:m.object({id:m.string(),displayName:m.string()}).nullable().optional().describe("User who last edited this component")})),pagination:m.object({limit:m.number(),hasNext:m.boolean(),lastId:m.string().nullable()})}),An=m.object({generatedName:m.string().describe("The generated name of the component")}),Pn=m.object({url:m.string().describe("Preview URL to open in a browser"),generatedName:m.string()}),Tn=m.object({themes:m.array(m.object({id:m.string(),name:m.string(),isPublic:m.boolean(),createdAt:m.string(),updatedAt:m.string()}))}),En=m.object({themeIdOrName:m.string().describe("Theme ID (numeric) or name (case-insensitive match)")}),Sn=m.object({id:m.string(),name:m.string(),theme:m.object({light:m.record(m.string(),m.string()),dark:m.record(m.string(),m.string())}),defaultTheme:m.string(),prompt:m.string().optional().describe("Styling instructions for AI agents"),fonts:m.record(m.string(),m.object({source:m.string(),weights:m.record(m.string(),m.object({fontId:m.string(),url:m.string(),format:m.string()})).optional()})).optional(),version:m.number()}),Oe={view:{description:"Get the preview URL for a MagicPath component",input:An,output:Pn},add:{description:"Add a MagicPath component to your project",input:un,output:fn},inspect:{description:"Inspect a MagicPath component's source code without installing",input:Yt,output:Qt},clone:{description:"Clone/download a MagicPath project",input:hn,output:yn},whoami:{description:"Show the currently authenticated user",output:wn},"list-projects":{description:"List all projects (personal and team)",input:bn,output:In},"list-teams":{description:"List teams you belong to",output:$n},"list-members":{description:"List members of a team",input:jn,output:xn},"list-components":{description:"List components in a project",input:vn,output:Cn},"list-themes":{description:"List all themes (design systems) for the current user",output:Tn},"get-theme":{description:"Get a theme definition with CSS variables, fonts, and styling prompt",input:En,output:Sn},selection:{description:"Get the currently selected component(s) from the web app canvas",output:m.object({components:m.array(m.object({id:m.string(),name:m.string(),generatedName:m.string().nullable(),clientId:m.string(),projectId:m.string(),projectName:m.string()}))})}};function ke(e){return fe(e)}function fe(e){let n=e._def;if(!n)return{};let o=n.typeName,t={};switch(n.description&&(t.description=n.description),o){case"ZodString":t.type="string";break;case"ZodNumber":t.type="number";break;case"ZodBoolean":t.type="boolean";break;case"ZodOptional":return fe(n.innerType);case"ZodDefault":return{...fe(n.innerType),default:n.defaultValue()};case"ZodArray":t.type="array",t.items=fe(n.type);break;case"ZodObject":{t.type="object",t.properties={};let r=[],s=n.shape();for(let[a,i]of Object.entries(s)){t.properties[a]=fe(i);let c=i._def;(c==null?void 0:c.typeName)!=="ZodOptional"&&(c==null?void 0:c.typeName)!=="ZodDefault"&&r.push(a)}r.length>0&&(t.required=r);break}default:t.type="string"}return t}function to(e){e.command("schema").description("Show JSON Schema for a command's input/output").argument("[command]","Command name (e.g., add, view)").option("--all","Show schemas for all commands").action((n,o)=>{if(o!=null&&o.all){let s={};for(let[a,i]of Object.entries(Oe))s[a]={description:i.description,input:i.input?ke(i.input):void 0,output:i.output?ke(i.output):void 0};console.log(JSON.stringify(s,null,2));return}if(!n){console.log("Available commands:",Object.keys(Oe).join(", ")),console.log(`
118
+ Usage: magicpath-ai schema <command>`),console.log(" magicpath-ai schema --all");return}let t=Oe[n];t||(console.error(`Unknown command: ${n}`),console.error("Available:",Object.keys(Oe).join(", ")),process.exit(1));let r={command:n,description:t.description};t.input&&(r.input=ke(t.input)),t.output&&(r.output=ke(t.output)),console.log(JSON.stringify(r,null,2))})}import{execSync as Nn}from"child_process";function oo(e){e.command("setup-skills").description("Set up MagicPath for AI agents").action(async()=>{console.log("Installing MagicPath skills..."),Nn("npx skills add https://github.com/MagicPathAI/agent-skills/tree/beta --skill magicpath -y",{stdio:"inherit"})})}import{exec as Rn}from"child_process";function On(e){return Ie("v1",e)}function no(e){e.command("view").alias("view-component").description("Open a component preview in the browser").argument("<generatedName>","The generated name of the component (e.g., wispy-river-5234)").action(n=>{let o=On(n);x()&&j({url:o,generatedName:n});let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Rn(`${t} ${o}`),console.log(`Opening ${o}`)})}import kn from"axios";function ro(e){e.command("info").description("Show project and auth status (useful for agent context injection)").action(async()=>{let n=x();try{let o=null,t=!1,r=null;process.env.MAGICPATH_TOKEN?(o="environment",t=!0,r=P()):X()&&(o="stored",t=!0,r=P());let s=null,a=null;if(t&&r)try{let l=await kn.get(Z(),{headers:r}),u=l.data.user??l.data,d=me(u);s={id:u.id,name:d.name??"Unknown",email:d.email??""},a=(u.organizationUsers??[]).map(g=>({id:String(g.organization.id),name:g.organization.name,role:g.role}))}catch{}let i=null;if(t&&r)try{i=(await G(r)).map(u=>{var d;return{id:u.id,name:u.name,componentCount:u.componentCount??((d=u._count)==null?void 0:d.components)??0,ownerType:u.ownerType,ownerName:u.ownerName}})}catch{}if(n&&j({auth:{authenticated:t,method:o,user:s},teams:a,projects:i,cli:{version:z,commands:["add","view","search","inspect","list-projects","list-components","list-teams","list-members","list-themes","get-theme","list-installed","selection","active-project","code","login","logout","whoami","info","clone","setup-skills","schema"]}}),console.log(""),console.log(` MagicPath CLI v${z}`),console.log(""),t&&s?(console.log(` Authenticated: yes (${o})`),console.log(` User: ${s.name} <${s.email}>`)):t?(console.log(` Authenticated: yes (${o})`),console.log(" User: (could not fetch)")):(console.log(" Authenticated: no"),console.log(" Run `magicpath-ai login` to authenticate.")),a&&a.length>0){console.log(""),console.log(` Teams: ${a.length}`);for(let l of a)console.log(` - ${l.name} (${l.role.toLowerCase()})`)}if(console.log(""),i&&i.length>0){console.log(` Projects: ${i.length}`);for(let l of i){let u=l.ownerType==="personal"?"":` [${l.ownerName}]`;console.log(` - ${l.name} (${l.componentCount} components)${u}`)}}else t&&console.log(" Projects: none");console.log("")}catch(o){n&&A(o),console.error(`Error: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}})}import so from"axios";function io(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,o)=>{var s,a;let t=x(),r=parseInt(o.limit,10)||20;try{if(o.team&&o.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 i;try{i=P()}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:S("Searching components...").start();try{let l;if(o.personal)l={personal:!0};else if(o.team){let h=await W(o.team,i);l={orgId:h.id,orgName:h.name}}let u=await G(i,l);if(u.length===0){c==null||c.succeed("No projects found"),t&&j([]),console.log(`
119
+ No projects found.`);return}let d=await Promise.all(u.map(async h=>{var b;try{let w=`${$e(h.id)}?limit=100&revisionStatus=COMPLETED`,T=await so.get(w,{headers:i}),F=((b=T.data.data)==null?void 0:b.components)??T.data.components??T.data;return{project:h,components:Array.isArray(F)?F:[]}}catch{return{project:h,components:[]}}})),y=n.toLowerCase(),g=[];for(let{project:h,components:b}of d){for(let w of b){if(g.length>=r)break;(w.name||"").toLowerCase().includes(y)&&g.push({name:w.name,generatedName:w.generatedName,id:w.id,projectName:h.name,projectId:h.id,previewImageUrl:w.previewImageUrl??null,ownerType:h.ownerType,ownerName:h.ownerName})}if(g.length>=r)break}if(c==null||c.succeed(`Found ${g.length} match(es) for "${n}"`),t&&j(g),g.length===0){console.log(`
120
+ No components matching "${n}".`);return}console.log("");let I=Math.max(4,...g.map(h=>h.name.length)),$=Math.max(13,...g.map(h=>h.generatedName.length)),C=Math.max(7,...g.map(h=>h.projectName.length)),f=Math.max(9,...g.map(h=>h.ownerType==="personal"?8:h.ownerName.length));console.log(` ${"Name".padEnd(I)} ${"Generated Name".padEnd($)} ${"Project".padEnd(C)} ${"Workspace".padEnd(f)}`),console.log(` ${"\u2500".repeat(I)} ${"\u2500".repeat($)} ${"\u2500".repeat(C)} ${"\u2500".repeat(f)}`);for(let h of g){let b=h.ownerType==="personal"?"Personal":h.ownerName;console.log(` ${h.name.padEnd(I)} ${h.generatedName.padEnd($)} ${h.projectName.padEnd(C)} ${b.padEnd(f)}`)}}catch(l){throw c==null||c.fail("Search failed"),l instanceof p?l:so.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: ${(a=l.response)==null?void 0:a.status}`):l}}catch(i){throw t&&A(i),i instanceof p&&(console.error(`
121
+ ${i.message}`),process.exit(1)),i}})}import Q from"path";import ce from"fs-extra";function Mn(e,n){if(!ce.existsSync(e))return[];let o=ce.readdirSync(e,{withFileTypes:!0}),t=[];for(let r of o){if(!r.isDirectory())continue;let s=Q.join(e,r.name),a=ce.readdirSync(s).filter(u=>!ce.statSync(Q.join(s,u)).isDirectory()),i=a.find(u=>(u.endsWith(".tsx")||u.endsWith(".ts"))&&u!=="usage.md"&&!u.includes(".test.")&&!u.includes(".spec.")),c=null,l=null;if(i)try{let u=ce.readFileSync(Q.join(s,i),"utf8"),d=Y(u);if(d){c=d.name;let y=i.replace(/\.tsx?$/,""),g=`@/components/magicpath/${r.name}/${y}`;d.isDefault?l=`import ${d.name} from '${g}';`:l=`import { ${d.name} } from '${g}';`}}catch{}t.push({name:c||r.name,folder:r.name,path:Q.relative(n,s),files:a.filter(u=>u!=="usage.md"),exportName:c,importStatement:l})}return t}function ao(e){e.command("list-installed").description("List MagicPath components installed in the current project").option("-p, --path <path>",`Custom components path (default: ${ue})`).action(async n=>{let o=x();try{let t=process.cwd(),r=Se(n.path,t);if(!ce.existsSync(r)){o&&j({components:[],total:0}),console.log(`
122
+ No MagicPath components found at ${Q.relative(t,r)||r}`);return}let s=Mn(r,t);if(o&&j({components:s,total:s.length,componentsPath:Q.relative(t,r)}),s.length===0){console.log(`
123
123
  No MagicPath components installed.`);return}console.log(`
124
- ${s.length} component(s) installed in ${Q.relative(e,r)}:
125
- `);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(e){throw o&&A(e),e instanceof p&&(console.error(`
126
- ${e.message}`),process.exit(1)),e}})}import so from"axios";function io(t){t.command("list-themes").description("List all themes (design systems)").option("--team <nameOrId>","List themes for a specific team").action(async n=>{var e,r,s;let o=x();try{let i;try{i=S()}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=o?null:E("Fetching themes...").start();try{let a=je(),l=i;if(n.team){let f=await z(n.team,i);a=ve(f.id),l={...i,"X-Organization-ID":f.id}}let u=await so.get(a,{headers:l}),d=((e=u.data.data)==null?void 0:e.design_systems)??u.data.design_systems??u.data,y=Array.isArray(d)?d:[];if(c==null||c.succeed(`Found ${y.length} theme(s)`),o&&j({themes:y.map(f=>({id:String(f.id),name:f.name,isPublic:f.isPublic,createdAt:f.createdAt,updatedAt:f.updatedAt}))}),y.length===0){console.log(`
127
- No themes found.`);return}console.log("");let g=Math.max(4,...y.map(f=>(f.name||"").length)),$=Math.max(2,...y.map(f=>String(f.id).length)),I=6,C=10;console.log(` ${"Name".padEnd(g)} ${"ID".padEnd($)} ${"Public".padEnd(I)} Updated`),console.log(` ${"\u2500".repeat(g)} ${"\u2500".repeat($)} ${"\u2500".repeat(I)} ${"\u2500".repeat(C)}`);for(let f of y){let h=(f.name||"").padEnd(g),b=String(f.id).padEnd($),w=(f.isPublic?"yes":"no").padEnd(I),P=f.updatedAt?new Date(f.updatedAt).toISOString().slice(0,10):"";console.log(` ${h} ${b} ${w} ${P}`)}}catch(a){throw c==null||c.fail("Failed to fetch themes"),so.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 o&&A(i),i instanceof p&&(console.error(`
128
- ${i.message}`),process.exit(1)),i}})}import et from"axios";function ao(t){t.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,o)=>{var r,s,i,c,a,l,u;let e=x();try{let d;try{d=S()}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 y=e?null:E("Fetching theme...").start();try{let g=n,$;if(!/^\d+$/.test(n)){let b=je(),w=d;if(o.team){let M=await z(o.team,d);b=ve(M.id),w={...d,"X-Organization-ID":M.id}}let P=await et.get(b,{headers:w}),F=((r=P.data.data)==null?void 0:r.design_systems)??P.data.design_systems??P.data,N=Array.isArray(F)?F:[],v=n.toLowerCase(),T=N.find(M=>(M.name||"").toLowerCase()===v);if(!T)throw new p(`Theme "${n}" not found.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai list-themes` to see available themes."});g=String(T.id),$=T.name}let I=await et.get(lt(g),{headers:d}),C=((s=I.data.data)==null?void 0:s.design_system)??I.data.design_system,f=C.name??$??g,h=C.data;y==null||y.succeed(`Theme: ${f}`),e&&j({id:String(C.id??g),name:f,theme:h.theme,defaultTheme:h.defaultTheme,prompt:h.prompt,fonts:h.fonts,version:h.version}),console.log(""),console.log(` Name: ${f}`),console.log(` ID: ${C.id??g}`),console.log(` Default Theme: ${h.defaultTheme??"light"}`),h.prompt&&console.log(` Prompt: ${h.prompt}`);for(let b of["light","dark"]){let w=(i=h.theme)==null?void 0:i[b];if(w&&Object.keys(w).length>0){console.log(`
129
- ${b.charAt(0).toUpperCase()+b.slice(1)} Theme Variables:`);let P=Math.max(8,...Object.keys(w).map(F=>F.length));console.log(` ${"Variable".padEnd(P)} Value`),console.log(` ${"\u2500".repeat(P)} ${"\u2500".repeat(30)}`);for(let[F,N]of Object.entries(w))console.log(` ${F.padEnd(P)} ${N}`)}}if(h.fonts&&Object.keys(h.fonts).length>0){console.log(`
130
- Fonts:`);for(let[b,w]of Object.entries(h.fonts)){let P=w.weights?Object.keys(w.weights).join(", "):"default";console.log(` ${b} (${w.source}, weights: ${P})`)}}}catch(g){throw y==null||y.fail("Failed to fetch theme"),et.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: ${(u=g.response)==null?void 0:u.status}`):(g instanceof p,g)}}catch(d){throw e&&A(d),d instanceof p&&(console.error(`
131
- ${d.message}`),process.exit(1)),d}})}import tt from"axios";import{createClient as Nn}from"@liveblocks/client";import Rn from"ws";function co(t){let n=mt();return Nn({polyfills:{fetch,WebSocket:Rn},authEndpoint:async o=>await(await fetch(n,{method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify({room:o})})).json()})}async function lo(t,n,o=1e4){let{room:e,leave:r}=t.enterRoom(n,{initialPresence:{}});return await new Promise((s,i)=>{let c=setTimeout(()=>{i(new Error(`Timed out connecting to room ${n}`))},o),a=e.subscribe("status",l=>{l==="connected"&&(clearTimeout(c),a(),s())});e.getStatus()==="connected"&&(clearTimeout(c),a(),s())}),await new Promise(s=>{if(e.getOthers().length>0){s();return}let c=setTimeout(()=>{a(),s()},3e3),a=e.subscribe("others",l=>{l.length>0&&(clearTimeout(c),a(),s())})}),{room:e,leave:r}}function mo(t){var e,r;let n=t.getOthers(),o=[];for(let s of n){let i=(e=s.presence)==null?void 0:e.presence;(r=i==null?void 0:i.selectedShapeIds)!=null&&r.length&&o.push(...i.selectedShapeIds)}return[...new Set(o)]}async function po(t,n){let{root:o}=await t.getStorage(),e=o.get("records");if(!e)return[];let r=[];for(let s of n){let i=e.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 go(t){t.command("selection").description("Get the currently selected component(s) from the web app canvas").action(async()=>{var o,e,r,s;let n=x();try{let i;try{i=S()}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:E("Checking canvas selection...").start();try{let a=await tt.get(xe(),{headers:i}),l=((o=a.data.data)==null?void 0:o.socket_rooms)??a.data.socket_rooms,u=(l==null?void 0:l.projectRooms)??[];if(u.length===0){c==null||c.succeed("No active canvas session"),n&&j({projects:[],components:[]}),console.log(`
132
- No active canvas session found.`);return}let d=new Map;try{let f=await G(i);d=new Map(f.map(h=>[String(h.id),{name:h.name??"",ownerType:h.ownerType,ownerName:h.ownerName}]))}catch{}let y=u.map(f=>{let h=d.get(String(f.id));return h?{id:String(f.id),name:h.name,ownerType:h.ownerType,ownerName:h.ownerName}:{id:String(f.id),name:null,ownerType:null,ownerName:null}}),g=u.map(f=>{var h;return{projectId:f.id,projectName:((h=d.get(String(f.id)))==null?void 0:h.name)??"",roomId:f.room}}),$=co(i),I=[];for(let f of g){let h=null;try{let b=await lo($,f.roomId);h=b.leave;let w=b.room,P=mo(w);if(P.length===0)continue;let F=await po(w,P);for(let N of F)try{let v=await tt.get(dt(N.serverId),{headers:i}),T=((e=v.data.data)==null?void 0:e.component)??v.data.component;I.push({id:N.serverId,name:(T==null?void 0:T.name)??N.name,generatedName:(T==null?void 0:T.generatedName)??null,clientId:N.clientId,projectId:f.projectId,projectName:f.projectName,selectedRevisionId:N.selectedRevisionId})}catch{I.push({id:N.serverId,name:N.name,generatedName:null,clientId:N.clientId,projectId:f.projectId,projectName:f.projectName,selectedRevisionId:N.selectedRevisionId})}}catch{}finally{h&&h()}}if(I.length===0){if(c==null||c.succeed("No components selected"),n&&j({projects:y,components:[]}),console.log(`
133
- No active selection.`),y.length>0){console.log(" Active project(s):");for(let f of y){let h=f.ownerType==="team"&&f.ownerName?` [${f.ownerName}]`:"",b=f.name??`(unresolved project ${f.id})`;console.log(` ${b}${h}`)}}return}c==null||c.succeed(`Found ${I.length} selected component(s)`),n&&j({projects:y,components:I});let C=new Map;for(let f of I){let h=f.projectId;C.has(h)||C.set(h,[]),C.get(h).push(f)}console.log("");for(let[,f]of C){console.log(` Selected in "${f[0].projectName}":`);for(let h of f){let b=h.generatedName?` (${h.generatedName})`:"";console.log(` ${h.name}${b}`)}}}catch(a){throw c==null||c.fail("Failed to check selection"),tt.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&&A(i),i instanceof p&&(console.error(`
134
- ${i.message}`),process.exit(1)),i}})}import uo from"axios";function fo(t){t.command("active-project").description("Get the project(s) the user currently has open in the MagicPath web app").action(async()=>{var o,e,r;let n=x();try{let s;try{s=S()}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 i=n?null:E("Checking active project...").start();try{let c=await uo.get(xe(),{headers:s}),a=((o=c.data.data)==null?void 0:o.socket_rooms)??c.data.socket_rooms,l=(a==null?void 0:a.projectRooms)??[];if(l.length===0){i==null||i.succeed("No active canvas session"),n&&j({projects:[]}),console.log(`
135
- No active canvas session found.`);return}let u=await G(s),d=new Map;for(let g of u)d.set(String(g.id),g);let y=[];for(let g of l){let $=String(g.id),I=d.get($);I?y.push({id:$,name:I.name??null,ownerType:I.ownerType,ownerName:I.ownerName}):y.push({id:$,name:null,ownerType:null,ownerName:null})}i==null||i.succeed(`Found ${y.length} active project${y.length===1?"":"s"}`),n&&j({projects:y}),console.log("");for(let g of y){let $=g.ownerType==="team"&&g.ownerName?` [${g.ownerName}]`:"",I=g.name??`(unresolved project ${g.id})`;console.log(` ${I}${$}`)}}catch(c){throw i==null||i.fail("Failed to check active project"),uo.isAxiosError(c)?((e=c.response)==null?void 0:e.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: ${(r=c.response)==null?void 0:r.status}`):c}}catch(s){throw n&&A(s),s instanceof p&&(console.error(`
136
- ${s.message}`),process.exit(1)),s}})}function ho(t){t.command("list-teams").description("List teams you belong to").action(async()=>{let n=x();try{let o;try{o=S()}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 e=n?null:E("Fetching teams...").start();try{let r=await de(o);if(e==null||e.succeed(`Found ${r.length} team(s)`),n&&j({teams:r}),r.length===0){console.log(`
137
- 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 e==null||e.fail("Failed to fetch teams"),r instanceof p,r}}catch(o){throw n&&A(o),o instanceof p&&(console.error(`
138
- ${o.message}`),process.exit(1)),o}})}import yo from"axios";function wo(t){t.command("list-members").description("List members of a team").requiredOption("--team <nameOrId>","Team name or ID").action(async n=>{var e,r,s;let o=x();try{let i;try{i=S()}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=o?null:E("Fetching members...").start();try{let a=await z(n.team,i),l=await yo.get(pt(a.id),{headers:{...i,"X-Organization-ID":a.id}}),y=((((e=l.data.data)==null?void 0:e.organization)??l.data.organization??l.data).users??[]).map(f=>{var h,b,w;return{id:String(((h=f.user)==null?void 0:h.id)??f.userId),displayName:((b=f.user)==null?void 0:b.displayName)??null,email:((w=f.user)==null?void 0:w.email)??null,role:f.role}});if(c==null||c.succeed(`${a.name}: ${y.length} member(s)`),o&&j({team:{id:a.id,name:a.name},members:y}),y.length===0){console.log(`
139
- No members found.`);return}console.log("");let g=Math.max(4,...y.map(f=>(f.displayName||"").length)),$=Math.max(5,...y.map(f=>(f.email||"").length)),I=Math.max(2,...y.map(f=>f.id.length)),C=Math.max(4,...y.map(f=>f.role.length));console.log(` ${"Name".padEnd(g)} ${"Email".padEnd($)} ${"ID".padEnd(I)} Role`),console.log(` ${"\u2500".repeat(g)} ${"\u2500".repeat($)} ${"\u2500".repeat(I)} ${"\u2500".repeat(C)}`);for(let f of y)console.log(` ${(f.displayName||"").padEnd(g)} ${(f.email||"").padEnd($)} ${f.id.padEnd(I)} ${f.role}`)}catch(a){throw c==null||c.fail("Failed to fetch members"),a instanceof p?a:yo.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 o&&A(i),i instanceof p&&(console.error(`
140
- ${i.message}`),process.exit(1)),i}})}import B from"axios";import kn from"crypto";import L from"fs-extra";import W from"path";var $o="magicpath-code.json",On=new Set(["src/App.tsx","src/index.css"]);function we(t){return kn.createHash("sha256").update(t).digest("hex")}function jo(t){return On.has(t)||t.startsWith("src/components/generated/")&&!t.endsWith("/")}function Me(t){return W.join(t,$o)}function Mn(t){let n=Me(t);if(!L.existsSync(n))throw new p(`No ${$o} found. Run \`magicpath-ai code context <componentId>\` or \`magicpath-ai code start --project <projectId>\` first.`);return L.readJsonSync(n)}function he(t,n){L.ensureDirSync(t),L.writeJsonSync(Me(t),n,{spaces:2})}function bo(t,n){if(!jo(n.path))throw new p(`Refusing to write disallowed path from API: ${n.path}`);let o=W.join(t,n.path);L.ensureDirSync(W.dirname(o)),L.writeFileSync(o,n.content,"utf8")}function be(t){let n=[],o=["src/App.tsx","src/index.css"],e=W.join(t,"src/components/generated");if(L.existsSync(e))for(let r of xo(e))o.push(W.relative(t,r).split(W.sep).join("/"));for(let r of Array.from(new Set(o)).sort()){if(!jo(r))continue;let s=W.join(t,r);if(!L.existsSync(s)||!L.statSync(s).isFile())continue;let i=L.readFileSync(s,"utf8");n.push({path:r,content:i,sha256:we(i)})}return n}function xo(t){let n=[];for(let o of L.readdirSync(t,{withFileTypes:!0})){let e=W.join(t,o.name);o.isDirectory()?n.push(...xo(e)):o.isFile()&&n.push(e)}return n}function Fn(t,n){if(n.mode==="create")return be(t);let o=new Map(n.editableFiles.map(e=>[e.path,e.sha256]));return be(t).map(e=>({...e,baseSha256:o.get(e.path)})).filter(e=>e.sha256!==e.baseSha256)}function Un(t,n){if(n.mode==="create")return[];let o=new Set(be(t).map(e=>e.path));return n.editableFiles.map(e=>e.path).filter(e=>!o.has(e))}async function Io(t,n){let o=S();for(;;){let r=(await B.get(Le(t),{headers:o})).data.data;if(r.status==="completed"||r.status==="failed"||r.status==="cancelled")return r;await new Promise(s=>setTimeout(s,n))}}function ye(t){var n,o;throw x()&&A(t),B.isAxiosError(t)?new p(((o=(n=t.response)==null?void 0:n.data)==null?void 0:o.message)??t.message):t}function vo(t){let n=t.command("code").description("Create and edit canvas components from local code");n.command("start").description("Create a pending canvas component/revision before writing code").requiredOption("--project <projectId>","Target MagicPath project ID").option("--dir <dir>","Working directory to initialize",".").option("--name <name>","Component name","External Agent Component").action(async o=>{try{let e=W.resolve(o.dir),s=(await B.post(Ue(),{projectId:o.project,name:o.name},{headers:S()})).data.data,i=s.editableFiles??[];L.ensureDirSync(e);for(let l of i)bo(e,l);let c={mode:"create",componentId:s.componentId,projectId:o.project,selectedRevisionId:s.revisionId,jobId:s.jobId,generatedName:s.generatedName,name:o.name,editableFiles:i.map(l=>({path:l.path,sha256:we(l.content)}))};he(e,c);let a={dir:e,manifestPath:Me(e),...c,status:"pending",scaffoldedPaths:i.map(l=>l.path)};x()&&j(a),console.log(`Started pending component ${c.componentId} in ${e}`+(i.length>0?` (scaffolded ${i.length} file${i.length===1?"":"s"})`:""))}catch(e){ye(e)}}),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(o,e)=>{try{let r=W.resolve(e.dir);L.ensureDirSync(r);let s=e.revision?`${De(o)}?revisionId=${encodeURIComponent(e.revision)}`:De(o),c=(await B.get(s,{headers:S()})).data.data;for(let u of c.editableFiles)bo(r,u);let a={mode:"edit",componentId:c.component.id,projectId:c.component.projectId,selectedRevisionId:c.component.selectedRevisionId,generatedName:c.component.generatedName,name:c.component.name,editableFiles:c.editableFiles.map(u=>({path:u.path,sha256:we(u.content)}))};he(r,a);let l={dir:r,manifestPath:Me(r),...a};x()&&j(l),console.log(`Fetched ${a.editableFiles.length} editable files into ${r}`)}catch(r){ye(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").action(async o=>{try{let e=W.resolve(o.dir),r=Mn(e),s=Fn(e,r),i=Un(e,r);if(r.mode==="create"&&!s.some(l=>l.path==="src/App.tsx"))throw new p("Create submit requires src/App.tsx in the working directory.");if(s.length===0&&i.length===0){let l={status:"unchanged",componentId:r.componentId,revisionId:r.selectedRevisionId};x()&&j(l),console.log("No editable file changes to submit.");return}let c=r.mode==="create"?await B.post(_e(r.componentId,r.selectedRevisionId),{files:s.map(l=>({path:l.path,content:l.content}))},{headers:S()}):await B.post(ct(r.componentId),{baseRevisionId:r.selectedRevisionId,files:s.map(l=>({path:l.path,content:l.content,baseSha256:l.baseSha256})),deletedPaths:i},{headers:S()}),a=c.data.data;if(o.wait&&(a=await Io(c.data.data.jobId,Number(o.interval))),a.status==="completed"){let l=be(e),u={...r,mode:"edit",jobId:c.data.data.jobId,selectedRevisionId:a.revisionId,editableFiles:l.map(d=>({path:d.path,sha256:d.sha256??we(d.content)}))};he(e,u)}x()&&j({...a,jobId:c.data.data.jobId,deletedPaths:i}),console.log(`Submitted ${s.length} file(s)`+(i.length>0?` and ${i.length} deletion(s)`:"")+`. Job ${c.data.data.jobId}: ${a.status}`)}catch(e){ye(e)}}),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","External Agent Component").option("--wait","Wait for the build job to finish",!1).action(async o=>{try{let e=W.resolve(o.dir),r=be(e);if(!r.some(l=>l.path==="src/App.tsx"))throw new p("Create requires src/App.tsx in the working directory.");let s=await B.post(Ue(),{projectId:o.project,name:o.name},{headers:S()}),i={mode:"create",componentId:s.data.data.componentId,projectId:o.project,selectedRevisionId:s.data.data.revisionId,jobId:s.data.data.jobId,generatedName:s.data.data.generatedName,name:o.name,editableFiles:[]};he(e,i);let c=await B.post(_e(i.componentId,i.selectedRevisionId),{files:r.map(l=>({path:l.path,content:l.content}))},{headers:S()}),a=c.data.data;o.wait&&(a=await Io(c.data.data.jobId,2e3)),a.status==="completed"&&he(e,{...i,mode:"edit",jobId:c.data.data.jobId,selectedRevisionId:a.revisionId,editableFiles:r.map(l=>({path:l.path,sha256:l.sha256??we(l.content)}))}),x()&&j({...a,jobId:c.data.data.jobId}),console.log(`Created component ${c.data.data.componentId}. Job ${c.data.data.jobId}: ${a.status}`)}catch(e){ye(e)}}),n.command("status").description("Fetch external-agent build job status").argument("<jobId>","External agent job ID").action(async o=>{try{let e=await B.get(Le(o),{headers:S()});x()&&j(e.data.data),console.log(`${o}: ${e.data.data.status}`)}catch(e){ye(e)}})}var Hn=_n(Wn(import.meta.url)),zn=JSON.parse(Dn(Ln(Hn,"..","package.json"),"utf8"));st(zn.version);process.argv.length<=2&&(It(H),process.exit(0));k.name("magicpath").description("").version(H).option("-o, --output <format>","Output format: json").hook("preAction",t=>{t.optsWithGlobals().output==="json"&&rt(!0)});Ot(k);Jt(k);Gt(k);Kt(k);Bt(k);Yt(k);Qt(k);eo(k);to(k);no(k);ro(k);Xt(k);io(k);ao(k);go(k);fo(k);ho(k);wo(k);vo(k);k.parse();
124
+ ${s.length} component(s) installed in ${Q.relative(t,r)}:
125
+ `);let a=Math.max(9,...s.map(l=>l.name.length)),i=Math.max(6,...s.map(l=>l.folder.length)),c=5;console.log(` ${"Component".padEnd(a)} ${"Folder".padEnd(i)} ${"Files".padEnd(c)}`),console.log(` ${"\u2500".repeat(a)} ${"\u2500".repeat(i)} ${"\u2500".repeat(c)}`);for(let l of s)console.log(` ${l.name.padEnd(a)} ${l.folder.padEnd(i)} ${String(l.files.length).padEnd(c)}`)}catch(t){throw o&&A(t),t instanceof p&&(console.error(`
126
+ ${t.message}`),process.exit(1)),t}})}import co from"axios";function lo(e){e.command("list-themes").description("List all themes (design systems)").option("--team <nameOrId>","List themes for a specific team").action(async n=>{var t,r,s;let o=x();try{let a;try{a=P()}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 i=o?null:S("Fetching themes...").start();try{let c=je(),l=a;if(n.team){let f=await W(n.team,a);c=ve(f.id),l={...a,"X-Organization-ID":f.id}}let u=await co.get(c,{headers:l}),d=((t=u.data.data)==null?void 0:t.design_systems)??u.data.design_systems??u.data,y=Array.isArray(d)?d:[];if(i==null||i.succeed(`Found ${y.length} theme(s)`),o&&j({themes:y.map(f=>({id:String(f.id),name:f.name,isPublic:f.isPublic,createdAt:f.createdAt,updatedAt:f.updatedAt}))}),y.length===0){console.log(`
127
+ No themes found.`);return}console.log("");let g=Math.max(4,...y.map(f=>(f.name||"").length)),I=Math.max(2,...y.map(f=>String(f.id).length)),$=6,C=10;console.log(` ${"Name".padEnd(g)} ${"ID".padEnd(I)} ${"Public".padEnd($)} Updated`),console.log(` ${"\u2500".repeat(g)} ${"\u2500".repeat(I)} ${"\u2500".repeat($)} ${"\u2500".repeat(C)}`);for(let f of y){let h=(f.name||"").padEnd(g),b=String(f.id).padEnd(I),w=(f.isPublic?"yes":"no").padEnd($),T=f.updatedAt?new Date(f.updatedAt).toISOString().slice(0,10):"";console.log(` ${h} ${b} ${w} ${T}`)}}catch(c){throw i==null||i.fail("Failed to fetch themes"),co.isAxiosError(c)?((r=c.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=c.response)==null?void 0:s.status}`):c}}catch(a){throw o&&A(a),a instanceof p&&(console.error(`
128
+ ${a.message}`),process.exit(1)),a}})}import et from"axios";function mo(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,o)=>{var r,s,a,i,c,l,u;let t=x();try{let d;try{d=P()}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 y=t?null:S("Fetching theme...").start();try{let g=n,I;if(!/^\d+$/.test(n)){let b=je(),w=d;if(o.team){let M=await W(o.team,d);b=ve(M.id),w={...d,"X-Organization-ID":M.id}}let T=await et.get(b,{headers:w}),F=((r=T.data.data)==null?void 0:r.design_systems)??T.data.design_systems??T.data,R=Array.isArray(F)?F:[],v=n.toLowerCase(),E=R.find(M=>(M.name||"").toLowerCase()===v);if(!E)throw new p(`Theme "${n}" not found.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai list-themes` to see available themes."});g=String(E.id),I=E.name}let $=await et.get(pt(g),{headers:d}),C=((s=$.data.data)==null?void 0:s.design_system)??$.data.design_system,f=C.name??I??g,h=C.data;y==null||y.succeed(`Theme: ${f}`),t&&j({id:String(C.id??g),name:f,theme:h.theme,defaultTheme:h.defaultTheme,prompt:h.prompt,fonts:h.fonts,version:h.version}),console.log(""),console.log(` Name: ${f}`),console.log(` ID: ${C.id??g}`),console.log(` Default Theme: ${h.defaultTheme??"light"}`),h.prompt&&console.log(` Prompt: ${h.prompt}`);for(let b of["light","dark"]){let w=(a=h.theme)==null?void 0:a[b];if(w&&Object.keys(w).length>0){console.log(`
129
+ ${b.charAt(0).toUpperCase()+b.slice(1)} Theme Variables:`);let T=Math.max(8,...Object.keys(w).map(F=>F.length));console.log(` ${"Variable".padEnd(T)} Value`),console.log(` ${"\u2500".repeat(T)} ${"\u2500".repeat(30)}`);for(let[F,R]of Object.entries(w))console.log(` ${F.padEnd(T)} ${R}`)}}if(h.fonts&&Object.keys(h.fonts).length>0){console.log(`
130
+ Fonts:`);for(let[b,w]of Object.entries(h.fonts)){let T=w.weights?Object.keys(w.weights).join(", "):"default";console.log(` ${b} (${w.source}, weights: ${T})`)}}}catch(g){throw y==null||y.fail("Failed to fetch theme"),et.isAxiosError(g)?((i=g.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."}):((c=g.response)==null?void 0:c.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: ${(u=g.response)==null?void 0:u.status}`):(g instanceof p,g)}}catch(d){throw t&&A(d),d instanceof p&&(console.error(`
131
+ ${d.message}`),process.exit(1)),d}})}import tt from"axios";import{createClient as Fn}from"@liveblocks/client";import Un from"ws";function po(e){let n=gt();return Fn({polyfills:{fetch,WebSocket:Un},authEndpoint:async o=>await(await fetch(n,{method:"POST",headers:{...e,"Content-Type":"application/json"},body:JSON.stringify({room:o})})).json()})}async function go(e,n,o=1e4){let{room:t,leave:r}=e.enterRoom(n,{initialPresence:{}});return await new Promise((s,a)=>{let i=setTimeout(()=>{a(new Error(`Timed out connecting to room ${n}`))},o),c=t.subscribe("status",l=>{l==="connected"&&(clearTimeout(i),c(),s())});t.getStatus()==="connected"&&(clearTimeout(i),c(),s())}),await new Promise(s=>{if(t.getOthers().length>0){s();return}let i=setTimeout(()=>{c(),s()},3e3),c=t.subscribe("others",l=>{l.length>0&&(clearTimeout(i),c(),s())})}),{room:t,leave:r}}function uo(e){var t,r;let n=e.getOthers(),o=[];for(let s of n){let a=(t=s.presence)==null?void 0:t.presence;(r=a==null?void 0:a.selectedShapeIds)!=null&&r.length&&o.push(...a.selectedShapeIds)}return[...new Set(o)]}async function fo(e,n){let{root:o}=await e.getStorage(),t=o.get("records");if(!t)return[];let r=[];for(let s of n){let a=t.get(s);if(!a)continue;let i=typeof a.toObject=="function"?a.toObject():a;if(i.type==="mp-component"&&i.props){let c=typeof i.props.toObject=="function"?i.props.toObject():i.props;c.serverId&&r.push({serverId:c.serverId,clientId:c.clientId??s.replace("shape:",""),name:c.name??"Unknown",selectedRevisionId:typeof c.selectedRevisionId=="string"&&c.selectedRevisionId.length>0?c.selectedRevisionId:null})}}return r}function ho(e){e.command("selection").description("Get the currently selected component(s) from the web app canvas").action(async()=>{var o,t,r,s;let n=x();try{let a;try{a=P()}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 i=n?null:S("Checking canvas selection...").start();try{let c=await tt.get(xe(),{headers:a}),l=((o=c.data.data)==null?void 0:o.socket_rooms)??c.data.socket_rooms,u=(l==null?void 0:l.projectRooms)??[];if(u.length===0){i==null||i.succeed("No active canvas session"),n&&j({projects:[],components:[]}),console.log(`
132
+ No active canvas session found.`);return}let d=new Map;try{let f=await G(a);d=new Map(f.map(h=>[String(h.id),{name:h.name??"",ownerType:h.ownerType,ownerName:h.ownerName}]))}catch{}let y=u.map(f=>{let h=d.get(String(f.id));return h?{id:String(f.id),name:h.name,ownerType:h.ownerType,ownerName:h.ownerName}:{id:String(f.id),name:null,ownerType:null,ownerName:null}}),g=u.map(f=>{var h;return{projectId:f.id,projectName:((h=d.get(String(f.id)))==null?void 0:h.name)??"",roomId:f.room}}),I=po(a),$=[];for(let f of g){let h=null;try{let b=await go(I,f.roomId);h=b.leave;let w=b.room,T=uo(w);if(T.length===0)continue;let F=await fo(w,T);for(let R of F)try{let v=await tt.get(ut(R.serverId),{headers:a}),E=((t=v.data.data)==null?void 0:t.component)??v.data.component;$.push({id:R.serverId,name:(E==null?void 0:E.name)??R.name,generatedName:(E==null?void 0:E.generatedName)??null,clientId:R.clientId,projectId:f.projectId,projectName:f.projectName,selectedRevisionId:R.selectedRevisionId})}catch{$.push({id:R.serverId,name:R.name,generatedName:null,clientId:R.clientId,projectId:f.projectId,projectName:f.projectName,selectedRevisionId:R.selectedRevisionId})}}catch{}finally{h&&h()}}if($.length===0){if(i==null||i.succeed("No components selected"),n&&j({projects:y,components:[]}),console.log(`
133
+ No active selection.`),y.length>0){console.log(" Active project(s):");for(let f of y){let h=f.ownerType==="team"&&f.ownerName?` [${f.ownerName}]`:"",b=f.name??`(unresolved project ${f.id})`;console.log(` ${b}${h}`)}}return}i==null||i.succeed(`Found ${$.length} selected component(s)`),n&&j({projects:y,components:$});let C=new Map;for(let f of $){let h=f.projectId;C.has(h)||C.set(h,[]),C.get(h).push(f)}console.log("");for(let[,f]of C){console.log(` Selected in "${f[0].projectName}":`);for(let h of f){let b=h.generatedName?` (${h.generatedName})`:"";console.log(` ${h.name}${b}`)}}}catch(c){throw i==null||i.fail("Failed to check selection"),tt.isAxiosError(c)?((r=c.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=c.response)==null?void 0:s.status}`):c}}catch(a){throw n&&A(a),a instanceof p&&(console.error(`
134
+ ${a.message}`),process.exit(1)),a}})}import yo from"axios";function wo(e){e.command("active-project").description("Get the project(s) the user currently has open in the MagicPath web app").action(async()=>{var o,t,r;let n=x();try{let s;try{s=P()}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=n?null:S("Checking active project...").start();try{let i=await yo.get(xe(),{headers:s}),c=((o=i.data.data)==null?void 0:o.socket_rooms)??i.data.socket_rooms,l=(c==null?void 0:c.projectRooms)??[];if(l.length===0){a==null||a.succeed("No active canvas session"),n&&j({projects:[]}),console.log(`
135
+ No active canvas session found.`);return}let u=await G(s),d=new Map;for(let g of u)d.set(String(g.id),g);let y=[];for(let g of l){let I=String(g.id),$=d.get(I);$?y.push({id:I,name:$.name??null,ownerType:$.ownerType,ownerName:$.ownerName}):y.push({id:I,name:null,ownerType:null,ownerName:null})}a==null||a.succeed(`Found ${y.length} active project${y.length===1?"":"s"}`),n&&j({projects:y}),console.log("");for(let g of y){let I=g.ownerType==="team"&&g.ownerName?` [${g.ownerName}]`:"",$=g.name??`(unresolved project ${g.id})`;console.log(` ${$}${I}`)}}catch(i){throw a==null||a.fail("Failed to check active project"),yo.isAxiosError(i)?((t=i.response)==null?void 0:t.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: ${(r=i.response)==null?void 0:r.status}`):i}}catch(s){throw n&&A(s),s instanceof p&&(console.error(`
136
+ ${s.message}`),process.exit(1)),s}})}function bo(e){e.command("list-teams").description("List teams you belong to").action(async()=>{let n=x();try{let o;try{o=P()}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 t=n?null:S("Fetching teams...").start();try{let r=await de(o);if(t==null||t.succeed(`Found ${r.length} team(s)`),n&&j({teams:r}),r.length===0){console.log(`
137
+ No teams found.`);return}console.log("");let s=Math.max(4,...r.map(c=>c.name.length)),a=Math.max(2,...r.map(c=>c.id.length)),i=Math.max(4,...r.map(c=>c.role.length));console.log(` ${"Name".padEnd(s)} ${"ID".padEnd(a)} Role`),console.log(` ${"\u2500".repeat(s)} ${"\u2500".repeat(a)} ${"\u2500".repeat(i)}`);for(let c of r)console.log(` ${c.name.padEnd(s)} ${c.id.padEnd(a)} ${c.role}`)}catch(r){throw t==null||t.fail("Failed to fetch teams"),r instanceof p,r}}catch(o){throw n&&A(o),o instanceof p&&(console.error(`
138
+ ${o.message}`),process.exit(1)),o}})}import Io from"axios";function $o(e){e.command("list-members").description("List members of a team").requiredOption("--team <nameOrId>","Team name or ID").action(async n=>{var t,r,s;let o=x();try{let a;try{a=P()}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 i=o?null:S("Fetching members...").start();try{let c=await W(n.team,a),l=await Io.get(ft(c.id),{headers:{...a,"X-Organization-ID":c.id}}),y=((((t=l.data.data)==null?void 0:t.organization)??l.data.organization??l.data).users??[]).map(f=>{var h,b,w;return{id:String(((h=f.user)==null?void 0:h.id)??f.userId),displayName:((b=f.user)==null?void 0:b.displayName)??null,email:((w=f.user)==null?void 0:w.email)??null,role:f.role}});if(i==null||i.succeed(`${c.name}: ${y.length} member(s)`),o&&j({team:{id:c.id,name:c.name},members:y}),y.length===0){console.log(`
139
+ No members found.`);return}console.log("");let g=Math.max(4,...y.map(f=>(f.displayName||"").length)),I=Math.max(5,...y.map(f=>(f.email||"").length)),$=Math.max(2,...y.map(f=>f.id.length)),C=Math.max(4,...y.map(f=>f.role.length));console.log(` ${"Name".padEnd(g)} ${"Email".padEnd(I)} ${"ID".padEnd($)} Role`),console.log(` ${"\u2500".repeat(g)} ${"\u2500".repeat(I)} ${"\u2500".repeat($)} ${"\u2500".repeat(C)}`);for(let f of y)console.log(` ${(f.displayName||"").padEnd(g)} ${(f.email||"").padEnd(I)} ${f.id.padEnd($)} ${f.role}`)}catch(c){throw i==null||i.fail("Failed to fetch members"),c instanceof p?c:Io.isAxiosError(c)?((r=c.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=c.response)==null?void 0:s.status}`):c}}catch(a){throw o&&A(a),a instanceof p&&(console.error(`
140
+ ${a.message}`),process.exit(1)),a}})}import B from"axios";import Dn from"crypto";import L from"fs-extra";import H from"path";var vo="magicpath-code.json",_n=new Set(["src/App.tsx","src/index.css"]);function we(e){return Dn.createHash("sha256").update(e).digest("hex")}function Co(e){return _n.has(e)||e.startsWith("src/components/generated/")&&!e.endsWith("/")}function Me(e){return H.join(e,vo)}function Ln(e){let n=Me(e);if(!L.existsSync(n))throw new p(`No ${vo} found. Run \`magicpath-ai code context <componentId>\` or \`magicpath-ai code start --project <projectId>\` first.`);return L.readJsonSync(n)}function he(e,n){L.ensureDirSync(e),L.writeJsonSync(Me(e),n,{spaces:2})}function jo(e,n){if(!Co(n.path))throw new p(`Refusing to write disallowed path from API: ${n.path}`);let o=H.join(e,n.path);L.ensureDirSync(H.dirname(o)),L.writeFileSync(o,n.content,"utf8")}function be(e){let n=[],o=["src/App.tsx","src/index.css"],t=H.join(e,"src/components/generated");if(L.existsSync(t))for(let r of Ao(t))o.push(H.relative(e,r).split(H.sep).join("/"));for(let r of Array.from(new Set(o)).sort()){if(!Co(r))continue;let s=H.join(e,r);if(!L.existsSync(s)||!L.statSync(s).isFile())continue;let a=L.readFileSync(s,"utf8");n.push({path:r,content:a,sha256:we(a)})}return n}function Ao(e){let n=[];for(let o of L.readdirSync(e,{withFileTypes:!0})){let t=H.join(e,o.name);o.isDirectory()?n.push(...Ao(t)):o.isFile()&&n.push(t)}return n}function Wn(e,n){if(n.mode==="create")return be(e);let o=new Map(n.editableFiles.map(t=>[t.path,t.sha256]));return be(e).map(t=>({...t,baseSha256:o.get(t.path)})).filter(t=>t.sha256!==t.baseSha256)}function Hn(e,n){if(n.mode==="create")return[];let o=new Set(be(e).map(t=>t.path));return n.editableFiles.map(t=>t.path).filter(t=>!o.has(t))}async function xo(e,n){let o=P();for(;;){let r=(await B.get(Le(e),{headers:o})).data.data;if(r.status==="completed"||r.status==="failed"||r.status==="cancelled")return r;await new Promise(s=>setTimeout(s,n))}}function ye(e){var n,o;throw x()&&A(e),B.isAxiosError(e)?new p(((o=(n=e.response)==null?void 0:n.data)==null?void 0:o.message)??e.message):e}function Po(e){let n=e.command("code").description("Create and edit canvas components from local code");n.command("start").description("Create a pending canvas component/revision before writing code").requiredOption("--project <projectId>","Target MagicPath project ID").option("--dir <dir>","Working directory to initialize",".").option("--name <name>","Component name","External Agent Component").action(async o=>{try{let t=H.resolve(o.dir),s=(await B.post(Ue(),{projectId:o.project,name:o.name},{headers:P()})).data.data,a=s.editableFiles??[];L.ensureDirSync(t);for(let l of a)jo(t,l);let i={mode:"create",componentId:s.componentId,projectId:o.project,selectedRevisionId:s.revisionId,jobId:s.jobId,generatedName:s.generatedName,name:o.name,editableFiles:a.map(l=>({path:l.path,sha256:we(l.content)}))};he(t,i);let c={dir:t,manifestPath:Me(t),...i,status:"pending",scaffoldedPaths:a.map(l=>l.path)};x()&&j(c),console.log(`Started pending component ${i.componentId} in ${t}`+(a.length>0?` (scaffolded ${a.length} file${a.length===1?"":"s"})`:""))}catch(t){ye(t)}}),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(o,t)=>{try{let r=H.resolve(t.dir);L.ensureDirSync(r);let s=t.revision?`${De(o)}?revisionId=${encodeURIComponent(t.revision)}`:De(o),i=(await B.get(s,{headers:P()})).data.data;for(let u of i.editableFiles)jo(r,u);let c={mode:"edit",componentId:i.component.id,projectId:i.component.projectId,selectedRevisionId:i.component.selectedRevisionId,jobId:i.jobId,generatedName:i.component.generatedName,name:i.component.name,editableFiles:i.editableFiles.map(u=>({path:u.path,sha256:we(u.content)}))};he(r,c);let l={dir:r,manifestPath:Me(r),...c};x()&&j(l),console.log(`Fetched ${c.editableFiles.length} editable files into ${r}`)}catch(r){ye(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").action(async o=>{try{let t=H.resolve(o.dir),r=Ln(t),s=Wn(t,r),a=Hn(t,r);if(r.mode==="create"&&!s.some(l=>l.path==="src/App.tsx"))throw new p("Create submit requires src/App.tsx in the working directory.");if(s.length===0&&a.length===0){let l={status:"unchanged",componentId:r.componentId,revisionId:r.selectedRevisionId};x()&&j(l),console.log("No editable file changes to submit.");return}let i=r.mode==="create"?await B.post(_e(r.componentId,r.selectedRevisionId),{files:s.map(l=>({path:l.path,content:l.content}))},{headers:P()}):await B.post(lt(r.componentId),{baseRevisionId:r.selectedRevisionId,files:s.map(l=>({path:l.path,content:l.content,baseSha256:l.baseSha256})),deletedPaths:a,jobId:r.jobId},{headers:P()}),c=i.data.data;if(o.wait&&(c=await xo(i.data.data.jobId,Number(o.interval))),c.status==="completed"){let l=be(t),u={...r,mode:"edit",jobId:i.data.data.jobId,selectedRevisionId:c.revisionId,editableFiles:l.map(d=>({path:d.path,sha256:d.sha256??we(d.content)}))};he(t,u)}x()&&j({...c,jobId:i.data.data.jobId,deletedPaths:a}),console.log(`Submitted ${s.length} file(s)`+(a.length>0?` and ${a.length} deletion(s)`:"")+`. Job ${i.data.data.jobId}: ${c.status}`)}catch(t){ye(t)}}),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","External Agent Component").option("--wait","Wait for the build job to finish",!1).action(async o=>{try{let t=H.resolve(o.dir),r=be(t);if(!r.some(l=>l.path==="src/App.tsx"))throw new p("Create requires src/App.tsx in the working directory.");let s=await B.post(Ue(),{projectId:o.project,name:o.name},{headers:P()}),a={mode:"create",componentId:s.data.data.componentId,projectId:o.project,selectedRevisionId:s.data.data.revisionId,jobId:s.data.data.jobId,generatedName:s.data.data.generatedName,name:o.name,editableFiles:[]};he(t,a);let i=await B.post(_e(a.componentId,a.selectedRevisionId),{files:r.map(l=>({path:l.path,content:l.content}))},{headers:P()}),c=i.data.data;o.wait&&(c=await xo(i.data.data.jobId,2e3)),c.status==="completed"&&he(t,{...a,mode:"edit",jobId:i.data.data.jobId,selectedRevisionId:c.revisionId,editableFiles:r.map(l=>({path:l.path,sha256:l.sha256??we(l.content)}))}),x()&&j({...c,jobId:i.data.data.jobId}),console.log(`Created component ${i.data.data.componentId}. Job ${i.data.data.jobId}: ${c.status}`)}catch(t){ye(t)}}),n.command("status").description("Fetch external-agent build job status").argument("<jobId>","External agent job ID").action(async o=>{try{let t=await B.get(Le(o),{headers:P()});x()&&j(t.data.data),console.log(`${o}: ${t.data.data.status}`)}catch(t){ye(t)}})}import ot from"axios";function To(e){var n;return((n=e==null?void 0:e.data)==null?void 0:n.project)??(e==null?void 0:e.project)??e}function Eo(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 t,r,s,a;let o=x();try{let i;try{i=P()}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=o?null:S("Creating project...").start();try{let l={...i},u=null;n.team&&(u=await W(n.team,i),l["X-Organization-ID"]=u.id);let d=await ot.post(mt(),{},{headers:l}),y=To(d.data);if(n.name){let I=await ot.patch(dt(String(y.id)),{data:{name:n.name}},{headers:l});y=To(I.data)}let g=u?{...y,ownerType:"team",ownerName:u.name}:{...y,ownerType:"personal",ownerName:((t=y.owner)==null?void 0:t.email)??""};c==null||c.succeed(`Created project "${g.name}"${u?` in ${u.name}`:""}`),o&&j({project:g}),console.log(""),console.log(` ID: ${g.id}`),console.log(` Name: ${g.name}`),console.log(` Workspace: ${u?u.name+" (team)":"personal"}`)}catch(l){throw c==null||c.fail("Failed to create project"),l instanceof p?l:ot.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: ${(a=l.response)==null?void 0:a.status}`):l}}catch(i){throw o&&A(i),i instanceof p&&(console.error(`
141
+ ${i.message}`),process.exit(1)),i}})}var Kn=Gn(Vn(import.meta.url)),Bn=JSON.parse(zn(Jn(Kn,"..","package.json"),"utf8"));it(Bn.version);process.argv.length<=2&&(xt(z),process.exit(0));N.name("magicpath").description("").version(z).option("-o, --output <format>","Output format: json").hook("preAction",e=>{e.optsWithGlobals().output==="json"&&st(!0)});Ut(N);Bt(N);Kt(N);Zt(N);Xt(N);to(N);oo(N);no(N);ro(N);io(N);ao(N);eo(N);lo(N);mo(N);ho(N);wo(N);bo(N);$o(N);Po(N);Eo(N);N.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "magicpath-ai",
3
- "version": "1.5.0-beta.3",
3
+ "version": "1.5.0-beta.5",
4
4
  "description": "Node CLI for MagicPath",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",