shadcn 0.0.0-beta.acc8bb5 → 0.0.0-beta.d89c2a4

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/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # shadcn-ui
1
+ # shadcn
2
2
 
3
3
  A CLI for adding components to your project.
4
4
 
@@ -9,7 +9,7 @@ Use the `init` command to initialize dependencies for a new project.
9
9
  The `init` command installs dependencies, adds the `cn` util, configures `tailwind.config.js`, and CSS variables for the project.
10
10
 
11
11
  ```bash
12
- npx shadcn-ui init
12
+ npx shadcn init
13
13
  ```
14
14
 
15
15
  ## add
@@ -19,19 +19,19 @@ Use the `add` command to add components to your project.
19
19
  The `add` command adds a component to your project and installs all required dependencies.
20
20
 
21
21
  ```bash
22
- npx shadcn-ui add [component]
22
+ npx shadcn add [component]
23
23
  ```
24
24
 
25
25
  ### Example
26
26
 
27
27
  ```bash
28
- npx shadcn-ui add alert-dialog
28
+ npx shadcn add alert-dialog
29
29
  ```
30
30
 
31
31
  You can also run the command without any arguments to view a list of all available components:
32
32
 
33
33
  ```bash
34
- npx shadcn-ui add
34
+ npx shadcn add
35
35
  ```
36
36
 
37
37
  ## Documentation
package/dist/index.js CHANGED
@@ -1,17 +1,22 @@
1
1
  #!/usr/bin/env node
2
- import Rr from"path";import{promises as Cr}from"fs";import rt from"path";import Ie from"path";var T="1";var W="3";var ie="5",ne="6",be="7";import se from"path";var C={"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 O from"path";import{cyan as mt,green as ft,red as dt,yellow as gt}from"kleur/colors";var l={error:dt,warn:gt,info:mt,success:ft};import{createMatchPath as ut}from"tsconfig-paths";async function P(e,t){return ut(t.absoluteBaseUrl,t.paths)(e,void 0,()=>!0,[".ts",".tsx"])}import{cosmiconfig as ht}from"cosmiconfig";import{loadConfig as yt}from"tsconfig-paths";import{z as u}from"zod";var Se="@/components",Ce="@/lib/utils",Pe="app/globals.css",Te="tailwind.config.js";var wt=ht("components",{searchPlaces:["components.json"]}),$=u.object({$schema:u.string().optional(),style:u.string(),rsc:u.coerce.boolean().default(!1),tsx:u.coerce.boolean().default(!0),tailwind:u.object({config:u.string(),css:u.string(),baseColor:u.string(),cssVariables:u.boolean().default(!0),prefix:u.string().default("").optional()}),aliases:u.object({components:u.string(),utils:u.string(),ui:u.string().optional(),lib:u.string().optional(),hooks:u.string().optional()})}).strict(),xt=$.extend({resolvedPaths:u.object({cwd:u.string(),tailwindConfig:u.string(),tailwindCss:u.string(),utils:u.string(),components:u.string(),lib:u.string(),hooks:u.string(),ui:u.string()})});async function v(e){let t=await bt(e);return t?await N(e,t):null}async function N(e,t){let r=await yt(e);if(r.resultType==="failed")throw new Error(`Failed to load ${t.tsx?"tsconfig":"jsconfig"}.json. ${r.message??""}`.trim());return xt.parse({...t,resolvedPaths:{cwd:e,tailwindConfig:O.resolve(e,t.tailwind.config),tailwindCss:O.resolve(e,t.tailwind.css),utils:await P(t.aliases.utils,r),components:await P(t.aliases.components,r),ui:t.aliases.ui?await P(t.aliases.ui,r):O.resolve(await P(t.aliases.components,r)??e,"ui"),lib:t.aliases.lib?await P(t.aliases.lib,r):O.resolve(await P(t.aliases.utils,r)??e,".."),hooks:t.aliases.hooks?await P(t.aliases.hooks,r):O.resolve(await P(t.aliases.components,r)??e,"..","hooks")}})}async function bt(e){try{let t=await wt.search(e);return t?$.parse(t.config):null}catch{let r=`${e}/component.json`;throw new Error(`Invalid configuration found in ${l.info(r)}.`)}}import U from"fast-glob";import oe from"fs-extra";import{loadConfig as St}from"tsconfig-paths";var G=["**/node_modules/**",".next","public","dist","build"];async function F(e){let[t,r,i,n,s,o]=await Promise.all([U.glob("**/{next,vite,astro}.config.*|gatsby-config.*|composer.json",{cwd:e,deep:3,ignore:G}),oe.pathExists(se.resolve(e,"src")),vt(e),Pt(e),Ct(e),Tt(e)]),p=await oe.pathExists(se.resolve(e,`${r?"src/":""}app`)),m={framework:C.manual,isSrcDir:r,isRSC:!1,isTsx:i,tailwindConfigFile:n,tailwindCssFile:s,aliasPrefix:o};return t.length?t.find(f=>f.startsWith("next.config."))?.length?(m.framework=p?C["next-app"]:C["next-pages"],m.isRSC=p,m):t.find(f=>f.startsWith("astro.config."))?.length?(m.framework=C.astro,m):t.find(f=>f.startsWith("gatsby-config."))?.length?(m.framework=C.gatsby,m):t.find(f=>f.startsWith("composer.json"))?.length?(m.framework=C.laravel,m):(t.find(f=>f.startsWith("vite.config."))?.length&&(m.framework=p?C.remix:C.vite),m):m}async function Ct(e){let t=await U.glob("**/*.css",{cwd:e,deep:5,ignore:G});if(!t.length)return null;for(let r of t)if((await oe.readFile(se.resolve(e,r),"utf8")).includes("@tailwind base"))return r;return null}async function Pt(e){let t=await U.glob("tailwind.config.*",{cwd:e,deep:3,ignore:G});return t.length?t[0]:null}async function Tt(e){let t=await St(e);if(t?.resultType==="failed"||!t?.paths)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.at(0)??null;return null}async function vt(e){return(await U.glob("tsconfig.*",{cwd:e,deep:1,ignore:G})).length>0}async function ve(e,t=null){let[r,i]=await Promise.all([v(e),t?Promise.resolve(t):F(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:""},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 N(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 It from"ora";function h(e,t){return It({text:e,isSilent:t?.silent})}import ae from"fs-extra";async function Re(e){let t={};if(!ae.existsSync(e.cwd)||!ae.existsSync(Ie.resolve(e.cwd,"package.json")))return t[T]=!0,{errors:t,projectInfo:null};let r=h("Preflight checks.",{silent:e.silent}).start();ae.existsSync(Ie.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 F(e.cwd);(!n||n?.framework.name==="manual")&&(t[be]=!0,i?.fail(),a.break(),n?.framework.links.installation&&a.error(`We could not detect a supported framework at ${l.info(e.cwd)}.
2
+ import $r from"path";import{promises as Rr}from"fs";import it from"path";import ke from"path";var T="1";var V="3";var ne="5",se="6",Ce="7";import oe from"path";var v={"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 N from"path";import{cyan as ut,green as gt,red as ht,yellow as yt}from"kleur/colors";var l={error:ht,warn:yt,info:ut,success:gt};import{createMatchPath as wt}from"tsconfig-paths";async function R(e,t){return wt(t.absoluteBaseUrl,t.paths)(e,void 0,()=>!0,[".ts",".tsx"])}import{cosmiconfig as xt}from"cosmiconfig";import{loadConfig as bt}from"tsconfig-paths";import{z as h}from"zod";var Pe="@/components",ve="@/lib/utils",Re="app/globals.css",Te="tailwind.config.js";var St=xt("components",{searchPlaces:["components.json"]}),A=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()})}).strict(),Ct=A.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 I(e){let t=await Pt(e);return t?await F(e,t):null}async function F(e,t){let r=await bt(e);if(r.resultType==="failed")throw new Error(`Failed to load ${t.tsx?"tsconfig":"jsconfig"}.json. ${r.message??""}`.trim());return Ct.parse({...t,resolvedPaths:{cwd:e,tailwindConfig:N.resolve(e,t.tailwind.config),tailwindCss:N.resolve(e,t.tailwind.css),utils:await R(t.aliases.utils,r),components:await R(t.aliases.components,r),ui:t.aliases.ui?await R(t.aliases.ui,r):N.resolve(await R(t.aliases.components,r)??e,"ui"),lib:t.aliases.lib?await R(t.aliases.lib,r):N.resolve(await R(t.aliases.utils,r)??e,".."),hooks:t.aliases.hooks?await R(t.aliases.hooks,r):N.resolve(await R(t.aliases.components,r)??e,"..","hooks")}})}async function Pt(e){try{let t=await St.search(e);return t?A.parse(t.config):null}catch{let r=`${e}/component.json`;throw new Error(`Invalid configuration found in ${l.info(r)}.`)}}import U from"fast-glob";import ae from"fs-extra";import{loadConfig as vt}from"tsconfig-paths";var G=["**/node_modules/**",".next","public","dist","build"];async function j(e){let[t,r,i,n,s,a]=await Promise.all([U.glob("**/{next,vite,astro}.config.*|gatsby-config.*|composer.json",{cwd:e,deep:3,ignore:G}),ae.pathExists(oe.resolve(e,"src")),kt(e),Tt(e),Rt(e),It(e)]),c=await ae.pathExists(oe.resolve(e,`${r?"src/":""}app`)),p={framework:v.manual,isSrcDir:r,isRSC:!1,isTsx:i,tailwindConfigFile:n,tailwindCssFile:s,aliasPrefix:a};return t.length?t.find(d=>d.startsWith("next.config."))?.length?(p.framework=c?v["next-app"]:v["next-pages"],p.isRSC=c,p):t.find(d=>d.startsWith("astro.config."))?.length?(p.framework=v.astro,p):t.find(d=>d.startsWith("gatsby-config."))?.length?(p.framework=v.gatsby,p):t.find(d=>d.startsWith("composer.json"))?.length?(p.framework=v.laravel,p):(t.find(d=>d.startsWith("vite.config."))?.length&&(p.framework=c?v.remix:v.vite),p):p}async function Rt(e){let t=await U.glob("**/*.css",{cwd:e,deep:5,ignore:G});if(!t.length)return null;for(let r of t)if((await ae.readFile(oe.resolve(e,r),"utf8")).includes("@tailwind base"))return r;return null}async function Tt(e){let t=await U.glob("tailwind.config.*",{cwd:e,deep:3,ignore:G});return t.length?t[0]:null}async function It(e){let t=await vt(e);if(t?.resultType==="failed"||!t?.paths)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.at(0)??null;return null}async function kt(e){return(await U.glob("tsconfig.*",{cwd:e,deep:1,ignore:G})).length>0}async function Ie(e,t=null){let[r,i]=await Promise.all([I(e),t?Promise.resolve(t):j(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:""},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 F(e,n)}var o={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 jt from"ora";function w(e,t){return jt({text:e,isSilent:t?.silent})}import le from"fs-extra";async function je(e){let t={};if(!le.existsSync(e.cwd)||!le.existsSync(ke.resolve(e.cwd,"package.json")))return t[T]=!0,{errors:t,projectInfo:null};let r=w("Preflight checks.",{silent:e.silent}).start();le.existsSync(ke.resolve(e.cwd,"components.json"))&&!e.force&&(r?.fail(),o.break(),o.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.`),o.break(),process.exit(1)),r?.succeed();let i=w("Verifying framework.",{silent:e.silent}).start(),n=await j(e.cwd);(!n||n?.framework.name==="manual")&&(t[Ce]=!0,i?.fail(),o.break(),n?.framework.links.installation&&o.error(`We could not detect a supported framework at ${l.info(e.cwd)}.
4
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 s=h("Validating Tailwind CSS.",{silent:e.silent}).start();!n?.tailwindConfigFile||!n?.tailwindCssFile?(t[ie]=!0,s?.fail()):s?.succeed();let o=h("Validating import alias.",{silent:e.silent}).start();return n?.aliasPrefix?o?.succeed():(t[ne]=!0,o?.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[ne]&&(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{z as Rt}from"zod";function b(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 Rt.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 Vt from"path";import{z as c}from"zod";var ke=c.enum(["registry:style","registry:lib","registry:example","registry:block","registry:component","registry:ui","registry:hook","registry:theme","registry:page"]),Ee=c.object({path:c.string(),content:c.string().optional(),type:ke,target:c.string().optional()}),kt=c.object({config:c.object({content:c.array(c.string()).optional(),theme:c.record(c.string(),c.any()).optional(),plugins:c.array(c.string()).optional()}).optional()}),Et=c.object({light:c.record(c.string(),c.string()).optional(),dark:c.record(c.string(),c.string()).optional()}),A=c.object({name:c.string(),type:ke,description:c.string().optional(),dependencies:c.array(c.string()).optional(),devDependencies:c.array(c.string()).optional(),registryDependencies:c.array(c.string()).optional(),files:c.array(Ee).optional(),tailwind:kt.optional(),cssVars:Et.optional()}),le=c.array(A.extend({files:c.array(c.union([c.string(),Ee])).optional()})),je=c.array(c.object({name:c.string(),label:c.string()})),Oe=c.object({inlineColors:c.object({light:c.record(c.string(),c.string()),dark:c.record(c.string(),c.string())}),cssVars:c.object({light:c.record(c.string(),c.string()),dark:c.record(c.string(),c.string())}),inlineColorsTemplate:c.string(),cssVarsTemplate:c.string()}),$e=A.pick({dependencies:!0,devDependencies:!0,files:!0,tailwind:!0,cssVars:!0});import{promises as ce}from"fs";import{tmpdir as jt}from"os";import D from"path";import Ot from"deepmerge";import $t from"stringify-object";import{Project as Nt,QuoteKind as Ft,ScriptKind as Ne,SyntaxKind as g}from"ts-morph";async function Fe(e,t,r){if(!e)return;r={silent:!1,...r};let i=D.relative(t.resolvedPaths.cwd,t.resolvedPaths.tailwindConfig),n=h(`Updating ${l.info(i)}`,{silent:r.silent}).start(),s=await ce.readFile(t.resolvedPaths.tailwindConfig,"utf8"),o=await At(s,e,t);await ce.writeFile(t.resolvedPaths.tailwindConfig,o,"utf8"),n?.succeed()}async function At(e,t,r){let i=await Ae(e,r),n=i.getDescendantsOfKind(g.ObjectLiteralExpression).find(o=>o.getProperties().some(p=>p.isKind(g.PropertyAssignment)&&p.getName()==="content"));if(!n)return e;let s=zt(n);return Dt(n,{name:"darkMode",value:"class"},{quoteChar:s}),t.plugins?.forEach(o=>{_t(n,o)}),t.theme&&await Lt(n,t.theme),i.getFullText()}function Dt(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(),s=`${r}${t.value}${r}`;if(n?.isKind(g.StringLiteral)){let o=n.getText();return n.replaceWithText(`[${o}, ${s}]`),e}if(n?.isKind(g.ArrayLiteralExpression)){if(n.getElements().map(o=>o.getText()).includes(s))return e;n.addElement(s)}return e}return e}async function Lt(e,t){e.getProperty("theme")||e.addPropertyAssignment({name:"theme",initializer:"{}"}),De(e);let i=(e.getPropertyOrThrow("theme")?.asKindOrThrow(g.PropertyAssignment)).getInitializer();if(i?.isKind(g.ObjectLiteralExpression)){let n=i.getText(),s=await Kt(n),o=Ot(s,t),p=$t(o).replace(/\'\"/g,"'").replace(/\"\'/g,"'").replace(/\'\[/g,"[").replace(/\]\'/g,"]").replace(/\\\'/g,"").replace(/\\\'/g,"");i.replaceWithText(p)}Le(e)}function _t(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 Ae(e,t){let r=await ce.mkdtemp(D.join(jt(),"shadcn-")),i=t?.resolvedPaths?.tailwindConfig||"tailwind.config.ts",n=D.join(r,`shadcn-${D.basename(i)}`);return new Nt({compilerOptions:{}}).createSourceFile(n,e,{scriptKind:D.extname(i)===".ts"?Ne.TS:Ne.JS})}function zt(e){return e.getFirstDescendantByKind(g.StringLiteral)?.getQuoteKind()===Ft.Single?"'":'"'}function De(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),s=n.getExpression().getText();e.insertPropertyAssignment(r,{name:`___${s.replace(/^\.\.\./,"")}`,initializer:`"...${s.replace(/^\.\.\./,"")}"`}),n.remove()}else if(i.isKind(g.PropertyAssignment)){let s=i.asKindOrThrow(g.PropertyAssignment).getInitializer();s&&s.isKind(g.ObjectLiteralExpression)&&De(s.asKindOrThrow(g.ObjectLiteralExpression))}}}function Le(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,s=n.getInitializer();if(s?.isKind(g.StringLiteral)){let o=s.getLiteralValue();o.startsWith("...")&&(e.insertSpreadAssignment(r,{expression:o.slice(3)}),n.remove())}else s?.isKind(g.ObjectLiteralExpression)&&Le(s)}}}async function Kt(e){let r=(await Ae(`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 _e(n)}throw new Error("Invalid input: not an object literal")}function _e(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]=_e(r.getInitializer()):t[i]=ze(r.getInitializer())}return t}function ze(e){switch(e.kind){case g.StringLiteral:return e.text;case g.NumericLiteral:return Number(e.text);case g.TrueKeyword:return!0;case g.FalseKeyword:return!1;case g.NullKeyword:return null;case g.ArrayLiteralExpression:return e.elements.map(ze);default:return e.getText()}}function Ke(e){let t={};for(let r of Object.keys(e)){let i=r.split("-"),n=i[0],s=i.slice(1).join("-");s===""?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][s]=`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 L from"deepmerge";import{HttpsProxyAgent as Wt}from"https-proxy-agent";import Mt from"node-fetch";import{z as Ut}from"zod";var Gt=process.env.REGISTRY_URL??"https://ui.shadcn.com/registry",Bt=process.env.https_proxy?new Wt(process.env.https_proxy):void 0;async function _(){try{let[e]=await E(["index.json"]);return le.parse(e)}catch(e){a.error(`
6
- `),b(e)}}async function pe(){try{let[e]=await E(["styles/index.json"]);return je.parse(e)}catch(e){return a.error(`
7
- `),b(e),[]}}async function Ve(e,t){try{let[r]=await E([fe(e)?e:`styles/${t}/${e}.json`]);return A.parse(r)}catch(r){return a.break(),b(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 z(e){try{let[t]=await E([`colors/${e}.json`]);return Oe.parse(t)}catch(t){b(t)}}async function We(e,t){try{let r=t.map(n=>`styles/${e}/${n.name}.json`),i=await E(r);return le.parse(i)}catch(r){b(r)}}async function Me(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?Vt.join(e.resolvedPaths[i],n):null}async function E(e){try{return await Promise.all(e.map(async r=>{let i=Be(r),n=await Mt(i,{agent:Bt});if(!n.ok){let s={400:"Bad request",401:"Unauthorized",403:"Forbidden",404:"Not found",500:"Internal server error"},o=n.statusText||s[n.status];throw new Error(`Failed to fetch from ${l.info(i)}. ${o}.`)}return n.json()}))}catch(t){return a.error(`
8
- `),b(t),[]}}function Ue(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 Ge(e,t){try{if(!await _())return null;let i=(await Promise.all(e.map(async d=>await Ve(d,t.style)))).filter(d=>d!==null);if(!i.length)return null;let n=i.map(d=>d.registryDependencies??[]).flat(),s=Array.from(new Set(n)),o=Array.from([...e,...s]).map(d=>Be(fe(d)?d:`styles/${t.style}/${d}.json`)),p=await E(o),m=Ut.array(A).parse(p);if(!m)return null;if(e.includes("index")){let d=await Ve("index",t.style);if(d&&m.unshift(d),t.tailwind.baseColor){let w=await Jt(t.tailwind.baseColor,t);w&&m.unshift(w)}}let f={};m.forEach(d=>{f=L(f,d.tailwind??{})});let x={};return m.forEach(d=>{x=L(x,d.cssVars??{})}),$e.parse({dependencies:L.all(m.map(d=>d.dependencies??[])),devDependencies:L.all(m.map(d=>d.devDependencies??[])),files:L.all(m.map(d=>d.files??[])),tailwind:f,cssVars:x})}catch(r){return b(r),null}}async function Jt(e,t){let r=await z(e);if(!r)return null;let i={name:e,type:"registry:theme",tailwind:{config:{theme:{extend:{borderRadius:{lg:"var(--radius)",md:"calc(var(--radius) - 2px)",sm:"calc(var(--radius) - 4px)"},colors:{}}}}},cssVars:{light:{radius:"0.5rem"},dark:{}}};return t.tailwind.cssVariables&&(i.tailwind.config.theme.extend.colors={...i.tailwind.config.theme.extend.colors,...Ke(r.cssVars.dark)},i.cssVars={light:{...r.cssVars.light,...i.cssVars.light},dark:{...r.cssVars.dark,...i.cssVars.dark}}),i}function Be(e){return fe(e)?e:`${Gt}/${e}`}function fe(e){try{return new URL(e),!0}catch{return!1}}import{promises as Je}from"fs";import Yt from"path";import R from"postcss";import Ht from"postcss/lib/at-rule";async function Ye(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=Yt.relative(t.resolvedPaths.cwd,i),s=h(`Updating ${l.info(n)}`,{silent:r.silent}).start(),o=await Je.readFile(i,"utf8"),p=await Qt(o,e,t,{cleanupDefaultNextStyles:r.cleanupDefaultNextStyles});await Je.writeFile(i,p,"utf8"),s.succeed()}async function Qt(e,t,r,i){i={cleanupDefaultNextStyles:!1,...i};let n=[Zt(t)];return i.cleanupDefaultNextStyles&&n.push(qt()),r.tailwind.cssVariables&&n.push(Xt()),(await R(n).process(e,{from:void 0})).css}function Xt(){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:s})=>i.nodes?.some(o=>o.type==="rule"&&o.selector===n&&o.nodes.some(p=>p.type==="atrule"&&p.name==="apply"&&p.params===s))));r||(r=R.atRule({name:"layer",params:"base",raws:{semicolon:!0,between:" ",before:`
9
- `}}),e.append(r)),t.forEach(({selector:i,apply:n})=>{r?.nodes?.find(o=>o.type==="rule"&&o.selector===i)||r?.append(R.rule({selector:i,nodes:[R.atRule({name:"apply",params:n,raws:{semicolon:!0,before:`
5
+ Once configured, you can use the cli to add components.`),o.break(),process.exit(1)),i?.succeed(`Verifying framework. Found ${l.info(n.framework.label)}.`);let s=w("Validating Tailwind CSS.",{silent:e.silent}).start();!n?.tailwindConfigFile||!n?.tailwindCssFile?(t[ne]=!0,s?.fail()):s?.succeed();let a=w("Validating import alias.",{silent:e.silent}).start();return n?.aliasPrefix?a?.succeed():(t[se]=!0,a?.fail()),Object.keys(t).length>0&&(t[ne]&&(o.break(),o.error(`No Tailwind CSS configuration found at ${l.info(e.cwd)}.`),o.error("It is likely you do not have Tailwind CSS installed or have an invalid configuration."),o.error("Install Tailwind CSS then try again."),n?.framework.links.tailwind&&o.error(`Visit ${l.info(n?.framework.links.tailwind)} to get started.`)),t[se]&&(o.break(),o.error("No import alias found in your tsconfig.json file."),n?.framework.links.installation&&o.error(`Visit ${l.info(n?.framework.links.installation)} to learn how to set an import alias.`)),o.break(),process.exit(1)),{errors:t,projectInfo:n}}import{z as Et}from"zod";function x(e){if(o.error("Something went wrong. Please check the error below for more details."),o.error("If the problem persists, please open an issue on GitHub."),o.error(""),typeof e=="string"&&(o.error(e),o.break(),process.exit(1)),e instanceof Et.ZodError){o.error("Validation failed:");for(let[t,r]of Object.entries(e.flatten().fieldErrors))o.error(`- ${l.info(t)}: ${r}`);o.break(),process.exit(1)}e instanceof Error&&(o.error(e.message),o.break(),process.exit(1)),o.break(),process.exit(1)}import Ut from"path";import{z as m}from"zod";var Ee=m.enum(["registry:style","registry:lib","registry:example","registry:block","registry:component","registry:ui","registry:hook","registry:theme","registry:page"]),$e=m.object({path:m.string(),content:m.string().optional(),type:Ee,target:m.string().optional()}),$t=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()}),Ot=m.object({light:m.record(m.string(),m.string()).optional(),dark:m.record(m.string(),m.string()).optional()}),D=m.object({name:m.string(),type:Ee,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($e).optional(),tailwind:$t.optional(),cssVars:Ot.optional(),meta:m.record(m.string(),m.any()).optional()}),ce=m.array(D.extend({files:m.array(m.union([m.string(),$e])).optional()})),Oe=m.array(m.object({name:m.string(),label:m.string()})),Ne=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()}),Ae=D.pick({dependencies:!0,devDependencies:!0,files:!0,tailwind:!0,cssVars:!0});import{promises as pe}from"fs";import{tmpdir as Nt}from"os";import L from"path";import At from"deepmerge";import Ft from"stringify-object";import{Project as Dt,QuoteKind as Lt,ScriptKind as Fe,SyntaxKind as g}from"ts-morph";async function De(e,t,r){if(!e)return;r={silent:!1,...r};let i=L.relative(t.resolvedPaths.cwd,t.resolvedPaths.tailwindConfig),n=w(`Updating ${l.info(i)}`,{silent:r.silent}).start(),s=await pe.readFile(t.resolvedPaths.tailwindConfig,"utf8"),a=await _t(s,e,t);await pe.writeFile(t.resolvedPaths.tailwindConfig,a,"utf8"),n?.succeed()}async function _t(e,t,r){let i=await Le(e,r),n=i.getDescendantsOfKind(g.ObjectLiteralExpression).find(a=>a.getProperties().some(c=>c.isKind(g.PropertyAssignment)&&c.getName()==="content"));if(!n)return e;let s=Vt(n);return zt(n,{name:"darkMode",value:"class"},{quoteChar:s}),t.plugins?.forEach(a=>{Wt(n,a)}),t.theme&&await Kt(n,t.theme),i.getFullText()}function zt(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(),s=`${r}${t.value}${r}`;if(n?.isKind(g.StringLiteral)){let a=n.getText();return n.replaceWithText(`[${a}, ${s}]`),e}if(n?.isKind(g.ArrayLiteralExpression)){if(n.getElements().map(a=>a.getText()).includes(s))return e;n.addElement(s)}return e}return e}async function Kt(e,t){e.getProperty("theme")||e.addPropertyAssignment({name:"theme",initializer:"{}"}),_e(e);let i=(e.getPropertyOrThrow("theme")?.asKindOrThrow(g.PropertyAssignment)).getInitializer();if(i?.isKind(g.ObjectLiteralExpression)){let n=i.getText(),s=await Mt(n),a=At(s,t),c=Ft(a).replace(/\'\"/g,"'").replace(/\"\'/g,"'").replace(/\'\[/g,"[").replace(/\]\'/g,"]").replace(/\'\\\'/g,"'").replace(/\\\'/g,"'").replace(/\\\'\'/g,"'").replace(/\'\'/g,"'");i.replaceWithText(c)}ze(e)}function Wt(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 Le(e,t){let r=await pe.mkdtemp(L.join(Nt(),"shadcn-")),i=t?.resolvedPaths?.tailwindConfig||"tailwind.config.ts",n=L.join(r,`shadcn-${L.basename(i)}`);return new Dt({compilerOptions:{}}).createSourceFile(n,e,{scriptKind:L.extname(i)===".ts"?Fe.TS:Fe.JS})}function Vt(e){return e.getFirstDescendantByKind(g.StringLiteral)?.getQuoteKind()===Lt.Single?"'":'"'}function _e(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),s=n.getExpression().getText();e.insertPropertyAssignment(r,{name:`___${s.replace(/^\.\.\./,"")}`,initializer:`"...${s.replace(/^\.\.\./,"")}"`}),n.remove()}else if(i.isKind(g.PropertyAssignment)){let s=i.asKindOrThrow(g.PropertyAssignment).getInitializer();s&&s.isKind(g.ObjectLiteralExpression)&&_e(s.asKindOrThrow(g.ObjectLiteralExpression))}}}function ze(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,s=n.getInitializer();if(s?.isKind(g.StringLiteral)){let a=s.getLiteralValue();a.startsWith("...")&&(e.insertSpreadAssignment(r,{expression:a.slice(3)}),n.remove())}else s?.isKind(g.ObjectLiteralExpression)&&ze(s)}}}async function Mt(e){let r=(await Le(`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 Ke(n)}throw new Error("Invalid input: not an object literal")}function Ke(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]=Ke(r.getInitializer()):t[i]=We(r.getInitializer())}return t}function We(e){switch(e.kind){case g.StringLiteral:return e.text;case g.NumericLiteral:return Number(e.text);case g.TrueKeyword:return!0;case g.FalseKeyword:return!1;case g.NullKeyword:return null;case g.ArrayLiteralExpression:return e.elements.map(We);default:return e.getText()}}function Ve(e){let t={};for(let r of Object.keys(e)){let i=r.split("-"),n=i[0],s=i.slice(1).join("-");s===""?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][s]=`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 _ from"deepmerge";import{HttpsProxyAgent as Gt}from"https-proxy-agent";import Bt from"node-fetch";import{z as Jt}from"zod";var Yt=process.env.REGISTRY_URL??"https://ui.shadcn.com/r",Ht=process.env.https_proxy?new Gt(process.env.https_proxy):void 0;async function z(){try{let[e]=await O(["index.json"]);return ce.parse(e)}catch(e){o.error(`
6
+ `),x(e)}}async function me(){try{let[e]=await O(["styles/index.json"]);return Oe.parse(e)}catch(e){return o.error(`
7
+ `),x(e),[]}}async function B(e,t){try{let[r]=await O([de(e)?e:`styles/${t}/${e}.json`]);return D.parse(r)}catch(r){return o.break(),x(r),null}}async function fe(){return[{name:"neutral",label:"Neutral"},{name:"gray",label:"Gray"},{name:"zinc",label:"Zinc"},{name:"stone",label:"Stone"},{name:"slate",label:"Slate"}]}async function K(e){try{let[t]=await O([`colors/${e}.json`]);return Ne.parse(t)}catch(t){x(t)}}async function Me(e,t){try{let r=t.map(n=>`styles/${e}/${n.name}.json`),i=await O(r);return ce.parse(i)}catch(r){x(r)}}async function Ue(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?Ut.join(e.resolvedPaths[i],n):null}async function O(e){try{return await Promise.all(e.map(async r=>{let i=Je(r),n=await Bt(i,{agent:Ht});if(!n.ok){let s={400:"Bad request",401:"Unauthorized",403:"Forbidden",404:"Not found",500:"Internal server error"},a=await n.json(),c=a&&typeof a=="object"&&"error"in a?a.error:n.statusText||s[n.status];throw new Error(`Failed to fetch from ${l.info(i)}.
8
+ ${c}`)}return n.json()}))}catch(t){return o.error(`
9
+ `),x(t),[]}}function Ge(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 Be(e,t){try{if(!await z())return null;let i=(await Promise.all(e.map(async f=>await B(f,t.style)))).filter(f=>f!==null);if(!i.length)return null;let n=i.map(f=>f.registryDependencies??[]).flat(),s=Array.from(new Set(n)),a=Array.from([...e,...s]).map(f=>Je(de(f)?f:`styles/${t.style}/${f}.json`)),c=await O(a),p=Jt.array(D).parse(c);if(!p)return null;if(e.includes("index")){let f=await B("index",t.style);if(f&&p.unshift(f),t.tailwind.baseColor){let b=await Qt(t.tailwind.baseColor,t);b&&p.unshift(b)}}let d={};p.forEach(f=>{d=_(d,f.tailwind??{})});let u={};return p.forEach(f=>{u=_(u,f.cssVars??{})}),Ae.parse({dependencies:_.all(p.map(f=>f.dependencies??[])),devDependencies:_.all(p.map(f=>f.devDependencies??[])),files:_.all(p.map(f=>f.files??[])),tailwind:d,cssVars:u})}catch(r){return x(r),null}}async function Qt(e,t){let r=await K(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,...Ve(r.cssVars.dark)},i.cssVars={light:{...r.cssVars.light,...i.cssVars.light},dark:{...r.cssVars.dark,...i.cssVars.dark}}),i}function Je(e){if(de(e)){let t=new URL(e);return t.pathname.match(/\/chat\/b\//)&&!t.pathname.endsWith("/json")&&(t.pathname=`${t.pathname}/json`),t.toString()}return`${Yt}/${e}`}function de(e){try{return new URL(e),!0}catch{return!1}}import{promises as Ye}from"fs";import Xt from"path";import E from"postcss";import Zt from"postcss/lib/at-rule";async function He(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=Xt.relative(t.resolvedPaths.cwd,i),s=w(`Updating ${l.info(n)}`,{silent:r.silent}).start(),a=await Ye.readFile(i,"utf8"),c=await qt(a,e,t,{cleanupDefaultNextStyles:r.cleanupDefaultNextStyles});await Ye.writeFile(i,c,"utf8"),s.succeed()}async function qt(e,t,r,i){i={cleanupDefaultNextStyles:!1,...i};let n=[tr(t)];return i.cleanupDefaultNextStyles&&n.push(rr()),r.tailwind.cssVariables&&n.push(er()),(await E(n).process(e,{from:void 0})).css}function er(){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:s})=>i.nodes?.some(a=>a.type==="rule"&&a.selector===n&&a.nodes.some(c=>c.type==="atrule"&&c.name==="apply"&&c.params===s))));r||(r=E.atRule({name:"layer",params:"base",raws:{semicolon:!0,between:" ",before:`
10
+ `}}),e.append(r)),t.forEach(({selector:i,apply:n})=>{r?.nodes?.find(a=>a.type==="rule"&&a.selector===i)||r?.append(E.rule({selector:i,nodes:[E.atRule({name:"apply",params:n,raws:{semicolon:!0,before:`
10
11
  `}})],raws:{semicolon:!0,between:" ",before:`
11
- `}}))})}}}function Zt(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 Ht||(r=R.atRule({name:"layer",params:"base",nodes:[],raws:{semicolon:!0,before:`
12
- `,between:" "}}),t.append(r)),r&&Object.entries(e).forEach(([i,n])=>{let s=i==="light"?":root":`.${i}`;er(r,s,n)})}}}function qt(){return{postcssPlugin:"cleanup-default-next-styles",Once(e){let t=e.nodes.find(r=>r.type==="rule"&&r.selector==="body");t&&(t.nodes.find(r=>r.type==="decl"&&r.prop==="color"&&r.value==="rgb(var(--foreground-rgb))")?.remove(),t.nodes.find(r=>r.type==="decl"&&r.prop==="background"&&r.value.startsWith("linear-gradient"))?.remove(),t.nodes.length===0&&t.remove())}}}function er(e,t,r){let i=e.nodes?.find(n=>n.type==="rule"&&n.selector===t);i||Object.keys(r).length>0&&(i=R.rule({selector:t,raws:{between:" ",before:`
13
- `}}),e.append(i)),Object.entries(r).forEach(([n,s])=>{let o=`--${n.replace(/^--/,"")}`,p=R.decl({prop:o,value:s,raws:{semicolon:!0}}),m=i?.nodes.find(f=>f.type==="decl"&&f.prop===o);m?m.replaceWith(p):i?.append(p)})}import{detect as tr}from"@antfu/ni";async function B(e,{withFallback:t}={withFallback:!1}){let r=await tr({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 rr}from"execa";async function He(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 B(t.resolvedPaths.cwd);await rr(n,[n==="npm"?"install":"add",...e],{cwd:t.resolvedPaths.cwd}),i?.succeed()}import{existsSync as Ze,promises as qe}from"fs";import j,{basename as wr}from"path";import{promises as fr}from"fs";import{tmpdir as dr}from"os";import Xe from"path";import{SyntaxKind as ir}from"ts-morph";var J=async({sourceFile:e,config:t,baseColor:r})=>(t.tailwind?.cssVariables||!r?.inlineColors||e.getDescendantsOfKind(ir.StringLiteral).forEach(i=>{let n=i.getText();if(n){let s=sr(n.replace(/"/g,""),r.inlineColors);i.replaceWithText(`"${s.trim()}"`)}}),e);function de(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(":"),s=n.pop(),o=n.join(":");return t.push(o??null,s??null,i??null),t}var nr=["bg-","text-","border-","ring-offset-","ring-"];function sr(e,t){e.includes(" border ")&&(e=e.replace(" border "," border border-border "));let r=e.split(" "),i=new Set,n=new Set;for(let s of r){let[o,p,m]=de(s),f=nr.find(d=>p?.startsWith(d));if(!f){i.has(s)||i.add(s);continue}let x=p?.replace(f,"");if(x&&x in t.light){i.add([o,`${f}${t.light[x]}`].filter(Boolean).join(":")+(m?`/${m}`:"")),n.add(["dark",o,`${f}${t.dark[x]}`].filter(Boolean).join(":")+(m?`/${m}`:""));continue}i.has(s)||i.add(s)}return[...Array.from(i),...Array.from(n)].join(" ").trim()}var Y=async({sourceFile:e,config:t})=>{let r=e.getImportDeclarations();for(let i of r){let n=or(i.getModuleSpecifierValue(),t);i.setModuleSpecifier(n),n=="@/lib/utils"&&i.getNamedImports().find(p=>p.getName()==="cn")&&i.setModuleSpecifier(n.replace(/^@\/lib\/utils/,t.aliases.utils))}return e};function or(e,t){return e.startsWith("@/registry/")?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):e}import{transformFromAstSync as ar}from"@babel/core";import{parse as lr}from"@babel/parser";import cr from"@babel/plugin-transform-typescript";import*as H from"recast";var pr={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"]},Qe=async({sourceFile:e,config:t})=>{let r=e.getFullText();if(t.tsx)return r;let i=H.parse(r,{parser:{parse:s=>lr(s,pr)}}),n=ar(i,r,{cloneInputAst:!1,code:!1,ast:!0,plugins:[cr],configFile:!1});if(!n||!n.ast)throw new Error("Failed to transform JSX");return H.print(n.ast).code};import{SyntaxKind as mr}from"ts-morph";var Q=async({sourceFile:e,config:t})=>{if(t.rsc)return e;let r=e.getFirstChildByKind(mr.ExpressionStatement);return r?.getText()==='"use client"'&&r.remove(),e};import{Project as gr,ScriptKind as ur}from"ts-morph";import{SyntaxKind as y}from"ts-morph";var X=async({sourceFile:e,config:t})=>(t.tailwind?.prefix&&(e.getDescendantsOfKind(y.CallExpression).filter(r=>r.getExpression().getText()==="cva").forEach(r=>{if(r.getArguments()[0]?.isKind(y.StringLiteral)){let i=r.getArguments()[0];i&&i.replaceWithText(`"${I(i.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)}r.getArguments()[1]?.isKind(y.ObjectLiteralExpression)&&r.getArguments()[1]?.getDescendantsOfKind(y.PropertyAssignment).find(i=>i.getName()==="variants")?.getDescendantsOfKind(y.PropertyAssignment).forEach(i=>{i.getDescendantsOfKind(y.PropertyAssignment).forEach(n=>{let s=n.getInitializerIfKind(y.StringLiteral);s&&s?.replaceWithText(`"${I(s.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)})})}),e.getDescendantsOfKind(y.JsxAttribute).forEach(r=>{if(r.getName()==="className"){if(r.getInitializer()?.isKind(y.StringLiteral)){let i=r.getInitializer();i&&i.replaceWithText(`"${I(i.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)}if(r.getInitializer()?.isKind(y.JsxExpression)){let i=r.getInitializer()?.getDescendantsOfKind(y.CallExpression).find(n=>n.getExpression().getText()==="cn");i&&i.getArguments().forEach(n=>{(n.isKind(y.ConditionalExpression)||n.isKind(y.BinaryExpression))&&n.getChildrenOfKind(y.StringLiteral).forEach(s=>{s.replaceWithText(`"${I(s.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)}),n.isKind(y.StringLiteral)&&n.replaceWithText(`"${I(n.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)})}}r.getName()==="classNames"&&r.getInitializer()?.isKind(y.JsxExpression)&&r.getDescendantsOfKind(y.PropertyAssignment).forEach(i=>{if(i.getInitializer()?.isKind(y.CallExpression)){let n=i.getInitializerIfKind(y.CallExpression);n&&n.getArguments().forEach(s=>{s.isKind(y.ConditionalExpression)&&s.getChildrenOfKind(y.StringLiteral).forEach(o=>{o.replaceWithText(`"${I(o.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)}),s.isKind(y.StringLiteral)&&s.replaceWithText(`"${I(s.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)})}if(i.getInitializer()?.isKind(y.StringLiteral)&&i.getName()!=="variant"){let n=i.getInitializer();n&&n.replaceWithText(`"${I(n.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)}})})),e);function I(e,t=""){let r=e.split(" "),i=[];for(let n of r){let[s,o,p]=de(n);s?p?i.push(`${s}:${t}${o}/${p}`):i.push(`${s}:${t}${o}`):p?i.push(`${t}${o}/${p}`):i.push(`${t}${o}`)}return i.join(" ")}var hr=new gr({compilerOptions:{}});async function yr(e){let t=await fr.mkdtemp(Xe.join(dr(),"shadcn-"));return Xe.join(t,e)}async function Z(e,t=[Y,Q,J,X]){let r=await yr(e.filename),i=hr.createSourceFile(r,e.raw,{scriptKind:ur.TSX});for(let n of t)n({sourceFile:i,...e});return e.transformJsx?await Qe({sourceFile:i,...e}):i.getText()}import xr from"prompts";async function et(e,t,r){if(!e?.length)return;r={overwrite:!1,force:!1,silent:!1,...r};let i=h("Updating files.",{silent:r.silent})?.start(),n=await z(t.tailwind.baseColor),s=[],o=[],p=[];for(let f of e){if(!f.content)continue;let x=Ue(f,t),d=wr(f.path),w=j.join(x,d);f.target&&(w=j.join(t.resolvedPaths.cwd,f.target),x=j.dirname(w)),t.tsx||(w=w.replace(/\.tsx?$/,re=>re===".tsx"?".jsx":".js"));let V=Ze(w);if(V&&!r.overwrite){i.stop();let{overwrite:re}=await xr({type:"confirm",name:"overwrite",message:`The file ${l.info(d)} already exists. Would you like to overwrite?`,initial:!1});if(!re){p.push(j.relative(t.resolvedPaths.cwd,w));continue}i?.start()}Ze(x)||await qe.mkdir(x,{recursive:!0});let pt=await Z({filename:f.path,raw:f.content,config:t,baseColor:n,transformJsx:!t.tsx},[Y,Q,J,X]);await qe.writeFile(w,pt,"utf-8"),V?o.push(j.relative(t.resolvedPaths.cwd,w)):s.push(j.relative(t.resolvedPaths.cwd,w))}if(!(s.length||o.length)&&!p.length&&i?.info("No files updated."),s.length){if(i?.succeed(`Created ${s.length} ${s.length===1?"file":"files"}:`),!r.silent)for(let f of s)a.log(` - ${f}`)}else i?.stop();if(o.length&&(h(`Updated ${o.length} ${o.length===1?"file":"files"}:`,{silent:r.silent})?.info(),!r.silent))for(let f of o)a.log(` - ${f}`);if(p.length&&(h(`Skipped ${p.length} ${o.length===1?"file":"files"}:`,{silent:r.silent})?.info(),!r.silent))for(let f of p)a.log(` - ${f}`);r.silent||a.break()}async function q(e,t,r){r={overwrite:!1,silent:!1,isNewProject:!1,...r};let i=h("Checking registry.",{silent:r.silent})?.start(),n=await Ge(e,t);if(!n)return i?.fail(),b(new Error("Failed to fetch components from registry."));i?.succeed(),await Fe(n.tailwind?.config,t,{silent:r.silent}),await Ye(n.cssVars,t,{cleanupDefaultNextStyles:r.isNewProject,silent:r.silent}),await He(n.dependencies,t,{silent:r.silent}),await et(n.files,t,{overwrite:r.overwrite,silent:r.silent})}import br from"path";import{execa as Sr}from"execa";import ge from"fs-extra";import tt from"prompts";async function ee(e){if(!e.force){let{proceed:o}=await tt({type:"confirm",name:"proceed",message:`The path ${l.info(e.cwd)} is empty. Would you like to start a new ${l.info("Next.js")} project?`,initial:!0});if(!o)return{projectPath:null,projectName:null}}let t=await B(e.cwd),{name:r}=await tt({type:"text",name:"name",message:"What is your project named?",initial:"my-app",format:o=>o.trim(),validate:o=>o.length>128?"Name should be less than 128 characters.":!0}),i=`${e.cwd}/${r}`;try{await ge.access(e.cwd,ge.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)}ge.existsSync(br.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));let n=h("Creating a new Next.js project.").start(),s=["--tailwind","--eslint","--typescript","--app","--no-src-dir","--no-import-alias",`--use-${t}`];try{await Sr("npx",["create-next-app@latest",i,"--silent",...s],{cwd:e.cwd})}catch{a.break(),a.error("Something went wront creating a new Next.js project. Please try again."),process.exit(1)}return n?.succeed(),{projectPath:i,projectName:r}}import{Command as Pr}from"commander";import ue from"prompts";import{z as k}from"zod";var Tr=k.object({cwd:k.string(),yes:k.boolean(),defaults:k.boolean(),force:k.boolean(),silent:k.boolean(),isNewProject:k.boolean()}),it=new Pr().name("init").description("initialize your project and install dependencies").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).action(async e=>{try{let t=Tr.parse({cwd:rt.resolve(e.cwd),isNewProject:!1,...e});await te(t),a.log(`${l.success("Success!")} Project initialization completed.
14
- You may now add components.`),a.break()}catch(t){a.break(),b(t)}});async function te(e){let t;if(e.skipPreflight)t=await F(e.cwd);else{let p=await Re(e);if(p.errors[T]){let{projectPath:m}=await ee(e);m||process.exit(1),e.cwd=m,e.isNewProject=!0}t=p.projectInfo}let r=await ve(e.cwd,t),i=r?await Ir(r,e):await vr(await v(e.cwd));if(!e.yes){let{proceed:p}=await ue({type:"confirm",name:"proceed",message:`Write configuration to ${l.info("components.json")}. Proceed?`,initial:!0});p||process.exit(0)}let n=h("Writing components.json.").start(),s=rt.resolve(e.cwd,"components.json");await Cr.writeFile(s,JSON.stringify(i,null,2),"utf8"),n.succeed();let o=await N(e.cwd,i);return await q(["index"],o,{overwrite:!0,silent:e.silent,isNewProject:e.isNewProject||t?.framework.name==="next-app"}),o}async function vr(e=null){let[t,r]=await Promise.all([pe(),me()]);a.info("");let i=await ue([{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??Pe},{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??Te},{type:"text",name:"components",message:`Configure the import alias for ${l.info("components")}:`,initial:e?.aliases.components??Se},{type:"text",name:"utils",message:`Configure the import alias for ${l.info("utils")}:`,initial:e?.aliases.utils??Ce},{type:"toggle",name:"rsc",message:`Are you using ${l.info("React Server Components")}?`,initial:e?.rsc??!0,active:"yes",inactive:"no"}]);return $.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 Ir(e,t){let r=e.style,i=e.tailwind.baseColor,n=e.tailwind.cssVariables;if(!t.defaults){let[s,o]=await Promise.all([pe(),me()]),p=await ue([{type:"select",name:"style",message:`Which ${l.info("style")} would you like to use?`,choices:s.map(m=>({title:m.label,value:m.name})),initial:s.findIndex(m=>m.name===r)},{type:"select",name:"tailwindBaseColor",message:`Which color would you like to use as the ${l.info("base color")}?`,choices:o.map(m=>({title:m.label,value:m.name}))},{type:"toggle",name:"tailwindCssVariables",message:`Would you like to use ${l.info("CSS variables")} for theming?`,initial:e?.tailwind.cssVariables,active:"yes",inactive:"no"}]);r=p.style,i=p.tailwindBaseColor,n=p.tailwindCssVariables}return $.parse({$schema:e?.$schema,style:r,tailwind:{...e?.tailwind,baseColor:i,cssVariables:n},rsc:e?.rsc,tsx:e?.tsx,aliases:e?.aliases})}import nt from"path";import he from"fs-extra";async function st(e){let t={};if(!he.existsSync(e.cwd)||!he.existsSync(nt.resolve(e.cwd,"package.json")))return t[T]=!0,{errors:t,config:null};if(!he.existsSync(nt.resolve(e.cwd,"components.json")))return t[W]=!0,{errors:t,config:null};let r=h("Preflight checks.",{silent:e.silent})?.start();try{let i=await v(e.cwd);return r?.succeed(),{errors:t,config:i}}catch{r?.fail(),a.break(),a.error(`An invalid ${l.info("components.json")} file was found at ${l.info(e.cwd)}.
15
- 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{Command as kr}from"commander";import ye from"prompts";import{z as S}from"zod";var Er=S.object({components:S.array(S.string()).optional(),yes:S.boolean(),overwrite:S.boolean(),cwd:S.string(),all:S.boolean(),path:S.string().optional(),silent:S.boolean()}),ot=new kr().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).action(async(e,t)=>{try{let r=Er.parse({components:e,cwd:Rr.resolve(t.cwd),...t}),i=r.components?.some(o=>o.includes("theme-"));if(!r.yes&&i){a.break();let{confirm:o}=await ye({type:"confirm",name:"confirm",message:l.warn(`You are about to install a new theme.
16
- Existing CSS variables will be overwritten. Continue?`)});o||(a.break(),a.log("Theme installation cancelled."),a.break(),process.exit(1))}r.components?.length||(r.components=await jr(r));let{errors:n,config:s}=await st(r);if(n[W]){let{proceed:o}=await ye({type:"confirm",name:"proceed",message:`You need to create a ${l.info("component.json")} file to add components. Proceed?`,initial:!0});o||(a.break(),process.exit(1)),s=await te({cwd:r.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!1,silent:!0,isNewProject:!1})}if(n[T]){let{projectPath:o}=await ee({cwd:r.cwd,force:r.overwrite});o||(a.break(),process.exit(1)),r.cwd=o,s=await te({cwd:r.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!0,silent:!0,isNewProject:!0})}if(!s)throw new Error(`Failed to read config at ${l.info(r.cwd)}.`);await q(r.components,s,r)}catch(r){a.break(),b(r)}});async function jr(e){let t=await _();if(!t)return a.break(),b(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 ye({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=S.array(S.string()).safeParse(r);return i.success?i.data:(a.error(""),b(new Error("Something went wrong. Please try again.")),[])}import{existsSync as we,promises as Or}from"fs";import xe from"path";import{Command as $r}from"commander";import{diffLines as Nr}from"diff";import{z as K}from"zod";var Fr=K.object({component:K.string().optional(),yes:K.boolean(),cwd:K.string(),path:K.string().optional()}),lt=new $r().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=Fr.parse({component:e,...t}),i=xe.resolve(r.cwd);we(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 s=await _();if(s||(b(new Error("Failed to fetch registry index.")),process.exit(1)),!r.component){let m=n.resolvedPaths.components,f=s.filter(d=>{for(let w of d.files??[]){let V=xe.resolve(m,typeof w=="string"?w:w.path);if(we(V))return!0}return!1}),x=[];for(let d of f){let w=await at(d,n);w.length&&x.push({name:d.name,changes:w})}x.length||(a.info("No updates found."),process.exit(0)),a.info("The following components have updates available:");for(let d of x){a.info(`- ${d.name}`);for(let w of d.changes)a.info(` - ${w.filePath}`)}a.break(),a.info(`Run ${l.success("diff <component>")} to see the changes.`),process.exit(0)}let o=s.find(m=>m.name===r.component);o||(a.error(`The component ${l.success(r.component)} does not exist.`),process.exit(1));let p=await at(o,n);p.length||(a.info(`No updates found for ${r.component}.`),process.exit(0));for(let m of p)a.info(`- ${m.filePath}`),await Ar(m.patch),a.info("")}catch(r){b(r)}});async function at(e,t){let r=await We(t.style,[e]),i=await z(t.tailwind.baseColor);if(!r)return[];let n=[];for(let s of r){let o=await Me(t,s);if(o)for(let p of s.files??[]){let m=xe.resolve(o,typeof p=="string"?p:p.path);if(!we(m))continue;let f=await Or.readFile(m,"utf8");if(typeof p=="string"||!p.content)continue;let x=await Z({filename:p.path,raw:p.content,config:t,baseColor:i}),d=Nr(x,f);d.length>1&&n.push({filePath:m,patch:d})}}return n}async function Ar(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 _r}from"commander";import Dr from"path";import Lr from"fs-extra";function ct(){let e=Dr.join("package.json");return Lr.readJSONSync(e)}process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function zr(){let e=await ct(),t=new _r().name("shadcn").description("add components and dependencies to your project").version(e.version||"1.0.0","-v, --version","display the version number");t.addCommand(it).addCommand(ot).addCommand(lt),t.parse()}zr();
12
+ `}}))})}}}function tr(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 Zt||(r=E.atRule({name:"layer",params:"base",nodes:[],raws:{semicolon:!0,before:`
13
+ `,between:" "}}),t.append(r)),r!==void 0&&Object.entries(e).forEach(([i,n])=>{let s=i==="light"?":root":`.${i}`;ir(r,s,n)})}}}function rr(){return{postcssPlugin:"cleanup-default-next-styles",Once(e){let t=e.nodes.find(r=>r.type==="rule"&&r.selector==="body");t&&(t.nodes.find(r=>r.type==="decl"&&r.prop==="color"&&r.value==="rgb(var(--foreground-rgb))")?.remove(),t.nodes.find(r=>r.type==="decl"&&r.prop==="background"&&r.value.startsWith("linear-gradient"))?.remove(),t.nodes.length===0&&t.remove())}}}function ir(e,t,r){let i=e.nodes?.find(n=>n.type==="rule"&&n.selector===t);i||Object.keys(r).length>0&&(i=E.rule({selector:t,raws:{between:" ",before:`
14
+ `}}),e.append(i)),Object.entries(r).forEach(([n,s])=>{let a=`--${n.replace(/^--/,"")}`,c=E.decl({prop:a,value:s,raws:{semicolon:!0}}),p=i?.nodes.find(d=>d.type==="decl"&&d.prop===a);p?p.replaceWith(c):i?.append(c)})}import{detect as nr}from"@antfu/ni";async function J(e,{withFallback:t}={withFallback:!1}){let r=await nr({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 sr}from"execa";async function Qe(e,t,r){if(e=Array.from(new Set(e)),!e?.length)return;r={silent:!1,...r};let i=w("Installing dependencies.",{silent:r.silent})?.start(),n=await J(t.resolvedPaths.cwd);await sr(n,[n==="npm"?"install":"add",...e],{cwd:t.resolvedPaths.cwd}),i?.succeed()}import{existsSync as qe,promises as et}from"fs";import $,{basename as Sr}from"path";import{promises as gr}from"fs";import{tmpdir as hr}from"os";import Ze from"path";import{SyntaxKind as or}from"ts-morph";var Y=async({sourceFile:e,config:t,baseColor:r})=>(t.tailwind?.cssVariables||!r?.inlineColors||e.getDescendantsOfKind(or.StringLiteral).forEach(i=>{let n=i.getText();if(n){let s=lr(n.replace(/"/g,""),r.inlineColors);i.replaceWithText(`"${s.trim()}"`)}}),e);function ue(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(":"),s=n.pop(),a=n.join(":");return t.push(a??null,s??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 s of r){let[a,c,p]=ue(s),d=ar.find(f=>c?.startsWith(f));if(!d){i.has(s)||i.add(s);continue}let u=c?.replace(d,"");if(u&&u in t.light){i.add([a,`${d}${t.light[u]}`].filter(Boolean).join(":")+(p?`/${p}`:"")),n.add(["dark",a,`${d}${t.dark[u]}`].filter(Boolean).join(":")+(p?`/${p}`:""));continue}i.has(s)||i.add(s)}return[...Array.from(i),...Array.from(n)].join(" ").trim()}var H=async({sourceFile:e,config:t})=>{let r=e.getImportDeclarations();for(let i of r){let n=cr(i.getModuleSpecifierValue(),t);i.setModuleSpecifier(n),n=="@/lib/utils"&&i.getNamedImports().find(c=>c.getName()==="cn")&&i.setModuleSpecifier(n.replace(/^@\/lib\/utils/,t.aliases.utils))}return e};function cr(e,t){if(!e.startsWith("@/"))return e;if(!e.startsWith("@/registry/")){let r=t.aliases.components.charAt(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 pr}from"@babel/core";import{parse as mr}from"@babel/parser";import fr from"@babel/plugin-transform-typescript";import*as Q from"recast";var dr={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"]},Xe=async({sourceFile:e,config:t})=>{let r=e.getFullText();if(t.tsx)return r;let i=Q.parse(r,{parser:{parse:s=>mr(s,dr)}}),n=pr(i,r,{cloneInputAst:!1,code:!1,ast:!0,plugins:[fr],configFile:!1});if(!n||!n.ast)throw new Error("Failed to transform JSX");return Q.print(n.ast).code};import{SyntaxKind as ur}from"ts-morph";var X=async({sourceFile:e,config:t})=>{if(t.rsc)return e;let r=e.getFirstChildByKind(ur.ExpressionStatement);return r?.getText()==='"use client"'&&r.remove(),e};import{Project as yr,ScriptKind as wr}from"ts-morph";import{SyntaxKind as y}from"ts-morph";var Z=async({sourceFile:e,config:t})=>(t.tailwind?.prefix&&(e.getDescendantsOfKind(y.CallExpression).filter(r=>r.getExpression().getText()==="cva").forEach(r=>{if(r.getArguments()[0]?.isKind(y.StringLiteral)){let i=r.getArguments()[0];i&&i.replaceWithText(`"${k(i.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)}r.getArguments()[1]?.isKind(y.ObjectLiteralExpression)&&r.getArguments()[1]?.getDescendantsOfKind(y.PropertyAssignment).find(i=>i.getName()==="variants")?.getDescendantsOfKind(y.PropertyAssignment).forEach(i=>{i.getDescendantsOfKind(y.PropertyAssignment).forEach(n=>{let s=n.getInitializerIfKind(y.StringLiteral);s&&s?.replaceWithText(`"${k(s.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)})})}),e.getDescendantsOfKind(y.JsxAttribute).forEach(r=>{if(r.getName()==="className"){if(r.getInitializer()?.isKind(y.StringLiteral)){let i=r.getInitializer();i&&i.replaceWithText(`"${k(i.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)}if(r.getInitializer()?.isKind(y.JsxExpression)){let i=r.getInitializer()?.getDescendantsOfKind(y.CallExpression).find(n=>n.getExpression().getText()==="cn");i&&i.getArguments().forEach(n=>{(n.isKind(y.ConditionalExpression)||n.isKind(y.BinaryExpression))&&n.getChildrenOfKind(y.StringLiteral).forEach(s=>{s.replaceWithText(`"${k(s.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)}),n.isKind(y.StringLiteral)&&n.replaceWithText(`"${k(n.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)})}}r.getName()==="classNames"&&r.getInitializer()?.isKind(y.JsxExpression)&&r.getDescendantsOfKind(y.PropertyAssignment).forEach(i=>{if(i.getInitializer()?.isKind(y.CallExpression)){let n=i.getInitializerIfKind(y.CallExpression);n&&n.getArguments().forEach(s=>{s.isKind(y.ConditionalExpression)&&s.getChildrenOfKind(y.StringLiteral).forEach(a=>{a.replaceWithText(`"${k(a.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)}),s.isKind(y.StringLiteral)&&s.replaceWithText(`"${k(s.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)})}if(i.getInitializer()?.isKind(y.StringLiteral)&&i.getName()!=="variant"){let n=i.getInitializer();n&&n.replaceWithText(`"${k(n.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)}})})),e);function k(e,t=""){let r=e.split(" "),i=[];for(let n of r){let[s,a,c]=ue(n);s?c?i.push(`${s}:${t}${a}/${c}`):i.push(`${s}:${t}${a}`):c?i.push(`${t}${a}/${c}`):i.push(`${t}${a}`)}return i.join(" ")}var xr=new yr({compilerOptions:{}});async function br(e){let t=await gr.mkdtemp(Ze.join(hr(),"shadcn-"));return Ze.join(t,e)}async function q(e,t=[H,X,Y,Z]){let r=await br(e.filename),i=xr.createSourceFile(r,e.raw,{scriptKind:wr.TSX});for(let n of t)n({sourceFile:i,...e});return e.transformJsx?await Xe({sourceFile:i,...e}):i.getText()}import Cr from"prompts";async function tt(e,t,r){if(!e?.length)return;r={overwrite:!1,force:!1,silent:!1,...r};let i=w("Updating files.",{silent:r.silent})?.start(),[n,s]=await Promise.all([j(t.resolvedPaths.cwd),K(t.tailwind.baseColor)]),a=[],c=[],p=[];for(let u of e){if(!u.content)continue;let f=Ge(u,t),b=Sr(u.path),C=$.join(f,b);u.target&&(C=n?.isSrcDir?$.join(t.resolvedPaths.cwd,"src",u.target):$.join(t.resolvedPaths.cwd,u.target),f=$.dirname(C)),t.tsx||(C=C.replace(/\.tsx?$/,ie=>ie===".tsx"?".jsx":".js"));let Se=qe(C);if(Se&&!r.overwrite){i.stop();let{overwrite:ie}=await Cr({type:"confirm",name:"overwrite",message:`The file ${l.info(b)} already exists. Would you like to overwrite?`,initial:!1});if(!ie){p.push($.relative(t.resolvedPaths.cwd,C));continue}i?.start()}qe(f)||await et.mkdir(f,{recursive:!0});let dt=await q({filename:u.path,raw:u.content,config:t,baseColor:s,transformJsx:!t.tsx},[H,X,Y,Z]);await et.writeFile(C,dt,"utf-8"),Se?c.push($.relative(t.resolvedPaths.cwd,C)):a.push($.relative(t.resolvedPaths.cwd,C))}if(!(a.length||c.length)&&!p.length&&i?.info("No files updated."),a.length){if(i?.succeed(`Created ${a.length} ${a.length===1?"file":"files"}:`),!r.silent)for(let u of a)o.log(` - ${u}`)}else i?.stop();if(c.length&&(w(`Updated ${c.length} ${c.length===1?"file":"files"}:`,{silent:r.silent})?.info(),!r.silent))for(let u of c)o.log(` - ${u}`);if(p.length&&(w(`Skipped ${p.length} ${c.length===1?"file":"files"}:`,{silent:r.silent})?.info(),!r.silent))for(let u of p)o.log(` - ${u}`);r.silent||o.break()}async function ee(e,t,r){r={overwrite:!1,silent:!1,isNewProject:!1,...r};let i=w("Checking registry.",{silent:r.silent})?.start(),n=await Be(e,t);if(!n)return i?.fail(),x(new Error("Failed to fetch components from registry."));i?.succeed(),await De(n.tailwind?.config,t,{silent:r.silent}),await He(n.cssVars,t,{cleanupDefaultNextStyles:r.isNewProject,silent:r.silent}),await Qe(n.dependencies,t,{silent:r.silent}),await tt(n.files,t,{overwrite:r.overwrite,silent:r.silent})}import Pr from"path";import{execa as vr}from"execa";import ge from"fs-extra";import rt from"prompts";async function te(e){if(e={srcDir:!1,...e},!e.force){let{proceed:a}=await rt({type:"confirm",name:"proceed",message:`The path ${l.info(e.cwd)} is does not contain a package.json file. Would you like to start a new ${l.info("Next.js")} project?`,initial:!0});if(!a)return{projectPath:null,projectName:null}}let t=await J(e.cwd),{name:r}=await rt({type:"text",name:"name",message:"What is your project named?",initial:"my-app",format:a=>a.trim(),validate:a=>a.length>128?"Name should be less than 128 characters.":!0}),i=`${e.cwd}/${r}`;try{await ge.access(e.cwd,ge.constants.W_OK)}catch{o.break(),o.error(`The path ${l.info(e.cwd)} is not writable.`),o.error(`It is likely you do not have write permissions for this folder or the path ${l.info(e.cwd)} does not exist.`),o.break(),process.exit(1)}ge.existsSync(Pr.resolve(e.cwd,r,"package.json"))&&(o.break(),o.error(`A project with the name ${l.info(r)} already exists.`),o.error("Please choose a different name and try again."),o.break(),process.exit(1));let n=w("Creating a new Next.js project. This may take a few minutes.").start(),s=["--tailwind","--eslint","--typescript","--app",e.srcDir?"--src-dir":"--no-src-dir","--no-import-alias",`--use-${t}`];try{await vr("npx",["create-next-app@latest",i,"--silent",...s],{cwd:e.cwd})}catch{o.break(),o.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{Command as Tr}from"commander";import he from"prompts";import{z as P}from"zod";var Ir=P.object({cwd:P.string(),components:P.array(P.string()).optional(),yes:P.boolean(),defaults:P.boolean(),force:P.boolean(),silent:P.boolean(),isNewProject:P.boolean(),srcDir:P.boolean().optional()}),nt=new Tr().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=Ir.parse({cwd:it.resolve(t.cwd),isNewProject:!1,components:e,...t});await re(r),o.log(`${l.success("Success!")} Project initialization completed.
15
+ You may now add components.`),o.break()}catch(r){o.break(),x(r)}});async function re(e){let t;if(e.skipPreflight)t=await j(e.cwd);else{let p=await je(e);if(p.errors[T]){let{projectPath:d}=await te(e);d||process.exit(1),e.cwd=d,e.isNewProject=!0}t=p.projectInfo}let r=await Ie(e.cwd,t),i=r?await jr(r,e):await kr(await I(e.cwd));if(!e.yes){let{proceed:p}=await he({type:"confirm",name:"proceed",message:`Write configuration to ${l.info("components.json")}. Proceed?`,initial:!0});p||process.exit(0)}let n=w("Writing components.json.").start(),s=it.resolve(e.cwd,"components.json");await Rr.writeFile(s,JSON.stringify(i,null,2),"utf8"),n.succeed();let a=await F(e.cwd,i),c=["index",...e.components||[]];return await ee(c,a,{overwrite:!0,silent:e.silent,isNewProject:e.isNewProject||t?.framework.name==="next-app"}),a}async function kr(e=null){let[t,r]=await Promise.all([me(),fe()]);o.info("");let i=await he([{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??Re},{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??Te},{type:"text",name:"components",message:`Configure the import alias for ${l.info("components")}:`,initial:e?.aliases.components??Pe},{type:"text",name:"utils",message:`Configure the import alias for ${l.info("utils")}:`,initial:e?.aliases.utils??ve},{type:"toggle",name:"rsc",message:`Are you using ${l.info("React Server Components")}?`,initial:e?.rsc??!0,active:"yes",inactive:"no"}]);return A.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 jr(e,t){let r=e.style,i=e.tailwind.baseColor,n=e.tailwind.cssVariables;if(!t.defaults){let[s,a]=await Promise.all([me(),fe()]),c=await he([{type:"select",name:"style",message:`Which ${l.info("style")} would you like to use?`,choices:s.map(p=>({title:p.label,value:p.name})),initial:s.findIndex(p=>p.name===r)},{type:"select",name:"tailwindBaseColor",message:`Which color would you like to use as the ${l.info("base color")}?`,choices:a.map(p=>({title:p.label,value:p.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 A.parse({$schema:e?.$schema,style:r,tailwind:{...e?.tailwind,baseColor:i,cssVariables:n},rsc:e?.rsc,tsx:e?.tsx,aliases:e?.aliases})}import st from"path";import ye from"fs-extra";async function ot(e){let t={};if(!ye.existsSync(e.cwd)||!ye.existsSync(st.resolve(e.cwd,"package.json")))return t[T]=!0,{errors:t,config:null};if(!ye.existsSync(st.resolve(e.cwd,"components.json")))return t[V]=!0,{errors:t,config:null};try{let r=await I(e.cwd);return{errors:t,config:r}}catch{o.break(),o.error(`An invalid ${l.info("components.json")} file was found at ${l.info(e.cwd)}.
16
+ Before you can add components, you must create a valid ${l.info("components.json")} file by running the ${l.info("init")} command.`),o.error(`Learn more at ${l.info("https://ui.shadcn.com/docs/components-json")}.`),o.break(),process.exit(1)}}import at from"fs/promises";import Er from"path";async function lt(e,t){let r=Er.join(t.resolvedPaths.cwd,"app/page.tsx");if(!(await at.stat(r)).isFile())return;let i=await B(e,t.style);if(!i?.meta?.importSpecifier||!i?.meta?.moduleSpecifier)return;let n=`import { ${i?.meta?.importSpecifier} } from "${i.meta.moduleSpecifier}"
17
+
18
+ export default function Page() {
19
+ return <${i?.meta?.importSpecifier} />
20
+ }`;await at.writeFile(r,n,"utf8")}import{Command as Or}from"commander";import we from"prompts";import{z as S}from"zod";var Nr=S.object({components:S.array(S.string()).optional(),yes:S.boolean(),overwrite:S.boolean(),cwd:S.string(),all:S.boolean(),path:S.string().optional(),silent:S.boolean(),srcDir:S.boolean().optional()}),ct=new Or().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=Nr.parse({components:e,cwd:$r.resolve(t.cwd),...t}),i=r.components?.some(c=>c.includes("theme-"));if(!r.yes&&i){o.break();let{confirm:c}=await we({type:"confirm",name:"confirm",message:l.warn(`You are about to install a new theme.
21
+ Existing CSS variables will be overwritten. Continue?`)});c||(o.break(),o.log("Theme installation cancelled."),o.break(),process.exit(1))}r.components?.length||(r.components=await Ar(r));let{errors:n,config:s}=await ot(r);if(n[V]){let{proceed:c}=await we({type:"confirm",name:"proceed",message:`You need to create a ${l.info("component.json")} file to add components. Proceed?`,initial:!0});c||(o.break(),process.exit(1)),s=await re({cwd:r.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!1,silent:!0,isNewProject:!1,srcDir:r.srcDir})}let a=!1;if(n[T]){let{projectPath:c}=await te({cwd:r.cwd,force:r.overwrite,srcDir:r.srcDir});c||(o.break(),process.exit(1)),r.cwd=c,s=await re({cwd:r.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!0,silent:!0,isNewProject:!0,srcDir:r.srcDir}),a=r.components?.length===1&&!!r.components[0].match(/\/chat\/b\//)}if(!s)throw new Error(`Failed to read config at ${l.info(r.cwd)}.`);await ee(r.components,s,r),a&&await lt(r.components[0],s)}catch(r){o.break(),x(r)}});async function Ar(e){let t=await z();if(!t)return o.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 we({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||(o.warn("No components selected. Exiting."),o.info(""),process.exit(1));let i=S.array(S.string()).safeParse(r);return i.success?i.data:(o.error(""),x(new Error("Something went wrong. Please try again.")),[])}import{existsSync as xe,promises as Fr}from"fs";import be from"path";import{Command as Dr}from"commander";import{diffLines as Lr}from"diff";import{z as W}from"zod";var _r=W.object({component:W.string().optional(),yes:W.boolean(),cwd:W.string(),path:W.string().optional()}),mt=new Dr().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=_r.parse({component:e,...t}),i=be.resolve(r.cwd);xe(i)||(o.error(`The path ${i} does not exist. Please try again.`),process.exit(1));let n=await I(i);n||(o.warn(`Configuration is missing. Please run ${l.success("init")} to create a components.json file.`),process.exit(1));let s=await z();if(s||(x(new Error("Failed to fetch registry index.")),process.exit(1)),!r.component){let p=n.resolvedPaths.components,d=s.filter(f=>{for(let b of f.files??[]){let C=be.resolve(p,typeof b=="string"?b:b.path);if(xe(C))return!0}return!1}),u=[];for(let f of d){let b=await pt(f,n);b.length&&u.push({name:f.name,changes:b})}u.length||(o.info("No updates found."),process.exit(0)),o.info("The following components have updates available:");for(let f of u){o.info(`- ${f.name}`);for(let b of f.changes)o.info(` - ${b.filePath}`)}o.break(),o.info(`Run ${l.success("diff <component>")} to see the changes.`),process.exit(0)}let a=s.find(p=>p.name===r.component);a||(o.error(`The component ${l.success(r.component)} does not exist.`),process.exit(1));let c=await pt(a,n);c.length||(o.info(`No updates found for ${r.component}.`),process.exit(0));for(let p of c)o.info(`- ${p.filePath}`),await zr(p.patch),o.info("")}catch(r){x(r)}});async function pt(e,t){let r=await Me(t.style,[e]),i=await K(t.tailwind.baseColor);if(!r)return[];let n=[];for(let s of r){let a=await Ue(t,s);if(a)for(let c of s.files??[]){let p=be.resolve(a,typeof c=="string"?c:c.path);if(!xe(p))continue;let d=await Fr.readFile(p,"utf8");if(typeof c=="string"||!c.content)continue;let u=await q({filename:c.path,raw:c.content,config:t,baseColor:i}),f=Lr(u,d);f.length>1&&n.push({filePath:p,patch:f})}}return n}async function zr(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 Wr}from"commander";var ft={name:"shadcn",version:"0.0.0-beta.d89c2a4",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:"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 Vr(){let e=new Wr().name("shadcn").description("add components and dependencies to your project").version(ft.version||"1.0.0","-v, --version","display the version number");e.addCommand(nt).addCommand(ct).addCommand(mt),e.parse()}Vr();
17
22
  //# sourceMappingURL=index.js.map