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