shadcn 0.0.0-beta.82ec1a9 → 0.0.0-beta.8d9e2ae

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,30 +1,31 @@
1
1
  #!/usr/bin/env node
2
- import mi from"path";import{promises as oi}from"fs";import bt from"path";import Me from"path";var I="1";var j="3";var ue="5",he="6",Le="7";import ye from"path";var k={"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"}}};import K from"path";import{cyan as Dt,green as _t,red as zt,yellow as Kt}from"kleur/colors";var c={error:zt,warn:Kt,info:Dt,success:_t};import{createMatchPath as Mt}from"tsconfig-paths";async function T(e,t){return Mt(t.absoluteBaseUrl,t.paths)(e,void 0,()=>!0,[".ts",".tsx"])}import{cosmiconfig as Wt}from"cosmiconfig";import{loadConfig as Ut}from"tsconfig-paths";import{z as h}from"zod";var Fe="@/components",De="@/lib/utils",_e="app/globals.css",ze="tailwind.config.js";var Vt=Wt("components",{searchPlaces:["components.json"]}),M=h.object({$schema:h.string().optional(),style:h.string(),rsc:h.coerce.boolean().default(!1),tsx:h.coerce.boolean().default(!0),tailwind:h.object({config:h.string(),css:h.string(),baseColor:h.string(),cssVariables:h.boolean().default(!0),prefix:h.string().default("").optional()}),aliases:h.object({components:h.string(),utils:h.string(),ui:h.string().optional(),lib:h.string().optional(),hooks:h.string().optional()}),iconLibrary:h.string().optional()}).strict(),Bt=M.extend({resolvedPaths:h.object({cwd:h.string(),tailwindConfig:h.string(),tailwindCss:h.string(),utils:h.string(),components:h.string(),lib:h.string(),hooks:h.string(),ui:h.string()})});async function C(e){let t=await Gt(e);return t?(t.iconLibrary||(t.iconLibrary=t.style==="new-york"?"radix":"lucide"),await W(e,t)):null}async function W(e,t){let r=await Ut(e);if(r.resultType==="failed")throw new Error(`Failed to load ${t.tsx?"tsconfig":"jsconfig"}.json. ${r.message??""}`.trim());return Bt.parse({...t,resolvedPaths:{cwd:e,tailwindConfig:K.resolve(e,t.tailwind.config),tailwindCss:K.resolve(e,t.tailwind.css),utils:await T(t.aliases.utils,r),components:await T(t.aliases.components,r),ui:t.aliases.ui?await T(t.aliases.ui,r):K.resolve(await T(t.aliases.components,r)??e,"ui"),lib:t.aliases.lib?await T(t.aliases.lib,r):K.resolve(await T(t.aliases.utils,r)??e,".."),hooks:t.aliases.hooks?await T(t.aliases.hooks,r):K.resolve(await T(t.aliases.components,r)??e,"..","hooks")}})}async function Gt(e){try{let t=await Vt.search(e);return t?M.parse(t.config):null}catch{let r=`${e}/components.json`;throw new Error(`Invalid configuration found in ${c.info(r)}.`)}}import Jt from"path";import Yt from"fs-extra";function Y(e="",t=!0){let r=Jt.join(e,"package.json");return Yt.readJSONSync(r,{throws:t})}import H from"fast-glob";import we from"fs-extra";import{loadConfig as Ht}from"tsconfig-paths";import{z as _}from"zod";var Q=["**/node_modules/**",".next","public","dist","build"],an=_.object({compilerOptions:_.object({paths:_.record(_.string().or(_.array(_.string())))})});async function E(e){let[t,r,i,n,o,s,l]=await Promise.all([H.glob("**/{next,vite,astro}.config.*|gatsby-config.*|composer.json",{cwd:e,deep:3,ignore:Q}),we.pathExists(ye.resolve(e,"src")),Zt(e),Xt(e),Qt(e),qt(e),Y(e,!1)]),f=await we.pathExists(ye.resolve(e,`${r?"src/":""}app`)),d={framework:k.manual,isSrcDir:r,isRSC:!1,isTsx:i,tailwindConfigFile:n,tailwindCssFile:o,aliasPrefix:s};return t.find(p=>p.startsWith("next.config."))?.length?(d.framework=f?k["next-app"]:k["next-pages"],d.isRSC=f,d):t.find(p=>p.startsWith("astro.config."))?.length?(d.framework=k.astro,d):t.find(p=>p.startsWith("gatsby-config."))?.length?(d.framework=k.gatsby,d):t.find(p=>p.startsWith("composer.json"))?.length?(d.framework=k.laravel,d):Object.keys(l?.dependencies??{}).find(p=>p.startsWith("@remix-run/"))?(d.framework=k.remix,d):(t.find(p=>p.startsWith("vite.config."))?.length&&(d.framework=k.vite),d)}async function Qt(e){let t=await H.glob(["**/*.css","**/*.scss"],{cwd:e,deep:5,ignore:Q});if(!t.length)return null;for(let r of t)if((await we.readFile(ye.resolve(e,r),"utf8")).includes("@tailwind base"))return r;return null}async function Xt(e){let t=await H.glob("tailwind.config.*",{cwd:e,deep:3,ignore:Q});return t.length?t[0]:null}async function qt(e){let t=await Ht(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 Zt(e){return(await H.glob("tsconfig.*",{cwd:e,deep:1,ignore:Q})).length>0}async function Ke(e,t=null){let[r,i]=await Promise.all([C(e),t?Promise.resolve(t):E(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 W(e,n)}var a={error(...e){console.log(c.error(e.join(" ")))},warn(...e){console.log(c.warn(e.join(" ")))},info(...e){console.log(c.info(e.join(" ")))},success(...e){console.log(c.success(e.join(" ")))},log(...e){console.log(e.join(" "))},break(){console.log("")}};import er from"ora";function y(e,t){return er({text:e,isSilent:t?.silent})}import xe from"fs-extra";async function We(e){let t={};if(!xe.existsSync(e.cwd)||!xe.existsSync(Me.resolve(e.cwd,"package.json")))return t[I]=!0,{errors:t,projectInfo:null};let r=y("Preflight checks.",{silent:e.silent}).start();xe.existsSync(Me.resolve(e.cwd,"components.json"))&&!e.force&&(r?.fail(),a.break(),a.error(`A ${c.info("components.json")} file already exists at ${c.info(e.cwd)}.
3
- To start over, remove the ${c.info("components.json")} file and run ${c.info("init")} again.`),a.break(),process.exit(1)),r?.succeed();let i=y("Verifying framework.",{silent:e.silent}).start(),n=await E(e.cwd);(!n||n?.framework.name==="manual")&&(t[Le]=!0,i?.fail(),a.break(),n?.framework.links.installation&&a.error(`We could not detect a supported framework at ${c.info(e.cwd)}.
4
- Visit ${c.info(n?.framework.links.installation)} to manually configure your project.
5
- Once configured, you can use the cli to add components.`),a.break(),process.exit(1)),i?.succeed(`Verifying framework. Found ${c.info(n.framework.label)}.`);let o=y("Validating Tailwind CSS.",{silent:e.silent}).start();!n?.tailwindConfigFile||!n?.tailwindCssFile?(t[ue]=!0,o?.fail()):o?.succeed();let s=y("Validating import alias.",{silent:e.silent}).start();return n?.aliasPrefix?s?.succeed():(t[he]=!0,s?.fail()),Object.keys(t).length>0&&(t[ue]&&(a.break(),a.error(`No Tailwind CSS configuration found at ${c.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 ${c.info(n?.framework.links.tailwind)} to get started.`)),t[he]&&(a.break(),a.error("No import alias found in your tsconfig.json file."),n?.framework.links.installation&&a.error(`Visit ${c.info(n?.framework.links.installation)} to learn how to set an import alias.`)),a.break(),process.exit(1)),{errors:t,projectInfo:n}}import{z as tr}from"zod";function x(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 tr.ZodError){a.error("Validation failed:");for(let[t,r]of Object.entries(e.flatten().fieldErrors))a.error(`- ${c.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)}import gr from"path";import{z as m}from"zod";var Ue=m.enum(["registry:style","registry:lib","registry:example","registry:block","registry:component","registry:ui","registry:hook","registry:theme","registry:page"]),Ve=m.object({path:m.string(),content:m.string().optional(),type:Ue,target:m.string().optional()}),rr=m.object({config:m.object({content:m.array(m.string()).optional(),theme:m.record(m.string(),m.any()).optional(),plugins:m.array(m.string()).optional()}).optional()}),ir=m.object({light:m.record(m.string(),m.string()).optional(),dark:m.record(m.string(),m.string()).optional()}),z=m.object({name:m.string(),type:Ue,description:m.string().optional(),dependencies:m.array(m.string()).optional(),devDependencies:m.array(m.string()).optional(),registryDependencies:m.array(m.string()).optional(),files:m.array(Ve).optional(),tailwind:rr.optional(),cssVars:ir.optional(),meta:m.record(m.string(),m.any()).optional(),docs:m.string().optional()}),be=m.array(z.extend({files:m.array(m.union([m.string(),Ve])).optional()})),Be=m.array(m.object({name:m.string(),label:m.string()})),Ge=m.record(m.string(),m.record(m.string(),m.string())),Je=m.object({inlineColors:m.object({light:m.record(m.string(),m.string()),dark:m.record(m.string(),m.string())}),cssVars:m.object({light:m.record(m.string(),m.string()),dark:m.record(m.string(),m.string())}),inlineColorsTemplate:m.string(),cssVarsTemplate:m.string()}),Ye=z.pick({dependencies:!0,devDependencies:!0,files:!0,tailwind:!0,cssVars:!0,docs:!0});import{promises as Se}from"fs";import{tmpdir as nr}from"os";import U from"path";import or from"deepmerge";import sr from"stringify-object";import{Project as ar,QuoteKind as cr,ScriptKind as He,SyntaxKind as u}from"ts-morph";async function Qe(e,t,r){if(!e)return;r={silent:!1,...r};let i=U.relative(t.resolvedPaths.cwd,t.resolvedPaths.tailwindConfig),n=y(`Updating ${c.info(i)}`,{silent:r.silent}).start(),o=await Se.readFile(t.resolvedPaths.tailwindConfig,"utf8"),s=await lr(o,e,t);await Se.writeFile(t.resolvedPaths.tailwindConfig,s,"utf8"),n?.succeed()}async function lr(e,t,r){let i=await X(e,r),n=i.getDescendantsOfKind(u.ObjectLiteralExpression).find(s=>s.getProperties().some(l=>l.isKind(u.PropertyAssignment)&&l.getName()==="content"));if(!n)return e;let o=Ie(n);return pr(n,{name:"darkMode",value:"class"},{quoteChar:o}),t.plugins?.forEach(s=>{fr(n,s)}),t.theme&&await mr(n,t.theme),i.getFullText()}function pr(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(u.PropertyAssignment)){let n=i.getInitializer(),o=`${r}${t.value}${r}`;if(n?.isKind(u.StringLiteral)){let s=n.getText();return n.replaceWithText(`[${s}, ${o}]`),e}if(n?.isKind(u.ArrayLiteralExpression)){if(n.getElements().map(s=>s.getText()).includes(o))return e;n.addElement(o)}return e}return e}async function mr(e,t){e.getProperty("theme")||e.addPropertyAssignment({name:"theme",initializer:"{}"}),Xe(e);let i=(e.getPropertyOrThrow("theme")?.asKindOrThrow(u.PropertyAssignment)).getInitializer();if(i?.isKind(u.ObjectLiteralExpression)){let n=i.getText(),o=await dr(n),s=or(o,t),l=sr(s).replace(/\'\"/g,"'").replace(/\"\'/g,"'").replace(/\'\[/g,"[").replace(/\]\'/g,"]").replace(/\'\\\'/g,"'").replace(/\\\'/g,"'").replace(/\\\'\'/g,"'").replace(/\'\'/g,"'");i.replaceWithText(l)}qe(e)}function fr(e,t){let r=e.getProperty("plugins");if(!r)return e.addPropertyAssignment({name:"plugins",initializer:`[${t}]`}),e;if(r.isKind(u.PropertyAssignment)){let i=r.getInitializer();if(i?.isKind(u.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 X(e,t){let r=await Se.mkdtemp(U.join(nr(),"shadcn-")),i=t?.resolvedPaths?.tailwindConfig||"tailwind.config.ts",n=U.join(r,`shadcn-${U.basename(i)}`);return new ar({compilerOptions:{}}).createSourceFile(n,e,{scriptKind:U.extname(i)===".ts"?He.TS:He.JS})}function Ie(e){return e.getFirstDescendantByKind(u.StringLiteral)?.getQuoteKind()===cr.Single?"'":'"'}function Xe(e){let t=e.getProperties();for(let r=0;r<t.length;r++){let i=t[r];if(i.isKind(u.SpreadAssignment)){let n=i.asKindOrThrow(u.SpreadAssignment),o=n.getExpression().getText();e.insertPropertyAssignment(r,{name:`___${o.replace(/^\.\.\./,"")}`,initializer:`"...${o.replace(/^\.\.\./,"")}"`}),n.remove()}else if(i.isKind(u.PropertyAssignment)){let o=i.asKindOrThrow(u.PropertyAssignment).getInitializer();o&&o.isKind(u.ObjectLiteralExpression)&&Xe(o.asKindOrThrow(u.ObjectLiteralExpression))}}}function qe(e){let t=e.getProperties();for(let r=0;r<t.length;r++){let i=t[r];if(i.isKind(u.PropertyAssignment)){let n=i,o=n.getInitializer();if(o?.isKind(u.StringLiteral)){let s=o.getLiteralValue();s.startsWith("...")&&(e.insertSpreadAssignment(r,{expression:s.slice(3)}),n.remove())}else o?.isKind(u.ObjectLiteralExpression)&&qe(o)}}}async function dr(e){let r=(await X(`const theme = ${e}`,null)).getStatements()[0];if(r?.getKind()===u.VariableStatement){let n=(r.getDeclarationList()?.getDeclarations()[0]).getInitializer();if(n?.isKind(u.ObjectLiteralExpression))return await Ze(n)}throw new Error("Invalid input: not an object literal")}function Ze(e){let t={};for(let r of e.getProperties())if(r.isKind(u.PropertyAssignment)){let i=r.getName().replace(/\'/g,"");r.getInitializer()?.isKind(u.ObjectLiteralExpression)?t[i]=Ze(r.getInitializer()):t[i]=et(r.getInitializer())}return t}function et(e){switch(e.kind){case u.StringLiteral:return e.text;case u.NumericLiteral:return Number(e.text);case u.TrueKeyword:return!0;case u.FalseKeyword:return!1;case u.NullKeyword:return null;case u.ArrayLiteralExpression:return e.elements.map(et);default:return e.getText()}}function tt(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}import V from"deepmerge";import{HttpsProxyAgent as ur}from"https-proxy-agent";import hr from"node-fetch";import{z as yr}from"zod";var wr=process.env.REGISTRY_URL??"https://ui.shadcn.com/r",xr=process.env.https_proxy?new ur(process.env.https_proxy):void 0;async function B(){try{let[e]=await $(["index.json"]);return be.parse(e)}catch(e){a.error(`
6
- `),x(e)}}async function Ce(){try{let[e]=await $(["styles/index.json"]);return Be.parse(e)}catch(e){return a.error(`
7
- `),x(e),[]}}async function q(){try{let[e]=await $(["icons/index.json"]);return Ge.parse(e)}catch(e){return x(e),{}}}async function rt(e,t){try{let[r]=await $([Pe(e)?e:`styles/${t}/${e}.json`]);return z.parse(r)}catch(r){return a.break(),x(r),null}}async function Re(){return[{name:"neutral",label:"Neutral"},{name:"gray",label:"Gray"},{name:"zinc",label:"Zinc"},{name:"stone",label:"Stone"},{name:"slate",label:"Slate"}]}async function G(e){try{let[t]=await $([`colors/${e}.json`]);return Je.parse(t)}catch(t){x(t)}}async function it(e,t){try{let r=t.map(n=>`styles/${e}/${n.name}.json`),i=await $(r);return be.parse(i)}catch(r){x(r)}}async function nt(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?gr.join(e.resolvedPaths[i],n):null}async function $(e){try{return await Promise.all(e.map(async r=>{let i=at(r),n=await hr(i,{agent:xr});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 ${c.info(i)}.
8
- If this is a remote registry, you may need to authenticate.`);if(n.status===404)throw new Error(`The component at ${c.info(i)} was not found.
9
- 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 ${c.info(i)}.
10
- If this is a remote registry, you may need to authenticate or a token.`);let s=await n.json(),l=s&&typeof s=="object"&&"error"in s?s.error:n.statusText||o[n.status];throw new Error(`Failed to fetch from ${c.info(i)}.
11
- ${l}`)}return n.json()}))}catch(t){return a.error(`
12
- `),x(t),[]}}function ot(e,t,r){return r||(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:(e.type==="registry:page",t.resolvedPaths.components))}async function st(e,t){try{if(!await B())return null;e.includes("index")&&e.unshift("index");let i=[];for(let p of e){let g=await br(p,t);i.push(...g)}let n=Array.from(new Set(i)),o=await $(n),s=yr.array(z).parse(o);if(!s)return null;if(e.includes("index")&&t.tailwind.baseColor){let p=await Sr(t.tailwind.baseColor,t);p&&s.unshift(p)}let l={};s.forEach(p=>{l=V(l,p.tailwind??{})});let f={};s.forEach(p=>{f=V(f,p.cssVars??{})});let d="";return s.forEach(p=>{p.docs&&(d+=`${p.docs}
13
- `)}),Ye.parse({dependencies:V.all(s.map(p=>p.dependencies??[])),devDependencies:V.all(s.map(p=>p.devDependencies??[])),files:V.all(s.map(p=>p.files??[])),tailwind:l,cssVars:f,docs:d})}catch(r){return x(r),null}}async function br(e,t){let r=new Set,i=[];async function n(o){let s=at(Pe(o)?o:`styles/${t.style}/${o}.json`);if(!r.has(s)){r.add(s);try{let[l]=await $([s]),f=z.parse(l);if(i.push(s),f.registryDependencies)for(let d of f.registryDependencies)await n(d)}catch(l){console.error(`Error fetching or parsing registry item at ${o}:`,l)}}}return await n(e),Array.from(new Set(i))}async function Sr(e,t){let r=await G(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,...tt(r.cssVars.dark)},i.cssVars={light:{...r.cssVars.light,...i.cssVars.light},dark:{...r.cssVars.dark,...i.cssVars.dark}}),i}function at(e){if(Pe(e)){let t=new URL(e);return t.pathname.match(/\/chat\/b\//)&&!t.pathname.endsWith("/json")&&(t.pathname=`${t.pathname}/json`),t.toString()}return`${wr}/${e}`}function Pe(e){try{return new URL(e),!0}catch{return!1}}import{promises as ct}from"fs";import Ir from"path";import F from"postcss";import Cr from"postcss/lib/at-rule";async function pt(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=Ir.relative(t.resolvedPaths.cwd,i),o=y(`Updating ${c.info(n)}`,{silent:r.silent}).start(),s=await ct.readFile(i,"utf8"),l=await Rr(s,e,t,{cleanupDefaultNextStyles:r.cleanupDefaultNextStyles});await ct.writeFile(i,l,"utf8"),o.succeed()}async function Rr(e,t,r,i){i={cleanupDefaultNextStyles:!1,...i};let n=[vr(t)];return i.cleanupDefaultNextStyles&&n.push(kr()),r.tailwind.cssVariables&&n.push(Pr()),(await F(n).process(e,{from:void 0})).css}function Pr(){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(l=>l.type==="atrule"&&l.name==="apply"&&l.params===o))));r||(r=F.atRule({name:"layer",params:"base",raws:{semicolon:!0,between:" ",before:`
14
- `}}),e.append(r)),t.forEach(({selector:i,apply:n})=>{r?.nodes?.find(s=>s.type==="rule"&&s.selector===i)||r?.append(F.rule({selector:i,nodes:[F.atRule({name:"apply",params:n,raws:{semicolon:!0,before:`
2
+ import Bt from"path";import{promises as Li}from"fs";import Je from"path";import lt from"path";var R="1";var A="3";var Ie="5",Pe="6",tt="7";import Te from"path";var O={"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"}}};import E from"path";import{cyan as nr,green as or,red as sr,yellow as ar}from"kleur/colors";var l={error:sr,warn:ar,info:nr,success:or};import{createMatchPath as cr}from"tsconfig-paths";async function $(e,t){return cr(t.absoluteBaseUrl,t.paths)(e,void 0,()=>!0,[".ts",".tsx"])}import{cosmiconfig as lr}from"cosmiconfig";import pr from"fast-glob";import{loadConfig as mr}from"tsconfig-paths";import{z as y}from"zod";var rt="@/components",it="@/lib/utils",nt="app/globals.css",ot="tailwind.config.js";var fr=lr("components",{searchPlaces:["components.json"]}),Y=y.object({$schema:y.string().optional(),style:y.string(),rsc:y.coerce.boolean().default(!1),tsx:y.coerce.boolean().default(!0),tailwind:y.object({config:y.string(),css:y.string(),baseColor:y.string(),cssVariables:y.boolean().default(!0),prefix:y.string().default("").optional()}),aliases:y.object({components:y.string(),utils:y.string(),ui:y.string().optional(),lib:y.string().optional(),hooks:y.string().optional()}),iconLibrary:y.string().optional()}).strict(),st=Y.extend({resolvedPaths:y.object({cwd:y.string(),tailwindConfig:y.string(),tailwindCss:y.string(),utils:y.string(),components:y.string(),lib:y.string(),hooks:y.string(),ui:y.string()})}),dr=y.record(st);async function v(e){let t=await gr(e);return t?(t.iconLibrary||(t.iconLibrary=t.style==="new-york"?"radix":"lucide"),await H(e,t)):null}async function H(e,t){let r=await mr(e);if(r.resultType==="failed")throw new Error(`Failed to load ${t.tsx?"tsconfig":"jsconfig"}.json. ${r.message??""}`.trim());return st.parse({...t,resolvedPaths:{cwd:e,tailwindConfig:E.resolve(e,t.tailwind.config),tailwindCss:E.resolve(e,t.tailwind.css),utils:await $(t.aliases.utils,r),components:await $(t.aliases.components,r),ui:t.aliases.ui?await $(t.aliases.ui,r):E.resolve(await $(t.aliases.components,r)??e,"ui"),lib:t.aliases.lib?await $(t.aliases.lib,r):E.resolve(await $(t.aliases.utils,r)??e,".."),hooks:t.aliases.hooks?await $(t.aliases.hooks,r):E.resolve(await $(t.aliases.components,r)??e,"..","hooks")}})}async function gr(e){try{let t=await fr.search(e);return t?Y.parse(t.config):null}catch{let r=`${e}/components.json`;throw new Error(`Invalid configuration found in ${l.info(r)}.`)}}async function at(e){let t={};for(let i of Object.keys(e.aliases)){if(!ur(i,e))continue;let n=e.resolvedPaths[i],o=await ke(e.resolvedPaths.cwd,n);if(!o){t[i]=e;continue}t[i]=await v(o)}let r=dr.safeParse(t);return r.success?r.data:null}async function ke(e,t){let r=Ee(e,t),i=E.relative(r,t),o=(await pr.glob("**/package.json",{cwd:r,deep:3,ignore:["**/node_modules/**","**/dist/**","**/build/**","**/public/**"]})).map(s=>E.dirname(s)).find(s=>i.startsWith(s));return o?E.join(r,o):null}function ur(e,t){return Object.keys(t.resolvedPaths).filter(r=>r!=="utils").includes(e)}function Ee(e,t){let r=e.split(E.sep),i=t.split(E.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(E.sep)}import hr from"path";import yr from"fs-extra";function re(e="",t=!0){let r=hr.join(e,"package.json");return yr.readJSONSync(r,{throws:t})}import ie from"fast-glob";import je from"fs-extra";import{loadConfig as wr}from"tsconfig-paths";import{z as B}from"zod";var ne=["**/node_modules/**",".next","public","dist","build"],Fn=B.object({compilerOptions:B.object({paths:B.record(B.string().or(B.array(B.string())))})});async function N(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}),je.pathExists(Te.resolve(e,"src")),Cr(e),br(e),xr(e),Sr(e),re(e,!1)]),f=await je.pathExists(Te.resolve(e,`${r?"src/":""}app`)),p={framework:O.manual,isSrcDir:r,isRSC:!1,isTsx:i,tailwindConfigFile:n,tailwindCssFile:o,aliasPrefix:s};return t.find(d=>d.startsWith("next.config."))?.length?(p.framework=f?O["next-app"]:O["next-pages"],p.isRSC=f,p):t.find(d=>d.startsWith("astro.config."))?.length?(p.framework=O.astro,p):t.find(d=>d.startsWith("gatsby-config."))?.length?(p.framework=O.gatsby,p):t.find(d=>d.startsWith("composer.json"))?.length?(p.framework=O.laravel,p):Object.keys(c?.dependencies??{}).find(d=>d.startsWith("@remix-run/"))?(p.framework=O.remix,p):(t.find(d=>d.startsWith("vite.config."))?.length&&(p.framework=O.vite),p)}async function xr(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 je.readFile(Te.resolve(e,r),"utf8")).includes("@tailwind base"))return r;return null}async function br(e){let t=await ie.glob("tailwind.config.*",{cwd:e,deep:3,ignore:ne});return t.length?t[0]:null}async function Sr(e){let t=await wr(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 Cr(e){return(await ie.glob("tsconfig.*",{cwd:e,deep:1,ignore:ne})).length>0}async function ct(e,t=null){let[r,i]=await Promise.all([v(e),t?Promise.resolve(t):N(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 H(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("")}};import vr from"ora";function h(e,t){return vr({text:e,isSilent:t?.silent})}import Oe from"fs-extra";async function pt(e){let t={};if(!Oe.existsSync(e.cwd)||!Oe.existsSync(lt.resolve(e.cwd,"package.json")))return t[R]=!0,{errors:t,projectInfo:null};let r=h("Preflight checks.",{silent:e.silent}).start();Oe.existsSync(lt.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)}.
3
+ 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=h("Verifying framework.",{silent:e.silent}).start(),n=await N(e.cwd);(!n||n?.framework.name==="manual")&&(t[tt]=!0,i?.fail(),a.break(),n?.framework.links.installation&&a.error(`We could not detect a supported framework at ${l.info(e.cwd)}.
4
+ Visit ${l.info(n?.framework.links.installation)} to manually configure your project.
5
+ 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=h("Validating Tailwind CSS.",{silent:e.silent}).start();!n?.tailwindConfigFile||!n?.tailwindCssFile?(t[Ie]=!0,o?.fail()):o?.succeed();let s=h("Validating import alias.",{silent:e.silent}).start();return n?.aliasPrefix?s?.succeed():(t[Pe]=!0,s?.fail()),Object.keys(t).length>0&&(t[Ie]&&(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[Pe]&&(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}}import K from"path";import{z as Rr}from"zod";function w(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 Rr.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)}import Dr from"path";import{z as m}from"zod";var mt=m.enum(["registry:style","registry:lib","registry:example","registry:block","registry:component","registry:ui","registry:hook","registry:theme","registry:page"]),ft=m.object({path:m.string(),content:m.string().optional(),type:mt,target:m.string().optional()}),Ir=m.object({config:m.object({content:m.array(m.string()).optional(),theme:m.record(m.string(),m.any()).optional(),plugins:m.array(m.string()).optional()}).optional()}),Pr=m.object({light:m.record(m.string(),m.string()).optional(),dark:m.record(m.string(),m.string()).optional()}),F=m.object({name:m.string(),type:mt,description:m.string().optional(),dependencies:m.array(m.string()).optional(),devDependencies:m.array(m.string()).optional(),registryDependencies:m.array(m.string()).optional(),files:m.array(ft).optional(),tailwind:Ir.optional(),cssVars:Pr.optional(),meta:m.record(m.string(),m.any()).optional(),docs:m.string().optional()}),$e=m.array(F.extend({files:m.array(m.union([m.string(),ft])).optional()})),dt=m.array(m.object({name:m.string(),label:m.string()})),gt=m.record(m.string(),m.record(m.string(),m.string())),ut=m.object({inlineColors:m.object({light:m.record(m.string(),m.string()),dark:m.record(m.string(),m.string())}),cssVars:m.object({light:m.record(m.string(),m.string()),dark:m.record(m.string(),m.string())}),inlineColorsTemplate:m.string(),cssVarsTemplate:m.string()}),ht=F.pick({dependencies:!0,devDependencies:!0,files:!0,tailwind:!0,cssVars:!0,docs:!0});import{promises as Ne}from"fs";import{tmpdir as kr}from"os";import Q from"path";import Er from"deepmerge";import Tr from"stringify-object";import{Project as jr,QuoteKind as Or,ScriptKind as yt,SyntaxKind as g}from"ts-morph";async function Le(e,t,r){if(!e)return;r={silent:!1,...r};let i=Q.relative(t.resolvedPaths.cwd,t.resolvedPaths.tailwindConfig),n=h(`Updating ${l.info(i)}`,{silent:r.silent}).start(),o=await Ne.readFile(t.resolvedPaths.tailwindConfig,"utf8"),s=await $r(o,e,t);await Ne.writeFile(t.resolvedPaths.tailwindConfig,s,"utf8"),n?.succeed()}async function $r(e,t,r){let i=await oe(e,r),n=i.getDescendantsOfKind(g.ObjectLiteralExpression).find(s=>s.getProperties().some(c=>c.isKind(g.PropertyAssignment)&&c.getName()==="content"));if(!n)return e;let o=Ae(n);return Nr(n,{name:"darkMode",value:"class"},{quoteChar:o}),t.plugins?.forEach(s=>{Ar(n,s)}),t.theme&&await Lr(n,t.theme),i.getFullText()}function Nr(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(g.PropertyAssignment)){let n=i.getInitializer(),o=`${r}${t.value}${r}`;if(n?.isKind(g.StringLiteral)){let s=n.getText();return n.replaceWithText(`[${s}, ${o}]`),e}if(n?.isKind(g.ArrayLiteralExpression)){if(n.getElements().map(s=>s.getText()).includes(o))return e;n.addElement(o)}return e}return e}async function Lr(e,t){e.getProperty("theme")||e.addPropertyAssignment({name:"theme",initializer:"{}"}),Fe(e);let i=(e.getPropertyOrThrow("theme")?.asKindOrThrow(g.PropertyAssignment)).getInitializer();if(i?.isKind(g.ObjectLiteralExpression)){let n=i.getText(),o=await Fr(n),s=Er(o,t,{arrayMerge:(f,p)=>p}),c=Tr(s).replace(/\'\.\.\.(.*)\'/g,"...$1").replace(/\'\"/g,"'").replace(/\"\'/g,"'").replace(/\'\[/g,"[").replace(/\]\'/g,"]").replace(/\'\\\'/g,"'").replace(/\\\'/g,"'").replace(/\\\'\'/g,"'").replace(/\'\'/g,"'");i.replaceWithText(c)}De(e)}function Ar(e,t){let r=e.getProperty("plugins");if(!r)return e.addPropertyAssignment({name:"plugins",initializer:`[${t}]`}),e;if(r.isKind(g.PropertyAssignment)){let i=r.getInitializer();if(i?.isKind(g.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 Ne.mkdtemp(Q.join(kr(),"shadcn-")),i=t?.resolvedPaths?.tailwindConfig||"tailwind.config.ts",n=Q.join(r,`shadcn-${Q.basename(i)}`);return new jr({compilerOptions:{}}).createSourceFile(n,e,{scriptKind:Q.extname(i)===".ts"?yt.TS:yt.JS})}function Ae(e){return e.getFirstDescendantByKind(g.StringLiteral)?.getQuoteKind()===Or.Single?"'":'"'}function Fe(e){let t=e.getProperties();for(let r=0;r<t.length;r++){let i=t[r];if(i.isKind(g.SpreadAssignment)){let n=i.asKindOrThrow(g.SpreadAssignment),o=n.getExpression().getText();e.insertPropertyAssignment(r,{name:`"___${o.replace(/^\.\.\./,"")}"`,initializer:`"...${o.replace(/^\.\.\./,"")}"`}),n.remove()}else if(i.isKind(g.PropertyAssignment)){let o=i.asKindOrThrow(g.PropertyAssignment).getInitializer();o&&o.isKind(g.ObjectLiteralExpression)?Fe(o.asKindOrThrow(g.ObjectLiteralExpression)):o&&o.isKind(g.ArrayLiteralExpression)&&wt(o.asKindOrThrow(g.ArrayLiteralExpression))}}}function wt(e){let t=e.getElements();for(let r=0;r<t.length;r++){let i=t[r];if(i.isKind(g.ObjectLiteralExpression))Fe(i.asKindOrThrow(g.ObjectLiteralExpression));else if(i.isKind(g.ArrayLiteralExpression))wt(i.asKindOrThrow(g.ArrayLiteralExpression));else if(i.isKind(g.SpreadElement)){let n=i.getText();e.removeElement(r),e.insertElement(r,`"${n}"`)}}}function De(e){let t=e.getProperties();for(let r=0;r<t.length;r++){let i=t[r];if(i.isKind(g.PropertyAssignment)){let n=i,o=n.getInitializer();if(o&&o.isKind(g.StringLiteral)){let s=o.asKindOrThrow(g.StringLiteral).getLiteralValue();s.startsWith("...")&&(e.insertSpreadAssignment(r,{expression:s.slice(3)}),n.remove())}else o?.isKind(g.ObjectLiteralExpression)?De(o):o&&o.isKind(g.ArrayLiteralExpression)&&xt(o.asKindOrThrow(g.ArrayLiteralExpression))}}}function xt(e){let t=e.getElements();for(let r=0;r<t.length;r++){let i=t[r];if(i.isKind(g.ObjectLiteralExpression))De(i.asKindOrThrow(g.ObjectLiteralExpression));else if(i.isKind(g.ArrayLiteralExpression))xt(i.asKindOrThrow(g.ArrayLiteralExpression));else if(i.isKind(g.StringLiteral)){let n=i.getText(),o=/(?:^['"])(\.\.\..*)(?:['"]$)/g;o.test(n)&&(e.removeElement(r),e.insertElement(r,n.replace(o,"$1")))}}}async function Fr(e){let r=(await oe(`const theme = ${e}`,null)).getStatements()[0];if(r?.getKind()===g.VariableStatement){let n=(r.getDeclarationList()?.getDeclarations()[0]).getInitializer();if(n?.isKind(g.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(g.PropertyAssignment)){let i=r.getName().replace(/\'/g,"");r.getInitializer()?.isKind(g.ObjectLiteralExpression)?t[i]=se(r.getInitializer()):r.getInitializer()?.isKind(g.ArrayLiteralExpression)?t[i]=bt(r.getInitializer()):t[i]=_e(r.getInitializer())}return t}function bt(e){let t=[];for(let r of e.getElements())r.isKind(g.ObjectLiteralExpression)?t.push(se(r.asKindOrThrow(g.ObjectLiteralExpression))):r.isKind(g.ArrayLiteralExpression)?t.push(bt(r.asKindOrThrow(g.ArrayLiteralExpression))):t.push(_e(r));return t}function _e(e){switch(e.getKind()){case g.StringLiteral:return e.getText();case g.NumericLiteral:return Number(e.getText());case g.TrueKeyword:return!0;case g.FalseKeyword:return!1;case g.NullKeyword:return null;case g.ArrayLiteralExpression:return e.getElements().map(_e);case g.ObjectLiteralExpression:return se(e);default:return e.getText()}}function St(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}import X from"deepmerge";import{HttpsProxyAgent as _r}from"https-proxy-agent";import Kr from"node-fetch";import{z as Mr}from"zod";var zr=process.env.REGISTRY_URL??"https://ui.shadcn.com/r",Wr=process.env.https_proxy?new _r(process.env.https_proxy):void 0;async function Z(){try{let[e]=await I(["index.json"]);return $e.parse(e)}catch(e){a.error(`
6
+ `),w(e)}}async function Ke(){try{let[e]=await I(["styles/index.json"]);return dt.parse(e)}catch(e){return a.error(`
7
+ `),w(e),[]}}async function ae(){try{let[e]=await I(["icons/index.json"]);return gt.parse(e)}catch(e){return w(e),{}}}async function Ct(e,t){try{let[r]=await I([ze(e)?e:`styles/${t}/${e}.json`]);return F.parse(r)}catch(r){return a.break(),w(r),null}}async function Me(){return[{name:"neutral",label:"Neutral"},{name:"gray",label:"Gray"},{name:"zinc",label:"Zinc"},{name:"stone",label:"Stone"},{name:"slate",label:"Slate"}]}async function q(e){try{let[t]=await I([`colors/${e}.json`]);return ut.parse(t)}catch(t){w(t)}}async function vt(e,t){try{let r=t.map(n=>`styles/${e}/${n.name}.json`),i=await I(r);return $e.parse(i)}catch(r){w(r)}}async function Rt(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?Dr.join(e.resolvedPaths[i],n):null}async function I(e){try{return await Promise.all(e.map(async r=>{let i=kt(r),n=await Kr(i,{agent:Wr});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)}.
8
+ 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.
9
+ 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)}.
10
+ 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)}.
11
+ ${c}`)}return n.json()}))}catch(t){return a.error(`
12
+ `),w(t),[]}}function It(e,t,r){return r||(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:(e.type==="registry:page",t.resolvedPaths.components))}async function Pt(e,t){try{if(!await Z())return null;e.includes("index")&&e.unshift("index");let i=await We(e,t),n=await I(i),o=Mr.array(F).parse(n);if(!o)return null;if(e.includes("index")&&t.tailwind.baseColor){let p=await Vr(t.tailwind.baseColor,t);p&&o.unshift(p)}let s={};o.forEach(p=>{s=X(s,p.tailwind??{})});let c={};o.forEach(p=>{c=X(c,p.cssVars??{})});let f="";return o.forEach(p=>{p.docs&&(f+=`${p.docs}
13
+ `)}),ht.parse({dependencies:X.all(o.map(p=>p.dependencies??[])),devDependencies:X.all(o.map(p=>p.devDependencies??[])),files:X.all(o.map(p=>p.files??[])),tailwind:s,cssVars:c,docs:f})}catch(r){return w(r),null}}async function Ur(e,t){let r=new Set,i=[];async function n(o){let s=kt(ze(o)?o:`styles/${t.style}/${o}.json`);if(!r.has(s)){r.add(s);try{let[c]=await I([s]),f=F.parse(c);if(i.push(s),f.registryDependencies)for(let p of f.registryDependencies)await n(p)}catch(c){console.error(`Error fetching or parsing registry item at ${o}:`,c)}}}return await n(e),Array.from(new Set(i))}async function Vr(e,t){let r=await q(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,...St(r.cssVars.dark)},i.cssVars={light:{...r.cssVars.light,...i.cssVars.light},dark:{...r.cssVars.dark,...i.cssVars.dark}}),i}function kt(e){if(ze(e)){let t=new URL(e);return t.pathname.match(/\/chat\/b\//)&&!t.pathname.endsWith("/json")&&(t.pathname=`${t.pathname}/json`),t.toString()}return`${zr}/${e}`}function ze(e){try{return new URL(e),!0}catch{return!1}}async function We(e,t){let r=[];for(let i of e){let n=await Ur(i,t);r.push(...n)}return Array.from(new Set(r))}function Et(){return new Map([["registry:ui","ui"],["registry:lib","lib"],["registry:hook","hooks"],["registry:block","components"],["registry:component","components"]])}function Tt(e){let t=new Map;return e.forEach(r=>{r.registryDependencies&&r.registryDependencies.forEach(i=>{t.set(i,r)})}),t}import{promises as jt}from"fs";import Br from"path";import z from"postcss";import Gr from"postcss/lib/at-rule";async function Ue(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=Br.relative(t.resolvedPaths.cwd,i),o=h(`Updating ${l.info(n)}`,{silent:r.silent}).start(),s=await jt.readFile(i,"utf8"),c=await Jr(s,e,t,{cleanupDefaultNextStyles:r.cleanupDefaultNextStyles});await jt.writeFile(i,c,"utf8"),o.succeed()}async function Jr(e,t,r,i){i={cleanupDefaultNextStyles:!1,...i};let n=[Hr(t)];return i.cleanupDefaultNextStyles&&n.push(Qr()),r.tailwind.cssVariables&&n.push(Yr()),(await z(n).process(e,{from:void 0})).css}function Yr(){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=z.atRule({name:"layer",params:"base",raws:{semicolon:!0,between:" ",before:`
14
+ `}}),e.append(r)),t.forEach(({selector:i,apply:n})=>{r?.nodes?.find(s=>s.type==="rule"&&s.selector===i)||r?.append(z.rule({selector:i,nodes:[z.atRule({name:"apply",params:n,raws:{semicolon:!0,before:`
15
15
  `}})],raws:{semicolon:!0,between:" ",before:`
16
- `}}))})}}}function vr(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 Cr||(r=F.atRule({name:"layer",params:"base",nodes:[],raws:{semicolon:!0,before:`
17
- `,between:" "}}),t.append(r)),r!==void 0&&Object.entries(e).forEach(([i,n])=>{let o=i==="light"?":root":`.${i}`;Tr(r,o,n)})}}}function lt(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 kr(){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()),lt(e);let r=e.nodes.find(i=>i.type==="atrule"&&i.params==="(prefers-color-scheme: dark)");r&&(lt(r),r.nodes.length===0&&r.remove())}}}function Tr(e,t,r){let i=e.nodes?.find(n=>n.type==="rule"&&n.selector===t);i||Object.keys(r).length>0&&(i=F.rule({selector:t,raws:{between:" ",before:`
18
- `}}),e.append(i)),Object.entries(r).forEach(([n,o])=>{let s=`--${n.replace(/^--/,"")}`,l=F.decl({prop:s,value:o,raws:{semicolon:!0}}),f=i?.nodes.find(d=>d.type==="decl"&&d.prop===s);f?f.replaceWith(l):i?.append(l)})}import{detect as Er}from"@antfu/ni";async function Z(e,{withFallback:t}={withFallback:!1}){let r=await Er({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"}import{execa as jr}from"execa";import $r from"prompts";async function ee(e,t,r){if(e=Array.from(new Set(e)),!e?.length)return;r={silent:!1,...r};let i=y("Installing dependencies.",{silent:r.silent})?.start(),n=await Z(t.resolvedPaths.cwd),o="";if(Or(t)&&n==="npm"){i.stopAndPersist(),a.warn(`
16
+ `}}))})}}}function Hr(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 Gr||(r=z.atRule({name:"layer",params:"base",nodes:[],raws:{semicolon:!0,before:`
17
+ `,between:" "}}),t.append(r)),r!==void 0&&Object.entries(e).forEach(([i,n])=>{let o=i==="light"?":root":`.${i}`;Xr(r,o,n)})}}}function Ot(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 Qr(){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()),Ot(e);let r=e.nodes.find(i=>i.type==="atrule"&&i.params==="(prefers-color-scheme: dark)");r&&(Ot(r),r.nodes.length===0&&r.remove())}}}function Xr(e,t,r){let i=e.nodes?.find(n=>n.type==="rule"&&n.selector===t);i||Object.keys(r).length>0&&(i=z.rule({selector:t,raws:{between:" ",before:`
18
+ `}}),e.append(i)),Object.entries(r).forEach(([n,o])=>{let s=`--${n.replace(/^--/,"")}`,c=z.decl({prop:s,value:o,raws:{semicolon:!0}}),f=i?.nodes.find(p=>p.type==="decl"&&p.prop===s);f?f.replaceWith(c):i?.append(c)})}import{detect as Zr}from"@antfu/ni";async function ce(e,{withFallback:t}={withFallback:!1}){let r=await Zr({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"}import{execa as qr}from"execa";import ei from"prompts";async function ee(e,t,r){if(e=Array.from(new Set(e)),!e?.length)return;r={silent:!1,...r};let i=h("Installing dependencies.",{silent:r.silent})?.start(),n=await ce(t.resolvedPaths.cwd),o="";if(ti(t)&&n==="npm"){i.stopAndPersist(),a.warn(`
19
19
  It looks like you are using React 19.
20
20
  Some packages may fail to install due to peer dependency issues in npm (see https://ui.shadcn.com/react-19).
21
- `);let s=await $r([{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 jr(n,[n==="npm"?"install":"add",...n==="npm"&&o?[`--${o}`]:[],...e],{cwd:t.resolvedPaths.cwd}),i?.succeed()}function Or(e){let t=Y(e.resolvedPaths.cwd);return t?.dependencies?.react?/^(?:\^|~)?19(?:\.\d+)*(?:-.*)?$/.test(t.dependencies.react):!1}import{existsSync as gt,promises as ut}from"fs";import N,{basename as Xr}from"path";import{promises as Br}from"fs";import{tmpdir as Gr}from"os";import dt from"path";import{SyntaxKind as Nr}from"ts-morph";var te=async({sourceFile:e,config:t,baseColor:r})=>(t.tailwind?.cssVariables||!r?.inlineColors||e.getDescendantsOfKind(Nr.StringLiteral).forEach(i=>{let n=i.getText();if(n){let o=Lr(n.replace(/"/g,""),r.inlineColors);i.replaceWithText(`"${o.trim()}"`)}}),e);function ve(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 Ar=["bg-","text-","border-","ring-offset-","ring-"];function Lr(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,l,f]=ve(o),d=Ar.find(g=>l?.startsWith(g));if(!d){i.has(o)||i.add(o);continue}let p=l?.replace(d,"");if(p&&p in t.light){i.add([s,`${d}${t.light[p]}`].filter(Boolean).join(":")+(f?`/${f}`:"")),n.add(["dark",s,`${d}${t.dark[p]}`].filter(Boolean).join(":")+(f?`/${f}`:""));continue}i.has(o)||i.add(o)}return[...Array.from(i),...Array.from(n)].join(" ").trim()}var R={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"}};import{SyntaxKind as Fr}from"ts-morph";var mt="lucide",re=async({sourceFile:e,config:t})=>{if(!t.iconLibrary||!(t.iconLibrary in R))return e;let r=await q(),i=mt,n=t.iconLibrary;if(i===n)return e;let o=[];for(let s of e.getImportDeclarations()??[])if(s.getModuleSpecifier()?.getText()===`"${R[mt].import}"`){for(let l of s.getNamedImports()??[]){let f=l.getName(),d=r[f]?.[n];!d||o.includes(d)||(o.push(d),l.remove(),e.getDescendantsOfKind(Fr.JsxSelfClosingElement).filter(p=>p.getTagNameNode()?.getText()===f).forEach(p=>p.getTagNameNode()?.replaceWithText(d)))}s.getNamedImports()?.length===0&&s.remove()}if(o.length>0){let s=e.addImportDeclaration({moduleSpecifier:R[n]?.import,namedImports:o.map(l=>({name:l}))});Dr(e)||s.replaceWithText(s.getText().replace(";",""))}return e};function Dr(e){return e.getImportDeclarations()?.[0]?.getText().endsWith(";")??!1}var ie=async({sourceFile:e,config:t})=>{let r=e.getImportDeclarations();for(let i of r){let n=_r(i.getModuleSpecifierValue(),t);i.setModuleSpecifier(n),n=="@/lib/utils"&&i.getNamedImports().find(l=>l.getName()==="cn")&&i.setModuleSpecifier(n.replace(/^@\/lib\/utils/,t.aliases.utils))}return e};function _r(e,t){if(!e.startsWith("@/"))return e;if(!e.startsWith("@/registry/")){let r=t.aliases.components.split("/")[0];return e.replace(/^@\//,`${r}/`)}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)}import{transformFromAstSync as zr}from"@babel/core";import{parse as Kr}from"@babel/parser";import Mr from"@babel/plugin-transform-typescript";import*as ne from"recast";var Wr={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"]},ft=async({sourceFile:e,config:t})=>{let r=e.getFullText();if(t.tsx)return r;let i=ne.parse(r,{parser:{parse:o=>Kr(o,Wr)}}),n=zr(i,r,{cloneInputAst:!1,code:!1,ast:!0,plugins:[Mr],configFile:!1});if(!n||!n.ast)throw new Error("Failed to transform JSX");return ne.print(n.ast).code};import{SyntaxKind as Ur}from"ts-morph";var Vr=/^["']use client["']$/g,oe=async({sourceFile:e,config:t})=>{if(t.rsc)return e;let r=e.getFirstChildByKind(Ur.ExpressionStatement);return r&&Vr.test(r.getText())&&r.remove(),e};import{Project as Jr,ScriptKind as Yr}from"ts-morph";import{SyntaxKind as w}from"ts-morph";var se=async({sourceFile:e,config:t})=>(t.tailwind?.prefix&&(e.getDescendantsOfKind(w.CallExpression).filter(r=>r.getExpression().getText()==="cva").forEach(r=>{if(r.getArguments()[0]?.isKind(w.StringLiteral)){let i=r.getArguments()[0];i&&i.replaceWithText(`"${O(i.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}r.getArguments()[1]?.isKind(w.ObjectLiteralExpression)&&r.getArguments()[1]?.getDescendantsOfKind(w.PropertyAssignment).find(i=>i.getName()==="variants")?.getDescendantsOfKind(w.PropertyAssignment).forEach(i=>{i.getDescendantsOfKind(w.PropertyAssignment).forEach(n=>{let o=n.getInitializerIfKind(w.StringLiteral);o&&o?.replaceWithText(`"${O(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)})})}),e.getDescendantsOfKind(w.JsxAttribute).forEach(r=>{if(r.getName()==="className"){if(r.getInitializer()?.isKind(w.StringLiteral)){let i=r.getInitializer();i&&i.replaceWithText(`"${O(i.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}if(r.getInitializer()?.isKind(w.JsxExpression)){let i=r.getInitializer()?.getDescendantsOfKind(w.CallExpression).find(n=>n.getExpression().getText()==="cn");i&&i.getArguments().forEach(n=>{(n.isKind(w.ConditionalExpression)||n.isKind(w.BinaryExpression))&&n.getChildrenOfKind(w.StringLiteral).forEach(o=>{o.replaceWithText(`"${O(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}),n.isKind(w.StringLiteral)&&n.replaceWithText(`"${O(n.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)})}}r.getName()==="classNames"&&r.getInitializer()?.isKind(w.JsxExpression)&&r.getDescendantsOfKind(w.PropertyAssignment).forEach(i=>{if(i.getInitializer()?.isKind(w.CallExpression)){let n=i.getInitializerIfKind(w.CallExpression);n&&n.getArguments().forEach(o=>{o.isKind(w.ConditionalExpression)&&o.getChildrenOfKind(w.StringLiteral).forEach(s=>{s.replaceWithText(`"${O(s.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}),o.isKind(w.StringLiteral)&&o.replaceWithText(`"${O(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)})}if(i.getInitializer()?.isKind(w.StringLiteral)&&i.getName()!=="variant"){let n=i.getInitializer();n&&n.replaceWithText(`"${O(n.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}})})),e);function O(e,t=""){let r=e.split(" "),i=[];for(let n of r){let[o,s,l]=ve(n);o?l?i.push(`${o}:${t}${s}/${l}`):i.push(`${o}:${t}${s}`):l?i.push(`${t}${s}/${l}`):i.push(`${t}${s}`)}return i.join(" ")}var Hr=new Jr({compilerOptions:{}});async function Qr(e){let t=await Br.mkdtemp(dt.join(Gr(),"shadcn-"));return dt.join(t,e)}async function ae(e,t=[ie,oe,te,se,re]){let r=await Qr(e.filename),i=Hr.createSourceFile(r,e.raw,{scriptKind:Yr.TSX});for(let n of t)await n({sourceFile:i,...e});return e.transformJsx?await ft({sourceFile:i,...e}):i.getText()}import qr from"prompts";function Zr(e,t,r){return r.startsWith("~/")?N.join(t.resolvedPaths.cwd,r.replace("~/","")):e?.isSrcDir?N.join(t.resolvedPaths.cwd,"src",r):N.join(t.resolvedPaths.cwd,r)}async function ht(e,t,r){if(!e?.length)return;r={overwrite:!1,force:!1,silent:!1,...r};let i=y("Updating files.",{silent:r.silent})?.start(),[n,o]=await Promise.all([E(t.resolvedPaths.cwd),G(t.tailwind.baseColor)]),s=[],l=[],f=[];for(let p of e){if(!p.content)continue;let g=ot(p,t),b=Xr(p.path),S=N.join(g,b);p.target&&(S=Zr(n,t,p.target),g=N.dirname(S)),t.tsx||(S=S.replace(/\.tsx?$/,ge=>ge===".tsx"?".jsx":".js"));let A=gt(S);if(A&&!r.overwrite){i.stop();let{overwrite:ge}=await qr({type:"confirm",name:"overwrite",message:`The file ${c.info(b)} already exists. Would you like to overwrite?`,initial:!1});if(!ge){f.push(N.relative(t.resolvedPaths.cwd,S));continue}i?.start()}gt(g)||await ut.mkdir(g,{recursive:!0});let L=await ae({filename:p.path,raw:p.content,config:t,baseColor:o,transformJsx:!t.tsx},[ie,oe,te,se,re]);await ut.writeFile(S,L,"utf-8"),A?l.push(N.relative(t.resolvedPaths.cwd,S)):s.push(N.relative(t.resolvedPaths.cwd,S))}if(!(s.length||l.length)&&!f.length&&i?.info("No files updated."),s.length){if(i?.succeed(`Created ${s.length} ${s.length===1?"file":"files"}:`),!r.silent)for(let p of s)a.log(` - ${p}`)}else i?.stop();if(l.length&&(y(`Updated ${l.length} ${l.length===1?"file":"files"}:`,{silent:r.silent})?.info(),!r.silent))for(let p of l)a.log(` - ${p}`);if(f.length&&(y(`Skipped ${f.length} ${l.length===1?"file":"files"}:`,{silent:r.silent})?.info(),!r.silent))for(let p of f)a.log(` - ${p}`);r.silent||a.break()}async function ce(e,t,r){r={overwrite:!1,silent:!1,isNewProject:!1,...r};let i=y("Checking registry.",{silent:r.silent})?.start(),n=await st(e,t);if(!n)return i?.fail(),x(new Error("Failed to fetch components from registry."));i?.succeed(),await Qe(n.tailwind?.config,t,{silent:r.silent}),await pt(n.cssVars,t,{cleanupDefaultNextStyles:r.isNewProject,silent:r.silent}),await ee(n.dependencies,t,{silent:r.silent}),await ht(n.files,t,{overwrite:r.overwrite,silent:r.silent}),n.docs&&a.info(n.docs)}import ei from"path";import{execa as ti}from"execa";import ke from"fs-extra";import yt from"prompts";async function le(e){if(e={srcDir:!1,...e},!e.force){let{proceed:s}=await yt({type:"confirm",name:"proceed",message:`The path ${c.info(e.cwd)} does not contain a package.json file. Would you like to start a new ${c.info("Next.js")} project?`,initial:!0});if(!s)return{projectPath:null,projectName:null}}let t=await Z(e.cwd,{withFallback:!0}),{name:r}=await yt({type:"text",name:"name",message:"What is your project named?",initial:"my-app",format:s=>s.trim(),validate:s=>s.length>128?"Name should be less than 128 characters.":!0}),i=`${e.cwd}/${r}`;try{await ke.access(e.cwd,ke.constants.W_OK)}catch{a.break(),a.error(`The path ${c.info(e.cwd)} is not writable.`),a.error(`It is likely you do not have write permissions for this folder or the path ${c.info(e.cwd)} does not exist.`),a.break(),process.exit(1)}ke.existsSync(ei.resolve(e.cwd,r,"package.json"))&&(a.break(),a.error(`A project with the name ${c.info(r)} already exists.`),a.error("Please choose a different name and try again."),a.break(),process.exit(1));let n=y("Creating a new Next.js project. This may take a few minutes.").start(),o=["--tailwind","--eslint","--typescript","--app",e.srcDir?"--src-dir":"--no-src-dir","--no-import-alias",`--use-${t}`];try{await ti("npx",["create-next-app@14.2.16",i,"--silent",...o],{cwd:e.cwd})}catch{a.break(),a.error("Something went wrong creating a new Next.js project. Please try again."),process.exit(1)}return n?.succeed("Creating a new Next.js project."),{projectPath:i,projectName:r}}import{promises as wt}from"fs";import ri from"path";import{SyntaxKind as pe}from"ts-morph";async function xt(e,t,r){if(!e)return;r={silent:!1,...r};let i=ri.relative(t.resolvedPaths.cwd,t.resolvedPaths.tailwindConfig),n=y(`Updating ${c.info(i)}`,{silent:r.silent}).start(),o=await wt.readFile(t.resolvedPaths.tailwindConfig,"utf8"),s=await ii(o,e,t);await wt.writeFile(t.resolvedPaths.tailwindConfig,s,"utf8"),n?.succeed()}async function ii(e,t,r){let i=await X(e,r),n=i.getDescendantsOfKind(pe.ObjectLiteralExpression).find(o=>o.getProperties().some(s=>s.isKind(pe.PropertyAssignment)&&s.getName()==="content"));return n?(ni(n,t),i.getFullText()):e}async function ni(e,t){let r=Ie(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(pe.PropertyAssignment)){let n=i.getInitializer();if(n?.isKind(pe.ArrayLiteralExpression))for(let o of t){let s=`${r}${o}${r}`;n.getElements().map(l=>l.getText()).includes(s)||n.addElement(s)}return e}return e}import{Command as si}from"commander";import Te from"prompts";import{z as v}from"zod";var ai=v.object({cwd:v.string(),components:v.array(v.string()).optional(),yes:v.boolean(),defaults:v.boolean(),force:v.boolean(),silent:v.boolean(),isNewProject:v.boolean(),srcDir:v.boolean().optional()}),St=new si().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=ai.parse({cwd:bt.resolve(t.cwd),isNewProject:!1,components:e,...t});await me(r),a.log(`${c.success("Success!")} Project initialization completed.
22
- You may now add components.`),a.break()}catch(r){a.break(),x(r)}});async function me(e){let t;if(e.skipPreflight)t=await E(e.cwd);else{let f=await We(e);if(f.errors[I]){let{projectPath:d}=await le(e);d||process.exit(1),e.cwd=d,e.isNewProject=!0}t=f.projectInfo}let r=await Ke(e.cwd,t),i=r?await li(r,e):await ci(await C(e.cwd));if(!e.yes){let{proceed:f}=await Te({type:"confirm",name:"proceed",message:`Write configuration to ${c.info("components.json")}. Proceed?`,initial:!0});f||process.exit(0)}let n=y("Writing components.json.").start(),o=bt.resolve(e.cwd,"components.json");await oi.writeFile(o,JSON.stringify(i,null,2),"utf8"),n.succeed();let s=await W(e.cwd,i),l=["index",...e.components||[]];return await ce(l,s,{overwrite:!0,silent:e.silent,isNewProject:e.isNewProject||t?.framework.name==="next-app"}),e.isNewProject&&e.srcDir&&await xt(["./src/**/*.{js,ts,jsx,tsx,mdx}"],s,{silent:e.silent}),s}async function ci(e=null){let[t,r]=await Promise.all([Ce(),Re()]);a.info("");let i=await Te([{type:"toggle",name:"typescript",message:`Would you like to use ${c.info("TypeScript")} (recommended)?`,initial:e?.tsx??!0,active:"yes",inactive:"no"},{type:"select",name:"style",message:`Which ${c.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 ${c.info("base color")}?`,choices:r.map(n=>({title:n.label,value:n.name}))},{type:"text",name:"tailwindCss",message:`Where is your ${c.info("global CSS")} file?`,initial:e?.tailwind.css??_e},{type:"toggle",name:"tailwindCssVariables",message:`Would you like to use ${c.info("CSS variables")} for theming?`,initial:e?.tailwind.cssVariables??!0,active:"yes",inactive:"no"},{type:"text",name:"tailwindPrefix",message:`Are you using a custom ${c.info("tailwind prefix eg. tw-")}? (Leave blank if not)`,initial:""},{type:"text",name:"tailwindConfig",message:`Where is your ${c.info("tailwind.config.js")} located?`,initial:e?.tailwind.config??ze},{type:"text",name:"components",message:`Configure the import alias for ${c.info("components")}:`,initial:e?.aliases.components??Fe},{type:"text",name:"utils",message:`Configure the import alias for ${c.info("utils")}:`,initial:e?.aliases.utils??De},{type:"toggle",name:"rsc",message:`Are you using ${c.info("React Server Components")}?`,initial:e?.rsc??!0,active:"yes",inactive:"no"}]);return M.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 li(e,t){let r=e.style,i=e.tailwind.baseColor,n=e.tailwind.cssVariables;if(!t.defaults){let[o,s]=await Promise.all([Ce(),Re()]),l=await Te([{type:"select",name:"style",message:`Which ${c.info("style")} would you like to use?`,choices:o.map(f=>({title:f.label,value:f.name})),initial:o.findIndex(f=>f.name===r)},{type:"select",name:"tailwindBaseColor",message:`Which color would you like to use as the ${c.info("base color")}?`,choices:s.map(f=>({title:f.label,value:f.name}))},{type:"toggle",name:"tailwindCssVariables",message:`Would you like to use ${c.info("CSS variables")} for theming?`,initial:e?.tailwind.cssVariables,active:"yes",inactive:"no"}]);r=l.style,i=l.tailwindBaseColor,n=l.tailwindCssVariables}return M.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})}import It from"path";import Ee from"fs-extra";async function Ct(e){let t={};if(!Ee.existsSync(e.cwd)||!Ee.existsSync(It.resolve(e.cwd,"package.json")))return t[I]=!0,{errors:t,config:null};if(!Ee.existsSync(It.resolve(e.cwd,"components.json")))return t[j]=!0,{errors:t,config:null};try{let r=await C(e.cwd);return{errors:t,config:r}}catch{a.break(),a.error(`An invalid ${c.info("components.json")} file was found at ${c.info(e.cwd)}.
23
- Before you can add components, you must create a valid ${c.info("components.json")} file by running the ${c.info("init")} command.`),a.error(`Learn more at ${c.info("https://ui.shadcn.com/docs/components-json")}.`),a.break(),process.exit(1)}}import Rt from"fs/promises";import pi from"path";async function Pt(e,t){let r=pi.join(t.resolvedPaths.cwd,"app/page.tsx");if(!(await Rt.stat(r)).isFile())return;let i=await rt(e,t.style);if(!i?.meta?.importSpecifier||!i?.meta?.moduleSpecifier)return;let n=`import { ${i?.meta?.importSpecifier} } from "${i.meta.moduleSpecifier}"
21
+ `);let s=await ei([{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 qr(n,[n==="npm"?"install":"add",...n==="npm"&&o?[`--${o}`]:[],...e],{cwd:t.resolvedPaths.cwd}),i?.succeed()}function ti(e){let t=re(e.resolvedPaths.cwd);return t?.dependencies?.react?/^(?:\^|~)?19(?:\.\d+)*(?:-.*)?$/.test(t.dependencies.react):!1}import{existsSync as Ft,promises as Dt}from"fs";import _,{basename as bi}from"path";import{promises as gi}from"fs";import{tmpdir as ui}from"os";import At from"path";import{SyntaxKind as ri}from"ts-morph";var le=async({sourceFile:e,config:t,baseColor:r})=>(t.tailwind?.cssVariables||!r?.inlineColors||e.getDescendantsOfKind(ri.StringLiteral).forEach(i=>{let n=i.getText();if(n){let o=ni(n.replace(/"/g,""),r.inlineColors);i.replaceWithText(`"${o.trim()}"`)}}),e);function Ve(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 ii=["bg-","text-","border-","ring-offset-","ring-"];function ni(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,f]=Ve(o),p=ii.find(u=>c?.startsWith(u));if(!p){i.has(o)||i.add(o);continue}let d=c?.replace(p,"");if(d&&d in t.light){i.add([s,`${p}${t.light[d]}`].filter(Boolean).join(":")+(f?`/${f}`:"")),n.add(["dark",s,`${p}${t.dark[d]}`].filter(Boolean).join(":")+(f?`/${f}`:""));continue}i.has(o)||i.add(o)}return[...Array.from(i),...Array.from(n)].join(" ").trim()}var P={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"}};import{SyntaxKind as oi}from"ts-morph";var $t="lucide",pe=async({sourceFile:e,config:t})=>{if(!t.iconLibrary||!(t.iconLibrary in P))return e;let r=await ae(),i=$t,n=t.iconLibrary;if(i===n)return e;let o=[];for(let s of e.getImportDeclarations()??[])if(s.getModuleSpecifier()?.getText()===`"${P[$t].import}"`){for(let c of s.getNamedImports()??[]){let f=c.getName(),p=r[f]?.[n];!p||o.includes(p)||(o.push(p),c.remove(),e.getDescendantsOfKind(oi.JsxSelfClosingElement).filter(d=>d.getTagNameNode()?.getText()===f).forEach(d=>d.getTagNameNode()?.replaceWithText(p)))}s.getNamedImports()?.length===0&&s.remove()}if(o.length>0){let s=e.addImportDeclaration({moduleSpecifier:P[n]?.import,namedImports:o.map(c=>({name:c}))});si(e)||s.replaceWithText(s.getText().replace(";",""))}return e};function si(e){return e.getImportDeclarations()?.[0]?.getText().endsWith(";")??!1}var Nt={"@/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=ai(n.getModuleSpecifierValue(),t,r);n.setModuleSpecifier(o),Nt[o]&&n.getNamedImports().find(f=>f.getName()==="cn")&&n.setModuleSpecifier(o.replace(Nt[o],t.aliases.utils))}return e};function ai(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)}import{transformFromAstSync as ci}from"@babel/core";import{parse as li}from"@babel/parser";import pi from"@babel/plugin-transform-typescript";import*as fe from"recast";var mi={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"]},Lt=async({sourceFile:e,config:t})=>{let r=e.getFullText();if(t.tsx)return r;let i=fe.parse(r,{parser:{parse:o=>li(o,mi)}}),n=ci(i,r,{cloneInputAst:!1,code:!1,ast:!0,plugins:[pi],configFile:!1});if(!n||!n.ast)throw new Error("Failed to transform JSX");return fe.print(n.ast).code};import{SyntaxKind as fi}from"ts-morph";var di=/^["']use client["']$/g,de=async({sourceFile:e,config:t})=>{if(t.rsc)return e;let r=e.getFirstChildByKind(fi.ExpressionStatement);return r&&di.test(r.getText())&&r.remove(),e};import{Project as hi,ScriptKind as yi}from"ts-morph";import{SyntaxKind as S}from"ts-morph";var ge=async({sourceFile:e,config:t})=>(t.tailwind?.prefix&&(e.getDescendantsOfKind(S.CallExpression).filter(r=>r.getExpression().getText()==="cva").forEach(r=>{if(r.getArguments()[0]?.isKind(S.StringLiteral)){let i=r.getArguments()[0];i&&i.replaceWithText(`"${D(i.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}r.getArguments()[1]?.isKind(S.ObjectLiteralExpression)&&r.getArguments()[1]?.getDescendantsOfKind(S.PropertyAssignment).find(i=>i.getName()==="variants")?.getDescendantsOfKind(S.PropertyAssignment).forEach(i=>{i.getDescendantsOfKind(S.PropertyAssignment).forEach(n=>{let o=n.getInitializerIfKind(S.StringLiteral);o&&o?.replaceWithText(`"${D(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)})})}),e.getDescendantsOfKind(S.JsxAttribute).forEach(r=>{if(r.getName()==="className"){if(r.getInitializer()?.isKind(S.StringLiteral)){let i=r.getInitializer();i&&i.replaceWithText(`"${D(i.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}if(r.getInitializer()?.isKind(S.JsxExpression)){let i=r.getInitializer()?.getDescendantsOfKind(S.CallExpression).find(n=>n.getExpression().getText()==="cn");i&&i.getArguments().forEach(n=>{(n.isKind(S.ConditionalExpression)||n.isKind(S.BinaryExpression))&&n.getChildrenOfKind(S.StringLiteral).forEach(o=>{o.replaceWithText(`"${D(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}),n.isKind(S.StringLiteral)&&n.replaceWithText(`"${D(n.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)})}}r.getName()==="classNames"&&r.getInitializer()?.isKind(S.JsxExpression)&&r.getDescendantsOfKind(S.PropertyAssignment).forEach(i=>{if(i.getInitializer()?.isKind(S.CallExpression)){let n=i.getInitializerIfKind(S.CallExpression);n&&n.getArguments().forEach(o=>{o.isKind(S.ConditionalExpression)&&o.getChildrenOfKind(S.StringLiteral).forEach(s=>{s.replaceWithText(`"${D(s.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}),o.isKind(S.StringLiteral)&&o.replaceWithText(`"${D(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)})}if(i.getInitializer()?.isKind(S.StringLiteral)&&i.getName()!=="variant"){let n=i.getInitializer();n&&n.replaceWithText(`"${D(n.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}})})),e);function D(e,t=""){let r=e.split(" "),i=[];for(let n of r){let[o,s,c]=Ve(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 wi=new hi({compilerOptions:{}});async function xi(e){let t=await gi.mkdtemp(At.join(ui(),"shadcn-"));return At.join(t,e)}async function ue(e,t=[me,de,le,ge,pe]){let r=await xi(e.filename),i=wi.createSourceFile(r,e.raw,{scriptKind:yi.TSX});for(let n of t)await n({sourceFile:i,...e});return e.transformJsx?await Lt({sourceFile:i,...e}):i.getText()}import Si from"prompts";function Ci(e,t,r){return r.startsWith("~/")?_.join(t.resolvedPaths.cwd,r.replace("~/","")):e?.isSrcDir?_.join(t.resolvedPaths.cwd,"src",r):_.join(t.resolvedPaths.cwd,r)}async function Be(e,t,r){if(!e?.length)return{filesCreated:[],filesUpdated:[],filesSkipped:[]};r={overwrite:!1,force:!1,silent:!1,isRemote:!1,...r};let i=h("Updating files.",{silent:r.silent})?.start(),[n,o]=await Promise.all([N(t.resolvedPaths.cwd),q(t.tailwind.baseColor)]),s=[],c=[],f=[];for(let d of e){if(!d.content)continue;let u=It(d,t),x=bi(d.path),C=_.join(u,x);d.target&&(C=Ci(n,t,d.target),u=_.dirname(C)),t.tsx||(C=C.replace(/\.tsx?$/,G=>G===".tsx"?".jsx":".js"));let L=Ft(C);if(L&&!r.overwrite){i.stop(),r.rootSpinner&&r.rootSpinner.stop();let{overwrite:G}=await Si({type:"confirm",name:"overwrite",message:`The file ${l.info(x)} already exists. Would you like to overwrite?`,initial:!1});if(!G){f.push(_.relative(t.resolvedPaths.cwd,C)),r.rootSpinner&&r.rootSpinner.start();continue}i?.start(),r.rootSpinner&&r.rootSpinner.start()}Ft(u)||await Dt.mkdir(u,{recursive:!0});let b=await ue({filename:d.path,raw:d.content,config:t,baseColor:o,transformJsx:!t.tsx,isRemote:r.isRemote},[me,de,le,ge,pe]);await Dt.writeFile(C,b,"utf-8"),L?c.push(_.relative(t.resolvedPaths.cwd,C)):s.push(_.relative(t.resolvedPaths.cwd,C))}if(!(s.length||c.length)&&!f.length&&i?.info("No files updated."),s.length){if(i?.succeed(`Created ${s.length} ${s.length===1?"file":"files"}:`),!r.silent)for(let d of s)a.log(` - ${d}`)}else i?.stop();if(c.length&&(h(`Updated ${c.length} ${c.length===1?"file":"files"}:`,{silent:r.silent})?.info(),!r.silent))for(let d of c)a.log(` - ${d}`);if(f.length&&(h(`Skipped ${f.length} ${c.length===1?"file":"files"}: (use --overwrite to overwrite)`,{silent:r.silent})?.info(),!r.silent))for(let d of f)a.log(` - ${d}`);return r.silent||a.break(),{filesCreated:s,filesUpdated:c,filesSkipped:f}}import{z as vi}from"zod";async function he(e,t,r){r={overwrite:!1,silent:!1,isNewProject:!1,...r};let i=await at(t);return i&&i?.ui.resolvedPaths.cwd!==t.resolvedPaths.cwd?await Ii(e,t,i,{...r,isRemote:e?.length===1&&!!e[0].match(/\/chat\/b\//)}):await Ri(e,t,r)}async function Ri(e,t,r){let i=h("Checking registry.",{silent:r.silent})?.start(),n=await Pt(e,t);if(!n)return i?.fail(),w(new Error("Failed to fetch components from registry."));i?.succeed(),await Le(n.tailwind?.config,t,{silent:r.silent}),await Ue(n.cssVars,t,{cleanupDefaultNextStyles:r.isNewProject,silent:r.silent}),await ee(n.dependencies,t,{silent:r.silent}),await Be(n.files,t,{overwrite:r.overwrite,silent:r.silent}),n.docs&&a.info(n.docs)}async function Ii(e,t,r,i){let n=h("Checking registry.",{silent:i.silent})?.start(),o=await We(e,t),s=await I(o),c=vi.array(F).parse(s);if(!c)return n?.fail(),w(new Error("Failed to fetch components from registry."));n?.succeed();let f=Tt(c),p=Et(),d=[],u=[],x=[],C=h("Installing components.")?.start();for(let b of c){let G=p.get(b.type),ir=f.get(b.name);if(!G)continue;let j=b.type==="registry:ui"||ir?.type==="registry:ui"?r.ui:t,U=Ee(t.resolvedPaths.cwd,j.resolvedPaths.ui),ve=await ke(U,j.resolvedPaths.cwd)??j.resolvedPaths.cwd;b.tailwind?.config&&(await Le(b.tailwind?.config,j,{silent:!0}),u.push(K.relative(U,j.resolvedPaths.tailwindConfig))),b.cssVars&&(await Ue(b.cssVars,j,{silent:!0}),u.push(K.relative(U,j.resolvedPaths.tailwindCss))),await ee(b.dependencies,j,{silent:!0});let Re=await Be(b.files,j,{overwrite:i.overwrite,silent:!0,rootSpinner:C,isRemote:i.isRemote});d.push(...Re.filesCreated.map(J=>K.relative(U,K.join(ve,J)))),u.push(...Re.filesUpdated.map(J=>K.relative(U,K.join(ve,J)))),x.push(...Re.filesSkipped.map(J=>K.relative(U,K.join(ve,J))))}if(C?.succeed(),d.sort(),u.sort(),x.sort(),!(d.length||u.length)&&!x.length&&h("No files updated.",{silent:i.silent})?.info(),d.length){h(`Created ${d.length} ${d.length===1?"file":"files"}:`,{silent:i.silent})?.succeed();for(let b of d)a.log(` - ${b}`)}if(u.length){h(`Updated ${u.length} ${u.length===1?"file":"files"}:`,{silent:i.silent})?.info();for(let b of u)a.log(` - ${b}`)}if(x.length){h(`Skipped ${x.length} ${u.length===1?"file":"files"}: (use --overwrite to overwrite)`,{silent:i.silent})?.info();for(let b of x)a.log(` - ${b}`)}}import Pi from"os";import ye from"path";import{execa as M}from"execa";import W from"fs-extra";import ki from"prompts";import{z as Ge}from"zod";var Ei="https://codeload.github.com/shadcn-ui/ui/tar.gz/shadcn/cli-monorepo";async function we(e){e={srcDir:!1,...e};let t="next",r="my-app",i="14.2.16",n=e.components?.length===1&&!!e.components[0].match(/\/chat\/b\//);if(e.components&&n)try{let[c]=await I(e.components),{meta:f}=Ge.object({meta:Ge.object({nextVersion:Ge.string()})}).parse(c);i=f.nextVersion}catch(c){a.break(),w(c)}if(!e.force){let{type:c,name:f}=await ki([{type:"select",name:"type",message:`The path ${l.info(e.cwd)} does not contain a package.json file.
22
+ 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=f}let o=await ce(e.cwd,{withFallback:!0}),s=`${e.cwd}/${r}`;try{await W.access(e.cwd,W.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 W.existsSync(ye.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 Ti(s,{version:i,cwd:e.cwd,packageManager:o,srcDir:!!e.srcDir}),t==="monorepo"&&await ji(s,{packageManager:o}),{projectPath:s,projectName:r,projectType:t}}async function Ti(e,t){let r=h("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 M("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 ji(e,t){let r=h("Creating a new Next.js monorepo. This may take a few minutes.").start();try{let i=ye.join(Pi.tmpdir(),`shadcn-template-${Date.now()}`);await W.ensureDir(i);let n=await fetch(Ei);if(!n.ok)throw new Error(`Failed to download template: ${n.statusText}`);let o=ye.resolve(i,"template.tar.gz");await W.writeFile(o,Buffer.from(await n.arrayBuffer())),await M("tar",["-xzf",o,"-C",i,"--strip-components=2","ui-shadcn-cli-monorepo/templates/monorepo-next"]);let s=ye.resolve(i,"monorepo-next");await W.move(s,e),await W.remove(i),await M(t.packageManager,["install"],{cwd:e});let c=process.cwd();await M("git",["--version"],{cwd:e}),await M("git",["init"],{cwd:e}),await M("git",["add","-A"],{cwd:e}),await M("git",["commit","-m","Initial commit"],{cwd:e}),await M("cd",[c]),r?.succeed("Creating a new Next.js monorepo.")}catch(i){r?.fail("Something went wrong creating a new Next.js monorepo."),w(i)}}import{promises as _t}from"fs";import Oi from"path";import{SyntaxKind as xe}from"ts-morph";async function Kt(e,t,r){if(!e)return;r={silent:!1,...r};let i=Oi.relative(t.resolvedPaths.cwd,t.resolvedPaths.tailwindConfig),n=h(`Updating ${l.info(i)}`,{silent:r.silent}).start(),o=await _t.readFile(t.resolvedPaths.tailwindConfig,"utf8"),s=await $i(o,e,t);await _t.writeFile(t.resolvedPaths.tailwindConfig,s,"utf8"),n?.succeed()}async function $i(e,t,r){let i=await oe(e,r),n=i.getDescendantsOfKind(xe.ObjectLiteralExpression).find(o=>o.getProperties().some(s=>s.isKind(xe.PropertyAssignment)&&s.getName()==="content"));return n?(Ni(n,t),i.getFullText()):e}async function Ni(e,t){let r=Ae(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(xe.PropertyAssignment)){let n=i.getInitializer();if(n?.isKind(xe.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}import{Command as Ai}from"commander";import Ye from"prompts";import{z as T}from"zod";var Fi=T.object({cwd:T.string(),components:T.array(T.string()).optional(),yes:T.boolean(),defaults:T.boolean(),force:T.boolean(),silent:T.boolean(),isNewProject:T.boolean(),srcDir:T.boolean().optional()}),Mt=new Ai().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=Fi.parse({cwd:Je.resolve(t.cwd),isNewProject:!1,components:e,...t});await be(r),a.log(`${l.success("Success!")} Project initialization completed.
23
+ You may now add components.`),a.break()}catch(r){a.break(),w(r)}});async function be(e){let t,r;if(e.skipPreflight)t=await N(e.cwd);else{let p=await pt(e);if(p.errors[R]){let{projectPath:d,projectType:u}=await we(e);d||process.exit(1),e.cwd=d,e.isNewProject=!0,r=u}t=p.projectInfo}if(r==="monorepo")return e.cwd=Je.resolve(e.cwd,"apps/web"),await v(e.cwd);let i=await ct(e.cwd,t),n=i?await _i(i,e):await Di(await v(e.cwd));if(!e.yes){let{proceed:p}=await Ye({type:"confirm",name:"proceed",message:`Write configuration to ${l.info("components.json")}. Proceed?`,initial:!0});p||process.exit(0)}let o=h("Writing components.json.").start(),s=Je.resolve(e.cwd,"components.json");await Li.writeFile(s,JSON.stringify(n,null,2),"utf8"),o.succeed();let c=await H(e.cwd,n),f=["index",...e.components||[]];return await he(f,c,{overwrite:!0,silent:e.silent,isNewProject:e.isNewProject||t?.framework.name==="next-app"}),e.isNewProject&&e.srcDir&&await Kt(["./src/**/*.{js,ts,jsx,tsx,mdx}"],c,{silent:e.silent}),c}async function Di(e=null){let[t,r]=await Promise.all([Ke(),Me()]);a.info("");let i=await Ye([{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??nt},{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??ot},{type:"text",name:"components",message:`Configure the import alias for ${l.info("components")}:`,initial:e?.aliases.components??rt},{type:"text",name:"utils",message:`Configure the import alias for ${l.info("utils")}:`,initial:e?.aliases.utils??it},{type:"toggle",name:"rsc",message:`Are you using ${l.info("React Server Components")}?`,initial:e?.rsc??!0,active:"yes",inactive:"no"}]);return Y.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 _i(e,t){let r=e.style,i=e.tailwind.baseColor,n=e.tailwind.cssVariables;if(!t.defaults){let[o,s]=await Promise.all([Ke(),Me()]),c=await Ye([{type:"select",name:"style",message:`Which ${l.info("style")} would you like to use?`,choices:o.map(f=>({title:f.label,value:f.name})),initial:o.findIndex(f=>f.name===r)},{type:"select",name:"tailwindBaseColor",message:`Which color would you like to use as the ${l.info("base color")}?`,choices:s.map(f=>({title:f.label,value:f.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 Y.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})}import zt from"path";import He from"fs-extra";async function Wt(e){let t={};if(!He.existsSync(e.cwd)||!He.existsSync(zt.resolve(e.cwd,"package.json")))return t[R]=!0,{errors:t,config:null};if(!He.existsSync(zt.resolve(e.cwd,"components.json")))return t[A]=!0,{errors:t,config:null};try{let r=await v(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)}.
24
+ 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)}}import Ut from"fs/promises";import Ki from"path";async function Vt(e,t){let r=Ki.join(t.resolvedPaths.cwd,"app/page.tsx");if(!(await Ut.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}"
24
25
 
25
26
  export default function Page() {
26
27
  return <${i?.meta?.importSpecifier} />
27
- }`;await Rt.writeFile(r,n,"utf8")}import{Command as fi}from"commander";import je from"prompts";import{z as P}from"zod";var di=P.object({components:P.array(P.string()).optional(),yes:P.boolean(),overwrite:P.boolean(),cwd:P.string(),all:P.boolean(),path:P.string().optional(),silent:P.boolean(),srcDir:P.boolean().optional()}),vt=new fi().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=di.parse({components:e,cwd:mi.resolve(t.cwd),...t}),i=r.components?.some(l=>l.includes("theme-"));if(!r.yes&&i){a.break();let{confirm:l}=await je({type:"confirm",name:"confirm",message:c.warn(`You are about to install a new theme.
28
- Existing CSS variables will be overwritten. Continue?`)});l||(a.break(),a.log("Theme installation cancelled."),a.break(),process.exit(1))}r.components?.length||(r.components=await gi(r));let{errors:n,config:o}=await Ct(r);if(n[j]){let{proceed:l}=await je({type:"confirm",name:"proceed",message:`You need to create a ${c.info("components.json")} file to add components. Proceed?`,initial:!0});l||(a.break(),process.exit(1)),o=await me({cwd:r.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!1,silent:!0,isNewProject:!1,srcDir:r.srcDir})}let s=!1;if(n[I]){let{projectPath:l}=await le({cwd:r.cwd,force:r.overwrite,srcDir:r.srcDir});l||(a.break(),process.exit(1)),r.cwd=l,o=await me({cwd:r.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!0,silent:!0,isNewProject:!0,srcDir:r.srcDir}),s=r.components?.length===1&&!!r.components[0].match(/\/chat\/b\//)}if(!o)throw new Error(`Failed to read config at ${c.info(r.cwd)}.`);await ce(r.components,o,r),s&&await Pt(r.components[0],o)}catch(r){a.break(),x(r)}});async function gi(e){let t=await B();if(!t)return a.break(),x(new Error("Failed to fetch registry index.")),[];if(e.all)return t.map(n=>n.name);if(e.components?.length)return e.components;let{components:r}=await je({type:"multiselect",name:"components",message:"Which components would you like to add?",hint:"Space to select. A to toggle all. Enter to submit.",instructions:!1,choices:t.filter(n=>n.type==="registry:ui").map(n=>({title:n.name,value:n.name,selected:e.all?!0:e.components?.includes(n.name)}))});r?.length||(a.warn("No components selected. Exiting."),a.info(""),process.exit(1));let i=P.array(P.string()).safeParse(r);return i.success?i.data:(a.error(""),x(new Error("Something went wrong. Please try again.")),[])}import{existsSync as $e,promises as ui}from"fs";import Oe from"path";import{Command as hi}from"commander";import{diffLines as yi}from"diff";import{z as J}from"zod";var wi=J.object({component:J.string().optional(),yes:J.boolean(),cwd:J.string(),path:J.string().optional()}),Tt=new hi().name("diff").description("check for updates against the registry").argument("[component]","the component name").option("-y, --yes","skip confirmation prompt.",!1).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async(e,t)=>{try{let r=wi.parse({component:e,...t}),i=Oe.resolve(r.cwd);$e(i)||(a.error(`The path ${i} does not exist. Please try again.`),process.exit(1));let n=await C(i);n||(a.warn(`Configuration is missing. Please run ${c.success("init")} to create a components.json file.`),process.exit(1));let o=await B();if(o||(x(new Error("Failed to fetch registry index.")),process.exit(1)),!r.component){let f=n.resolvedPaths.components,d=o.filter(g=>{for(let b of g.files??[]){let S=Oe.resolve(f,typeof b=="string"?b:b.path);if($e(S))return!0}return!1}),p=[];for(let g of d){let b=await kt(g,n);b.length&&p.push({name:g.name,changes:b})}p.length||(a.info("No updates found."),process.exit(0)),a.info("The following components have updates available:");for(let g of p){a.info(`- ${g.name}`);for(let b of g.changes)a.info(` - ${b.filePath}`)}a.break(),a.info(`Run ${c.success("diff <component>")} to see the changes.`),process.exit(0)}let s=o.find(f=>f.name===r.component);s||(a.error(`The component ${c.success(r.component)} does not exist.`),process.exit(1));let l=await kt(s,n);l.length||(a.info(`No updates found for ${r.component}.`),process.exit(0));for(let f of l)a.info(`- ${f.filePath}`),await xi(f.patch),a.info("")}catch(r){x(r)}});async function kt(e,t){let r=await it(t.style,[e]),i=await G(t.tailwind.baseColor);if(!r)return[];let n=[];for(let o of r){let s=await nt(t,o);if(s)for(let l of o.files??[]){let f=Oe.resolve(s,typeof l=="string"?l:l.path);if(!$e(f))continue;let d=await ui.readFile(f,"utf8");if(typeof l=="string"||!l.content)continue;let p=await ae({filename:l.path,raw:l.content,config:t,baseColor:i}),g=yi(p,d);g.length>1&&n.push({filePath:f,patch:g})}}return n}async function xi(e){e.forEach(t=>{if(t)return t.added?process.stdout.write(c.success(t.value)):t.removed?process.stdout.write(c.error(t.value)):process.stdout.write(t.value)})}import{Command as bi}from"commander";var Et=new bi().name("info").description("get information about your project").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{a.info("> project info"),console.log(await E(e.cwd)),a.break(),a.info("> components.json"),console.log(await C(e.cwd))});import Ti from"path";import{randomBytes as Si}from"crypto";import{promises as Ne}from"fs";import{tmpdir as Ii}from"os";import fe from"path";import Ci from"fast-glob";import jt from"prompts";import{Project as Ri,ScriptKind as Pi,SyntaxKind as vi}from"ts-morph";async function $t(e){if(!e.resolvedPaths.ui)throw new Error("We could not find a valid `ui` path in your `components.json` file. Please ensure you have a valid `ui` path in your `components.json` file.");let t=e.resolvedPaths.ui,[r,i]=await Promise.all([Ci("**/*.{js,ts,jsx,tsx}",{cwd:t}),q()]);if(Object.keys(i).length===0)throw new Error("Something went wrong fetching the registry icons.");let n=Object.entries(R).map(([p,g])=>({title:g.name,value:p})),o=await jt([{type:"select",name:"sourceLibrary",message:`Which icon library would you like to ${c.info("migrate from")}?`,choices:n},{type:"select",name:"targetLibrary",message:`Which icon library would you like to ${c.info("migrate to")}?`,choices:n}]);if(o.sourceLibrary===o.targetLibrary)throw new Error("You cannot migrate to the same icon library. Please choose a different icon library.");if(!(o.sourceLibrary in R&&o.targetLibrary in R))throw new Error("Invalid icon library. Please choose a valid icon library.");let s=R[o.sourceLibrary],l=R[o.targetLibrary],{confirm:f}=await jt({type:"confirm",name:"confirm",initial:!0,message:`We will migrate ${c.info(r.length)} files in ${c.info(`./${fe.relative(e.resolvedPaths.cwd,t)}`)} from ${c.info(s.name)} to ${c.info(l.name)}. Continue?`});f||(a.info("Migration cancelled."),process.exit(0)),l.package&&await ee([l.package],e,{silent:!1});let d=y("Migrating icons...")?.start();await Promise.all(r.map(async p=>{d.text=`Migrating ${p}...`;let g=fe.join(t,p),b=await Ne.readFile(g,"utf-8"),S=await ki(b,o.sourceLibrary,o.targetLibrary,i);await Ne.writeFile(g,S)})),d.succeed("Migration complete.")}async function ki(e,t,r,i){let n=R[t]?.import,o=R[r]?.import,s=await Ne.mkdtemp(fe.join(Ii(),"shadcn-")),l=new Ri({compilerOptions:{}}),f=fe.join(s,`shadcn-icons-${Si(4).toString("hex")}.tsx`),d=l.createSourceFile(f,e,{scriptKind:Pi.TSX}),p=[];for(let g of d.getImportDeclarations()??[])if(g.getModuleSpecifier()?.getText()===`"${n}"`){for(let b of g.getNamedImports()??[]){let S=b.getName(),A=Object.values(i).find(L=>L[t]===S)?.[r];!A||p.includes(A)||(p.push(A),b.remove(),d.getDescendantsOfKind(vi.JsxSelfClosingElement).filter(L=>L.getTagNameNode()?.getText()===S).forEach(L=>L.getTagNameNode()?.replaceWithText(A)))}g.getNamedImports()?.length===0&&g.remove()}return p.length>0&&d.addImportDeclaration({moduleSpecifier:o,namedImports:p.map(g=>({name:g}))}),await d.getText()}import Ot from"path";import Ae from"fs-extra";async function Nt(e){let t={};if(!Ae.existsSync(e.cwd)||!Ae.existsSync(Ot.resolve(e.cwd,"package.json")))return t[I]=!0,{errors:t,config:null};if(!Ae.existsSync(Ot.resolve(e.cwd,"components.json")))return t[j]=!0,{errors:t,config:null};try{let r=await C(e.cwd);return{errors:t,config:r}}catch{a.break(),a.error(`An invalid ${c.info("components.json")} file was found at ${c.info(e.cwd)}.
29
- Before you can run a migration, you must create a valid ${c.info("components.json")} file by running the ${c.info("init")} command.`),a.error(`Learn more at ${c.info("https://ui.shadcn.com/docs/components-json")}.`),a.break(),process.exit(1)}}import{Command as Ei}from"commander";import{z as de}from"zod";var At=[{name:"icons",description:"migrate your ui components to a different icon library."}],ji=de.object({cwd:de.string(),list:de.boolean(),migration:de.string().refine(e=>e&&At.some(t=>t.name===e),{message:"You must specify a valid migration. Run `shadcn migrate --list` to see available migrations."}).optional()}),Lt=new Ei().name("migrate").description("run a migration.").argument("[migration]","the migration to run.").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-l, --list","list all migrations.",!1).action(async(e,t)=>{try{let r=ji.parse({cwd:Ti.resolve(t.cwd),migration:e,list:t.list});if(r.list||!r.migration){a.info("Available migrations:");for(let o of At)a.info(`- ${o.name}: ${o.description}`);return}if(!r.migration)throw new Error("You must specify a migration. Run `shadcn migrate --list` to see available migrations.");let{errors:i,config:n}=await Nt(r);if(i[I]||i[j])throw new Error("No `components.json` file found. Ensure you are at the root of your project.");if(!n)throw new Error("Something went wrong reading your `components.json` file. Please ensure you have a valid `components.json` file.");r.migration==="icons"&&await $t(n)}catch(r){a.break(),x(r)}});import{Command as Oi}from"commander";var Ft={name:"shadcn",version:"0.0.0-beta.82ec1a9",description:"Add components to your apps.",publishConfig:{access:"public"},license:"MIT",author:{name:"shadcn",url:"https://twitter.com/shadcn"},repository:{type:"git",url:"https://github.com/shadcn/ui.git",directory:"packages/shadcn"},files:["dist"],keywords:["components","ui","tailwind","radix-ui","shadcn"],type:"module",exports:"./dist/index.js",bin:"./dist/index.js",scripts:{dev:"tsup --watch",build:"tsup",typecheck:"tsc --noEmit",clean:"rimraf dist && rimraf components","start:dev":"cross-env REGISTRY_URL=http://localhost:3333/r node dist/index.js","start:prod":"cross-env REGISTRY_URL=https://ui.shadcn.com/r node dist/index.js",start:"node dist/index.js","format:write":'prettier --write "**/*.{ts,tsx,mdx}" --cache',"format:check":'prettier --check "**/*.{ts,tsx,mdx}" --cache',release:"changeset version","pub:beta":"pnpm build && pnpm publish --no-git-checks --access public --tag beta","pub:next":"pnpm build && pnpm publish --no-git-checks --access public --tag next","pub:release":"pnpm build && pnpm publish --access public",test:"vitest run","test:dev":"REGISTRY_URL=http://localhost:3333/r vitest run"},dependencies:{"@antfu/ni":"^0.21.4","@babel/core":"^7.22.1","@babel/parser":"^7.22.6","@babel/plugin-transform-typescript":"^7.22.5",commander:"^10.0.0",cosmiconfig:"^8.1.3",deepmerge:"^4.3.1",diff:"^5.1.0",execa:"^7.0.0","fast-glob":"^3.3.2","fs-extra":"^11.1.0","https-proxy-agent":"^6.2.0",kleur:"^4.1.5","lodash.template":"^4.5.0","node-fetch":"^3.3.0",ora:"^6.1.2",postcss:"^8.4.24",prompts:"^2.4.2",recast:"^0.23.2","stringify-object":"^5.0.0","ts-morph":"^18.0.0","tsconfig-paths":"^4.2.0",zod:"^3.20.2"},devDependencies:{"@types/babel__core":"^7.20.1","@types/diff":"^5.0.3","@types/fs-extra":"^11.0.1","@types/lodash.template":"^4.5.1","@types/prompts":"^2.4.2","@types/stringify-object":"^4.0.5",rimraf:"^6.0.1",tsup:"^6.6.3","type-fest":"^3.8.0",typescript:"^4.9.3"}};process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function Ni(){let e=new Oi().name("shadcn").description("add components and dependencies to your project").version(Ft.version||"1.0.0","-v, --version","display the version number");e.addCommand(St).addCommand(vt).addCommand(Tt).addCommand(Lt).addCommand(Et),e.parse()}Ni();
28
+ }`;await Ut.writeFile(r,n,"utf8")}import{Command as Mi}from"commander";import Qe from"prompts";import{z as k}from"zod";var zi=k.object({components:k.array(k.string()).optional(),yes:k.boolean(),overwrite:k.boolean(),cwd:k.string(),all:k.boolean(),path:k.string().optional(),silent:k.boolean(),srcDir:k.boolean().optional()}),Gt=new Mi().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=zi.parse({components:e,cwd:Bt.resolve(t.cwd),...t}),i=r.components?.some(c=>c.includes("theme-"));if(!r.yes&&i){a.break();let{confirm:c}=await Qe({type:"confirm",name:"confirm",message:l.warn(`You are about to install a new theme.
29
+ 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 Wi(r));let{errors:n,config:o}=await Wt(r);if(n[A]){let{proceed:c}=await Qe({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[R]){let{projectPath:c,projectType:f}=await we({cwd:r.cwd,force:r.overwrite,srcDir:r.srcDir,components:r.components});c||(a.break(),process.exit(1)),r.cwd=c,f==="monorepo"?(r.cwd=Bt.resolve(r.cwd,"apps/web"),o=await v(r.cwd)):(o=await be({cwd:r.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!0,silent:!0,isNewProject:!0,srcDir:r.srcDir}),s=r.components?.length===1&&!!r.components[0].match(/\/chat\/b\//))}if(!o)throw new Error(`Failed to read config at ${l.info(r.cwd)}.`);await he(r.components,o,r),s&&await Vt(r.components[0],o)}catch(r){a.break(),w(r)}});async function Wi(e){let t=await Z();if(!t)return a.break(),w(new Error("Failed to fetch registry index.")),[];if(e.all)return t.map(n=>n.name);if(e.components?.length)return e.components;let{components:r}=await Qe({type:"multiselect",name:"components",message:"Which components would you like to add?",hint:"Space to select. A to toggle all. Enter to submit.",instructions:!1,choices:t.filter(n=>n.type==="registry:ui").map(n=>({title:n.name,value:n.name,selected:e.all?!0:e.components?.includes(n.name)}))});r?.length||(a.warn("No components selected. Exiting."),a.info(""),process.exit(1));let i=k.array(k.string()).safeParse(r);return i.success?i.data:(a.error(""),w(new Error("Something went wrong. Please try again.")),[])}import{existsSync as Xe,promises as Ui}from"fs";import Ze from"path";import{Command as Vi}from"commander";import{diffLines as Bi}from"diff";import{z as te}from"zod";var Gi=te.object({component:te.string().optional(),yes:te.boolean(),cwd:te.string(),path:te.string().optional()}),Yt=new Vi().name("diff").description("check for updates against the registry").argument("[component]","the component name").option("-y, --yes","skip confirmation prompt.",!1).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async(e,t)=>{try{let r=Gi.parse({component:e,...t}),i=Ze.resolve(r.cwd);Xe(i)||(a.error(`The path ${i} does not exist. Please try again.`),process.exit(1));let n=await v(i);n||(a.warn(`Configuration is missing. Please run ${l.success("init")} to create a components.json file.`),process.exit(1));let o=await Z();if(o||(w(new Error("Failed to fetch registry index.")),process.exit(1)),!r.component){let f=n.resolvedPaths.components,p=o.filter(u=>{for(let x of u.files??[]){let C=Ze.resolve(f,typeof x=="string"?x:x.path);if(Xe(C))return!0}return!1}),d=[];for(let u of p){let x=await Jt(u,n);x.length&&d.push({name:u.name,changes:x})}d.length||(a.info("No updates found."),process.exit(0)),a.info("The following components have updates available:");for(let u of d){a.info(`- ${u.name}`);for(let x of u.changes)a.info(` - ${x.filePath}`)}a.break(),a.info(`Run ${l.success("diff <component>")} to see the changes.`),process.exit(0)}let s=o.find(f=>f.name===r.component);s||(a.error(`The component ${l.success(r.component)} does not exist.`),process.exit(1));let c=await Jt(s,n);c.length||(a.info(`No updates found for ${r.component}.`),process.exit(0));for(let f of c)a.info(`- ${f.filePath}`),await Ji(f.patch),a.info("")}catch(r){w(r)}});async function Jt(e,t){let r=await vt(t.style,[e]),i=await q(t.tailwind.baseColor);if(!r)return[];let n=[];for(let o of r){let s=await Rt(t,o);if(s)for(let c of o.files??[]){let f=Ze.resolve(s,typeof c=="string"?c:c.path);if(!Xe(f))continue;let p=await Ui.readFile(f,"utf8");if(typeof c=="string"||!c.content)continue;let d=await ue({filename:c.path,raw:c.content,config:t,baseColor:i}),u=Bi(d,p);u.length>1&&n.push({filePath:f,patch:u})}}return n}async function Ji(e){e.forEach(t=>{if(t)return t.added?process.stdout.write(l.success(t.value)):t.removed?process.stdout.write(l.error(t.value)):process.stdout.write(t.value)})}import{Command as Yi}from"commander";var Ht=new Yi().name("info").description("get information about your project").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{a.info("> project info"),console.log(await N(e.cwd)),a.break(),a.info("> components.json"),console.log(await v(e.cwd))});import rn from"path";import{randomBytes as Hi}from"crypto";import{promises as qe}from"fs";import{tmpdir as Qi}from"os";import Se from"path";import Xi from"fast-glob";import Qt from"prompts";import{Project as Zi,ScriptKind as qi,SyntaxKind as en}from"ts-morph";async function Xt(e){if(!e.resolvedPaths.ui)throw new Error("We could not find a valid `ui` path in your `components.json` file. Please ensure you have a valid `ui` path in your `components.json` file.");let t=e.resolvedPaths.ui,[r,i]=await Promise.all([Xi("**/*.{js,ts,jsx,tsx}",{cwd:t}),ae()]);if(Object.keys(i).length===0)throw new Error("Something went wrong fetching the registry icons.");let n=Object.entries(P).map(([d,u])=>({title:u.name,value:d})),o=await Qt([{type:"select",name:"sourceLibrary",message:`Which icon library would you like to ${l.info("migrate from")}?`,choices:n},{type:"select",name:"targetLibrary",message:`Which icon library would you like to ${l.info("migrate to")}?`,choices:n}]);if(o.sourceLibrary===o.targetLibrary)throw new Error("You cannot migrate to the same icon library. Please choose a different icon library.");if(!(o.sourceLibrary in P&&o.targetLibrary in P))throw new Error("Invalid icon library. Please choose a valid icon library.");let s=P[o.sourceLibrary],c=P[o.targetLibrary],{confirm:f}=await Qt({type:"confirm",name:"confirm",initial:!0,message:`We will migrate ${l.info(r.length)} files in ${l.info(`./${Se.relative(e.resolvedPaths.cwd,t)}`)} from ${l.info(s.name)} to ${l.info(c.name)}. Continue?`});f||(a.info("Migration cancelled."),process.exit(0)),c.package&&await ee([c.package],e,{silent:!1});let p=h("Migrating icons...")?.start();await Promise.all(r.map(async d=>{p.text=`Migrating ${d}...`;let u=Se.join(t,d),x=await qe.readFile(u,"utf-8"),C=await tn(x,o.sourceLibrary,o.targetLibrary,i);await qe.writeFile(u,C)})),p.succeed("Migration complete.")}async function tn(e,t,r,i){let n=P[t]?.import,o=P[r]?.import,s=await qe.mkdtemp(Se.join(Qi(),"shadcn-")),c=new Zi({compilerOptions:{}}),f=Se.join(s,`shadcn-icons-${Hi(4).toString("hex")}.tsx`),p=c.createSourceFile(f,e,{scriptKind:qi.TSX}),d=[];for(let u of p.getImportDeclarations()??[])if(u.getModuleSpecifier()?.getText()===`"${n}"`){for(let x of u.getNamedImports()??[]){let C=x.getName(),L=Object.values(i).find(b=>b[t]===C)?.[r];!L||d.includes(L)||(d.push(L),x.remove(),p.getDescendantsOfKind(en.JsxSelfClosingElement).filter(b=>b.getTagNameNode()?.getText()===C).forEach(b=>b.getTagNameNode()?.replaceWithText(L)))}u.getNamedImports()?.length===0&&u.remove()}return d.length>0&&p.addImportDeclaration({moduleSpecifier:o,namedImports:d.map(u=>({name:u}))}),await p.getText()}import Zt from"path";import et from"fs-extra";async function qt(e){let t={};if(!et.existsSync(e.cwd)||!et.existsSync(Zt.resolve(e.cwd,"package.json")))return t[R]=!0,{errors:t,config:null};if(!et.existsSync(Zt.resolve(e.cwd,"components.json")))return t[A]=!0,{errors:t,config:null};try{let r=await v(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)}.
30
+ Before you can run a migration, 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)}}import{Command as nn}from"commander";import{z as Ce}from"zod";var er=[{name:"icons",description:"migrate your ui components to a different icon library."}],on=Ce.object({cwd:Ce.string(),list:Ce.boolean(),migration:Ce.string().refine(e=>e&&er.some(t=>t.name===e),{message:"You must specify a valid migration. Run `shadcn migrate --list` to see available migrations."}).optional()}),tr=new nn().name("migrate").description("run a migration.").argument("[migration]","the migration to run.").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-l, --list","list all migrations.",!1).action(async(e,t)=>{try{let r=on.parse({cwd:rn.resolve(t.cwd),migration:e,list:t.list});if(r.list||!r.migration){a.info("Available migrations:");for(let o of er)a.info(`- ${o.name}: ${o.description}`);return}if(!r.migration)throw new Error("You must specify a migration. Run `shadcn migrate --list` to see available migrations.");let{errors:i,config:n}=await qt(r);if(i[R]||i[A])throw new Error("No `components.json` file found. Ensure you are at the root of your project.");if(!n)throw new Error("Something went wrong reading your `components.json` file. Please ensure you have a valid `components.json` file.");r.migration==="icons"&&await Xt(n)}catch(r){a.break(),w(r)}});import{Command as an}from"commander";var rr={name:"shadcn",version:"0.0.0-beta.8d9e2ae",description:"Add components to your apps.",publishConfig:{access:"public"},license:"MIT",author:{name:"shadcn",url:"https://twitter.com/shadcn"},repository:{type:"git",url:"https://github.com/shadcn/ui.git",directory:"packages/shadcn"},files:["dist"],keywords:["components","ui","tailwind","radix-ui","shadcn"],type:"module",exports:"./dist/index.js",bin:"./dist/index.js",scripts:{dev:"tsup --watch",build:"tsup",typecheck:"tsc --noEmit",clean:"rimraf dist && rimraf components","start:dev":"cross-env REGISTRY_URL=http://localhost:3333/r node dist/index.js","start:prod":"cross-env REGISTRY_URL=https://ui.shadcn.com/r node dist/index.js",start:"node dist/index.js","format:write":'prettier --write "**/*.{ts,tsx,mdx}" --cache',"format:check":'prettier --check "**/*.{ts,tsx,mdx}" --cache',release:"changeset version","pub:beta":"pnpm build && pnpm publish --no-git-checks --access public --tag beta","pub:next":"pnpm build && pnpm publish --no-git-checks --access public --tag next","pub:release":"pnpm build && pnpm publish --access public",test:"vitest run","test:dev":"REGISTRY_URL=http://localhost:3333/r vitest run"},dependencies:{"@antfu/ni":"^0.21.4","@babel/core":"^7.22.1","@babel/parser":"^7.22.6","@babel/plugin-transform-typescript":"^7.22.5",commander:"^10.0.0",cosmiconfig:"^8.1.3",deepmerge:"^4.3.1",diff:"^5.1.0",execa:"^7.0.0","fast-glob":"^3.3.2","fs-extra":"^11.1.0","https-proxy-agent":"^6.2.0",kleur:"^4.1.5","lodash.template":"^4.5.0","node-fetch":"^3.3.0",ora:"^6.1.2",postcss:"^8.4.24",prompts:"^2.4.2",recast:"^0.23.2","stringify-object":"^5.0.0","ts-morph":"^18.0.0","tsconfig-paths":"^4.2.0",zod:"^3.20.2"},devDependencies:{"@types/babel__core":"^7.20.1","@types/diff":"^5.0.3","@types/fs-extra":"^11.0.1","@types/lodash.template":"^4.5.1","@types/prompts":"^2.4.2","@types/stringify-object":"^4.0.5",rimraf:"^6.0.1",tsup:"^6.6.3","type-fest":"^3.8.0",typescript:"^4.9.3"}};process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function cn(){let e=new an().name("shadcn").description("add components and dependencies to your project").version(rr.version||"1.0.0","-v, --version","display the version number");e.addCommand(Mt).addCommand(Gt).addCommand(Yt).addCommand(tr).addCommand(Ht),e.parse()}cn();
30
31
  //# sourceMappingURL=index.js.map