heroui-cli
Version:
A CLI tool that unlocks seamless HeroUI integration
39 lines (38 loc) • 45.2 kB
JavaScript
import I from'chalk';import {Command}from'commander';import wt from'gradient-string';import y,{existsSync,mkdirSync,writeFileSync,renameSync,statSync,readFileSync}from'fs';import lr,{resolve,join}from'pathe';import {execSync,exec}from'child_process';import {validate,compareVersions}from'compare-versions';import oo from'ora';import {fileURLToPath}from'url';import'fast-glob';import {PostHog}from'posthog-node';import A,{dirname}from'path';import vo,{homedir}from'os';import gt from'@winches/prompts';import*as Y from'@clack/prompts';import {spinner,select,text,cancel,isCancel}from'@clack/prompts';import {Readable}from'stream';import {pipeline}from'stream/promises';import ar from'async-retry';import*as ln from'tar';import {findUp}from'find-up';var kt=["#F54180","#338EF7"],Ke=wt(...kt),Xn=Ke("HeroUI CLI:"),a=class{static log(...t){console.log(...t);}static info(...t){console.info(...t.map(n=>I.blue(n)));}static success(...t){console.info(...t.map(n=>I.green(n)));}static warn(...t){console.warn(...t.map(n=>I.yellow(n)));}static error(...t){console.error(...t.map(n=>I.red(n)));}static grey(...t){console.log(...t.map(n=>I.gray(n)));}static gradient(t,n){this.log(wt(...n?.colors??kt)(String(t)));}static prefix(t,...n){return this[t](Xn,...n)}static newLine(t=1){for(let n=0;n<t;n++)this.log();}};function Qn(e,t){let n=0,r=e.length,o=t.length,i=0,s=0;for(;i<r&&s<o;)e[i]===t[s]&&(n++,s++),i++;return n}function ze(e,t){let n=0,r="";for(let o of e){let i=Qn(o,t);i>n&&(n=i,r=o);}return r!==""?r:null}function Je(e,t){let n=ze(e,t);n?a.error(`Unknown option '${t}', Did you mean '${n}'?`):a.error(`Unknown option '${t}'`),process.exit(1);}var qe={bold:{bottomLeft:"\u2517",bottomRight:"\u251B",horizontal:"\u2501",topLeft:"\u250F",topRight:"\u2513",vertical:"\u2503"},classic:{bottomLeft:"+",bottomRight:"+",horizontal:"-",topLeft:"+",topRight:"+",vertical:"|"},double:{bottomLeft:"\u255A",bottomRight:"\u255D",horizontal:"\u2550",topLeft:"\u2554",topRight:"\u2557",vertical:"\u2551"},doubleSingle:{bottomLeft:"\u2558",bottomRight:"\u255B",horizontal:"\u2550",topLeft:"\u2552",topRight:"\u2555",vertical:"\u2502"},round:{bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",topLeft:"\u256D",topRight:"\u256E",vertical:"\u2502"},single:{bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",topLeft:"\u250C",topRight:"\u2510",vertical:"\u2502"},singleDouble:{bottomLeft:"\u2559",bottomRight:"\u255C",horizontal:"\u2500",topLeft:"\u2553",topRight:"\u2556",vertical:"\u2551"}};var At="heroui-cli";var se="@heroui/react",Zn="@heroui/styles",b=[se,Zn];var Et="https://heroui.com/docs/react/getting-started/quick-start";function O(e="",t=""){if(!validate(e))return -1;try{return compareVersions(e,t)}catch{return 0}}async function Xe(e,t){t=t??`Executing ${e}`;let n=oo({discardStdin:false,spinner:{frames:[`\u280B ${I.gray(`${t}.`)}`,`\u2819 ${I.gray(`${t}..`)}`,`\u2839 ${I.gray(`${t}...`)}`,`\u2838 ${I.gray(`${t}.`)}`,`\u283C ${I.gray(`${t}..`)}`,`\u2834 ${I.gray(`${t}...`)}`,`\u2826 ${I.gray(`${t}.`)}`,`\u2827 ${I.gray(`${t}..`)}`,`\u2807 ${I.gray(`${t}...`)}`,`\u280F ${I.gray(`${t}.`)}`],interval:150}});n.start();let r=await new Promise(o=>{exec(e,(i,s)=>{i&&(a.error(`Exec cmd ${e} error`),process.exit(1)),o(s.trim());});});return n.stop(),r}async function T(e){return (await Dt(e)).version}process.env.CI==="true";var Ct=resolve(fileURLToPath(import.meta.url),"../.."),Qe=e=>resolve(Ct,e),de=resolve(Ct,"..","node_modules/.heroui-cli-cache"),ae=resolve(`${de}/data.json`);var ao=30*6e4,Ze=false;function Te(e=Ze){Ze=!!e,existsSync(de)||mkdirSync(de,{recursive:true}),existsSync(ae)||writeFileSync(ae,JSON.stringify({}),"utf8");}function _e(){(!existsSync(de)||!existsSync(ae))&&Te();let e=readFileSync(ae,"utf8");return JSON.parse(e)}function $t(e,t,n){Te();let r=n??_e(),o=new Date,i=+o+ao;r[e]={...t,date:o,expiredDate:i,expiredFormatDate:new Date(i).toString(),formatDate:o.toString()},writeFileSync(ae,JSON.stringify(r,void 0,2),"utf-8");}function co(){return Date.now()}function It(e,t){if(Ze)return true;let r=(t??_e())[e];return r?.expiredDate?co()>r.expiredDate:true}async function Dt(e){let t=_e();if(It(e,t)){let o={version:await Xe(`npm view ${e} version`,`Fetching ${e} latest version`)};return $t(e,o,t),o}return {version:t[e].version}}async function N(e,t){let n=_e();if(It(e,n)){let i={execResult:await Xe(e,t)};return $t(e,i,n),i.execResult}return n[e].execResult}var V=process.cwd(),_=e=>resolve(V,e);var he=/([\^~])/;function Ot(e,t){return a.gradient(e),t}function Tt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function ye(e,t){return e=ee(e),t=ee(t),et(e,t)?et(e,t):tt(e,t)?tt(e,t):Rt(e,t)?Rt(e,t):t}function et(e,t){let n=e.split("."),r=t.split(".");return n[0]!==r[0]?I.redBright(r.join(".")):""}function tt(e,t){let n=e.split("."),r=t.split(".");return n[1]!==r[1]?`${I.white(r[0])}${I.white(".")}${I.cyanBright(r.slice(1).join("."))}`:""}function Rt(e,t){let n=e.split("."),r=t.split(".");return n[2]!==r[2]?`${I.white(r.slice(0,2).join("."))}${I.white(".")}${I.greenBright(r.slice(2).join("."))}`:""}function $(e,t){let n=e[t].replace(he,""),r=e[t].match(he)?.[1]||"";return {currentVersion:n,versionMode:r}}function ce(e){return {bun:{install:"add",remove:"remove",run:"run"},npm:{install:"install",remove:"uninstall",run:"run"},pnpm:{install:"add",remove:"remove",run:"run"},yarn:{install:"add",remove:"remove",run:"run"}}[e]}function ee(e,t=false){return e.split("||").map(o=>o.trim()).map(o=>o.replace(/^[<=>^~]+\s*/,"").trim()).sort((o,i)=>t?compareVersions(i,o):compareVersions(o,i))[0]??e}function W(e,t){let n=e.replace(H,""),r=t-n.length>0?" ".repeat(t-n.length):"";return `${e}${r}`}function xe(e){return e.replace(H,"")}function L(e){(!e||typeof e!="string")&&(a.prefix("error","Invalid package.json path. Please provide a valid file path."),process.exit(1));try{statSync(e).isDirectory()&&(e=resolve(e,"package.json"));}catch{}let t;try{t=JSON.parse(readFileSync(e,"utf-8"));}catch(c){a.prefix("error",`Error reading package.json file: ${e}
Error: ${c}`),process.exit(1);}let n=t.devDependencies||{},r=t.dependencies||{},o={...n,...r},i=new Set(Object.keys(o)),s=i.has(se);return {allDependencies:o,allDependenciesKeys:i,dependencies:r,devDependencies:n,isAllComponents:s,packageJson:t}}async function K(e,t,n=true){let r=[];for(let o of e){let i=o in t,s=i?$(t,o).currentVersion:"",c=i?$(t,o).versionMode:"",l=(await N(`npm show ${o} homepage`)||"").replace(/\n/,""),p=(await N(`npm show ${o} description`)||"").replace(/\n/,""),u=await T(o);s=i&&n?`${s} new: ${u}`:u;let d={description:p||"",docs:l||"",name:o,package:o,peerDependencies:{},status:"stable",style:"",version:s,versionMode:c};r.push(d);}return r}var H=/\u001b\[[\d;]+m/g,C=qe.round,nt=" ",ve=`${C.vertical}${nt}`,_t=`${nt}${C.vertical}${nt}`,Lt=/([\W\w]+)\snew:/,Mt=/new:\s([\W\w]+)/;function z({commandName:e,components:t,message:n=`Current installed components:
`,warnError:r=true}){if(!t.length){r&&a.prefix("warn","No components found");return}let o=["package","version","status","docs"],i=["package","version","status"],s={description:0,docs:0,name:0,originVersion:0,package:0,peerDependencies:0,status:0,style:0,version:0,versionMode:0};for(let m of t)for(let f in m){let h=String(m[f]);if(f==="version"){let g=h.match(Mt)?.[1],x=h.match(Lt)?.[1];if(x&&g){let D=xe(Nt(x,g));s[f]=Math.max(s[f],Math.max(D.length,7)),s.originVersion=Math.max(s.originVersion,x.length);}else s[f]=Math.max(s[f],Math.max(h.length,7));continue}s[f]=Math.max(s[f],h.length);}let c=t.reduce((m,f)=>{let h=ve;for(let g of o){let x=W(f[g],s[g]);if(e!=="list"&&g==="version"){let D=x.match(Lt)?.[1]?.trim(),k=x.match(Mt)?.[1]?.trim();D&&k&&(D===k?(x=x.replace(/\snew:\s[\W\w]+(\s+)?/,""),x=W(`${W(x,s.originVersion)} \u{1F680}latest`,s[g]),x=x.replace("latest",I.magentaBright.underline("latest"))):x=W(Nt(W(D,s.originVersion),k),s[g]));}f.status==="stable"&&i.includes(g)?x=I.greenBright(x):f.status==="new"?x=I.magentaBright(x):f.status==="updated"&&(x=I.blueBright(x)),h+=x+_t;}return m.push(h),m},[]),l=C.topLeft+ve.replace(/.*/g,C.horizontal).slice(1),p=ve,u=C.vertical+ve.replace(/.*/g,C.horizontal).slice(1);for(let m of o)l+=`${C.horizontal.padEnd(s[m]+7,C.horizontal)}`,p+=I.redBright(Tt(m).padEnd(s[m]))+_t,u+=`${C.horizontal.padEnd(s[m]+7,C.horizontal)}`;l=l.slice(0,-2)+C.topRight,u=u.slice(0,-2)+C.vertical;let d=C.bottomLeft+ve.replace(/.*/g,C.horizontal).slice(1);for(let m of o)d+=`${C.horizontal.padEnd(s[m]+7,C.horizontal)}`;d=d.slice(0,-2)+C.bottomRight,c=[l,p,u,...c,d],a.info(n),a.log(c.join(`
`));}function Ut(){a.newLine(),a.log(I.redBright("Environment Info:")),a.log(I.blueBright(" System:")),a.log(I.blueBright(" OS:"),process.platform),a.log(I.blueBright(" CPU:"),process.arch),a.log(I.greenBright(" Binaries:")),a.log(I.greenBright(" Node:"),process.version),a.newLine();}function J({align:e="center",borderStyle:t="round",center:n=false,color:r,log:o=true,padding:i=0,text:s,title:c}){let l=qe[t],p=r?Object.fromEntries(Object.entries(l).map(([v,w])=>[v,I[r](w)])):l,u=s.split(`
`),d=u.map(v=>v.replace(H,"")),m=i>0,f=i,h=n||m,g=d.reduce((v,w)=>w.length>v?w.length:v,0);g=m?g+f*4:g;let x=c?c.replace(H,""):"",D=c?x.length:0,k=g-D,me=2;for(;D+me+f>=g;)g+=Math.floor(D/2);k=g-D;let X=(()=>{if(c)if(e==="center"){let v=Math.floor(k/2)-1,w=Math.ceil(k/2)-1,Q=v>0?p.horizontal.repeat(v):"",R=w>0?p.horizontal.repeat(w):"";return `${Q} ${c} ${R}`}else return e==="left"?` ${c} ${p.horizontal.repeat(k-2)}`:`${p.horizontal.repeat(k-2)} ${c} `;return p.horizontal.repeat(g)})(),Be=p.topLeft+X+p.topRight,Ye=p.bottomLeft+p.horizontal.repeat(g)+p.bottomRight,S=u.reduce((v,w)=>{let Q=w.replace(H,""),R=g-Q.length,Ie=" ".repeat(R),ge=Math.floor(R/2),Pe=Math.ceil(R/2),We=ge>0?" ".repeat(ge):"",Jn=Pe>0?" ".repeat(Pe):"";if(n)v.push(`${p.vertical}${R?`${We}${w}${Jn}`:w}${p.vertical}`);else if(i){let qn=R-f*2;v.push(`${p.vertical}${" ".repeat(f*2)}${w}${" ".repeat(qn)}${p.vertical}`);}else v.push(`${p.vertical}${R>0?`${w}${Ie}`:w}${p.vertical}`);return v},[]);if(h)for(let v=0;v<f;v++)S.unshift(`${p.vertical}${" ".repeat(g)}${p.vertical}`),S.push(`${p.vertical}${" ".repeat(g)}${p.vertical}`);return S=[Be,...S,Ye],o&&a.log(S.join(`
`)),S.join(`
`)}function Nt(e,t){return `${I.white(`${e} ->`)} ${I.yellowBright(`${t} (new)`)}`}var Le={version:"3.0.4"};var jt=(e,t="Unknown error")=>{if(!e)return t;if(typeof e=="string")return e;if(typeof e=="object"){let n=e;if(Array.isArray(n.messages))return n.messages.join(", ");let r=["message","error","err","errorMessage","errorMsg"];for(let i of r)if(typeof n[i]=="string")return n[i];if(Object.keys(n).length>0)try{return JSON.stringify(n)}catch{return t}}try{return JSON.stringify(e)}catch{return t}};var Vt="cli",Ft="cli-anonymous",Se=class{constructor({dryRun:t,host:n,key:r}){this.posthog=null;t||r&&n&&(this.posthog=new PostHog(r,{host:n}));}track({event:t,properties:n={}}){this.posthog?.capture({distinctId:Ft,event:t,properties:{app:Vt,...n}});}trackError({error:t,errorEvent:n,fallbackMessage:r,properties:o={}}){this.posthog?.capture({distinctId:Ft,event:n,properties:{app:Vt,errorMessage:jt(t,r),isError:true,...o}});}async shutdown(){await this.posthog?.shutdown();}};var te=null,Ht="phc_PHTdOMrOlb4KQmlzTNf1K6B8AIVvf1S6v3Ryryytp9s",yo="https://us.i.posthog.com";function xo(){let e=process.env.HEROUI_ANALYTICS_DISABLED;return e==="1"||e==="true"}function Me(){return te!==null?te:xo()||!Ht?null:(te=new Se({dryRun:false,host:yo,key:Ht}),te)}async function we(){te&&(await te.shutdown(),te=null);}var So=["agent-index.mdx","hooks.mdx","styling.mdx"],ot="(workflows)",Gt="(migration-for-agents)",F="apps/docs/content/docs/en",wo=/<include>(.+?)<\/include>/g;function ko(e,t,n){let r=t.includes("/")?t.slice(0,t.lastIndexOf("/")):".";return e.replace(wo,(o,i)=>{let s=i.indexOf("#");if(s===-1)return o;let c=i.slice(0,s).trim(),l=i.slice(s+1).trim();if(!c||!l)return o;let p=A.normalize(A.join(r,c)).replace(/\\/g,"/"),u=A.join(n,p);if(!y.existsSync(u))return o;let d=y.readFileSync(u,"utf-8"),m=`<section id="${l}">`,f=d.indexOf(m);if(f===-1)return o;let h=f+m.length,g=d.indexOf("</section>",h);return g===-1?o:d.slice(h,g).trim()})}async function Bt(e,t,n,r){let o=y.mkdtempSync(A.join(vo.tmpdir(),"heroui-agents-md-")),i=r?"git@github.com:heroui-inc/heroui.git":"https://github.com/heroui-inc/heroui.git";try{try{execSync(`git clone --depth 1 --filter=blob:none --sparse --branch ${e} ${i} .`,{cwd:o,stdio:"pipe"});}catch(s){let c=s instanceof Error?s.message:String(s);throw c.includes("not found")||c.includes("did not match")?new Error(`Could not find documentation for HeroUI ${e}. This branch/tag may not exist on GitHub.`):s}if(n==="react"){let s=[`${F}/react`,`!${F}/react/migration`,"apps/docs/src/demos"].join(`
`);execSync("git sparse-checkout set --no-cone --stdin",{cwd:o,input:s,stdio:["pipe","pipe","pipe"]});}else n==="native"?execSync(`git sparse-checkout set ${F}/native`,{cwd:o,stdio:"pipe"}):execSync(`git sparse-checkout set ${F}/react/migration`,{cwd:o,stdio:"pipe"});if(y.mkdirSync(t,{recursive:!0}),n==="react"){let s=A.join(o,...F.split("/"),"react");if(!y.existsSync(s))throw new Error(`Expected React docs at "${F}/react" on branch "${e}" but the directory is missing. The upstream docs layout may have changed; please report this at https://github.com/heroui-inc/heroui-cli/issues.`);let c=A.join(t,"react");y.existsSync(c)&&y.rmSync(c,{recursive:!0}),y.mkdirSync(c,{recursive:!0}),y.cpSync(s,c,{recursive:!0});let l=A.join(o,"apps","docs","src","demos");if(y.existsSync(l)){let p=A.join(t,"react","demos");y.existsSync(p)&&y.rmSync(p,{recursive:!0}),y.mkdirSync(p,{recursive:!0}),y.cpSync(l,p,{recursive:!0});}}else if(n==="native"){let s=A.join(o,...F.split("/"),"native");if(!y.existsSync(s))throw new Error(`Expected Native docs at "${F}/native" on branch "${e}" but the directory is missing. The upstream docs layout may have changed; please report this at https://github.com/heroui-inc/heroui-cli/issues.`);let c=A.join(t,"native");y.existsSync(c)&&y.rmSync(c,{recursive:!0}),y.mkdirSync(c,{recursive:!0}),y.cpSync(s,c,{recursive:!0});}else {let s=A.join(o,...F.split("/"),"react","migration");if(!y.existsSync(s))throw new Error(`Expected Migration docs at "${F}/react/migration" on branch "${e}" but the directory is missing. The upstream docs layout may have changed; please report this at https://github.com/heroui-inc/heroui-cli/issues.`);let c=A.join(t,"migration");y.existsSync(c)&&y.rmSync(c,{recursive:!0}),y.mkdirSync(c,{recursive:!0});for(let d of So){let m=A.join(s,d);y.existsSync(m)&&y.copyFileSync(m,A.join(c,d));}let l=A.join(s,ot);if(y.existsSync(l)){let d=A.join(c,ot);y.mkdirSync(d,{recursive:!0});for(let m of y.readdirSync(l)){if(!m.startsWith("agent-"))continue;let f=A.join(l,m),h=A.join(d,m),g=`${ot}/${m}`;if(!y.statSync(f).isFile())continue;let x=y.readFileSync(f,"utf-8"),D=ko(x,g,s);y.writeFileSync(h,D,"utf-8");}}let p=A.join(s,"(components)");if(y.existsSync(p)){let d=A.join(c,"(components)");y.mkdirSync(d,{recursive:!0}),y.cpSync(p,d,{recursive:!0});}let u=A.join(s,Gt);if(y.existsSync(u)){let d=A.join(c,Gt);y.mkdirSync(d,{recursive:!0}),y.cpSync(u,d,{recursive:!0});}}}finally{y.existsSync(o)&&y.rmSync(o,{recursive:true});}}function je(e){return y.readdirSync(e,{recursive:true}).filter(t=>(t.endsWith(".mdx")||t.endsWith(".md"))&&!t.endsWith("/index.mdx")&&!t.endsWith("/index.md")&&!t.startsWith("index.")).sort().map(t=>({relativePath:t}))}function rt(e){return y.readdirSync(e,{recursive:true}).filter(t=>t.endsWith(".mdx")||t.endsWith(".md")).sort().map(t=>({relativePath:t}))}function it(e){return y.existsSync(e)?y.readdirSync(e,{recursive:true}).filter(t=>t.endsWith(".tsx")&&!t.endsWith("/index.tsx")).sort().map(t=>({relativePath:t})):[]}function ke(e){let t=new Map;for(let r of e){let o=r.relativePath.includes("/")?r.relativePath.slice(0,r.relativePath.lastIndexOf("/")):".";t.has(o)||t.set(o,{files:[],name:o,subsections:[]}),t.get(o).files.push(r);}let n=Array.from(t.values()).sort((r,o)=>r.name.localeCompare(o.name));for(let r of n)r.files.sort((o,i)=>o.relativePath.localeCompare(i.relativePath));return n}function Ae(e){let t=[];for(let n of e){for(let r of n.files)t.push(r.relativePath);t.push(...Ae(n.subsections));}return t}function Ee(e,t){let n=new Map;for(let r of e){let o=r.lastIndexOf("/"),i=o===-1?".":r.slice(0,o),s=o===-1?r:r.slice(o+1),c=t?`${t}/${i}`:i,l=n.get(c);l?l.push(s):n.set(c,[s]);}return n}function De(e,t){let{migrationDocsPath:n,migrationSections:r,nativeDocsPath:o,nativeSections:i,outputFile:s,reactDemoFiles:c,reactDocsPath:l,reactSections:p}=e,u=[];if(t==="react"){u.push("[HeroUI React v3 Docs Index]"),l&&u.push(`root: ${l}`),u.push("STOP. What you remember about HeroUI React v3 is WRONG for this project. Always search docs and read before any task.");let d=s||"AGENTS.md";if(u.push(`If docs missing, run this command first: heroui agents-md --react --output ${d}`),p){let m=Ae(p),f=Ee(m);for(let[h,g]of f)u.push(`${h}:{${g.join(",")}}`);}if(c&&c.length>0){let m=c.map(h=>h.relativePath),f=Ee(m,"demos");for(let[h,g]of f)u.push(`${h}:{${g.join(",")}}`);}}else if(t==="native"){u.push("[HeroUI Native Docs Index]"),o&&u.push(`root: ${o}`),u.push("STOP. What you remember about HeroUI Native is WRONG for this project. Always search docs and read before any task.");let d=s||"AGENTS.md";if(u.push(`If docs missing, run this command first: heroui agents-md --native --output ${d}`),i){let m=Ae(i),f=Ee(m);for(let[h,g]of f)u.push(`${h}:{${g.join(",")}}`);}}else {u.push("[HeroUI Migration Docs Index]"),n&&u.push(`root: ${n}`),u.push("STOP. Always search migration docs before migrating components from HeroUI v2 to v3."),u.push("Start with: agent-index.mdx, then follow the workflow and component guides.");let d=s||"AGENTS.md";if(u.push(`If docs missing, run this command first: heroui agents-md --migration --output ${d}`),r){let m=Ae(r),f=Ee(m);for(let[h,g]of f)u.push(`${h}:{${g.join(",")}}`);}}return u.join("|")}var Eo="<!-- HEROUI-REACT-AGENTS-MD-START -->",Do="<!-- HEROUI-REACT-AGENTS-MD-END -->",Co="<!-- HEROUI-NATIVE-AGENTS-MD-START -->",bo="<!-- HEROUI-NATIVE-AGENTS-MD-END -->",$o="<!-- HEROUI-MIGRATION-AGENTS-MD-START -->",Io="<!-- HEROUI-MIGRATION-AGENTS-MD-END -->";function ct(e){return e==="react"?{end:Do,start:Eo}:e==="native"?{end:bo,start:Co}:{end:Io,start:$o}}function Po(e,t){let{start:n}=ct(t);return e.includes(n)}function Ro(e,t){let{end:n,start:r}=ct(t);return `${r}
${e}
${n}`}function at(e,t,n){let{end:r,start:o}=ct(n),i=Ro(t,n);if(Po(e,n)){let c=e.indexOf(o),l=e.indexOf(r)+r.length;return e.slice(0,c)+i+e.slice(l)}let s=e.endsWith(`
`)?`
`:`
`;return e+s+i+`
`}function pt(e,t,n,r){let o=e;return t!==void 0&&(o=at(o,t,"react")),n!==void 0&&(o=at(o,n,"native")),r!==void 0&&(o=at(o,r,"migration")),o}var Oo=".heroui-docs/";function lt(e){let t=A.join(e,".gitignore"),n=/^\s*\.heroui-docs(?:\/.*)?$/,r="";if(y.existsSync(t)&&(r=y.readFileSync(t,"utf-8")),r.split(/\r?\n/).some(l=>n.test(l)))return {alreadyPresent:true,path:t,updated:false};let i=r.length>0&&!r.endsWith(`
`),s=r.includes("# heroui-agents-md")?"":`# heroui-agents-md
`,c=r+(i?`
`:"")+s+`${Oo}
`;return y.writeFileSync(t,c,"utf-8"),{alreadyPresent:false,path:t,updated:true}}function To(e){let t=A.join(e,"package.json"),n=A.join(e,"pnpm-workspace.yaml");if(y.existsSync(n)){let i=_o(n);if(i.length>0)return {isMonorepo:true,packages:i,type:"pnpm"}}if(y.existsSync(t)){let i=Wt(t);if(i.length>0)return {isMonorepo:true,packages:i,type:"npm"}}let r=A.join(e,"lerna.json");if(y.existsSync(r)){let i=Lo(r);if(i.length>0)return {isMonorepo:true,packages:i,type:"lerna"}}let o=A.join(e,"nx.json");if(y.existsSync(o)){let i=Mo(e,t);if(i.length>0)return {isMonorepo:true,packages:i,type:"nx"}}return {isMonorepo:false,packages:[],type:null}}function _o(e){try{let n=y.readFileSync(e,"utf-8").split(`
`),r=[],o=!1;for(let i of n){let s=i.trim();if(s==="packages:"){o=!0;continue}if(o){if(s&&!s.startsWith("-")&&!s.startsWith("#"))break;let c=s.match(/^-\s*["']?([^"']+)["']?$/);c&&c[1]&&r.push(c[1]);}}return r}catch{return []}}function Wt(e){try{let t=y.readFileSync(e,"utf-8"),n=JSON.parse(t);return Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages&&Array.isArray(n.workspaces.packages)?n.workspaces.packages:[]}catch{return []}}function Lo(e){try{let t=y.readFileSync(e,"utf-8"),n=JSON.parse(t);return Array.isArray(n.packages)?n.packages:["packages/*"]}catch{return []}}function Mo(e,t){if(y.existsSync(t)){let o=Wt(t);if(o.length>0)return o}let n=["apps/*","libs/*","packages/*"],r=[];for(let o of n){let i=A.join(e,o.replace("/*",""));y.existsSync(i)&&r.push(o);}return r}function No(e,t){let n=Uo(e,t),r=[],o=[];for(let c of n){let l=A.join(c,"package.json");if(y.existsSync(l))try{let p=y.readFileSync(l,"utf-8"),u=JSON.parse(p),d=u.dependencies?.["@heroui/react"]||u.devDependencies?.["@heroui/react"],m=u.dependencies?.["heroui-native"]||u.devDependencies?.["heroui-native"];d&&r.push(d.replace(/^[<=>^~]+/,"")),m&&o.push(m.replace(/^[<=>^~]+/,""));}catch{}}let i=Yt(o),s=Yt(r);return {...i?{native:i}:{},...s?{react:s}:{}}}function Uo(e,t){let n=[];for(let r of t)if(!r.startsWith("!"))if(r.includes("*"))n.push(...jo(e,r));else {let o=A.join(e,r);y.existsSync(o)&&n.push(o);}return [...new Set(n)]}function jo(e,t){let n=t.split("/"),r=[];function o(i,s){if(s>=n.length){y.existsSync(A.join(i,"package.json"))&&r.push(i);return}let c=n[s];if(c)if(c==="*"){if(!y.existsSync(i))return;try{for(let l of y.readdirSync(i)){let p=A.join(i,l);zt(p)&&(s===n.length-1?y.existsSync(A.join(p,"package.json"))&&r.push(p):o(p,s+1));}}catch{}}else c==="**"?Kt(i,r):o(A.join(i,c),s+1);}return o(e,0),r}function Kt(e,t){if(y.existsSync(e)){y.existsSync(A.join(e,"package.json"))&&t.push(e);try{for(let n of y.readdirSync(e)){if(n==="node_modules"||n.startsWith("."))continue;let r=A.join(e,n);zt(r)&&Kt(r,t);}}catch{}}}function zt(e){try{return y.statSync(e).isDirectory()}catch{return false}}function Yt(e){return e.length===0?null:e.length===1?e[0]??null:e.reduce((t,n)=>t?n&&Vo(n,t)>0?n:t:n??null)}function Vo(e,t){let n=p=>{let u=p.match(/^(\d+)\.(\d+)\.(\d+)/);return u?[parseInt(u[1]??"0",10),parseInt(u[2]??"0",10),parseInt(u[3]??"0",10)]:[0,0,0]},[r,o,i]=n(e),[s,c,l]=n(t);return r!==s?r-s:o!==c?o-c:i-l}function ut(e){let t=A.join(e,"package.json");if(!y.existsSync(t))return {error:"No package.json found in the current directory"};try{let n=JSON.parse(y.readFileSync(t,"utf-8")),r=n.dependencies||{},o=n.devDependencies||{},i=r["@heroui/react"]||o["@heroui/react"],s=r["heroui-native"]||o["heroui-native"],c={};if(i&&(c.react=i.replace(/^[<=>^~]+/,"")),s&&(c.native=s.replace(/^[<=>^~]+/,"")),!i&&!s){let l=To(e);if(l.isMonorepo&&l.packages.length>0){let p=No(e,l.packages);if(p.react&&(c.react=p.react),p.native&&(c.native=p.native),!p.react&&!p.native)return {error:`No HeroUI packages found in ${l.type} workspace packages.`}}else return {error:"HeroUI packages (@heroui/react or heroui-native) are not installed in this project."}}return c}catch(n){return {error:`Failed to parse package.json: ${n instanceof Error?n.message:String(n)}`}}}var Ho="v3";async function qt(e){let{cwd:t,docsDir:n,selection:r,useSsh:o}=e,i=Ho,s=n??A.join(t,".heroui-docs");try{return y.existsSync(s)||y.mkdirSync(s,{recursive:!0}),await Bt(i,s,r,o??!1),{docsPath:s,success:!0}}catch(c){return {error:c instanceof Error?c.message:String(c),success:false}}}var mt=class extends Error{constructor(n,r=1){super(n);this.exitCode=r;this.name="CLIError",Error.captureStackTrace(this,this.constructor);}},Ce=class extends mt{constructor(t){super(t,1),this.name="ValidationError";}};var zo="analytics-notice-seen";function Xt(){return `${homedir()}/.config/heroui/${zo}`}function Jo(){return existsSync(Xt())}function qo(){let e=Xt();mkdirSync(dirname(e),{recursive:true}),writeFileSync(e,"","utf8");}var Xo=`Anonymous usage data is collected for agents-md. Opt out: HEROUI_ANALYTICS_DISABLED=1. Learn more: https://github.com/heroui-inc/heroui-cli#analytics
`;function Qt(){Jo()||(a.log(Xo),qo());}var ft={onCancel:()=>{a.log(`${I.red("\u2716")} Operation cancelled`),process.exit(0);}};async function Zt(e,t){return (await gt({message:e,name:"value",type:"text",...{initial:t}},ft)).value}async function U(e,t){return (await gt({message:e,name:"value",type:"select",...t?{choices:t}:{}},ft)).value}async function dt(e){return (await gt({message:e,name:"value",type:"confirm"},ft)).value===true}var ne=".heroui-docs";function Zo(e){return e==="react"?"HeroUI React v3":e==="native"?"HeroUI Native":"HeroUI Migration (v2\u2192v3)"}function ht(e){if(e<1024)return `${e} B`;let t=e/1024;return t<1024?`${t.toFixed(1)} KB`:`${(t/1024).toFixed(1)} MB`}function er(e){let t=ut(e);return {hasNative:!!t.native,hasReact:!!t.react}}function tr(e,t){let n=A.join(e,"package.json");if(!y.existsSync(n))return {isValid:true,warnings:[]};try{let r=JSON.parse(y.readFileSync(n,"utf-8")),o=r.dependencies||{},i=r.devDependencies||{},s={...o,...i},c=[],l=s.tailwindcss||s["@tailwindcss/vite"];if(l){let p=l.replace(/^[<=>^~]+/,"");parseInt(p.split(".")[0]||"0",10)<4&&c.push(`Tailwind CSS version ${l} is installed, but HeroUI v3 requires Tailwind CSS v4+.`);}if(t==="react"){let p=s.react;if(p){let d=p.replace(/^[<=>^~]+/,"");O(d,"19.0.0")<0&&c.push(`React version ${p} is installed, but HeroUI v3 requires React 19+.`);}else c.push("React is not installed. HeroUI v3 requires React 19+.");let u=s["@heroui/react"];if(u&&!(u.includes("@beta")||u==="beta"||u.includes("@latest")||u==="latest")){let d=u.replace(/^[<=>^~]+/,"");O(d,"2.8.0")<0&&c.push(`@heroui/react version ${u} is installed, but these docs are recommended for version >= 2.8.0, @beta, or @latest (which supports Tailwind CSS v4).`);}}return {isValid:c.length===0,warnings:c}}catch{return {isValid:true,warnings:[]}}}async function nr(e,t){if(t==="migration")return await dt("Do you want to continue and install the migration docs?");let n=tr(e,t);if(n.isValid)return true;a.warn(`
\u26A0\uFE0F HeroUI v3 requirements not met:`);for(let o of n.warnings)a.warn(` \u2022 ${o}`);return a.newLine(),a.log("The downloaded documentation is for HeroUI v3 and may not be compatible with your current setup."),a.newLine(),await dt("Do you want to continue anyway?")}async function tn(e){let t=Date.now(),n=Me(),r=process.cwd();n&&Qt();try{let o,i;if([e.react,e.native,e.migration].filter(Boolean).length>1)throw new Ce("Only one library option is supported at a time. Use --react, --native, or --migration (not in combination).");if(e.react||e.native||e.migration)o=e.migration?"migration":e.native?"native":"react";else {let{hasNative:S,hasReact:v}=er(r);if(v&&S)if(e.output)o=await yt(!1);else {let w=await en(!1);o=w.selection,i=w.targetFiles;}else if(v)o="react",a.log(I.dim("Detected @heroui/react, using HeroUI React v3 docs"));else if(S)o="native",a.log(I.dim("Detected heroui-native, using HeroUI Native docs"));else if(e.output)o=await yt(!0);else {let w=await en(!0);o=w.selection,i=w.targetFiles;}}if(!i)if(e.output)i=Array.isArray(e.output)?e.output:[e.output];else {let S=await nn();S?i=Array.isArray(S)?S:[S]:i=["AGENTS.md"];}await nr(r,o)||(a.warn(`
Cancelled.`),process.exit(0));let l=A.join(r,ne),p=Zo(o);a.log(`
Downloading ${p} documentation to ${I.cyan(ne)}...`);let u=await qt({cwd:r,docsDir:l,selection:o,useSsh:e.ssh??!1});if(!u.success)throw new Ce(`Failed to pull docs: ${u.error}`);let d,m,f,h;if(o==="react"){let S=A.join(l,"react");if(y.existsSync(S)){let w=je(S);d=ke(w);}let v=A.join(l,"react","demos");y.existsSync(v)&&(h=it(v));}if(o==="native"){let S=A.join(l,"native");if(y.existsSync(S)){let v=je(S);m=ke(v);}}if(o==="migration"){let S=A.join(l,"migration");if(y.existsSync(S)){let v=rt(S);f=ke(v);}}let g=o==="react"?`./${ne}/react`:void 0,x=o==="native"?`./${ne}/native`:void 0,D=o==="migration"?`./${ne}/migration`:void 0,k={outputFile:i[0],selection:o};x&&(k.nativeDocsPath=x),m&&(k.nativeSections=m),D&&(k.migrationDocsPath=D),f&&(k.migrationSections=f),g&&(k.reactDocsPath=g),d&&(k.reactSections=d),h&&(k.reactDemoFiles=h);let me=o==="react"?De(k,"react"):void 0,X=o==="native"?De(k,"native"):void 0,Be=o==="migration"?De(k,"migration"):void 0,Ye=lt(r);for(let S of i){let v=A.join(r,S),w=0,Q=!0,R="";y.existsSync(v)&&(R=y.readFileSync(v,"utf-8"),w=Buffer.byteLength(R,"utf-8"),Q=!1);let Ie=pt(R,me,X,Be);y.writeFileSync(v,Ie,"utf-8");let ge=Buffer.byteLength(Ie,"utf-8"),Pe=Q?"Created":"Updated",We=Q?ht(ge):`${ht(w)} \u2192 ${ht(ge)}`;a.success(`\u2713 ${Pe} ${I.bold(S)} (${We})`);}Ye.updated&&a.success(`\u2713 Added ${I.bold(ne)} to .gitignore`),a.newLine(),a.log(I.cyan("\u{1F4DA} What was installed:")),a.log(` \u2022 Documentation files downloaded to ${I.bold(`${ne}/`)}`),a.log(` \u2022 Index generated in ${I.bold(i.join(", "))}`),o==="react"&&a.log(" \u2022 Demo files included for React code examples"),a.newLine(),a.log(I.cyan("\u{1F4A1} How it works:")),a.log(` \u2022 AI assistants (like Claude, Cursor) can now reference ${p} docs directly`),a.log(` \u2022 The index in ${I.bold(i[0])} helps assistants find relevant documentation`),a.log(` \u2022 Run ${I.bold("heroui agents-md")} again to update docs`),a.newLine(),n?.track({event:"AGENTS_MD_SUCCESS",properties:{duration:Date.now()-t,outputFileCount:i.length,outputFiles:i,selection:o}}),await we(),process.exit(0);}catch(o){n?.trackError({error:o,errorEvent:"AGENTS_MD_ERROR",fallbackMessage:"Failed to run agents-md",properties:{duration:Date.now()-t}}),await we(),process.exit(1);}}async function yt(e=false){e&&(a.warn("Neither @heroui/react nor heroui-native is installed in this project."),a.newLine());let t=await U("Select docs to include",[{title:"HeroUI React v3",value:"react"},{title:"HeroUI Native",value:"native"},{title:"HeroUI Migration (v2\u2192v3)",value:"migration"}]);return t===void 0&&(a.warn(`
Cancelled.`),process.exit(0)),t}async function en(e){a.log(I.cyan("HeroUI Documentation for AI Agents")),a.info(`Download the latest HeroUI documentation for AI agents to the current project
`);let t=await yt(e??false),n=await nn(),r=Array.isArray(n)?n:[n];return {selection:t,targetFiles:r}}async function nn(){let e=await U("Target markdown file",[{title:"AGENTS.md",value:"AGENTS.md"},{title:"CLAUDE.md",value:"CLAUDE.md"},{title:"Both",value:"__both__"},{title:"Custom...",value:"__custom__"}]);if(e===void 0&&(a.warn(`
Cancelled.`),process.exit(0)),e==="__both__")return ["AGENTS.md","CLAUDE.md"];let t=e;if(t==="__custom__"){let n=await Zt("Enter custom file path","AGENTS.md");(n===void 0||!n.trim())&&(a.warn(`
Cancelled.`),process.exit(0)),t=n.trim();}return t}function on(e){e.command("agents-md").description("Download HeroUI documentation for AI coding agents (Claude, Cursor, etc.) to the current project").option("--react","Include only React docs").option("--native","Include only Native docs").option("--migration","Include HeroUI v2 to v3 migration docs").option("--output <files...>","Target file path(s) (e.g., AGENTS.md, or AGENTS.md CLAUDE.md for multiple)").option("--ssh","Use SSH instead of HTTPS for git clone").action(tn);}async function rn(e){let{packagePath:t=_("package.json")}=e,{allDependencies:n,allDependenciesKeys:r}=L(t),o=b.filter(p=>r.has(p));if(!o.length){a.prefix("error",`\u274C No ${I.underline("HeroUI packages")} found in your project. Please consult the installation guide at: https://heroui.com/docs/react/getting-started/quick-start`);return}let i=[],s=b.filter(p=>!r.has(p));s.length&&i.push({level:"warn",name:"missingHeroUIPackages",outputFn:()=>{a.log("The following HeroUI packages are not installed:"),s.forEach(p=>{a.log(`- ${p}`);}),a.newLine(),a.log("Run `heroui install` to install them.");}});let c=[],l=new Set;for(let p of o){let u=await N(`npm show ${p} peerDependencies --json`),d=u?JSON.parse(u):{};for(let[m,f]of Object.entries(d))if(!(l.has(m)||b.includes(m)))if(l.add(m),!r.has(m))c.push(`${m} (${f})`);else {let{currentVersion:h}=$(n,m),g=ee(f);O(h,g)<0&&c.push(`${m} (${f}, current: ${h})`);}}if(c.length&&i.push({level:"error",name:"missingDependencies",outputFn:()=>{a.log("You have not installed the required dependencies"),a.newLine(),a.log("The required dependencies are:"),c.forEach(p=>{a.log(`- ${p}`);}),a.newLine(),a.log(`See more info here: ${I.underline(Et)}`);}}),!i.length){a.newLine(),a.success("\u2705 Your project has no detected issues.");return}a.prefix("error",`\u274C Your project has ${I.underline(i.length)} issue${i.length===1?"":"s"} that require attention`),a.newLine();for(let p=0;p<i.length;p++){let u=i[p];a[u.level](`\u2757\uFE0FIssue ${p+1}: ${I.bold(u.name)}`),a.newLine(),u.outputFn(),a.newLine();}process.exit(0);}function sn(e){e.command("doctor").description("Checks for issues in the project").option("-p, --packagePath [string]","Specify the path to the package.json file").action(rn);}async function an(e){let{packagePath:t=_("package.json")}=e,{allDependencies:n,allDependenciesKeys:r}=L(t),o=b.filter(i=>r.has(i));if(o.length){let i=await K([...o],n);z({components:i,warnError:false});}Ut(),process.exit(0);}function cn(e){e.command("env").description("Displays debugging information for the local environment").option("-p --packagePath [string]","Specify the path to the package.json file").action(an);}var rr="package-lock=true";function pn(e){writeFileSync(e,rr,"utf-8");}async function cr(e){let t=await fetch(e);if(!t.body)throw new Error(`Failed to download: ${e}`);return Readable.fromWeb(t.body)}async function un(e,t){await ar(async()=>{await pipeline(await cr(t),ln.x({cwd:e}));},{retries:3});}var Fe=["npm","bun","pnpm","yarn"];var mn={"bun.lock":"bun","bun.lockb":"bun","npm-shrinkwrap.json":"npm","package-lock.json":"npm","pnpm-lock.yaml":"pnpm","yarn.lock":"yarn"};async function pe(e=V){let t,n=await findUp(Object.keys(mn),{cwd:e});return n?t=mn[lr.basename(n)]:t=await U("No agent found, please choose one",Fe.map(r=>({title:r,value:r}))),t}function gn(e,t){e&&(Object.keys(re).includes(e)||Je(Object.keys(re),e)),t&&(Fe.includes(t)||Je(Fe,t));}var hn=e=>{isCancel(e)&&(cancel(`${I.red("\u2716")} Operation cancelled`),process.exit(0));},yn=async e=>{let t=await text(e);return hn(t),t},xt=async e=>{let t=await select(e);return hn(t),t};var fn=spinner(),xn=async e=>{let{failText:t,successText:n,task:r,text:o}=e,i=null;try{fn.start(o),i=await(r instanceof Promise?r:Promise.resolve(r)),fn.stop(n);}catch{cancel(t??i??"Task failed"),process.exit(0);}return i};var vn="https://codeload.github.com/heroui-inc/next-app-template/tar.gz/main",Sn="https://codeload.github.com/heroui-inc/next-pages-template/tar.gz/main",wn="https://codeload.github.com/heroui-inc/vite-template/tar.gz/main",kn="https://codeload.github.com/heroui-inc/react-router-template/tar.gz/main",An="next-app-template-main",En="next-pages-template-main",Dn="vite-template-main",Cn="react-router-template-main",bn="next-app-template",$n="next-pages-template",In="vite-template",Pn="react-router-template";var re={app:bn,pages:$n,"react-router":Pn,vite:In};async function On(e,t={}){let{package:n,template:r}=t;gn(r,n),Y.intro(I.cyanBright("Create a new project"));let{packageName:o,projectName:i,template:s}=await xr(n,e,r),{run:c}=ce(o);existsSync(Qe(`${V}/${i}`))&&(Y.cancel(`The project name ${I.redBright(i)} already exists`),process.exit(1)),s==="app"?(await He(vn),Ge(An,i)):s==="pages"?(await He(Sn),Ge(En,i)):s==="vite"?(await He(wn),Ge(Dn,i)):s==="react-router"?(await He(kn),Ge(Cn,i)):_exhaustiveCheck=s;let l=Qe(`${V}/${i}/.npmrc`);pn(l),Y.note(`cd ${I.cyanBright(i)}
${I.cyanBright(o)} install`,"Next steps"),Y.outro(`\u{1F680} Get started with ${I.cyanBright(`${o} ${c} dev`)}`),process.exit(0);}async function He(e){await xn({failText:"Template creation failed",successText:"Template created successfully!",task:un(V,e),text:"Creating template..."});}function Ge(e,t){try{renameSync(join(V,e),join(V,t));}catch(n){n&&(Y.cancel(`rename Error: ${n}`),process.exit(1));}}async function xr(e,t,n){return n||(n=await xt({message:"Select a template (Enter to select)",options:[{hint:"A Next.js 16 with app directory template pre-configured with HeroUI (v3) and Tailwind CSS.",label:"App",value:"app"},{hint:"A Next.js 16 with pages directory template pre-configured with HeroUI (v3) and Tailwind CSS.",label:"Pages",value:"pages"},{hint:"A Vite template pre-configured with HeroUI (v3) and Tailwind CSS.",label:"Vite",value:"vite"},{hint:"A React Router template pre-configured with HeroUI (v3) and Tailwind CSS.",label:"React Router",value:"react-router"}]})),t||(t=await yn({initialValue:re[n],message:"New project name (Enter to skip with default name)",placeholder:re[n]})),e||(e=await xt({message:"Select a package manager (Enter to select)",options:[{label:I.gray("npm"),value:"npm"},{label:I.gray("yarn"),value:"yarn"},{label:I.gray("pnpm"),value:"pnpm"},{label:I.gray("bun"),value:"bun"}]})),{packageName:e,projectName:t,template:n}}function Tn(e){e.command("init").description("Initializes a new project").argument("[projectName]","Name of the project to initialize").option("-t --template [string]",`Specify a template for the new project, e.g. ${Object.keys(re).join(", ")}`).option("-p --package [string]","The package manager to use for the new project").action(On);}var vt=new Map;async function le(e,t){return new Promise((n,r)=>{try{let{cache:o=!0,logCmd:i=!0,...s}=t||{};if(vt.has(e)&&o){let l=vt.get(e);if(l){n(l);return}}i&&(a.newLine(),a.log(`${e}`));let c=execSync(e,{stdio:"inherit",...s});if(c){let l=c.toString();vt.set(e,l),n(l);return}n("");}catch(o){r(o);}})}var q={debug:false,beta:false,cliLatestVersion:"",latestVersion:""};async function _n(e){let t=q[e];return t||((t=await T(At),q[e]=t)),t}var ie="".padEnd(7);function be(e,t=false){if(!e.length)return "";let n=[],r={latestVersion:0,package:0,version:0};for(let o of e)for(let i in o){if(!Object.prototype.hasOwnProperty.call(o,i)||!o[i])continue;i==="version"&&(o[i]=o[i].replace(he,""));let s=i==="version"?o[i].replace(H,"").length:o[i].length;r[i]=Math.max(r[i],s);}for(let o of e){if(o.isLatest){if(t)continue;n.push(` ${I.white(`${`${o.package}@${o.versionMode||""}${o.latestVersion}`.padEnd(r.package+ie.length+ie.length)}`)}${ie}${I.greenBright("latest").padStart(r.version)}${ie}`);continue}n.push(` ${I.white(`${o.package.padEnd(r.package+ie.length)}${ie}${W(`${o.versionMode||""}${o.version}`,r.version)} -> ${o.versionMode||""}${o.latestVersion}`)}${ie}`);}return n.join(`
`)}async function wr(e,t){let n=new Set,r=[];for(let o of e){let i=await N(`npm show ${o} peerDependencies --json`),s=i?JSON.parse(i):{};for(let c of Object.keys(s)){if(n.has(c))continue;n.add(c);let l=c in t,{currentVersion:p="",versionMode:u=""}=l?$(t,c):{};r.push({isLatest:l,latestVersion:l?p:await T(c),package:c,version:l?p:"Missing",versionMode:u});}}return r}async function Mn(e){let{packagePath:t=_("package.json")}=e,{allDependencies:n,allDependenciesKeys:r}=L(t),o=b.filter(m=>!r.has(m));o.length||(a.success("\u2705 @heroui/react and @heroui/styles are already installed"),process.exit(0));let i=await K([...o],n);z({components:i,message:I.cyanBright("\u{1F4E6} Packages to be installed:")});let s=await wr([...o],n);if(s.length){let m=be(s);m.length&&(a.newLine(),J({color:"yellow",text:m,title:I.yellow("PeerDependencies")}));}await U("Proceed with installation?",[{title:"Yes",value:true},{title:"No",value:false}])||process.exit(0);let l=await pe(),p=l==="npm"?"install":"add",u=s.filter(m=>!m.isLatest).map(m=>`${m.package}@${xe(m.latestVersion)}`),d=[...o,...u];await le(`${l} ${p} ${d.join(" ")}`),a.newLine(),a.success("\u2705 @heroui/react and @heroui/styles installed successfully"),process.exit(0);}function Nn(e){e.command("install").description("Installs @heroui/react and @heroui/styles in your project").option("-p, --packagePath [string]","Specify the path to the package.json file").action(Mn);}async function Un(e){let{packagePath:t=_("package.json")}=e;try{let{allDependencies:n,allDependenciesKeys:r}=L(t),o=b.filter(s=>r.has(s));if(!o.length){a.warn("No HeroUI packages found. Run `heroui install` to install @heroui/react and @heroui/styles.");return}let i=await K(o,n);z({components:i,message:`Installed HeroUI packages:
`});}catch(n){a.prefix("error",`An error occurred while listing packages: ${n}`);}process.exit(0);}function jn(e){e.command("list").description("Lists installed HeroUI packages (@heroui/react, @heroui/styles)").option("-p --packagePath [string]","Specify the path to the package.json file").action(Un);}async function Vn(e,t){let{remove:n}=ce(t);await le(`${t} ${n} ${e.join(" ")}`);}async function Hn(e){let{packagePath:t=_("package.json")}=e,{allDependencies:n,allDependenciesKeys:r}=L(t),o=b.filter(l=>r.has(l));o.length||(a.success("\u2705 No HeroUI packages to uninstall"),process.exit(0));let i=await K(o,n,false);z({components:i,message:I.yellowBright("\u2757\uFE0F Packages slated for uninstallation:")}),await U("Confirm uninstallation of these packages:",[{title:"Yes",value:true},{title:"No",value:false}])||process.exit(0);let c=await pe();await Vn([...o],c),a.newLine(),a.success(`\u2705 Successfully uninstalled: ${o.map(l=>I.underline(l)).join(", ")}`),process.exit(0);}function Gn(e){e.command("uninstall").description("Uninstalls @heroui/react and @heroui/styles from the project").option("-p, --packagePath [string]","Specify the path to the package.json file").action(Hn);}async function Yn(e){let{packagePath:t=_("package.json")}=e,{allDependencies:n,allDependenciesKeys:r}=L(t),o=b.filter(f=>r.has(f));if(!o.length){a.prefix("error","No HeroUI packages found. Run `heroui install` to install @heroui/react and @heroui/styles.");return}let i=[];await Promise.all(o.map(async f=>{let{currentVersion:h}=$(n,f),g=await T(f);O(h,g)<0&&i.push({current:h,latest:g,pkg:f});}));let s=[],c=new Set;for(let f of o){let h=await N(`npm show ${f} peerDependencies --json`),g=h?JSON.parse(h):{};for(let[x,D]of Object.entries(g)){if(c.has(x)||i.some(X=>X.pkg===x)||(c.add(x),!(x in n)))continue;let{currentVersion:k}=$(n,x),me=ee(D);if(O(k,me)<0){let X=await T(x);s.push({current:k,latest:X,pkg:x});}}}if(!i.length&&!s.length&&(a.success("\u2705 All packages are up to date"),process.exit(0)),i.length){let f=i.map(g=>({isLatest:false,latestVersion:ye(g.current,g.latest),package:g.pkg,version:g.current,versionMode:$(n,g.pkg).versionMode})),h=be(f);h.length&&J({color:"blue",text:h,title:I.blue("Upgrade")}),a.newLine();}if(s.length){let f=s.map(g=>({isLatest:false,latestVersion:ye(g.current,g.latest),package:g.pkg,version:g.current,versionMode:$(n,g.pkg).versionMode})),h=be(f);h.length&&J({color:"yellow",text:h,title:I.yellow("PeerDependencies")}),a.newLine();}await U("Would you like to proceed with the upgrade?",[{title:"Yes",value:true},{title:"No",value:false}])||process.exit(0);let p=await pe(),{install:u}=ce(p),m=[...i,...s].map(f=>`${f.pkg}@${f.latest}`).join(" ");await le(`${p} ${u} ${m}`),a.newLine(),a.success("\u2705 Upgrade complete"),process.exit(0);}function Wn(e){e.command("upgrade").description("Upgrades @heroui/react and @heroui/styles to the latest versions").option("-p --packagePath [string]","Specify the path to the package.json file").action(Yn);}function Kn(e){Tn(e),Nn(e),Wn(e),Gn(e),jn(e),cn(e),sn(e),on(e);}var zn=["install","agents-md","env","init","list","upgrade","doctor","uninstall"],$e=new Command;$e.name("heroui").usage("[command]").description(Ot(`
HeroUI CLI v${Le.version}
`,"")).version(Le.version,"-v, --version","Output the current version").helpOption("-h, --help","Display help for command").allowUnknownOption().option("--no-cache","Disable cache, by default data will be cached for 30m after the first request").option("-d, --debug","Debug mode will not install dependencies").action(async(e,t)=>{let n=false;if(t){let r=t.args?.[0];if(r&&!zn.includes(r)){n=true;let o=ze(zn,r);o?a.error(`Unknown command '${r}', Did you mean '${I.underline(o)}'?`):a.error(`Unknown command '${r}'`);}}if(!n){let o=$e.helpInformation().split(`
`);o=o.filter(i=>i&&!i.includes("HeroUI CLI v")),o=o.map(i=>{let s=i.match(/(\w+)\s\[/)?.[1];return s?i.replace(s,I.cyan(s)):i}),a.log(o.join(`
`));}process.exit(0);});Kn($e);$e.hook("preAction",async e=>{let t=e.args?.[0],n=e.rawArgs.slice(2),r=n.includes("--no-cache"),o=n.includes("--debug")||n.includes("-d");if(!t)return;Te(r),q.debug=o,q.beta=n.includes("-b")||n.includes("--beta");let[i]=await Promise.all([_n("cliLatestVersion")]);q.cliLatestVersion=i;let s=Le.version;O(s,i)===-1&&(J({center:true,color:"yellow",padding:1,text:`${I.gray(`Available upgrade: v${s} -> ${I.greenBright(`v${i}`)}
Run \`${I.cyan("npm install -g heroui-cli@latest")}\` to upgrade
Changelog: ${I.underline("https://github.com/heroui-inc/heroui-cli/releases")}`)}`,title:Ke("HeroUI CLI")}),a.newLine());});$e.parseAsync(process.argv).catch(async e=>{process.argv.includes("agents-md")&&(Me()?.trackError({error:e,errorEvent:"AGENTS_MD_ERROR",fallbackMessage:"Unexpected error in agents-md",properties:{}}),await we()),a.newLine(),a.error("Unexpected error. Please report it as a bug:"),a.log(e.message),e.stack&&a.grey(e.stack),a.newLine(),process.exit(1);});//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map