UNPKG

aoian

Version:
61 lines (59 loc) 62.8 kB
#!/usr/bin/env node import { f, e, g, h, i, j as j$1, k as k$1 } from './chunk-TPDUVJHA.js'; import * as k from 'path'; import k__default, { basename } from 'path'; import { promises, existsSync } from 'fs'; import { red, yellow, cyan, green } from 'kleur/colors'; import { loadConfig, createMatchPath } from 'tsconfig-paths'; import { cosmiconfig } from 'cosmiconfig'; import ie from 'fast-glob'; import { z } from 'zod'; import U from 'fs-extra'; import Er from 'ora'; import Ni, { tmpdir } from 'os'; import Q from 'deepmerge'; import $r from 'stringify-object'; import { Project, ScriptKind, SyntaxKind, QuoteKind } from 'ts-morph'; import { HttpsProxyAgent } from 'https-proxy-agent'; import Wr from 'node-fetch'; import W from 'postcss'; import Qr from 'postcss/lib/at-rule'; import { detect } from '@antfu/ni'; import { execa } from 'execa'; import Xe from 'prompts'; import { transformFromAstSync } from '@babel/core'; import { parse } from '@babel/parser'; import gi from '@babel/plugin-transform-typescript'; import * as fe from 'recast'; import { Command } from 'commander'; import * as ee from 'fs/promises'; import ee__default from 'fs/promises'; import { diffLines } from 'diff'; import { randomBytes } from 'crypto'; var v="1";var A="3";var Ee="5",Te="6",lt="7";var je="13";var j={"next-app":{name:"next-app",label:"Next.js",links:{installation:"https://ui.shadcn.com/docs/installation/next",tailwind:"https://tailwindcss.com/docs/guides/nextjs"}},"next-pages":{name:"next-pages",label:"Next.js",links:{installation:"https://ui.shadcn.com/docs/installation/next",tailwind:"https://tailwindcss.com/docs/guides/nextjs"}},remix:{name:"remix",label:"Remix",links:{installation:"https://ui.shadcn.com/docs/installation/remix",tailwind:"https://tailwindcss.com/docs/guides/remix"}},vite:{name:"vite",label:"Vite",links:{installation:"https://ui.shadcn.com/docs/installation/vite",tailwind:"https://tailwindcss.com/docs/guides/vite"}},astro:{name:"astro",label:"Astro",links:{installation:"https://ui.shadcn.com/docs/installation/astro",tailwind:"https://tailwindcss.com/docs/guides/astro"}},laravel:{name:"laravel",label:"Laravel",links:{installation:"https://ui.shadcn.com/docs/installation/laravel",tailwind:"https://tailwindcss.com/docs/guides/laravel"}},gatsby:{name:"gatsby",label:"Gatsby",links:{installation:"https://ui.shadcn.com/docs/installation/gatsby",tailwind:"https://tailwindcss.com/docs/guides/gatsby"}},manual:{name:"manual",label:"Manual",links:{installation:"https://ui.shadcn.com/docs/installation/manual",tailwind:"https://tailwindcss.com/docs/installation"}}};var l={error:red,warn:yellow,info:cyan,success:green};async function O(e,t){return createMatchPath(t.absoluteBaseUrl,t.paths)(e,void 0,()=>!0,[".ts",".tsx"])}var pt="@/components",mt="@/lib/utils",ft="app/globals.css",dt="tailwind.config.js";var yr=cosmiconfig("components",{searchPlaces:["components.json"]}),J=z.object({$schema:z.string().optional(),style:z.string(),rsc:z.coerce.boolean().default(!1),tsx:z.coerce.boolean().default(!0),tailwind:z.object({config:z.string(),css:z.string(),baseColor:z.string(),cssVariables:z.boolean().default(!0),prefix:z.string().default("").optional()}),aliases:z.object({components:z.string(),utils:z.string(),ui:z.string().optional(),lib:z.string().optional(),hooks:z.string().optional()}),iconLibrary:z.string().optional()}).strict(),gt=J.extend({resolvedPaths:z.object({cwd:z.string(),tailwindConfig:z.string(),tailwindCss:z.string(),utils:z.string(),components:z.string(),lib:z.string(),hooks:z.string(),ui:z.string()})}),wr=z.record(gt);async function S(e){let t=await xr(e);return t?(t.iconLibrary||(t.iconLibrary=t.style==="new-york"?"radix":"lucide"),await Y(e,t)):null}async function Y(e,t){let r=await loadConfig(e);if(r.resultType==="failed")throw new Error(`Failed to load ${t.tsx?"tsconfig":"jsconfig"}.json. ${r.message??""}`.trim());return gt.parse({...t,resolvedPaths:{cwd:e,tailwindConfig:k__default.resolve(e,t.tailwind.config),tailwindCss:k__default.resolve(e,t.tailwind.css),utils:await O(t.aliases.utils,r),components:await O(t.aliases.components,r),ui:t.aliases.ui?await O(t.aliases.ui,r):k__default.resolve(await O(t.aliases.components,r)??e,"ui"),lib:t.aliases.lib?await O(t.aliases.lib,r):k__default.resolve(await O(t.aliases.utils,r)??e,".."),hooks:t.aliases.hooks?await O(t.aliases.hooks,r):k__default.resolve(await O(t.aliases.components,r)??e,"..","hooks")}})}async function xr(e){try{let t=await yr.search(e);return t?J.parse(t.config):null}catch{let r=`${e}/components.json`;throw new Error(`Invalid configuration found in ${l.info(r)}.`)}}async function ut(e){let t={};for(let i of Object.keys(e.aliases)){if(!br(i,e))continue;let n=e.resolvedPaths[i],o=await Oe(e.resolvedPaths.cwd,n);if(!o){t[i]=e;continue}t[i]=await S(o);}let r=wr.safeParse(t);return r.success?r.data:null}async function Oe(e,t){let r=$e(e,t),i=k__default.relative(r,t),o=(await ie.glob("**/package.json",{cwd:r,deep:3,ignore:["**/node_modules/**","**/dist/**","**/build/**","**/public/**"]})).map(s=>k__default.dirname(s)).find(s=>i.startsWith(s));return o?k__default.join(r,o):null}function br(e,t){return Object.keys(t.resolvedPaths).filter(r=>r!=="utils").includes(e)}function $e(e,t){let r=e.split(k__default.sep),i=t.split(k__default.sep),n=[];for(let o=0;o<Math.min(r.length,i.length)&&r[o]===i[o];o++)n.push(r[o]);return n.join(k__default.sep)}function re(e="",t=!0){let r=k__default.join(e,"package.json");return U.readJSONSync(r,{throws:t})}var ne=["**/node_modules/**",".next","public","dist","build"];z.object({compilerOptions:z.object({paths:z.record(z.string().or(z.array(z.string())))})});async function $(e){let[t,r,i,n,o,s,c]=await Promise.all([ie.glob("**/{next,vite,astro}.config.*|gatsby-config.*|composer.json",{cwd:e,deep:3,ignore:ne}),U.pathExists(k__default.resolve(e,"src")),kr(e),Ir(e),Cr(e),Pr(e),re(e,!1)]),m=await U.pathExists(k__default.resolve(e,`${r?"src/":""}app`)),p={framework:j.manual,isSrcDir:r,isRSC:!1,isTsx:i,tailwindConfigFile:n,tailwindCssFile:o,aliasPrefix:s};return t.find(f=>f.startsWith("next.config."))?.length?(p.framework=m?j["next-app"]:j["next-pages"],p.isRSC=m,p):t.find(f=>f.startsWith("astro.config."))?.length?(p.framework=j.astro,p):t.find(f=>f.startsWith("gatsby-config."))?.length?(p.framework=j.gatsby,p):t.find(f=>f.startsWith("composer.json"))?.length?(p.framework=j.laravel,p):Object.keys(c?.dependencies??{}).find(f=>f.startsWith("@remix-run/"))?(p.framework=j.remix,p):(t.find(f=>f.startsWith("vite.config."))?.length&&(p.framework=j.vite),p)}async function Cr(e){let t=await ie.glob(["**/*.css","**/*.scss"],{cwd:e,deep:5,ignore:ne});if(!t.length)return null;for(let r of t)if((await U.readFile(k__default.resolve(e,r),"utf8")).includes("@tailwind base"))return r;return null}async function Ir(e){let t=await ie.glob("tailwind.config.*",{cwd:e,deep:3,ignore:ne});return t.length?t[0]:null}async function Pr(e){let t=await loadConfig(e);if(t?.resultType==="failed"||!Object.entries(t?.paths).length)return null;for(let[r,i]of Object.entries(t.paths))if(i.includes("./*")||i.includes("./src/*")||i.includes("./app/*")||i.includes("./resources/js/*"))return r.replace(/\/\*$/,"")??null;return Object.keys(t?.paths)?.[0].replace(/\/\*$/,"")??null}async function kr(e){return (await ie.glob("tsconfig.*",{cwd:e,deep:1,ignore:ne})).length>0}async function ht(e,t=null){let[r,i]=await Promise.all([S(e),t?Promise.resolve(t):$(e)]);if(r)return r;if(!i||!i.tailwindConfigFile||!i.tailwindCssFile)return null;let n={$schema:"https://ui.shadcn.com/schema.json",rsc:i.isRSC,tsx:i.isTsx,style:"new-york",tailwind:{config:i.tailwindConfigFile,baseColor:"zinc",css:i.tailwindCssFile,cssVariables:!0,prefix:""},iconLibrary:"lucide",aliases:{components:`${i.aliasPrefix}/components`,ui:`${i.aliasPrefix}/components/ui`,hooks:`${i.aliasPrefix}/hooks`,lib:`${i.aliasPrefix}/lib`,utils:`${i.aliasPrefix}/lib/utils`}};return await Y(e,n)}var a={error(...e){console.log(l.error(e.join(" ")));},warn(...e){console.log(l.warn(e.join(" ")));},info(...e){console.log(l.info(e.join(" ")));},success(...e){console.log(l.success(e.join(" ")));},log(...e){console.log(e.join(" "));},break(){console.log("");}};function u(e,t){return Er({text:e,isSilent:t?.silent})}async function wt(e){let t={};if(!U.existsSync(e.cwd)||!U.existsSync(k__default.resolve(e.cwd,"package.json")))return t[v]=!0,{errors:t,projectInfo:null};let r=u("Preflight checks.",{silent:e.silent}).start();U.existsSync(k__default.resolve(e.cwd,"components.json"))&&!e.force&&(r?.fail(),a.break(),a.error(`A ${l.info("components.json")} file already exists at ${l.info(e.cwd)}. To start over, remove the ${l.info("components.json")} file and run ${l.info("init")} again.`),a.break(),process.exit(1)),r?.succeed();let i=u("Verifying framework.",{silent:e.silent}).start(),n=await $(e.cwd);(!n||n?.framework.name==="manual")&&(t[lt]=!0,i?.fail(),a.break(),n?.framework.links.installation&&a.error(`We could not detect a supported framework at ${l.info(e.cwd)}. Visit ${l.info(n?.framework.links.installation)} to manually configure your project. Once configured, you can use the cli to add components.`),a.break(),process.exit(1)),i?.succeed(`Verifying framework. Found ${l.info(n.framework.label)}.`);let o=u("Validating Tailwind CSS.",{silent:e.silent}).start();!n?.tailwindConfigFile||!n?.tailwindCssFile?(t[Ee]=!0,o?.fail()):o?.succeed();let s=u("Validating import alias.",{silent:e.silent}).start();return n?.aliasPrefix?s?.succeed():(t[Te]=!0,s?.fail()),Object.keys(t).length>0&&(t[Ee]&&(a.break(),a.error(`No Tailwind CSS configuration found at ${l.info(e.cwd)}.`),a.error("It is likely you do not have Tailwind CSS installed or have an invalid configuration."),a.error("Install Tailwind CSS then try again."),n?.framework.links.tailwind&&a.error(`Visit ${l.info(n?.framework.links.tailwind)} to get started.`)),t[Te]&&(a.break(),a.error("No import alias found in your tsconfig.json file."),n?.framework.links.installation&&a.error(`Visit ${l.info(n?.framework.links.installation)} to learn how to set an import alias.`)),a.break(),process.exit(1)),{errors:t,projectInfo:n}}function y(e){if(a.error("Something went wrong. Please check the error below for more details."),a.error("If the problem persists, please open an issue on GitHub."),a.error(""),typeof e=="string"&&(a.error(e),a.break(),process.exit(1)),e instanceof z.ZodError){a.error("Validation failed:");for(let[t,r]of Object.entries(e.flatten().fieldErrors))a.error(`- ${l.info(t)}: ${r}`);a.break(),process.exit(1);}e instanceof Error&&(a.error(e.message),a.break(),process.exit(1)),a.break(),process.exit(1);}async function De(e,t,r){if(!e)return;r={silent:!1,...r};let i=k__default.relative(t.resolvedPaths.cwd,t.resolvedPaths.tailwindConfig),n=u(`Updating ${l.info(i)}`,{silent:r.silent}).start(),o=await promises.readFile(t.resolvedPaths.tailwindConfig,"utf8"),s=await Ar(o,e,t);await promises.writeFile(t.resolvedPaths.tailwindConfig,s,"utf8"),n?.succeed();}async function Ar(e,t,r){let i=await oe(e,r),n=i.getDescendantsOfKind(SyntaxKind.ObjectLiteralExpression).find(s=>s.getProperties().some(c=>c.isKind(SyntaxKind.PropertyAssignment)&&c.getName()==="content"));if(!n)return e;let o=_e(n);return Fr(n,{name:"darkMode",value:"class"},{quoteChar:o}),t.plugins?.forEach(s=>{_r(n,s);}),t.theme&&await Dr(n,t.theme),i.getFullText()}function Fr(e,t,{quoteChar:r}){let i=e.getProperty("darkMode");if(!i){let n={name:t.name,initializer:`[${r}${t.value}${r}]`};return t.name==="darkMode"?(e.insertPropertyAssignment(0,n),e):(e.addPropertyAssignment(n),e)}if(i.isKind(SyntaxKind.PropertyAssignment)){let n=i.getInitializer(),o=`${r}${t.value}${r}`;if(n?.isKind(SyntaxKind.StringLiteral)){let s=n.getText();return n.replaceWithText(`[${s}, ${o}]`),e}if(n?.isKind(SyntaxKind.ArrayLiteralExpression)){if(n.getElements().map(s=>s.getText()).includes(o))return e;n.addElement(o);}return e}return e}async function Dr(e,t){e.getProperty("theme")||e.addPropertyAssignment({name:"theme",initializer:"{}"}),Ke(e);let i=(e.getPropertyOrThrow("theme")?.asKindOrThrow(SyntaxKind.PropertyAssignment)).getInitializer();if(i?.isKind(SyntaxKind.ObjectLiteralExpression)){let n=i.getText(),o=await Kr(n),s=Q(o,t,{arrayMerge:(m,p)=>p}),c=$r(s).replace(/\'\.\.\.(.*)\'/g,"...$1").replace(/\'\"/g,"'").replace(/\"\'/g,"'").replace(/\'\[/g,"[").replace(/\]\'/g,"]").replace(/\'\\\'/g,"'").replace(/\\\'/g,"'").replace(/\\\'\'/g,"'").replace(/\'\'/g,"'");i.replaceWithText(c);}Me(e);}function _r(e,t){let r=e.getProperty("plugins");if(!r)return e.addPropertyAssignment({name:"plugins",initializer:`[${t}]`}),e;if(r.isKind(SyntaxKind.PropertyAssignment)){let i=r.getInitializer();if(i?.isKind(SyntaxKind.ArrayLiteralExpression)){if(i.getElements().map(n=>n.getText().replace(/["']/g,"")).includes(t.replace(/["']/g,"")))return e;i.addElement(t);}return e}return e}async function oe(e,t){let r=await promises.mkdtemp(k__default.join(tmpdir(),"shadcn-")),i=t?.resolvedPaths?.tailwindConfig||"tailwind.config.ts",n=k__default.join(r,`shadcn-${k__default.basename(i)}`);return new Project({compilerOptions:{}}).createSourceFile(n,e,{scriptKind:k__default.extname(i)===".ts"?ScriptKind.TS:ScriptKind.JS})}function _e(e){return e.getFirstDescendantByKind(SyntaxKind.StringLiteral)?.getQuoteKind()===QuoteKind.Single?"'":'"'}function Ke(e){let t=e.getProperties();for(let r=0;r<t.length;r++){let i=t[r];if(i.isKind(SyntaxKind.SpreadAssignment)){let n=i.asKindOrThrow(SyntaxKind.SpreadAssignment),o=n.getExpression().getText();e.insertPropertyAssignment(r,{name:`"___${o.replace(/^\.\.\./,"")}"`,initializer:`"...${o.replace(/^\.\.\./,"")}"`}),n.remove();}else if(i.isKind(SyntaxKind.PropertyAssignment)){let o=i.asKindOrThrow(SyntaxKind.PropertyAssignment).getInitializer();o&&o.isKind(SyntaxKind.ObjectLiteralExpression)?Ke(o.asKindOrThrow(SyntaxKind.ObjectLiteralExpression)):o&&o.isKind(SyntaxKind.ArrayLiteralExpression)&&bt(o.asKindOrThrow(SyntaxKind.ArrayLiteralExpression));}}}function bt(e){let t=e.getElements();for(let r=0;r<t.length;r++){let i=t[r];if(i.isKind(SyntaxKind.ObjectLiteralExpression))Ke(i.asKindOrThrow(SyntaxKind.ObjectLiteralExpression));else if(i.isKind(SyntaxKind.ArrayLiteralExpression))bt(i.asKindOrThrow(SyntaxKind.ArrayLiteralExpression));else if(i.isKind(SyntaxKind.SpreadElement)){let n=i.getText();e.removeElement(r),e.insertElement(r,`"${n}"`);}}}function Me(e){let t=e.getProperties();for(let r=0;r<t.length;r++){let i=t[r];if(i.isKind(SyntaxKind.PropertyAssignment)){let n=i,o=n.getInitializer();if(o&&o.isKind(SyntaxKind.StringLiteral)){let s=o.asKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();s.startsWith("...")&&(e.insertSpreadAssignment(r,{expression:s.slice(3)}),n.remove());}else o?.isKind(SyntaxKind.ObjectLiteralExpression)?Me(o):o&&o.isKind(SyntaxKind.ArrayLiteralExpression)&&St(o.asKindOrThrow(SyntaxKind.ArrayLiteralExpression));}}}function St(e){let t=e.getElements();for(let r=0;r<t.length;r++){let i=t[r];if(i.isKind(SyntaxKind.ObjectLiteralExpression))Me(i.asKindOrThrow(SyntaxKind.ObjectLiteralExpression));else if(i.isKind(SyntaxKind.ArrayLiteralExpression))St(i.asKindOrThrow(SyntaxKind.ArrayLiteralExpression));else if(i.isKind(SyntaxKind.StringLiteral)){let n=i.getText(),o=/(?:^['"])(\.\.\..*)(?:['"]$)/g;o.test(n)&&(e.removeElement(r),e.insertElement(r,n.replace(o,"$1")));}}}async function Kr(e){let r=(await oe(`const theme = ${e}`,null)).getStatements()[0];if(r?.getKind()===SyntaxKind.VariableStatement){let n=(r.getDeclarationList()?.getDeclarations()[0]).getInitializer();if(n?.isKind(SyntaxKind.ObjectLiteralExpression))return await se(n)}throw new Error("Invalid input: not an object literal")}function se(e){let t={};for(let r of e.getProperties())if(r.isKind(SyntaxKind.PropertyAssignment)){let i=r.getName().replace(/\'/g,"");r.getInitializer()?.isKind(SyntaxKind.ObjectLiteralExpression)?t[i]=se(r.getInitializer()):r.getInitializer()?.isKind(SyntaxKind.ArrayLiteralExpression)?t[i]=Rt(r.getInitializer()):t[i]=ze(r.getInitializer());}return t}function Rt(e){let t=[];for(let r of e.getElements())r.isKind(SyntaxKind.ObjectLiteralExpression)?t.push(se(r.asKindOrThrow(SyntaxKind.ObjectLiteralExpression))):r.isKind(SyntaxKind.ArrayLiteralExpression)?t.push(Rt(r.asKindOrThrow(SyntaxKind.ArrayLiteralExpression))):t.push(ze(r));return t}function ze(e){switch(e.getKind()){case SyntaxKind.StringLiteral:return e.getText();case SyntaxKind.NumericLiteral:return Number(e.getText());case SyntaxKind.TrueKeyword:return !0;case SyntaxKind.FalseKeyword:return !1;case SyntaxKind.NullKeyword:return null;case SyntaxKind.ArrayLiteralExpression:return e.getElements().map(ze);case SyntaxKind.ObjectLiteralExpression:return se(e);default:return e.getText()}}function vt(e){let t={};for(let r of Object.keys(e)){let i=r.split("-"),n=i[0],o=i.slice(1).join("-");o===""?typeof t[n]=="object"?t[n].DEFAULT=`hsl(var(--${r}))`:t[n]=`hsl(var(--${r}))`:(typeof t[n]!="object"&&(t[n]={DEFAULT:`hsl(var(--${n}))`}),t[n][o]=`hsl(var(--${r}))`);}for(let[r,i]of Object.entries(t))typeof i=="object"&&i.DEFAULT===`hsl(var(--${r}))`&&!(r in e)&&delete i.DEFAULT;return t}var Vr=process.env.REGISTRY_URL??"https://ui.shadcn.com/r",Br=process.env.https_proxy?new HttpsProxyAgent(process.env.https_proxy):void 0;async function X(){try{let[e]=await C(["index.json"]);return g.parse(e)}catch(e){a.error(` `),y(e);}}async function We(){try{let[e]=await C(["styles/index.json"]);return h.parse(e)}catch(e){return a.error(` `),y(e),[]}}async function ae(){try{let[e]=await C(["icons/index.json"]);return i.parse(e)}catch(e){return y(e),{}}}async function Ct(e$1,t){try{let[r]=await C([Ve(e$1)?e$1:`styles/${t}/${e$1}.json`]);return e.parse(r)}catch(r){return a.break(),y(r),null}}async function Ue(){return [{name:"neutral",label:"Neutral"},{name:"gray",label:"Gray"},{name:"zinc",label:"Zinc"},{name:"stone",label:"Stone"},{name:"slate",label:"Slate"}]}async function Z(e){try{let[t]=await C([`colors/${e}.json`]);return j$1.parse(t)}catch(t){y(t);}}async function Gr(e,t){let r=[];for(let i of t){let n=e.find(o=>o.name===i);if(n&&(r.push(n),n.registryDependencies)){let o=await Gr(e,n.registryDependencies);r.push(...o);}}return r.filter((i,n,o)=>o.findIndex(s=>s.name===i.name)===n)}async function It(e,t){try{let r=t.map(n=>`styles/${e}/${n.name}.json`),i=await C(r);return g.parse(i)}catch(r){y(r);}}async function Pt(e,t,r){if(r)return r;if(t.type==="registry:ui")return e.resolvedPaths.ui??e.resolvedPaths.components;let[i,n]=t.type?.split(":")??[];return i in e.resolvedPaths?k__default.join(e.resolvedPaths[i],n):null}async function C(e){try{return await Promise.all(e.map(async r=>{let i=Et(r),n=await Wr(i,{agent:Br});if(!n.ok){let o={400:"Bad request",401:"Unauthorized",403:"Forbidden",404:"Not found",500:"Internal server error"};if(n.status===401)throw new Error(`You are not authorized to access the component at ${l.info(i)}. If this is a remote registry, you may need to authenticate.`);if(n.status===404)throw new Error(`The component at ${l.info(i)} was not found. It may not exist at the registry. Please make sure it is a valid component.`);if(n.status===403)throw new Error(`You do not have access to the component at ${l.info(i)}. If this is a remote registry, you may need to authenticate or a token.`);let s=await n.json(),c=s&&typeof s=="object"&&"error"in s?s.error:n.statusText||o[n.status];throw new Error(`Failed to fetch from ${l.info(i)}. ${c}`)}return n.json()}))}catch(t){return a.error(` `),y(t),[]}}async function kt(e$1,t){try{if(!await X())return null;e$1.includes("index")&&e$1.unshift("index");let i=await Be(e$1,t),n=await C(i),o=z.array(e).parse(n);if(!o)return null;if(e$1.includes("index")&&t.tailwind.baseColor){let p=await Yr(t.tailwind.baseColor,t);p&&o.unshift(p);}let s={};o.forEach(p=>{s=Q(s,p.tailwind??{});});let c={};o.forEach(p=>{c=Q(c,p.cssVars??{});});let m="";return o.forEach(p=>{p.docs&&(m+=`${p.docs} `);}),k$1.parse({dependencies:Q.all(o.map(p=>p.dependencies??[])),devDependencies:Q.all(o.map(p=>p.devDependencies??[])),files:Q.all(o.map(p=>p.files??[])),tailwind:s,cssVars:c,docs:m})}catch(r){return y(r),null}}async function Jr(e$1,t){let r=new Set,i=[];async function n(o){let s=Et(Ve(o)?o:`styles/${t.style}/${o}.json`);if(!r.has(s)){r.add(s);try{let[c]=await C([s]),m=e.parse(c);if(i.push(s),m.registryDependencies)for(let p of m.registryDependencies)await n(p);}catch(c){console.error(`Error fetching or parsing registry item at ${o}:`,c);}}}return await n(e$1),Array.from(new Set(i))}async function Yr(e,t){let r=await Z(e);if(!r)return null;let i={name:e,type:"registry:theme",tailwind:{config:{theme:{extend:{borderRadius:{lg:"var(--radius)",md:"calc(var(--radius) - 2px)",sm:"calc(var(--radius) - 4px)"},colors:{}}}}},cssVars:{light:{radius:"0.5rem"},dark:{}}};return t.tailwind.cssVariables&&(i.tailwind.config.theme.extend.colors={...i.tailwind.config.theme.extend.colors,...vt(r.cssVars.dark)},i.cssVars={light:{...r.cssVars.light,...i.cssVars.light},dark:{...r.cssVars.dark,...i.cssVars.dark}}),i}function Et(e){if(Ve(e)){let t=new URL(e);return t.pathname.match(/\/chat\/b\//)&&!t.pathname.endsWith("/json")&&(t.pathname=`${t.pathname}/json`),t.toString()}return `${Vr}/${e}`}function Ve(e){try{return new URL(e),!0}catch{return !1}}async function Be(e,t){let r=[];for(let i of e){let n=await Jr(i,t);r.push(...n);}return Array.from(new Set(r))}function Tt(){return new Map([["registry:ui","ui"],["registry:lib","lib"],["registry:hook","hooks"],["registry:block","components"],["registry:component","components"]])}function jt(e){let t=new Map;return e.forEach(r=>{r.registryDependencies&&r.registryDependencies.forEach(i=>{t.set(i,r);});}),t}async function Ge(e,t,r){if(!e||!Object.keys(e).length||!t.resolvedPaths.tailwindCss)return;r={cleanupDefaultNextStyles:!1,silent:!1,...r};let i=t.resolvedPaths.tailwindCss,n=k__default.relative(t.resolvedPaths.cwd,i),o=u(`Updating ${l.info(n)}`,{silent:r.silent}).start(),s=await promises.readFile(i,"utf8"),c=await Xr(s,e,t,{cleanupDefaultNextStyles:r.cleanupDefaultNextStyles});await promises.writeFile(i,c,"utf8"),o.succeed();}async function Xr(e,t,r,i={cleanupDefaultNextStyles:!1}){i={cleanupDefaultNextStyles:!1,...i};let n=[qr(t)];return i.cleanupDefaultNextStyles&&n.push(ei()),r.tailwind.cssVariables&&n.push(Zr()),(await W(n).process(e,{from:void 0})).css}function Zr(){return {postcssPlugin:"update-base-layer",Once(e){let t=[{selector:"*",apply:"border-border"},{selector:"body",apply:"bg-background text-foreground"}],r=e.nodes.find(i=>i.type==="atrule"&&i.name==="layer"&&i.params==="base"&&t.every(({selector:n,apply:o})=>i.nodes?.some(s=>s.type==="rule"&&s.selector===n&&s.nodes.some(c=>c.type==="atrule"&&c.name==="apply"&&c.params===o))));r||(r=W.atRule({name:"layer",params:"base",raws:{semicolon:!0,between:" ",before:` `}}),e.append(r)),t.forEach(({selector:i,apply:n})=>{r?.nodes?.find(s=>s.type==="rule"&&s.selector===i)||r?.append(W.rule({selector:i,nodes:[W.atRule({name:"apply",params:n,raws:{semicolon:!0,before:` `}})],raws:{semicolon:!0,between:" ",before:` `}}));});}}}function qr(e){return {postcssPlugin:"update-css-vars",Once(t){let r=t.nodes.find(i=>i.type==="atrule"&&i.name==="layer"&&i.params==="base");r instanceof Qr||(r=W.atRule({name:"layer",params:"base",nodes:[],raws:{semicolon:!0,before:` `,between:" "}}),t.append(r)),r!==void 0&&Object.entries(e).forEach(([i,n])=>{let o=i==="light"?":root":`.${i}`;ti(r,o,n);});}}}function $t(e){let t=e.nodes.find(r=>r.type==="rule"&&r.selector===":root");if(t){let r=["--background","--foreground"];t.nodes.filter(i=>i.type==="decl"&&r.includes(i.prop)).forEach(i=>i.remove()),t.nodes.length===0&&t.remove();}}function ei(){return {postcssPlugin:"cleanup-default-next-styles",Once(e){let t=e.nodes.find(i=>i.type==="rule"&&i.selector==="body");t&&(t.nodes.find(i=>i.type==="decl"&&i.prop==="color"&&["rgb(var(--foreground-rgb))","var(--foreground)"].includes(i.value))?.remove(),t.nodes.find(i=>i.type==="decl"&&i.prop==="background"&&(i.value.startsWith("linear-gradient")||i.value==="var(--background)"))?.remove(),t.nodes.length===0&&t.remove()),$t(e);let r=e.nodes.find(i=>i.type==="atrule"&&i.params==="(prefers-color-scheme: dark)");r&&($t(r),r.nodes.length===0&&r.remove());}}}function ti(e,t,r){let i=e.nodes?.find(n=>n.type==="rule"&&n.selector===t);i||Object.keys(r).length>0&&(i=W.rule({selector:t,raws:{between:" ",before:` `}}),e.append(i)),Object.entries(r).forEach(([n,o])=>{let s=`--${n.replace(/^--/,"")}`,c=W.decl({prop:s,value:o,raws:{semicolon:!0}}),m=i?.nodes.find(p=>p.type==="decl"&&p.prop===s);m?m.replaceWith(c):i?.append(c);});}async function ce(e,{withFallback:t}={withFallback:!1}){let r=await detect({programmatic:!0,cwd:e});if(r==="yarn@berry")return "yarn";if(r==="pnpm@6")return "pnpm";if(r==="bun")return "bun";if(!t)return r??"npm";let i=process.env.npm_config_user_agent||"";return i.startsWith("yarn")?"yarn":i.startsWith("pnpm")?"pnpm":i.startsWith("bun")?"bun":"npm"}async function q(e,t,r){if(e=Array.from(new Set(e)),!e?.length)return;r={silent:!1,...r};let i=u("Installing dependencies.",{silent:r.silent})?.start(),n=await ce(t.resolvedPaths.cwd),o="";if(oi(t)&&n==="npm"){i.stopAndPersist(),a.warn(` It looks like you are using React 19. Some packages may fail to install due to peer dependency issues in npm (see https://ui.shadcn.com/react-19). `);let s=await Xe([{type:"select",name:"flag",message:"How would you like to proceed?",choices:[{title:"Use --force",value:"force"},{title:"Use --legacy-peer-deps",value:"legacy-peer-deps"}]}]);s&&(o=s.flag);}i?.start(),await execa(n,[n==="npm"?"install":"add",...n==="npm"&&o?[`--${o}`]:[],...e],{cwd:t.resolvedPaths.cwd}),i?.succeed();}function oi(e){let t=re(e.resolvedPaths.cwd);return t?.dependencies?.react?/^(?:\^|~)?19(?:\.\d+)*(?:-.*)?$/.test(t.dependencies.react):!1}var le=async({sourceFile:e,config:t,baseColor:r})=>(t.tailwind?.cssVariables||!r?.inlineColors||e.getDescendantsOfKind(SyntaxKind.StringLiteral).forEach(i=>{let n=i.getText();if(n){let o=ci(n.replace(/"/g,""),r.inlineColors);i.replaceWithText(`"${o.trim()}"`);}}),e);function Je(e){if(!e.includes("/")&&!e.includes(":"))return [null,e,null];let t=[],[r,i]=e.split("/");if(!r.includes(":"))return [null,r,i];let n=r.split(":"),o=n.pop(),s=n.join(":");return t.push(s??null,o??null,i??null),t}var ai=["bg-","text-","border-","ring-offset-","ring-"];function ci(e,t){e.includes(" border ")&&(e=e.replace(" border "," border border-border "));let r=e.split(" "),i=new Set,n=new Set;for(let o of r){let[s,c,m]=Je(o),p=ai.find(g=>c?.startsWith(g));if(!p){i.has(o)||i.add(o);continue}let f=c?.replace(p,"");if(f&&f in t.light){i.add([s,`${p}${t.light[f]}`].filter(Boolean).join(":")+(m?`/${m}`:"")),n.add(["dark",s,`${p}${t.dark[f]}`].filter(Boolean).join(":")+(m?`/${m}`:""));continue}i.has(o)||i.add(o);}return [...Array.from(i),...Array.from(n)].join(" ").trim()}var I={lucide:{name:"lucide-react",package:"lucide-react",import:"lucide-react"},radix:{name:"@radix-ui/react-icons",package:"@radix-ui/react-icons",import:"@radix-ui/react-icons"}};var Nt="lucide",pe=async({sourceFile:e,config:t})=>{if(!t.iconLibrary||!(t.iconLibrary in I))return e;let r=await ae(),i=Nt,n=t.iconLibrary;if(i===n)return e;let o=[];for(let s of e.getImportDeclarations()??[])if(s.getModuleSpecifier()?.getText()===`"${I[Nt].import}"`){for(let c of s.getNamedImports()??[]){let m=c.getName(),p=r[m]?.[n];!p||o.includes(p)||(o.push(p),c.remove(),e.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement).filter(f=>f.getTagNameNode()?.getText()===m).forEach(f=>f.getTagNameNode()?.replaceWithText(p)));}s.getNamedImports()?.length===0&&s.remove();}if(o.length>0){let s=e.addImportDeclaration({moduleSpecifier:I[n]?.import,namedImports:o.map(c=>({name:c}))});pi(e)||s.replaceWithText(s.getText().replace(";",""));}return e};function pi(e){return e.getImportDeclarations()?.[0]?.getText().endsWith(";")??!1}var Lt={"@/lib/utils":/^@\/lib\/utils/,"@workspace/lib/utils":/^@workspace\/lib\/utils/},me=async({sourceFile:e,config:t,isRemote:r})=>{let i=e.getImportDeclarations();for(let n of i){let o=mi(n.getModuleSpecifierValue(),t,r);n.setModuleSpecifier(o),Lt[o]&&n.getNamedImports().find(m=>m.getName()==="cn")&&n.setModuleSpecifier(o.replace(Lt[o],t.aliases.utils));}return e};function mi(e,t,r=!1){if(!e.startsWith("@/")&&!r)return e;if(r&&e.startsWith("@/")&&(e=e.replace(/^@\//,"@/registry/new-york/")),!e.startsWith("@/registry/")){let i=t.aliases.components.split("/")[0];return e.replace(/^@\//,`${i}/`)}return e.match(/^@\/registry\/(.+)\/ui/)?e.replace(/^@\/registry\/(.+)\/ui/,t.aliases.ui??`${t.aliases.components}/ui`):t.aliases.components&&e.match(/^@\/registry\/(.+)\/components/)?e.replace(/^@\/registry\/(.+)\/components/,t.aliases.components):t.aliases.lib&&e.match(/^@\/registry\/(.+)\/lib/)?e.replace(/^@\/registry\/(.+)\/lib/,t.aliases.lib):t.aliases.hooks&&e.match(/^@\/registry\/(.+)\/hooks/)?e.replace(/^@\/registry\/(.+)\/hooks/,t.aliases.hooks):e.replace(/^@\/registry\/[^/]+/,t.aliases.components)}var ui={sourceType:"module",allowImportExportEverywhere:!0,allowReturnOutsideFunction:!0,startLine:1,tokens:!0,plugins:["asyncGenerators","bigInt","classPrivateMethods","classPrivateProperties","classProperties","classStaticBlock","decimal","decorators-legacy","doExpressions","dynamicImport","exportDefaultFrom","exportNamespaceFrom","functionBind","functionSent","importAssertions","importMeta","nullishCoalescingOperator","numericSeparator","objectRestSpread","optionalCatchBinding","optionalChaining",["pipelineOperator",{proposal:"minimal"}],["recordAndTuple",{syntaxType:"hash"}],"throwExpressions","topLevelAwait","v8intrinsic","typescript","jsx"]},At=async({sourceFile:e,config:t})=>{let r=e.getFullText();if(t.tsx)return r;let i=fe.parse(r,{parser:{parse:o=>parse(o,ui)}}),n=transformFromAstSync(i,r,{cloneInputAst:!1,code:!1,ast:!0,plugins:[gi],configFile:!1});if(!n||!n.ast)throw new Error("Failed to transform JSX");return fe.print(n.ast).code};var yi=/^["']use client["']$/g,de=async({sourceFile:e,config:t})=>{if(t.rsc)return e;let r=e.getFirstChildByKind(SyntaxKind.ExpressionStatement);return r&&yi.test(r.getText())&&r.remove(),e};var ge=async({sourceFile:e,config:t})=>(t.tailwind?.prefix&&(e.getDescendantsOfKind(SyntaxKind.CallExpression).filter(r=>r.getExpression().getText()==="cva").forEach(r=>{if(r.getArguments()[0]?.isKind(SyntaxKind.StringLiteral)){let i=r.getArguments()[0];i&&i.replaceWithText(`"${F(i.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`);}r.getArguments()[1]?.isKind(SyntaxKind.ObjectLiteralExpression)&&r.getArguments()[1]?.getDescendantsOfKind(SyntaxKind.PropertyAssignment).find(i=>i.getName()==="variants")?.getDescendantsOfKind(SyntaxKind.PropertyAssignment).forEach(i=>{i.getDescendantsOfKind(SyntaxKind.PropertyAssignment).forEach(n=>{let o=n.getInitializerIfKind(SyntaxKind.StringLiteral);o&&o?.replaceWithText(`"${F(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`);});});}),e.getDescendantsOfKind(SyntaxKind.JsxAttribute).forEach(r=>{if(r.getName()==="className"){if(r.getInitializer()?.isKind(SyntaxKind.StringLiteral)){let i=r.getInitializer();i&&i.replaceWithText(`"${F(i.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`);}if(r.getInitializer()?.isKind(SyntaxKind.JsxExpression)){let i=r.getInitializer()?.getDescendantsOfKind(SyntaxKind.CallExpression).find(n=>n.getExpression().getText()==="cn");i&&i.getArguments().forEach(n=>{(n.isKind(SyntaxKind.ConditionalExpression)||n.isKind(SyntaxKind.BinaryExpression))&&n.getChildrenOfKind(SyntaxKind.StringLiteral).forEach(o=>{o.replaceWithText(`"${F(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`);}),n.isKind(SyntaxKind.StringLiteral)&&n.replaceWithText(`"${F(n.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`);});}}r.getName()==="classNames"&&r.getInitializer()?.isKind(SyntaxKind.JsxExpression)&&r.getDescendantsOfKind(SyntaxKind.PropertyAssignment).forEach(i=>{if(i.getInitializer()?.isKind(SyntaxKind.CallExpression)){let n=i.getInitializerIfKind(SyntaxKind.CallExpression);n&&n.getArguments().forEach(o=>{o.isKind(SyntaxKind.ConditionalExpression)&&o.getChildrenOfKind(SyntaxKind.StringLiteral).forEach(s=>{s.replaceWithText(`"${F(s.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`);}),o.isKind(SyntaxKind.StringLiteral)&&o.replaceWithText(`"${F(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`);});}if(i.getInitializer()?.isKind(SyntaxKind.StringLiteral)&&i.getName()!=="variant"){let n=i.getInitializer();n&&n.replaceWithText(`"${F(n.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`);}});})),e);function F(e,t=""){let r=e.split(" "),i=[];for(let n of r){let[o,s,c]=Je(n);o?c?i.push(`${o}:${t}${s}/${c}`):i.push(`${o}:${t}${s}`):c?i.push(`${t}${s}/${c}`):i.push(`${t}${s}`);}return i.join(" ")}var Ri=new Project({compilerOptions:{}});async function vi(e){let t=await promises.mkdtemp(k__default.join(tmpdir(),"shadcn-"));return k__default.join(t,e)}async function ue(e,t=[me,de,le,ge,pe]){let r=await vi(e.filename),i=Ri.createSourceFile(r,e.raw,{scriptKind:ScriptKind.TSX});for(let n of t)await n({sourceFile:i,...e});return e.transformJsx?await At({sourceFile:i,...e}):i.getText()}async function Ye(e,t,r){if(!e?.length)return {filesCreated:[],filesUpdated:[],filesSkipped:[]};r={overwrite:!1,force:!1,silent:!1,isRemote:!1,...r};let i=u("Updating files.",{silent:r.silent})?.start(),[n,o]=await Promise.all([$(t.resolvedPaths.cwd),Z(t.tailwind.baseColor)]),s=[],c=[],m=[];for(let f of e){if(!f.content)continue;let g=Pi(f,t,{isSrcDir:n?.isSrcDir,commonRoot:Ei(e.map(M=>M.path),f.path)}),b=basename(f.path),R=k__default.dirname(g);t.tsx||(g=g.replace(/\.tsx?$/,M=>M===".tsx"?".jsx":".js"));let N=existsSync(g);if(N&&!r.overwrite){i.stop(),r.rootSpinner&&r.rootSpinner.stop();let{overwrite:M}=await Xe({type:"confirm",name:"overwrite",message:`The file ${l.info(b)} already exists. Would you like to overwrite?`,initial:!1});if(!M){m.push(k__default.relative(t.resolvedPaths.cwd,g)),r.rootSpinner&&r.rootSpinner.start();continue}i?.start(),r.rootSpinner&&r.rootSpinner.start();}existsSync(R)||await promises.mkdir(R,{recursive:!0});let w=await ue({filename:f.path,raw:f.content,config:t,baseColor:o,transformJsx:!t.tsx,isRemote:r.isRemote},[me,de,le,ge,pe]);await promises.writeFile(g,w,"utf-8"),N?c.push(k__default.relative(t.resolvedPaths.cwd,g)):s.push(k__default.relative(t.resolvedPaths.cwd,g));}if(!(s.length||c.length)&&!m.length&&i?.info("No files updated."),s.length){if(i?.succeed(`Created ${s.length} ${s.length===1?"file":"files"}:`),!r.silent)for(let f of s)a.log(` - ${f}`);}else i?.stop();if(c.length&&(u(`Updated ${c.length} ${c.length===1?"file":"files"}:`,{silent:r.silent})?.info(),!r.silent))for(let f of c)a.log(` - ${f}`);if(m.length&&(u(`Skipped ${m.length} ${c.length===1?"file":"files"}: (use --overwrite to overwrite)`,{silent:r.silent})?.info(),!r.silent))for(let f of m)a.log(` - ${f}`);return r.silent||a.break(),{filesCreated:s,filesUpdated:c,filesSkipped:m}}function Pi(e,t,r){if(e.target)return e.target.startsWith("~/")?k__default.join(t.resolvedPaths.cwd,e.target.replace("~/","")):r.isSrcDir?k__default.join(t.resolvedPaths.cwd,"src",e.target.replace("src/","")):k__default.join(t.resolvedPaths.cwd,e.target.replace("src/",""));let i=ki(e,t),n=Ti(e.path,i);return k__default.join(i,n)}function ki(e,t){return e.type==="registry:ui"?t.resolvedPaths.ui:e.type==="registry:lib"?t.resolvedPaths.lib:e.type==="registry:block"||e.type==="registry:component"?t.resolvedPaths.components:e.type==="registry:hook"?t.resolvedPaths.hooks:t.resolvedPaths.components}function Ei(e,t){let r=e.map(s=>s.replace(/^\//,"")),i=t.replace(/^\//,""),n=i.split("/").slice(0,-1).join("/");if(!n)return "";let o=n.split("/");for(let s=o.length;s>0;s--){let c=o.slice(0,s).join("/");if(r.some(p=>p!==i&&p.startsWith(c+"/")))return "/"+c}return "/"+n}function Ti(e,t){let r=e.replace(/^\/|\/$/g,""),i=t.replace(/^\/|\/$/g,""),n=r.split("/"),o=i.split("/"),s=o[o.length-1],c=n.findIndex(m=>m===s);return c===-1?n[n.length-1]:n.slice(c+1).join("/")}async function he(e,t,r){r={overwrite:!1,silent:!1,isNewProject:!1,...r};let i=await ut(t);return i&&i?.ui.resolvedPaths.cwd!==t.resolvedPaths.cwd?await $i(e,t,i,{...r,isRemote:e?.length===1&&!!e[0].match(/\/chat\/b\//)}):await Oi(e,t,r)}async function Oi(e,t,r){let i=u("Checking registry.",{silent:r.silent})?.start(),n=await kt(e,t);if(!n)return i?.fail(),y(new Error("Failed to fetch components from registry."));i?.succeed(),await De(n.tailwind?.config,t,{silent:r.silent}),await Ge(n.cssVars,t,{cleanupDefaultNextStyles:r.isNewProject,silent:r.silent}),await q(n.dependencies,t,{silent:r.silent}),await Ye(n.files,t,{overwrite:r.overwrite,silent:r.silent}),n.docs&&a.info(n.docs);}async function $i(e$1,t,r,i){let n=u("Checking registry.",{silent:i.silent})?.start(),o=await Be(e$1,t),s=await C(o),c=z.array(e).parse(s);if(!c)return n?.fail(),y(new Error("Failed to fetch components from registry."));n?.succeed();let m=jt(c),p=Tt(),f=[],g=[],b=[],R=u("Installing components.")?.start();for(let w of c){let M=p.get(w.type),cr=m.get(w.name);if(!M)continue;let T=w.type==="registry:ui"||cr?.type==="registry:ui"?r.ui:t,V=$e(t.resolvedPaths.cwd,T.resolvedPaths.ui),Ie=await Oe(V,T.resolvedPaths.cwd)??T.resolvedPaths.cwd;w.tailwind?.config&&(await De(w.tailwind?.config,T,{silent:!0}),g.push(k__default.relative(V,T.resolvedPaths.tailwindConfig))),w.cssVars&&(await Ge(w.cssVars,T,{silent:!0}),g.push(k__default.relative(V,T.resolvedPaths.tailwindCss))),await q(w.dependencies,T,{silent:!0});let Pe=await Ye(w.files,T,{overwrite:i.overwrite,silent:!0,rootSpinner:R,isRemote:i.isRemote});f.push(...Pe.filesCreated.map(G=>k__default.relative(V,k__default.join(Ie,G)))),g.push(...Pe.filesUpdated.map(G=>k__default.relative(V,k__default.join(Ie,G)))),b.push(...Pe.filesSkipped.map(G=>k__default.relative(V,k__default.join(Ie,G))));}if(R?.succeed(),f.sort(),g.sort(),b.sort(),!(f.length||g.length)&&!b.length&&u("No files updated.",{silent:i.silent})?.info(),f.length){u(`Created ${f.length} ${f.length===1?"file":"files"}:`,{silent:i.silent})?.succeed();for(let w of f)a.log(` - ${w}`);}if(g.length){u(`Updated ${g.length} ${g.length===1?"file":"files"}:`,{silent:i.silent})?.info();for(let w of g)a.log(` - ${w}`);}if(b.length){u(`Skipped ${b.length} ${g.length===1?"file":"files"}: (use --overwrite to overwrite)`,{silent:i.silent})?.info();for(let w of b)a.log(` - ${w}`);}}var Ai="https://codeload.github.com/shadcn-ui/ui/tar.gz/main";async function we(e){e={srcDir:!1,...e};let t="next",r="my-app",i="15.1.0",n=e.components?.length===1&&!!e.components[0].match(/\/chat\/b\//);if(e.components&&n)try{let[c]=await C(e.components),{meta:m}=z.object({meta:z.object({nextVersion:z.string()})}).parse(c);i=m.nextVersion;}catch(c){a.break(),y(c);}if(!e.force){let{type:c,name:m}=await Xe([{type:"select",name:"type",message:`The path ${l.info(e.cwd)} does not contain a package.json file. Would you like to start a new project?`,choices:[{title:"Next.js",value:"next"},{title:"Next.js (Monorepo)",value:"monorepo"}],initial:0},{type:"text",name:"name",message:"What is your project named?",initial:r,format:p=>p.trim(),validate:p=>p.length>128?"Name should be less than 128 characters.":!0}]);t=c,r=m;}let o=await ce(e.cwd,{withFallback:!0}),s=`${e.cwd}/${r}`;try{await U.access(e.cwd,U.constants.W_OK);}catch{a.break(),a.error(`The path ${l.info(e.cwd)} is not writable.`),a.error(`It is likely you do not have write permissions for this folder or the path ${l.info(e.cwd)} does not exist.`),a.break(),process.exit(1);}return U.existsSync(k__default.resolve(e.cwd,r,"package.json"))&&(a.break(),a.error(`A project with the name ${l.info(r)} already exists.`),a.error("Please choose a different name and try again."),a.break(),process.exit(1)),t==="next"&&await Fi(s,{version:i,cwd:e.cwd,packageManager:o,srcDir:!!e.srcDir}),t==="monorepo"&&await Di(s,{packageManager:o}),{projectPath:s,projectName:r,projectType:t}}async function Fi(e,t){let r=u("Creating a new Next.js project. This may take a few minutes.").start(),i=["--tailwind","--eslint","--typescript","--app",t.srcDir?"--src-dir":"--no-src-dir","--no-import-alias",`--use-${t.packageManager}`];t.version.startsWith("15")&&i.push("--turbopack");try{await execa("npx",[`create-next-app@${t.version}`,e,"--silent",...i],{cwd:t.cwd});}catch{a.break(),a.error("Something went wrong creating a new Next.js project. Please try again."),process.exit(1);}r?.succeed("Creating a new Next.js project.");}async function Di(e,t){let r=u("Creating a new Next.js monorepo. This may take a few minutes.").start();try{let i=k__default.join(Ni.tmpdir(),`shadcn-template-${Date.now()}`);await U.ensureDir(i);let n=await fetch(Ai);if(!n.ok)throw new Error(`Failed to download template: ${n.statusText}`);let o=k__default.resolve(i,"template.tar.gz");await U.writeFile(o,Buffer.from(await n.arrayBuffer())),await execa("tar",["-xzf",o,"-C",i,"--strip-components=2","ui-main/templates/monorepo-next"]);let s=k__default.resolve(i,"monorepo-next");await U.move(s,e),await U.remove(i),await execa(t.packageManager,["install"],{cwd:e});let c=process.cwd();await execa("git",["--version"],{cwd:e}),await execa("git",["init"],{cwd:e}),await execa("git",["add","-A"],{cwd:e}),await execa("git",["commit","-m","Initial commit"],{cwd:e}),await execa("cd",[c]),r?.succeed("Creating a new Next.js monorepo.");}catch(i){r?.fail("Something went wrong creating a new Next.js monorepo."),y(i);}}async function Mt(e,t,r){if(!e)return;r={silent:!1,...r};let i=k__default.relative(t.resolvedPaths.cwd,t.resolvedPaths.tailwindConfig),n=u(`Updating ${l.info(i)}`,{silent:r.silent}).start(),o=await promises.readFile(t.resolvedPaths.tailwindConfig,"utf8"),s=await Ki(o,e,t);await promises.writeFile(t.resolvedPaths.tailwindConfig,s,"utf8"),n?.succeed();}async function Ki(e,t,r){let i=await oe(e,r),n=i.getDescendantsOfKind(SyntaxKind.ObjectLiteralExpression).find(o=>o.getProperties().some(s=>s.isKind(SyntaxKind.PropertyAssignment)&&s.getName()==="content"));return n?(Mi(n,t),i.getFullText()):e}async function Mi(e,t){let r=_e(e),i=e.getProperty("content");if(!i){let n={name:"content",initializer:`[${r}${t.join(`${r}, ${r}`)}${r}]`};return e.addPropertyAssignment(n),e}if(i.isKind(SyntaxKind.PropertyAssignment)){let n=i.getInitializer();if(n?.isKind(SyntaxKind.ArrayLiteralExpression))for(let o of t){let s=`${r}${o}${r}`;n.getElements().map(c=>c.getText()).includes(s)||n.addElement(s);}return e}return e}var Ui=z.object({cwd:z.string(),components:z.array(z.string()).optional(),yes:z.boolean(),defaults:z.boolean(),force:z.boolean(),silent:z.boolean(),isNewProject:z.boolean(),srcDir:z.boolean().optional()}),zt=new Command().name("init").description("initialize your project and install dependencies").argument("[components...]","the components to add or a url to the component.").option("-y, --yes","skip confirmation prompt.",!0).option("-d, --defaults,","use default configuration.",!1).option("-f, --force","force overwrite of existing configuration.",!1).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-s, --silent","mute output.",!1).option("--src-dir","use the src directory when creating a new project.",!1).action(async(e,t)=>{try{let r=Ui.parse({cwd:k__default.resolve(t.cwd),isNewProject:!1,components:e,...t});await be(r),a.log(`${l.success("Success!")} Project initialization completed. You may now add components.`),a.break();}catch(r){a.break(),y(r);}});async function be(e){let t,r;if(e.skipPreflight)t=await $(e.cwd);else {let p=await wt(e);if(p.errors[v]){let{projectPath:f,projectType:g}=await we(e);f||process.exit(1),e.cwd=f,e.isNewProject=!0,r=g;}t=p.projectInfo;}if(r==="monorepo")return e.cwd=k__default.resolve(e.cwd,"apps/web"),await S(e.cwd);let i=await ht(e.cwd,t),n=i?await Bi(i,e):await Vi(await S(e.cwd));if(!e.yes){let{proceed:p}=await Xe({type:"confirm",name:"proceed",message:`Write configuration to ${l.info("components.json")}. Proceed?`,initial:!0});p||process.exit(0);}let o=u("Writing components.json.").start(),s=k__default.resolve(e.cwd,"components.json");await promises.writeFile(s,JSON.stringify(n,null,2),"utf8"),o.succeed();let c=await Y(e.cwd,n),m=["index",...e.components||[]];return await he(m,c,{overwrite:!0,silent:e.silent,isNewProject:e.isNewProject||t?.framework.name==="next-app"}),e.isNewProject&&e.srcDir&&await Mt(["./src/**/*.{js,ts,jsx,tsx,mdx}"],c,{silent:e.silent}),c}async function Vi(e=null){let[t,r]=await Promise.all([We(),Ue()]);a.info("");let i=await Xe([{type:"toggle",name:"typescript",message:`Would you like to use ${l.info("TypeScript")} (recommended)?`,initial:e?.tsx??!0,active:"yes",inactive:"no"},{type:"select",name:"style",message:`Which ${l.info("style")} would you like to use?`,choices:t.map(n=>({title:n.label,value:n.name}))},{type:"select",name:"tailwindBaseColor",message:`Which color would you like to use as the ${l.info("base color")}?`,choices:r.map(n=>({title:n.label,value:n.name}))},{type:"text",name:"tailwindCss",message:`Where is your ${l.info("global CSS")} file?`,initial:e?.tailwind.css??ft},{type:"toggle",name:"tailwindCssVariables",message:`Would you like to use ${l.info("CSS variables")} for theming?`,initial:e?.tailwind.cssVariables??!0,active:"yes",inactive:"no"},{type:"text",name:"tailwindPrefix",message:`Are you using a custom ${l.info("tailwind prefix eg. tw-")}? (Leave blank if not)`,initial:""},{type:"text",name:"tailwindConfig",message:`Where is your ${l.info("tailwind.config.js")} located?`,initial:e?.tailwind.config??dt},{type:"text",name:"components",message:`Configure the import alias for ${l.info("components")}:`,initial:e?.aliases.components??pt},{type:"text",name:"utils",message:`Configure the import alias for ${l.info("utils")}:`,initial:e?.aliases.utils??mt},{type:"toggle",name:"rsc",message:`Are you using ${l.info("React Server Components")}?`,initial:e?.rsc??!0,active:"yes",inactive:"no"}]);return J.parse({$schema:"https://ui.shadcn.com/schema.json",style:i.style,tailwind:{config:i.tailwindConfig,css:i.tailwindCss,baseColor:i.tailwindBaseColor,cssVariables:i.tailwindCssVariables,prefix:i.tailwindPrefix},rsc:i.rsc,tsx:i.typescript,aliases:{utils:i.utils,components:i.components,lib:i.components.replace(/\/components$/,"lib"),hooks:i.components.replace(/\/components$/,"hooks")}})}async function Bi(e,t){let r=e.style,i=e.tailwind.baseColor,n=e.tailwind.cssVariables;if(!t.defaults){let[o,s]=await Promise.all([We(),Ue()]),c=await Xe([{type:"select",name:"style",message:`Which ${l.info("style")} would you like to use?`,choices:o.map(m=>({title:m.label,value:m.name})),initial:o.findIndex(m=>m.name===r)},{type:"select",name:"tailwindBaseColor",message:`Which color would you like to use as the ${l.info("base color")}?`,choices:s.map(m=>({title:m.label,value:m.name}))},{type:"toggle",name:"tailwindCssVariables",message:`Would you like to use ${l.info("CSS variables")} for theming?`,initial:e?.tailwind.cssVariables,active:"yes",inactive:"no"}]);r=c.style,i=c.tailwindBaseColor,n=c.tailwindCssVariables;}return J.parse({$schema:e?.$schema,style:r,tailwind:{...e?.tailwind,baseColor:i,cssVariables:n},rsc:e?.rsc,tsx:e?.tsx,aliases:e?.aliases,iconLibrary:e?.iconLibrary})}async function Ut(e){let t={};if(!U.existsSync(e.cwd)||!U.existsSync(k__default.resolve(e.cwd,"package.json")))return t[v]=!0,{errors:t,config:null};if(!U.existsSync(k__default.resolve(e.cwd,"components.json")))return t[A]=!0,{errors:t,config:null};try{let r=await S(e.cwd);return {errors:t,config:r}}catch{a.break(),a.error(`An invalid ${l.info("components.json")} file was found at ${l.info(e.cwd)}. Before you can add components, you must create a valid ${l.info("components.json")} file by running the ${l.info("init")} command.`),a.error(`Learn more at ${l.info("https://ui.shadcn.com/docs/components-json")}.`),a.break(),process.exit(1);}}async function Bt(e,t){let r=k__default.join(t.resolvedPaths.cwd,"app/page.tsx");if(!(await ee__default.stat(r)).isFile())return;let i=await Ct(e,t.style);if(!i?.meta?.importSpecifier||!i?.meta?.moduleSpecifier)return;let n=`import { ${i?.meta?.importSpecifier} } from "${i.meta.moduleSpecifier}" export default function Page() { return <${i?.meta?.importSpecifier} /> }`;await ee__default.writeFile(r,n,"utf8");}var Yi=z.object({components:z.array(z.string()).optional(),yes:z.boolean(),overwrite:z.boolean(),cwd:z.string(),all:z.boolean(),path:z.string().optional(),silent:z.boolean(),srcDir:z.boolean().optional()}),Jt=new Command().name("add").description("add a component to your project").argument("[components...]","the components to add or a url to the component.").option("-y, --yes","skip confirmation prompt.",!1).option("-o, --overwrite","overwrite existing files.",!1).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-a, --all","add all available components",!1).option("-p, --path <path>","the path to add the component to.").option("-s, --silent","mute output.",!1).option("--src-dir","use the src directory when creating a new project.",!1).action(async(e,t)=>{try{let r=Yi.parse({components:e,cwd:k__default.resolve(t.cwd),...t}),i=r.components?.some(c=>c.includes("theme-"));if(!r.yes&&i){a.break();let{confirm:c}=await Xe({type:"confirm",name:"confirm",message:l.warn(`You are about to install a new theme. Existing CSS variables will be overwritten. Continue?`)});c||(a.break(),a.log("Theme installation cancelled."),a.break(),process.exit(1));}r.components?.length||(r.components=await Hi(r));let{errors:n,config:o}=await Ut(r);if(n[A]){let{proceed:c}=await Xe({type:"confirm",name:"proceed",message:`You need to create a ${l.info("components.json")} file to add components. Proceed?`,initial:!0});c||(a.break(),process.exit(1)),o=await be({cwd:r.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!1,silent:!0,isNewProject:!1,srcDir:r.srcDir});}let s=!1;if(n[v]){let{projectPath:c,projectType:m}=await we({cwd:r.cwd,force:r.overwrite,srcDir:r.srcDir,components:r.component