magicpath-ai 1.5.0-beta.11 → 1.5.0-beta.15

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