magicpath-ai 1.5.0-beta.7 → 1.5.0-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +10 -10
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{readFileSync as Vn}from"fs";import{dirname as Kn,join as Bn}from"path";import{fileURLToPath as qn}from"url";import{program as N}from"commander";var p=class extends Error{code;suggestion;constructor(n,o){super(n),this.code=o==null?void 0:o.code,this.suggestion=o==null?void 0:o.suggestion}};var st=!1;function it(e){st=e}function x(){return st}function $(e){console.log(JSON.stringify(e,null,2)),process.exit(0)}function T(e){let o={error:e instanceof Error?e.message:String(e)};e instanceof p&&(e.code&&(o.code=e.code),e.suggestion&&(o.suggestion=e.suggestion)),console.error(JSON.stringify(o,null,2)),process.exit(1)}var z="0.0.0-dev";function at(e){z=e}import te from"chalk";import le from"fs-extra";import yt from"path";import ko from"os";import wt from"axios";var k=process.env.MAGICPATH_API_URL??"https://api.ngrok.magicpath.ai";function Ie(e,n){return`${k}/${e}/${n}`}function ct(e){return`${k}/v1/registry/${e}`}var Ro=process.env.MAGICPATH_WEB_URL??"https://web.ngrok.magicpath.ai";function lt(e){return`${Ro}${e}`}function Fe(e){return`${k}/auth/${e}`}function Ue(){return`${k}/v1/external-agent/components`}function De(e){return`${k}/v1/external-agent/components/${e}/context`}function mt(e){return`${k}/v1/external-agent/components/${e}/revisions`}function _e(e,n){return`${k}/v1/external-agent/components/${e}/revisions/${n}/files`}function Le(e){return`${k}/v1/external-agent/jobs/${e}`}function Z(){return`${k}/users/me`}function We(){return`${k}/users/me/projects`}function dt(){return`${k}/projects`}function pt(e){return`${k}/projects/${e}`}function je(e){return`${k}/projects/${e}/components`}function $e(){return`${k}/users/me/design-systems`}function gt(e){return`${k}/design-systems/${e}`}function xe(){return`${k}/users/me/socket-rooms`}function ut(){return`${k}/liveblocks/auth`}function ft(e){return`${k}/components/${e}`}function ht(e){return`${k}/organizations/${e}`}function He(e){return`${k}/organizations/${e}/projects`}function ve(e){return`${k}/organizations/${e}/design-systems`}var bt=yt.join(ko.homedir(),".magicpath"),Ce=yt.join(bt,"session.json");function Te(){try{if(!le.existsSync(Ce))return null;let e=le.readJsonSync(Ce);return e.accessToken&&e.refreshToken?e:null}catch{return null}}function It(e){le.ensureDirSync(bt),le.writeJsonSync(Ce,e)}function ze(e,n){let o=Te();It({accessToken:e,refreshToken:n,user:o==null?void 0:o.user})}function X(){let e=Te();return e?{accessToken:e.accessToken,refreshToken:e.refreshToken}:null}function jt(){try{le.removeSync(Ce)}catch{}}function Oo(e){try{let n=Te();n&&(n.user=e,It(n))}catch{}}function $t(){let e=Te();return(e==null?void 0:e.user)??null}function A(){let e=process.env.MAGICPATH_TOKEN;if(e)return{Authorization:`Bearer ${e}`,"X-Client-Type":"cli","X-Client-Version":z};let n=X();if(!n)throw new Error("Not logged in. Run `magicpath-ai login` first.");return{Authorization:`Bearer ${n.accessToken}`,"X-Client-Type":"cli","X-Client-Version":z}}function me(e){var t,s;let n=(t=e.subscription)!=null&&t.active?(s=e.subscription.type)!=null&&s.startsWith("PRO")?"Pro":"Creator":"Free",o={name:e.name||e.firstName||e.displayName,email:e.email,plan:n};return Oo(o),o}async function Ge(){let e=A(),n=await wt.get(Z(),{headers:e}),o=n.data.user??n.data;return me(o)}async function de(e){let n=await wt.get(Z(),{headers:e});return((n.data.user??n.data).organizationUsers??[]).map(s=>({id:String(s.organization.id),name:s.organization.name,role:s.role}))}async function H(e,n){let o=await de(n),t=o.find(a=>a.id===e);if(t)return{id:t.id,name:t.name};let s=e.toLowerCase(),r=o.find(a=>a.name.toLowerCase()===s);if(r)return{id:r.id,name:r.name};throw new p(`Team "${e}" not found.`,{code:"TEAM_NOT_FOUND",suggestion:"Run `magicpath-ai list-teams` to see your teams."})}var xt=["#95D5B2","#74C69D","#52B788","#40916C","#2D6A4F","#1B4332"];function Mo(e){return te.hex(xt[Math.min(e,xt.length-1)])}var Je=te.hex("#2D6A4F"),Fo=te.hex("#1B4332"),Uo=te.hex("#E8F5E9"),Ve=te.hex("#888888"),Do=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2551 ","\u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 ","\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D"],_o=["\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551","\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551","\u2588\u2588\u2554\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551","\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D"],Lo=Do.map((e,n)=>e+" "+_o[n]);function Wo(e){return e.map((n,o)=>{let t=Mo(o),s="";for(let r of n)s+=r===" "?r:t(r);return s})}function vt(e){let n=!!X(),o=n?$t():null;console.log();for(let r of Wo(Lo))console.log(r);if(console.log(),n&&o){let r=o.plan?` \xB7 ${o.plan}`:"";console.log(" "+Je("\u25CF")+" "+te.bold(Uo(o.name??"MagicPath User"))+Fo(" "+(o.email??"")+r))}else console.log(" "+Ve("\u25CB Not logged in \xB7 run")+" "+Je("magicpath-ai login"));console.log();let t=20,s=[["search <query>","Search components"],["add <name>","Add to project"],["list-projects","Your projects"],["setup-skills","Set up AI agents"]];for(let[r,a]of s)console.log(" "+Je(r.padEnd(t))+Ve(a));console.log(),console.log(" "+Ve(`v${e} \u2500 magicpath-ai --help`)),console.log()}import Pe from"prompts";import Ut from"ora";import{z as re}from"zod";import se from"path";import qo from"os";import qe from"fs-extra";import{pino as Ct}from"pino";var oe=Ct();function ne(){oe=Ct({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 zo from"axios";import Ae from"path";import Go from"os";import pe from"fs-extra";import Jo from"adm-zip";import{v4 as Vo}from"uuid";async function Tt(e){let n=Ie("v1","components/repository"),o=`${Vo()}.zip`,t=Ae.join(Go.tmpdir(),o);try{let s=await zo({url:n,params:{key:e},method:"GET",responseType:"stream"});return await pe.ensureDir(Ae.dirname(t)),await new Promise(async(r,a)=>{try{s.data.pipe(pe.createWriteStream(t)).on("error",a).once("close",()=>r(t))}catch(i){a(i)}}),t}catch{throw new p("Failed to download project. Make sure your key is valid.")}}function Ke(e){try{pe.removeSync(e)}catch{}}function At(e,n,o){try{let t=Ae.join(o,n),s=1;for(;pe.existsSync(t);)s++,t=Ae.join(o,`${n}-${s}`);return pe.mkdirSync(t,{recursive:!0}),new Jo(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 St from"ora";import Pt from"fs-extra";import Ko from"path";function Et(){try{return Be("yarn --version",{stdio:"ignore"}),"yarn"}catch{return"npm"}}function Nt(e){let n=Et(),o=St(`\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 Bo(e){let n=Ko.join(e,"package.json");if(!Pt.existsSync(n))return new Set;try{let o=Pt.readJsonSync(n),t=new Set;return o.dependencies&&Object.keys(o.dependencies).forEach(s=>t.add(s)),o.devDependencies&&Object.keys(o.devDependencies).forEach(s=>t.add(s)),t}catch{return new Set}}function Rt(e,n){if(e.length===0)return{installed:[],skipped:[]};let o=Bo(n),t=e.filter(i=>!o.has(i)),s=e.filter(i=>o.has(i));if(t.length===0)return O.debug("All dependencies already installed"),{installed:[],skipped:s};let r=Et(),a=St(`\u{1F4E6} Installing ${t.length} package${t.length>1?"s":""} using ${r}...`).start();try{let i=t.join(" "),c=r==="yarn"?`yarn add ${i}`:`npm install ${i}`;return O.debug({command:c}),Be(c,{cwd:n,stdio:"ignore"}),a.succeed(`Installed ${t.length} package${t.length>1?"s":""}`),{installed:t,skipped:s}}catch{throw a.fail("Failed to install packages"),new p(`Failed to install packages: ${t.join(", ")}. Please install them manually.`)}}import{execSync as kt}from"child_process";import Ot from"ora";function Mt(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"]},s=Ot(`\u{1F680} Opening project in ${o[n]}...`).start(),r=!1;try{for(let a of t[n]){if(r)break;try{kt(`${a} .`,{cwd:e,stdio:"ignore"}),r=!0}catch{r=!1}}if(!r)throw new Error("Failed to open with command.");s.succeed(`Project opened in ${o[n]}!`)}catch{s.fail(`Failed to open ${o[n]}`);let a={cursor:`\u274C Cursor command not found!
|
|
2
|
+
import{readFileSync as Vn}from"fs";import{dirname as Kn,join as Bn}from"path";import{fileURLToPath as qn}from"url";import{program as N}from"commander";var p=class extends Error{code;suggestion;constructor(n,o){super(n),this.code=o==null?void 0:o.code,this.suggestion=o==null?void 0:o.suggestion}};var st=!1;function it(e){st=e}function x(){return st}function $(e){console.log(JSON.stringify(e,null,2)),process.exit(0)}function T(e){let o={error:e instanceof Error?e.message:String(e)};e instanceof p&&(e.code&&(o.code=e.code),e.suggestion&&(o.suggestion=e.suggestion)),console.error(JSON.stringify(o,null,2)),process.exit(1)}var z="0.0.0-dev";function at(e){z=e}import te from"chalk";import le from"fs-extra";import yt from"path";import Oo from"os";import wt from"axios";var O=process.env.MAGICPATH_API_URL??"https://preview.api.magicpath.ai";function Ie(e,n){return`${O}/${e}/${n}`}function ct(e){return`${O}/v1/registry/${e}`}var Ro=process.env.MAGICPATH_WEB_URL??"https://preview.magicpath.ai";function lt(e){return`${Ro}${e}`}function Fe(e){return`${O}/auth/${e}`}function Ue(){return`${O}/v1/external-agent/components`}function De(e){return`${O}/v1/external-agent/components/${e}/context`}function mt(e){return`${O}/v1/external-agent/components/${e}/revisions`}function _e(e,n){return`${O}/v1/external-agent/components/${e}/revisions/${n}/files`}function Le(e){return`${O}/v1/external-agent/jobs/${e}`}function Z(){return`${O}/users/me`}function We(){return`${O}/users/me/projects`}function dt(){return`${O}/projects`}function pt(e){return`${O}/projects/${e}`}function je(e){return`${O}/projects/${e}/components`}function $e(){return`${O}/users/me/design-systems`}function gt(e){return`${O}/design-systems/${e}`}function xe(){return`${O}/users/me/socket-rooms`}function ut(){return`${O}/liveblocks/auth`}function ft(e){return`${O}/components/${e}`}function ht(e){return`${O}/organizations/${e}`}function He(e){return`${O}/organizations/${e}/projects`}function ve(e){return`${O}/organizations/${e}/design-systems`}var bt=yt.join(Oo.homedir(),".magicpath"),Ce=yt.join(bt,"session.json");function Te(){try{if(!le.existsSync(Ce))return null;let e=le.readJsonSync(Ce);return e.accessToken&&e.refreshToken?e:null}catch{return null}}function It(e){le.ensureDirSync(bt),le.writeJsonSync(Ce,e)}function ze(e,n){let o=Te();It({accessToken:e,refreshToken:n,user:o==null?void 0:o.user})}function X(){let e=Te();return e?{accessToken:e.accessToken,refreshToken:e.refreshToken}:null}function jt(){try{le.removeSync(Ce)}catch{}}function ko(e){try{let n=Te();n&&(n.user=e,It(n))}catch{}}function $t(){let e=Te();return(e==null?void 0:e.user)??null}function A(){let e=process.env.MAGICPATH_TOKEN;if(e)return{Authorization:`Bearer ${e}`,"X-Client-Type":"cli","X-Client-Version":z};let n=X();if(!n)throw new Error("Not logged in. Run `magicpath-ai login` first.");return{Authorization:`Bearer ${n.accessToken}`,"X-Client-Type":"cli","X-Client-Version":z}}function me(e){var t,s;let n=(t=e.subscription)!=null&&t.active?(s=e.subscription.type)!=null&&s.startsWith("PRO")?"Pro":"Creator":"Free",o={name:e.name||e.firstName||e.displayName,email:e.email,plan:n};return ko(o),o}async function Ge(){let e=A(),n=await wt.get(Z(),{headers:e}),o=n.data.user??n.data;return me(o)}async function de(e){let n=await wt.get(Z(),{headers:e});return((n.data.user??n.data).organizationUsers??[]).map(s=>({id:String(s.organization.id),name:s.organization.name,role:s.role}))}async function H(e,n){let o=await de(n),t=o.find(a=>a.id===e);if(t)return{id:t.id,name:t.name};let s=e.toLowerCase(),r=o.find(a=>a.name.toLowerCase()===s);if(r)return{id:r.id,name:r.name};throw new p(`Team "${e}" not found.`,{code:"TEAM_NOT_FOUND",suggestion:"Run `magicpath-ai list-teams` to see your teams."})}var xt=["#95D5B2","#74C69D","#52B788","#40916C","#2D6A4F","#1B4332"];function Mo(e){return te.hex(xt[Math.min(e,xt.length-1)])}var Je=te.hex("#2D6A4F"),Fo=te.hex("#1B4332"),Uo=te.hex("#E8F5E9"),Ve=te.hex("#888888"),Do=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2551 ","\u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 ","\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D"],_o=["\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551","\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551","\u2588\u2588\u2554\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551","\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D"],Lo=Do.map((e,n)=>e+" "+_o[n]);function Wo(e){return e.map((n,o)=>{let t=Mo(o),s="";for(let r of n)s+=r===" "?r:t(r);return s})}function vt(e){let n=!!X(),o=n?$t():null;console.log();for(let r of Wo(Lo))console.log(r);if(console.log(),n&&o){let r=o.plan?` \xB7 ${o.plan}`:"";console.log(" "+Je("\u25CF")+" "+te.bold(Uo(o.name??"MagicPath User"))+Fo(" "+(o.email??"")+r))}else console.log(" "+Ve("\u25CB Not logged in \xB7 run")+" "+Je("magicpath-ai login"));console.log();let t=20,s=[["search <query>","Search components"],["add <name>","Add to project"],["list-projects","Your projects"],["setup-skills","Set up AI agents"]];for(let[r,a]of s)console.log(" "+Je(r.padEnd(t))+Ve(a));console.log(),console.log(" "+Ve(`v${e} \u2500 magicpath-ai --help`)),console.log()}import Pe from"prompts";import Ut from"ora";import{z as re}from"zod";import se from"path";import qo from"os";import qe from"fs-extra";import{pino as Ct}from"pino";var oe=Ct();function ne(){oe=Ct({level:"debug"}),oe.debug({message:"DEBUG logger enabled. "})}var k={info:e=>{oe.info(e)},debug:e=>{oe.debug(e)},warn:e=>{oe.warn(e)},error:e=>{oe.error(e)}};import zo from"axios";import Ae from"path";import Go from"os";import pe from"fs-extra";import Jo from"adm-zip";import{v4 as Vo}from"uuid";async function Tt(e){let n=Ie("v1","components/repository"),o=`${Vo()}.zip`,t=Ae.join(Go.tmpdir(),o);try{let s=await zo({url:n,params:{key:e},method:"GET",responseType:"stream"});return await pe.ensureDir(Ae.dirname(t)),await new Promise(async(r,a)=>{try{s.data.pipe(pe.createWriteStream(t)).on("error",a).once("close",()=>r(t))}catch(i){a(i)}}),t}catch{throw new p("Failed to download project. Make sure your key is valid.")}}function Ke(e){try{pe.removeSync(e)}catch{}}function At(e,n,o){try{let t=Ae.join(o,n),s=1;for(;pe.existsSync(t);)s++,t=Ae.join(o,`${n}-${s}`);return pe.mkdirSync(t,{recursive:!0}),new Jo(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 St from"ora";import Pt from"fs-extra";import Ko from"path";function Et(){try{return Be("yarn --version",{stdio:"ignore"}),"yarn"}catch{return"npm"}}function Nt(e){let n=Et(),o=St(`\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 Bo(e){let n=Ko.join(e,"package.json");if(!Pt.existsSync(n))return new Set;try{let o=Pt.readJsonSync(n),t=new Set;return o.dependencies&&Object.keys(o.dependencies).forEach(s=>t.add(s)),o.devDependencies&&Object.keys(o.devDependencies).forEach(s=>t.add(s)),t}catch{return new Set}}function Rt(e,n){if(e.length===0)return{installed:[],skipped:[]};let o=Bo(n),t=e.filter(i=>!o.has(i)),s=e.filter(i=>o.has(i));if(t.length===0)return k.debug("All dependencies already installed"),{installed:[],skipped:s};let r=Et(),a=St(`\u{1F4E6} Installing ${t.length} package${t.length>1?"s":""} using ${r}...`).start();try{let i=t.join(" "),c=r==="yarn"?`yarn add ${i}`:`npm install ${i}`;return k.debug({command:c}),Be(c,{cwd:n,stdio:"ignore"}),a.succeed(`Installed ${t.length} package${t.length>1?"s":""}`),{installed:t,skipped:s}}catch{throw a.fail("Failed to install packages"),new p(`Failed to install packages: ${t.join(", ")}. Please install them manually.`)}}import{execSync as Ot}from"child_process";import kt from"ora";function Mt(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"]},s=kt(`\u{1F680} Opening project in ${o[n]}...`).start(),r=!1;try{for(let a of t[n]){if(r)break;try{Ot(`${a} .`,{cwd:e,stdio:"ignore"}),r=!0}catch{r=!1}}if(!r)throw new Error("Failed to open with command.");s.succeed(`Project opened in ${o[n]}!`)}catch{s.fail(`Failed to open ${o[n]}`);let a={cursor:`\u274C Cursor command not found!
|
|
3
3
|
|
|
4
4
|
\u{1F527} To fix this, you need to install the Cursor command line tools:
|
|
5
5
|
|
|
@@ -62,9 +62,9 @@ import{readFileSync as Vn}from"fs";import{dirname as Kn,join as Bn}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(a[n])}}function Ft(e){let n=process.platform,o;switch(n){case"darwin":o="open";break;case"win32":o="explorer";break;default:o="xdg-open";break}let s={darwin:"Finder",win32:"File Explorer",linux:"File Manager"}[n]||"File Manager",r=
|
|
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 Ft(e){let n=process.platform,o;switch(n){case"darwin":o="open";break;case"win32":o="explorer";break;default:o="xdg-open";break}let s={darwin:"Finder",win32:"File Explorer",linux:"File Manager"}[n]||"File Manager",r=kt(`\u{1F4C1} Opening project in ${s}...`).start();try{Ot(`${o} "${e}"`,{stdio:"ignore"}),r.succeed(`Project opened in ${s}!`)}catch{throw r.fail(`Failed to open ${s}`),new p(`Failed to open project in ${s}. The file manager may not be available.`)}}var Zo=re.object({key:re.string(),debug:re.boolean().default(!1),ide:re.enum(["cursor","antigravity","vscode","webstorm"]).optional(),dir:re.string().optional(),name:re.string().optional()});function Dt(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=Zo.parse(n)}catch{throw new Error("Invalid CLI options for clone command.")}o.debug&&ne();let t=x();t&&(!o.dir||!o.name)&&T(new Error("In JSON mode, --dir and --name are required for clone.")),k.debug({options:n}),k.debug({options:o});let s,r;if(o.dir&&o.name)s=se.resolve(o.dir),r=o.name,await qe.ensureDir(s);else{let g=qo.homedir(),I=[{name:"Documents",path:se.join(g,"Documents")},{name:"Desktop",path:se.join(g,"Desktop")},{name:"Downloads",path:se.join(g,"Downloads")}],C=(await Promise.all(I.map(async w=>{try{return await qe.pathExists(w.path)?w:null}catch{return null}}))).filter(w=>w!==null),f=[{title:`Right here (current folder: ${process.cwd()})`,value:process.cwd()},{title:`Home directory (${g})`,value:g}];C.forEach(w=>{f.push({title:w.name,value:w.path})}),f.push({title:"Other (specify custom path)",value:"custom"});let{targetDir:h}=await Pe({type:"select",name:"targetDir",message:"Where should we put your code?",choices:f,initial:0});if(s=h,h==="custom"){let{customPath:w}=await Pe({type:"text",name:"customPath",message:"Enter the full path where you want to create your project:",initial:g,validate:P=>{if(!P)return"Please enter a path";try{return se.resolve(P),!0}catch{return"Please enter a valid path"}}});if(!w)throw new p("Project creation cancelled");s=se.resolve(w);try{await qe.ensureDir(s)}catch{throw new p(`Failed to create or access directory: ${s}`)}}if(!s)throw new p("Download cancelled");if(r=(await Pe({type:"text",name:"projectName",message:"What would you like to name your project?",initial:"magicpath-project"})).projectName,!r)throw new p("Project creation cancelled")}let a,i=t?null:Ut("\u{1F4E5} Downloading project...").start();try{a=await Tt(o.key),k.debug({filename:a}),i==null||i.succeed("Project downloaded")}catch(g){throw i==null||i.fail("Download failed"),g instanceof p?g:new p("Something went wrong!")}let c=t?null:Ut("\u{1F4E6} Unpacking project...").start(),l;try{l=At(a,r,s),c==null||c.succeed(`Project unpacked to ${r}`)}catch(g){throw c==null||c.fail("Failed to unpack project"),Ke(a),g instanceof p?g:new p("Something went wrong!")}try{Nt(l)}catch(g){throw g instanceof p?g:new p("Something went wrong!")}t&&$({projectDir:l});let u=[{title:"Cursor",value:"cursor"},{title:"Antigravity",value:"antigravity"},{title:"VS Code",value:"vscode"},{title:"WebStorm",value:"webstorm"},{title:"Open in file manager",value:"filemanager"},{title:"None (just finish)",value:"none"}],d=0;if(o.ide){let g=u.findIndex(I=>I.value===o.ide);g!==-1&&(d=g)}let y=await Pe({type:"select",name:"ide",message:"Which IDE would you like to open the project in?",choices:u,initial:d});if(y.ide&&y.ide!=="none")try{y.ide==="filemanager"?Ft(l):Mt(l,y.ide)}catch(g){k.debug({err:g}),g instanceof p?console.log(g.message):console.log("\u26A0\uFE0F Opening failed, but your project is ready!")}console.log(`
|
|
66
66
|
\u{1F389} Done! Your project is ready to go at: ${l}`)})}import Ye from"prompts";import{z as U}from"zod";import K from"path";import un from"fs-extra";var J=class extends p{constructor(){super("You must be logged in to install components.")}};import Xo from"ora";var Yo="\x1B[38;2;32;140;80m",Qo="\x1B[0m",en=`${Yo}\u2714${Qo}`;function E(e){let n=Xo(e),o=n.stopAndPersist.bind(n);return n.succeed=t=>o({symbol:en,text:t}),n}import _t from"axios";import V from"fs-extra";import q from"path";import{z as W}from"zod";var tn=W.object({name:W.string(),path:W.string(),content:W.string()}),on=W.object({data:W.object({name:W.string(),generatedName:W.string(),files:W.array(tn),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]*)/),s=e.match(/export\s+const\s+([A-Z][a-zA-Z0-9]*)\s*[=:]/),r=null,a=!1;if(n?(r=n[1],a=!0):o?(r=o[1],a=!0):t?r=t[1]:s&&(r=s[1]),!r)return null;let i=`${r}Props`,c=new RegExp(`(?:interface|type)\\s+${i}\\s*(?:=\\s*)?\\{([^}]*)\\}`,"s"),l=e.match(c),u=[],d=[];if(l){let g=l[1].split(/[;\n]/).filter(I=>I.trim());for(let I of g){let j=I.trim();if(!j||j.startsWith("//")||j.startsWith("/*"))continue;let C=j.match(/^(\w+)(\?)?:/);if(C){let f=C[1],h=!!C[2];if(f==="children")continue;h?d.push(f):u.push(f)}}}return{name:r,isDefault:a,propsType:l?i:void 0,requiredProps:u,optionalProps:d}}function ie(e,n){return e.isDefault?`import ${e.name} from '${n}';`:`import { ${e.name} } from '${n}';`}function ae(e){let{name:n,requiredProps:o,optionalProps:t}=e;if(o.length===0&&t.length===0)return`<${n} />`;let s=o.map(r=>`${r}={/* TODO */}`).join(" ");return s?`<${n} ${s} />`:`<${n} />`}function nn(e){let{componentName:n,importPath:o,exportInfo:t,fileName:s}=e,r=[`# ${n}`,"","## Import","","```tsx"];if(t){if(r.push(ie(t,o)),r.push("```"),r.push(""),r.push("## Usage"),r.push(""),r.push("```tsx"),r.push(ae(t)),r.push("```"),t.requiredProps.length>0){r.push(""),r.push("## Required Props"),r.push("");for(let a of t.requiredProps)r.push(`- \`${a}\``)}if(t.optionalProps.length>0){r.push(""),r.push("## Optional Props"),r.push("");for(let a of t.optionalProps)r.push(`- \`${a}\``)}}else r.push(`import { ${s} } from '${o}';`),r.push("```");return r.push(""),r.join(`
|
|
67
|
-
`)}function Lt(e,n){let o=nn(n),t=q.join(e,"usage.md");V.writeFileSync(t,o,"utf8"),
|
|
67
|
+
`)}function Lt(e,n){let o=nn(n),t=q.join(e,"usage.md");V.writeFileSync(t,o,"utf8"),k.debug({message:"Wrote usage file",usagePath:t})}async function ge(e){var t,s,r;let n=ct(e);k.debug({message:"Fetching component from registry",url:n});let o;try{o=A()}catch{throw new J}try{let a=await _t.get(n,{headers:o});return on.parse(a.data).data}catch(a){throw _t.isAxiosError(a)?((t=a.response)==null?void 0:t.status)===401?new J:((s=a.response)==null?void 0:s.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"}):((r=a.response)==null?void 0:r.status)===404?new p(`Component "${e}" not found. Please check the name and try again.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai search <query>` to find available components."}):new p(`Failed to fetch component: ${a.message}`):new p("Failed to fetch component. Please check your internet connection and try again.")}}function Wt(e,n){let o=[];for(let t of e){let s=q.join(n,t.path);V.existsSync(s)&&o.push(t.path)}return o}function rn(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,(s,r,a,i)=>`${r}${o}${a}${i}`),t=t.replace(/(import\s*\(\s*['"])(\.\.\/)([^'"]+['"]\s*\))/g,(s,r,a,i)=>`${r}${o}${a}${i}`),t=t.replace(/(require\s*\(\s*['"])(\.\.\/)([^'"]+['"]\s*\))/g,(s,r,a,i)=>`${r}${o}${a}${i}`),t}function Ht(e,n,o=!1){V.ensureDirSync(n);for(let t of e){let s=q.join(n,t.path),r=q.dirname(s);V.ensureDirSync(r);let a=o?rn(t.content):t.content;V.writeFileSync(s,a,"utf8"),k.debug({message:"Wrote file",filePath:s})}}function zt(e){let n=q.join(e,"utils.ts");if(!V.existsSync(n))return!1;try{return V.readFileSync(n,"utf8").includes("export function cn")}catch{return!1}}function Gt(e,n){V.ensureDirSync(n);let o=q.join(n,"utils.ts");V.writeFileSync(o,e,"utf8"),k.debug({message:"Wrote utils file",utilsPath:o})}var ue="src/components/magicpath",sn="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 Ee(e,n=process.cwd()){let o=e||ue;return q.join(n,o)}function Jt(e=process.cwd()){return q.join(e,sn)}import an from"http";import cn from"ora";import Ze from"axios";import{exec as ln}from"child_process";var mn=12e4,Kt=`
|
|
68
68
|
*{margin:0;padding:0;box-sizing:border-box}
|
|
69
69
|
body{font-family:Geist,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;background:#fff;color:#1a1a1a;padding:1rem}
|
|
70
70
|
.card{position:relative;width:100%;max-width:32rem;background:#fff;border-radius:1.5rem;box-shadow:0 1px 3px rgba(0,0,0,.1),0 8px 10px -1px rgba(0,0,0,.1);overflow:hidden}
|
|
@@ -92,16 +92,16 @@ p{color:#999;font-size:.9rem;text-align:center;max-width:24rem;line-height:1.5}
|
|
|
92
92
|
Opening your browser to log in...
|
|
93
93
|
`),console.log(`If the browser doesn't open, visit: ${l}
|
|
94
94
|
`);let u=process.platform;ln(`${u==="darwin"?"open":u==="win32"?"start":"xdg-open"} "${l}"`)});let a=cn("Waiting for browser login...").start();t=setTimeout(()=>{o||(r(),a.fail("Login timed out"),console.log("\nTip: You can also log in with `magicpath-ai login --code <code>`."),o=!0,e(!1))},mn)})}function Bt(e){e.command("login").description("Log in to your MagicPath account").option("--code <code>","Exchange an authorization code non-interactively").action(async n=>{try{if(n.code){let t=await Ze.post(Fe("extension/tokens"),{token:n.code}),{access_token:s,refresh_token:r}=t.data;ze(s,r);try{await Ge()}catch{}x()&&$({authenticated:!0,method:"code"}),console.log("Logged in successfully!");return}x()&&(process.env.MAGICPATH_TOKEN&&$({authenticated:!0,method:"environment"}),X()&&$({authenticated:!0,method:"stored"}),T(new Error("Not authenticated. Set MAGICPATH_TOKEN environment variable or run login interactively."))),await Xe()||console.log("Login cancelled.")}catch(o){throw x()&&T(o),o instanceof p&&(console.error(`
|
|
95
|
-
${o.message}`),process.exit(1)),o}}),e.command("logout").description("Log out of your MagicPath account").action(()=>{jt(),x()&&$({loggedOut:!0}),console.log("Logged out successfully.")})}var fn=U.object({yes:U.boolean().default(!1),overwrite:U.boolean().default(!1),path:U.string().optional(),debug:U.boolean().default(!1),dryRun:U.boolean().default(!1)}),Ns=U.object({component:U.string(),generatedName:U.string(),filesWritten:U.array(U.string()),dependenciesInstalled:U.array(U.string()),importStatement:U.string().optional(),usage:U.string().optional(),dryRun:U.boolean()});function qt(e){e.command("add").description("Add a MagicPath component to your project").argument("<generatedNames...>","One or more generated names of components (e.g., wispy-river-5234 bold-moon-2031)").option("-y, --yes","Skip confirmation prompts",!1).option("--overwrite","Overwrite existing files",!1).option("-p, --path <path>",`Custom path for components (default: ${ue})`).option("-d, --debug","Enable debug logging",!1).option("--dry-run","Show what would happen without writing files",!1).action(async(n,o)=>{try{let t;try{t=fn.parse(o)}catch{throw new Error("Invalid CLI options for add command.")}t.debug&&ne();let s=x();s&&(t.yes=!0);let r=n.length>1;r&&(t.yes=!0),
|
|
95
|
+
${o.message}`),process.exit(1)),o}}),e.command("logout").description("Log out of your MagicPath account").action(()=>{jt(),x()&&$({loggedOut:!0}),console.log("Logged out successfully.")})}var fn=U.object({yes:U.boolean().default(!1),overwrite:U.boolean().default(!1),path:U.string().optional(),debug:U.boolean().default(!1),dryRun:U.boolean().default(!1)}),Ns=U.object({component:U.string(),generatedName:U.string(),filesWritten:U.array(U.string()),dependenciesInstalled:U.array(U.string()),importStatement:U.string().optional(),usage:U.string().optional(),dryRun:U.boolean()});function qt(e){e.command("add").description("Add a MagicPath component to your project").argument("<generatedNames...>","One or more generated names of components (e.g., wispy-river-5234 bold-moon-2031)").option("-y, --yes","Skip confirmation prompts",!1).option("--overwrite","Overwrite existing files",!1).option("-p, --path <path>",`Custom path for components (default: ${ue})`).option("-d, --debug","Enable debug logging",!1).option("--dry-run","Show what would happen without writing files",!1).action(async(n,o)=>{try{let t;try{t=fn.parse(o)}catch{throw new Error("Invalid CLI options for add command.")}t.debug&&ne();let s=x();s&&(t.yes=!0);let r=n.length>1;r&&(t.yes=!0),k.debug({generatedNames:n,options:t});let a=process.cwd(),i=K.join(a,"package.json");if(!un.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=[];r&&!s&&console.log(`
|
|
96
96
|
Adding ${n.length} components...
|
|
97
|
-
`);for(let l of n)try{let u=s?null:E(`Fetching component "${l}"...`).start(),d;try{d=await ge(l),u==null||u.succeed(`Found component: ${d.name}`)}catch(v){if(v instanceof J){if(u==null||u.fail("Not logged in"),s||r)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:S}=await Ye({type:"confirm",name:"shouldLogin",message:"You need to be logged in to install components. Log in now?",initial:!0});if(!S){console.log("Installation cancelled.");return}if(!await Xe()){console.log("Installation cancelled.");return}let ee=E(`Fetching component "${l}"...`).start();try{d=await ge(l),ee.succeed(`Found component: ${d.name}`)}catch(rt){throw ee.fail("Failed to fetch component"),rt instanceof p?rt:new p("Something went wrong!")}}else{if(u==null||u.fail("Failed to fetch component"),r){let S=v instanceof p?v.message:"Something went wrong!";c.push({component:l,generatedName:l,filesWritten:[],dependenciesInstalled:[],dryRun:t.dryRun,error:S}),s||console.log(` \u26A0\uFE0F Skipping "${l}": ${S}`);continue}throw v instanceof p?v:new p("Something went wrong!")}}let y=Ee(t.path,a),g=Se(d.name),I=K.join(y,g),j=Jt(a);
|
|
97
|
+
`);for(let l of n)try{let u=s?null:E(`Fetching component "${l}"...`).start(),d;try{d=await ge(l),u==null||u.succeed(`Found component: ${d.name}`)}catch(v){if(v instanceof J){if(u==null||u.fail("Not logged in"),s||r)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:S}=await Ye({type:"confirm",name:"shouldLogin",message:"You need to be logged in to install components. Log in now?",initial:!0});if(!S){console.log("Installation cancelled.");return}if(!await Xe()){console.log("Installation cancelled.");return}let ee=E(`Fetching component "${l}"...`).start();try{d=await ge(l),ee.succeed(`Found component: ${d.name}`)}catch(rt){throw ee.fail("Failed to fetch component"),rt instanceof p?rt:new p("Something went wrong!")}}else{if(u==null||u.fail("Failed to fetch component"),r){let S=v instanceof p?v.message:"Something went wrong!";c.push({component:l,generatedName:l,filesWritten:[],dependenciesInstalled:[],dryRun:t.dryRun,error:S}),s||console.log(` \u26A0\uFE0F Skipping "${l}": ${S}`);continue}throw v instanceof p?v:new p("Something went wrong!")}}let y=Ee(t.path,a),g=Se(d.name),I=K.join(y,g),j=Jt(a);k.debug({basePath:y,componentFolderName:g,componentsPath:I,utilsPath:j});let C=Wt(d.files,I);if(C.length>0&&!t.overwrite)if(s||(console.log(`
|
|
98
98
|
The following files already exist:`),C.forEach(v=>console.log(` - ${v}`))),t.yes){if(r){s||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(s)throw new p(`Files already exist: ${C.join(", ")}. Use --overwrite to replace.`,{code:"FILES_EXIST",suggestion:"Pass `--overwrite` to replace existing files."});console.log("Use --overwrite to replace existing files.");return}else{let{shouldOverwrite:v}=await Ye({type:"confirm",name:"shouldOverwrite",message:"Do you want to overwrite these files?",initial:!1});if(!v){console.log("Installation cancelled.");return}}if(!t.yes&&C.length===0){console.log(`
|
|
99
99
|
This will install:`),console.log(` Component: ${d.name}`),console.log(` Files: ${d.files.length} file(s) to ${K.relative(a,I)||"."}`),console.log(` Dependencies: ${d.dependencies.length} package(s)`);let{shouldProceed:v}=await Ye({type:"confirm",name:"shouldProceed",message:"Proceed with installation?",initial:!0});if(!v){console.log("Installation cancelled.");return}}let f=d.files.map(v=>K.relative(a,K.join(I,v.path))),h=d.files[0],b,w;if(h){let v=h.name.replace(/\.tsx?$/,""),S=t.path?`@/${t.path}/${g}/${v}`:`@/components/magicpath/${g}/${v}`,M=Y(h.content);M?(b=ie(M,S),w=ae(M)):b=`import { ${v} } from '${S}';`}if(t.dryRun){let v=s?d.files.map(S=>({path:S.path,name:S.name,content:S.content})):void 0;!r&&s&&$({component:d.name,generatedName:d.generatedName,filesWritten:f,files:v,dependenciesInstalled:d.dependencies,importStatement:b,usage:w,dryRun:!0}),c.push({component:d.name,generatedName:d.generatedName,filesWritten:f,dependenciesInstalled:d.dependencies,importStatement:b,usage:w,dryRun:!0}),s||(console.log(`
|
|
100
|
-
[Dry run] Would install:`),console.log(` Component: ${d.name}`),console.log(` Files: ${f.join(", ")}`),console.log(` Dependencies: ${d.dependencies.join(", ")||"none"}`),b&&console.log(` Import: ${b}`));continue}let P=s?null:E("Writing component files...").start();try{Ht(d.files,I,!0),P==null||P.succeed(`Wrote ${d.files.length} file(s) to ${K.relative(a,I)||"."}`)}catch{if(P==null||P.fail("Failed to write component files"),r){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(!zt(j)&&d.utils.content){let v=s?null:E("Installing utilities...").start();try{Gt(d.utils.content,j),v==null||v.succeed(`Wrote utils.ts to ${K.relative(a,j)||"."}`)}catch(S){v==null||v.fail("Failed to write utils file"),
|
|
100
|
+
[Dry run] Would install:`),console.log(` Component: ${d.name}`),console.log(` Files: ${f.join(", ")}`),console.log(` Dependencies: ${d.dependencies.join(", ")||"none"}`),b&&console.log(` Import: ${b}`));continue}let P=s?null:E("Writing component files...").start();try{Ht(d.files,I,!0),P==null||P.succeed(`Wrote ${d.files.length} file(s) to ${K.relative(a,I)||"."}`)}catch{if(P==null||P.fail("Failed to write component files"),r){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(!zt(j)&&d.utils.content){let v=s?null:E("Installing utilities...").start();try{Gt(d.utils.content,j),v==null||v.succeed(`Wrote utils.ts to ${K.relative(a,j)||"."}`)}catch(S){v==null||v.fail("Failed to write utils file"),k.debug({err:S}),s||console.log(" Warning: Could not write utils.ts. You may need to create it manually.")}}let R=[];if(d.dependencies.length>0)try{let{installed:v,skipped:S}=Rt(d.dependencies,a);R.push(...v),S.length>0&&k.debug({message:"Skipped already installed packages",skipped:S})}catch(v){v instanceof p&&(s||console.log(`
|
|
101
101
|
\u26A0\uFE0F ${v.message}`))}if(c.push({component:d.name,generatedName:d.generatedName,filesWritten:f,dependenciesInstalled:R,importStatement:b,usage:w,dryRun:!1}),!r&&s&&$({component:d.name,generatedName:d.generatedName,filesWritten:f,dependenciesInstalled:R,importStatement:b,usage:w,dryRun:!1}),s||(console.log(`
|
|
102
102
|
\u2705 Successfully added "${d.name}" to your project!`),r||console.log(`
|
|
103
103
|
Usage:`)),h){let v=h.name.replace(/\.tsx?$/,""),S=t.path?`@/${t.path}/${g}/${v}`:`@/components/magicpath/${g}/${v}`,M=Y(h.content);!r&&!s&&(M?(console.log(` ${ie(M,S)}`),console.log(""),console.log(` ${ae(M)}`),M.requiredProps.length>0&&(console.log(""),console.log(` Required props: ${M.requiredProps.join(", ")}`))):console.log(` import { ${v} } from '${S}';`));try{Lt(I,{componentName:d.name,importPath:S,exportInfo:M,fileName:v}),!r&&!s&&console.log(`
|
|
104
|
-
\u{1F4C4} Usage documentation written to ${K.relative(a,K.join(I,"usage.md"))}`)}catch(ee){
|
|
104
|
+
\u{1F4C4} Usage documentation written to ${K.relative(a,K.join(I,"usage.md"))}`)}catch(ee){k.debug({err:ee})}}}catch(u){if(r){let d=u instanceof Error?u.message:String(u);c.push({component:l,generatedName:l,filesWritten:[],dependenciesInstalled:[],dryRun:t.dryRun,error:d}),s||console.log(` \u26A0\uFE0F Failed "${l}": ${d}`);continue}throw u}if(r){s&&$({results:c,total:c.length,succeeded:c.filter(d=>!d.error).length,failed:c.filter(d=>d.error).length});let l=c.filter(d=>!d.error),u=c.filter(d=>d.error);console.log(`
|
|
105
105
|
${l.length} of ${c.length} component(s) added successfully.`),u.length>0&&console.log(` ${u.length} failed: ${u.map(d=>d.generatedName).join(", ")}`)}}catch(t){throw x()&&T(t),t instanceof p&&(console.error(`
|
|
106
106
|
${t.message}`),process.exit(1)),t}})}import Zt from"axios";function Xt(e){e.command("whoami").description("Show the currently authenticated user").action(async()=>{var o,t,s;let n=x();try{let r;try{r=A()}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("Fetching user info...").start();try{let i=await Zt.get(Z(),{headers:r}),c=i.data.user??i.data;a==null||a.succeed("Authenticated");let l=me(c);n&&$(c),console.log(`
|
|
107
107
|
Name: ${l.name||"N/A"}`),console.log(` Email: ${l.email||"N/A"}`),c.id&&console.log(` ID: ${c.id}`),console.log(` Plan: ${l.plan}`)}catch(i){throw a==null||a.fail("Failed to fetch user info"),Zt.isAxiosError(i)?((o=i.response)==null?void 0:o.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login` to re-authenticate.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):new p(`API error: ${(t=i.response)==null?void 0:t.status} ${(s=i.response)==null?void 0:s.statusText}`):i}}catch(r){throw n&&T(r),r instanceof p&&(console.error(`
|
|
@@ -111,11 +111,11 @@ ${r.message}`),process.exit(1)),r}})}import Qe from"axios";import Ne from"axios"
|
|
|
111
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 r,a,i,c,l;let t=x(),s=parseInt(o.limit,10)||100;try{let u;try{u=A()}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 y=new URLSearchParams({limit:String(s),revisionStatus:"COMPLETED",sortBy:o.sortBy,order:o.order});o.after&&y.set("after",o.after),o.createdBy&&y.set("createdBy",o.createdBy);let g=`${je(n)}?${y}`,I=await Qe.get(g,{headers:u}),j=((r=I.data.data)==null?void 0:r.components)??I.data.components??I.data,C=((a=I.data.data)==null?void 0:a.pagination)??I.data.pagination,f=Array.isArray(j)?j.length:0;if(d==null||d.succeed(`Found ${f} component(s)`),t&&$({components:j,pagination:C??{limit:s,hasNext:!1,lastId:null}}),!Array.isArray(j)||j.length===0){console.log(`
|
|
112
112
|
No components found.`);return}console.log("");let h=Math.max(4,...j.map(w=>(w.name||"").length)),b=Math.max(14,...j.map(w=>(w.generatedName||"").length));console.log(` ${"Name".padEnd(h)} ${"Generated Name".padEnd(b)} ${"Rev".padEnd(4)} ${"Views".padEnd(6)} ${"Likes".padEnd(6)} ${"Remixes".padEnd(7)} ${"Updated".padEnd(10)} ID`),console.log(` ${"\u2500".repeat(h)} ${"\u2500".repeat(b)} ${"\u2500".repeat(4)} ${"\u2500".repeat(6)} ${"\u2500".repeat(6)} ${"\u2500".repeat(7)} ${"\u2500".repeat(10)} ${"\u2500".repeat(20)}`);for(let w of j){let P=(w.name||"").padEnd(h),F=(w.generatedName||"").padEnd(b),R=String(w.revisionCount??"?").padEnd(4),v=String(w.viewCount??0).padEnd(6),S=String(w.likeCount??0).padEnd(6),M=String(w.remixCount??0).padEnd(7),ee=w.updatedAt?new Date(w.updatedAt).toISOString().slice(0,10):"";console.log(` ${P} ${F} ${R} ${v} ${S} ${M} ${ee.padEnd(10)} ${w.id||""}`)}C!=null&&C.hasNext&&console.log(`
|
|
113
113
|
More results available. Use --after ${C.lastId} to see the next page.`)}catch(y){throw d==null||d.fail("Failed to fetch components"),Qe.isAxiosError(y)?((i=y.response)==null?void 0:i.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`.",{code:"TOKEN_EXPIRED",suggestion:"Run `magicpath-ai login` to re-authenticate."}):((c=y.response)==null?void 0:c.status)===404?new p(`Project "${n}" not found.`,{code:"NOT_FOUND",suggestion:"Run `magicpath-ai list-projects` to see available projects."}):new p(`API error: ${(l=y.response)==null?void 0:l.status}`):y}}catch(u){throw t&&T(u),u instanceof p&&(console.error(`
|
|
114
|
-
${u.message}`),process.exit(1)),u}})}import{z as m}from"zod";import{z as L}from"zod";var Qt=L.object({generatedName:L.string().describe("The generated name of the component (e.g., wispy-river-5234)")}),eo=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 to(e){e.command("inspect").description("Inspect a MagicPath component's source code without installing").argument("<generatedName>","Generated name of the component (e.g., wispy-river-5234)").option("-d, --debug","Enable debug logging",!1).action(async(n,o)=>{try{o.debug&&ne();let t=x();
|
|
114
|
+
${u.message}`),process.exit(1)),u}})}import{z as m}from"zod";import{z as L}from"zod";var Qt=L.object({generatedName:L.string().describe("The generated name of the component (e.g., wispy-river-5234)")}),eo=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 to(e){e.command("inspect").description("Inspect a MagicPath component's source code without installing").argument("<generatedName>","Generated name of the component (e.g., wispy-river-5234)").option("-d, --debug","Enable debug logging",!1).action(async(n,o)=>{try{o.debug&&ne();let t=x();k.debug({generatedName:n,options:o});let s=t?null:E(`Fetching component "${n}"...`).start(),r;try{r=await ge(n),s==null||s.succeed(`Found component: ${r.name}`)}catch(d){throw s==null||s.fail("Failed to fetch component"),d instanceof J?new p("Not authenticated. Set MAGICPATH_TOKEN or run `magicpath-ai login`.",{code:"NOT_AUTHENTICATED",suggestion:"Run `magicpath-ai login` or set the MAGICPATH_TOKEN environment variable."}):d instanceof p?d:new p("Something went wrong!")}let a=Se(r.name),i=r.files[0],c,l;if(i){let d=i.name.replace(/\.tsx?$/,""),y=`@/components/magicpath/${a}/${d}`,g=Y(i.content);g?(c=ie(g,y),l=ae(g)):c=`import { ${d} } from '${y}';`}let u=r.files.map(d=>({path:d.path,name:d.name,content:d.content}));if(t){$({component:r.name,generatedName:r.generatedName,files:u,dependencies:r.dependencies,importStatement:c,usage:l});return}console.log(`
|
|
115
115
|
Component: ${r.name}`),console.log(` Files: ${r.files.map(d=>d.path).join(", ")}`),console.log(` Dependencies: ${r.dependencies.join(", ")||"none"}`),c&&console.log(` Import: ${c}`);for(let d of r.files)console.log(`
|
|
116
116
|
${"\u2500".repeat(60)}`),console.log(` ${d.path}`),console.log(`${"\u2500".repeat(60)}`),console.log(d.content)}catch(t){throw x()&&T(t),t instanceof p&&(console.error(`
|
|
117
|
-
${t.message}`),process.exit(1)),t}})}var hn=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")}),yn=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")}),wn=m.object({key:m.string().describe("One-time access key"),dir:m.string().describe("Target directory"),name:m.string().describe("Project name")}),bn=m.object({projectDir:m.string().describe("Path to the created project")}),In=m.object({id:m.string().optional(),displayName:m.string().optional(),email:m.string().optional()}),jn=m.object({team:m.string().optional().describe("Team name or ID to filter by"),personal:m.boolean().optional().describe("Show only personal projects")}),$n=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()})}),xn=m.object({teams:m.array(m.object({id:m.string(),name:m.string(),role:m.string()}))}),vn=m.object({team:m.string().describe("Team name or ID (required)")}),Cn=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()}))}),Tn=m.object({projectId:m.string().describe("The project ID"),createdBy:m.string().optional().describe("Filter to components created or edited by this user ID")}),An=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()})}),Pn=m.object({generatedName:m.string().describe("The generated name of the component")}),Sn=m.object({url:m.string().describe("Preview URL to open in a browser"),generatedName:m.string()}),En=m.object({themes:m.array(m.object({id:m.string(),name:m.string(),isPublic:m.boolean(),createdAt:m.string(),updatedAt:m.string()}))}),Nn=m.object({themeIdOrName:m.string().describe("Theme ID (numeric) or name (case-insensitive match)")}),Rn=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()}),
|
|
118
|
-
Usage: magicpath-ai schema <command>`),console.log(" magicpath-ai schema --all");return}let t=
|
|
117
|
+
${t.message}`),process.exit(1)),t}})}var hn=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")}),yn=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")}),wn=m.object({key:m.string().describe("One-time access key"),dir:m.string().describe("Target directory"),name:m.string().describe("Project name")}),bn=m.object({projectDir:m.string().describe("Path to the created project")}),In=m.object({id:m.string().optional(),displayName:m.string().optional(),email:m.string().optional()}),jn=m.object({team:m.string().optional().describe("Team name or ID to filter by"),personal:m.boolean().optional().describe("Show only personal projects")}),$n=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()})}),xn=m.object({teams:m.array(m.object({id:m.string(),name:m.string(),role:m.string()}))}),vn=m.object({team:m.string().describe("Team name or ID (required)")}),Cn=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()}))}),Tn=m.object({projectId:m.string().describe("The project ID"),createdBy:m.string().optional().describe("Filter to components created or edited by this user ID")}),An=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()})}),Pn=m.object({generatedName:m.string().describe("The generated name of the component")}),Sn=m.object({url:m.string().describe("Preview URL to open in a browser"),generatedName:m.string()}),En=m.object({themes:m.array(m.object({id:m.string(),name:m.string(),isPublic:m.boolean(),createdAt:m.string(),updatedAt:m.string()}))}),Nn=m.object({themeIdOrName:m.string().describe("Theme ID (numeric) or name (case-insensitive match)")}),Rn=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:Pn,output:Sn},add:{description:"Add a MagicPath component to your project",input:hn,output:yn},inspect:{description:"Inspect a MagicPath component's source code without installing",input:Qt,output:eo},clone:{description:"Clone/download a MagicPath project",input:wn,output:bn},whoami:{description:"Show the currently authenticated user",output:In},"list-projects":{description:"List all projects (personal and team)",input:jn,output:$n},"list-teams":{description:"List teams you belong to",output:xn},"list-members":{description:"List members of a team",input:vn,output:Cn},"list-components":{description:"List components in a project",input:Tn,output:An},"list-themes":{description:"List all themes (design systems) for the current user",output:En},"get-theme":{description:"Get a theme definition with CSS variables, fonts, and styling prompt",input:Nn,output:Rn},selection:{description:"Get the currently selected component(s) from the web app canvas",output:m.object({components:m.array(m.object({id:m.string(),name:m.string(),generatedName:m.string().nullable(),clientId:m.string(),projectId:m.string(),projectName:m.string()}))})}};function ke(e){return fe(e)}function fe(e){let n=e._def;if(!n)return{};let o=n.typeName,t={};switch(n.description&&(t.description=n.description),o){case"ZodString":t.type="string";break;case"ZodNumber":t.type="number";break;case"ZodBoolean":t.type="boolean";break;case"ZodOptional":return fe(n.innerType);case"ZodDefault":return{...fe(n.innerType),default:n.defaultValue()};case"ZodArray":t.type="array",t.items=fe(n.type);break;case"ZodObject":{t.type="object",t.properties={};let s=[],r=n.shape();for(let[a,i]of Object.entries(r)){t.properties[a]=fe(i);let c=i._def;(c==null?void 0:c.typeName)!=="ZodOptional"&&(c==null?void 0:c.typeName)!=="ZodDefault"&&s.push(a)}s.length>0&&(t.required=s);break}default:t.type="string"}return t}function oo(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 r={};for(let[a,i]of Object.entries(Oe))r[a]={description:i.description,input:i.input?ke(i.input):void 0,output:i.output?ke(i.output):void 0};console.log(JSON.stringify(r,null,2));return}if(!n){console.log("Available commands:",Object.keys(Oe).join(", ")),console.log(`
|
|
118
|
+
Usage: magicpath-ai schema <command>`),console.log(" magicpath-ai schema --all");return}let t=Oe[n];t||(console.error(`Unknown command: ${n}`),console.error("Available:",Object.keys(Oe).join(", ")),process.exit(1));let s={command:n,description:t.description};t.input&&(s.input=ke(t.input)),t.output&&(s.output=ke(t.output)),console.log(JSON.stringify(s,null,2))})}import{execSync as On}from"child_process";function no(e){e.command("setup-skills").description("Set up MagicPath for AI agents").action(async()=>{console.log("Installing MagicPath skills..."),On("npx skills add https://github.com/MagicPathAI/agent-skills/tree/beta --skill magicpath -y",{stdio:"inherit"})})}import{exec as kn}from"child_process";function Mn(e){return Ie("v1",e)}function ro(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=Mn(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 Fn from"axios";function so(e){e.command("info").description("Show project and auth status (useful for agent context injection)").action(async()=>{let n=x();try{let o=null,t=!1,s=null;process.env.MAGICPATH_TOKEN?(o="environment",t=!0,s=A()):X()&&(o="stored",t=!0,s=A());let r=null,a=null;if(t&&s)try{let l=await Fn.get(Z(),{headers:s}),u=l.data.user??l.data,d=me(u);r={id:u.id,name:d.name??"Unknown",email:d.email??""},a=(u.organizationUsers??[]).map(g=>({id:String(g.organization.id),name:g.organization.name,role:g.role}))}catch{}let i=null;if(t&&s)try{i=(await G(s)).map(u=>{var d;return{id:u.id,name:u.name,componentCount:u.componentCount??((d=u._count)==null?void 0:d.components)??0,ownerType:u.ownerType,ownerName:u.ownerName}})}catch{}if(n&&$({auth:{authenticated:t,method:o,user:r},teams:a,projects:i,cli:{version:z,commands:["add","view","search","inspect","list-projects","list-components","list-teams","list-members","list-themes","get-theme","list-installed","selection","active-project","code","login","logout","whoami","info","clone","setup-skills","schema"]}}),console.log(""),console.log(` MagicPath CLI v${z}`),console.log(""),t&&r?(console.log(` Authenticated: yes (${o})`),console.log(` User: ${r.name} <${r.email}>`)):t?(console.log(` Authenticated: yes (${o})`),console.log(" User: (could not fetch)")):(console.log(" Authenticated: no"),console.log(" Run `magicpath-ai login` to authenticate.")),a&&a.length>0){console.log(""),console.log(` Teams: ${a.length}`);for(let l of a)console.log(` - ${l.name} (${l.role.toLowerCase()})`)}if(console.log(""),i&&i.length>0){console.log(` Projects: ${i.length}`);for(let l of i){let u=l.ownerType==="personal"?"":` [${l.ownerName}]`;console.log(` - ${l.name} (${l.componentCount} components)${u}`)}}else t&&console.log(" Projects: none");console.log("")}catch(o){n&&T(o),console.error(`Error: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}})}import io from"axios";function ao(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 r,a;let t=x(),s=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=A()}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 h=await H(o.team,i);l={orgId:h.id,orgName:h.name}}let u=await G(i,l);if(u.length===0){c==null||c.succeed("No projects found"),t&&$([]),console.log(`
|
|
119
119
|
No projects found.`);return}let d=await Promise.all(u.map(async h=>{var b;try{let w=`${je(h.id)}?limit=100&revisionStatus=COMPLETED`,P=await io.get(w,{headers:i}),F=((b=P.data.data)==null?void 0:b.components)??P.data.components??P.data;return{project:h,components:Array.isArray(F)?F:[]}}catch{return{project:h,components:[]}}})),y=n.toLowerCase(),g=[];for(let{project:h,components:b}of d){for(let w of b){if(g.length>=s)break;(w.name||"").toLowerCase().includes(y)&&g.push({name:w.name,generatedName:w.generatedName,id:w.id,projectName:h.name,projectId:h.id,previewImageUrl:w.previewImageUrl??null,ownerType:h.ownerType,ownerName:h.ownerName})}if(g.length>=s)break}if(c==null||c.succeed(`Found ${g.length} match(es) for "${n}"`),t&&$(g),g.length===0){console.log(`
|
|
120
120
|
No components matching "${n}".`);return}console.log("");let I=Math.max(4,...g.map(h=>h.name.length)),j=Math.max(13,...g.map(h=>h.generatedName.length)),C=Math.max(7,...g.map(h=>h.projectName.length)),f=Math.max(9,...g.map(h=>h.ownerType==="personal"?8:h.ownerName.length));console.log(` ${"Name".padEnd(I)} ${"Generated Name".padEnd(j)} ${"Project".padEnd(C)} ${"Workspace".padEnd(f)}`),console.log(` ${"\u2500".repeat(I)} ${"\u2500".repeat(j)} ${"\u2500".repeat(C)} ${"\u2500".repeat(f)}`);for(let h of g){let b=h.ownerType==="personal"?"Personal":h.ownerName;console.log(` ${h.name.padEnd(I)} ${h.generatedName.padEnd(j)} ${h.projectName.padEnd(C)} ${b.padEnd(f)}`)}}catch(l){throw c==null||c.fail("Search failed"),l instanceof p?l:io.isAxiosError(l)?((r=l.response)==null?void 0:r.status)===401?new p("Token is invalid or expired. Run `magicpath-ai login`."):new p(`API error: ${(a=l.response)==null?void 0:a.status}`):l}}catch(i){throw t&&T(i),i instanceof p&&(console.error(`
|
|
121
121
|
${i.message}`),process.exit(1)),i}})}import Q from"path";import ce from"fs-extra";function Un(e,n){if(!ce.existsSync(e))return[];let o=ce.readdirSync(e,{withFileTypes:!0}),t=[];for(let s of o){if(!s.isDirectory())continue;let r=Q.join(e,s.name),a=ce.readdirSync(r).filter(u=>!ce.statSync(Q.join(r,u)).isDirectory()),i=a.find(u=>(u.endsWith(".tsx")||u.endsWith(".ts"))&&u!=="usage.md"&&!u.includes(".test.")&&!u.includes(".spec.")),c=null,l=null;if(i)try{let u=ce.readFileSync(Q.join(r,i),"utf8"),d=Y(u);if(d){c=d.name;let y=i.replace(/\.tsx?$/,""),g=`@/components/magicpath/${s.name}/${y}`;d.isDefault?l=`import ${d.name} from '${g}';`:l=`import { ${d.name} } from '${g}';`}}catch{}t.push({name:c||s.name,folder:s.name,path:Q.relative(n,r),files:a.filter(u=>u!=="usage.md"),exportName:c,importStatement:l})}return t}function co(e){e.command("list-installed").description("List MagicPath components installed in the current project").option("-p, --path <path>",`Custom components path (default: ${ue})`).action(async n=>{let o=x();try{let t=process.cwd(),s=Ee(n.path,t);if(!ce.existsSync(s)){o&&$({components:[],total:0}),console.log(`
|