shadcn 2.9.1 → 2.9.2
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 +10 -10
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -11,7 +11,7 @@ import vr from 'postcss/lib/at-rule';
|
|
|
11
11
|
import { z } from 'zod';
|
|
12
12
|
import { detect } from '@antfu/ni';
|
|
13
13
|
import { execa } from 'execa';
|
|
14
|
-
import
|
|
14
|
+
import qe from 'prompts';
|
|
15
15
|
import Ii, { tmpdir } from 'os';
|
|
16
16
|
import { Project, ScriptKind, SyntaxKind } from 'ts-morph';
|
|
17
17
|
import { transformFromAstSync } from '@babel/core';
|
|
@@ -27,10 +27,10 @@ import { randomBytes } from 'crypto';
|
|
|
27
27
|
import Qi from 'fast-glob';
|
|
28
28
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
29
29
|
|
|
30
|
-
var A="1";var D="3";var se="5",
|
|
30
|
+
var A="1";var D="3";var se="5",ze="6",jt="7";var q="13";async function Et(e){let t={};if(!Q.existsSync(e.cwd)||!Q.existsSync(x__default.resolve(e.cwd,"package.json")))return t[A]=!0,{errors:t,projectInfo:null};let r$1=s("Preflight checks.",{silent:e.silent}).start();Q.existsSync(x__default.resolve(e.cwd,"components.json"))&&!e.force&&(r$1?.fail(),r.break(),r.error(`A ${a.info("components.json")} file already exists at ${a.info(e.cwd)}.
|
|
31
31
|
To start over, remove the ${a.info("components.json")} file and run ${a.info("init")} again.`),r.break(),process.exit(1)),r$1?.succeed();let i=s("Verifying framework.",{silent:e.silent}).start(),o$1=await o(e.cwd);(!o$1||o$1?.framework.name==="manual")&&(t[jt]=!0,i?.fail(),r.break(),o$1?.framework.links.installation&&r.error(`We could not detect a supported framework at ${a.info(e.cwd)}.
|
|
32
32
|
Visit ${a.info(o$1?.framework.links.installation)} to manually configure your project.
|
|
33
|
-
Once configured, you can use the cli to add components.`),r.break(),process.exit(1)),i?.succeed(`Verifying framework. Found ${a.info(o$1.framework.label)}.`);let n="Validating Tailwind CSS.";o$1.tailwindVersion==="v4"&&(n=`Validating Tailwind CSS config. Found ${a.info("v4")}.`);let a$1=s(n,{silent:e.silent}).start();o$1.tailwindVersion==="v3"&&(!o$1?.tailwindConfigFile||!o$1?.tailwindCssFile)?(t[se]=!0,a$1?.fail()):o$1.tailwindVersion==="v4"&&!o$1?.tailwindCssFile?(t[se]=!0,a$1?.fail()):o$1.tailwindVersion?a$1?.succeed():(t[se]=!0,a$1?.fail());let s$1=s("Validating import alias.",{silent:e.silent}).start();return o$1?.aliasPrefix?s$1?.succeed():(t[
|
|
33
|
+
Once configured, you can use the cli to add components.`),r.break(),process.exit(1)),i?.succeed(`Verifying framework. Found ${a.info(o$1.framework.label)}.`);let n="Validating Tailwind CSS.";o$1.tailwindVersion==="v4"&&(n=`Validating Tailwind CSS config. Found ${a.info("v4")}.`);let a$1=s(n,{silent:e.silent}).start();o$1.tailwindVersion==="v3"&&(!o$1?.tailwindConfigFile||!o$1?.tailwindCssFile)?(t[se]=!0,a$1?.fail()):o$1.tailwindVersion==="v4"&&!o$1?.tailwindCssFile?(t[se]=!0,a$1?.fail()):o$1.tailwindVersion?a$1?.succeed():(t[se]=!0,a$1?.fail());let s$1=s("Validating import alias.",{silent:e.silent}).start();return o$1?.aliasPrefix?s$1?.succeed():(t[ze]=!0,s$1?.fail()),Object.keys(t).length>0&&(t[se]&&(r.break(),r.error(`No Tailwind CSS configuration found at ${a.info(e.cwd)}.`),r.error("It is likely you do not have Tailwind CSS installed or have an invalid configuration."),r.error("Install Tailwind CSS then try again."),o$1?.framework.links.tailwind&&r.error(`Visit ${a.info(o$1?.framework.links.tailwind)} to get started.`)),t[ze]&&(r.break(),r.error("No import alias found in your tsconfig.json file."),o$1?.framework.links.installation&&r.error(`Visit ${a.info(o$1?.framework.links.installation)} to learn how to set an import alias.`)),r.break(),process.exit(1)),{errors:t,projectInfo:o$1}}function $t(e,t){if(e.includes("\0"))return !1;let r;try{r=e;let u="";for(;r!==u&&r.includes("%");)u=r,r=decodeURIComponent(r);}catch{return !1}let i=x__default.normalize(r.replace(/\\/g,"/")),o=x__default.normalize(t),n=u=>u.replace(/\[\.\.\..*?\]/g,"").includes("..");if(n(i)||n(r)||n(e))return !1;let a=u=>u.replace(/\[\.\.\..*?\]/g,""),s=a(e),c=a(r);if([/\.\.[\/\\]/,/[\/\\]\.\./,/\.\./,/\.\.%/,/\x00/,/[\x01-\x1f]/].some(u=>u.test(s)||u.test(c))||(e.includes("~")||r.includes("~"))&&(e.includes("../")||r.includes("../")))return !1;if(/^[a-zA-Z]:[\/\\]/.test(r))return process.platform==="win32"?r.toLowerCase().startsWith(t.toLowerCase()):!1;if(x__default.isAbsolute(i))return i.startsWith(o+x__default.sep);let m=x__default.resolve(o,i);return m.startsWith(o+x__default.sep)||m===o}async function Be(e,t,r){if(!t.resolvedPaths.tailwindCss||!e||Object.keys(e).length===0)return;r={silent:!1,...r};let i=t.resolvedPaths.tailwindCss,o=x__default.relative(t.resolvedPaths.cwd,i),n=s(`Updating ${a.info(o)}`,{silent:r.silent}).start(),a$1=await promises.readFile(i,"utf8"),s$1=await br(a$1,e);await promises.writeFile(i,s$1,"utf8"),n.succeed();}async function br(e,t){let r=[Sr(t)],o=(await S$1(r).process(e,{from:void 0})).css;return o=o.replace(/\/\* ---break--- \*\//g,""),o=o.replace(/(\n\s*\n)+/g,`
|
|
34
34
|
|
|
35
35
|
`),o=o.trimEnd(),o}function Sr(e){return {postcssPlugin:"update-css",Once(t){for(let[r,i]of Object.entries(e))if(r.startsWith("@")){let o=r.match(/@([a-zA-Z-]+)\s*(.*)/);if(!o)continue;let[,n,a]=o;if(n==="plugin"){if(!t.nodes?.find(c=>c.type==="atrule"&&c.name==="plugin"&&c.params===a)){let c=S$1.atRule({name:"plugin",params:a,raws:{semicolon:!0,before:`
|
|
36
36
|
`}}),l=t.nodes?.filter(m=>m.type==="atrule"&&m.name==="import"),f=t.nodes?.filter(m=>m.type==="atrule"&&m.name==="plugin");if(f&&f.length>0){let m=f[f.length-1];t.insertAfter(m,c);}else if(l&&l.length>0){let m=l[l.length-1];t.insertAfter(m,c),t.insertBefore(c,S$1.comment({text:"---break---"})),t.insertAfter(c,S$1.comment({text:"---break---"}));}else t.prepend(c),t.insertBefore(c,S$1.comment({text:"---break---"})),t.insertAfter(c,S$1.comment({text:"---break---"}));}}else if(n==="keyframes"){let s=t.nodes?.find(l=>l.type==="atrule"&&l.name==="theme"&&l.params==="inline");s||(s=S$1.atRule({name:"theme",params:"inline",raws:{semicolon:!0,between:" ",before:`
|
|
@@ -44,7 +44,7 @@ Once configured, you can use the cli to add components.`),r.break(),process.exit
|
|
|
44
44
|
`,s.append(l);}}),s.nodes?.length&&o.append(s);}}catch(n){throw console.error("Error parsing at-rule content:",i,n),n}}function te(e,t,r){let i=e.nodes?.find(o=>o.type==="rule"&&o.selector===t);if(i||(i=S$1.rule({selector:t,raws:{semicolon:!0,between:" ",before:`
|
|
45
45
|
`}}),e.append(i)),typeof r=="object"){for(let[o,n]of Object.entries(r))if(typeof n=="string"){let a=S$1.decl({prop:o,value:n,raws:{semicolon:!0,before:`
|
|
46
46
|
`}}),s=i.nodes?.find(c=>c.type==="decl"&&c.prop===o);s?s.replaceWith(a):i.append(a);}else if(typeof n=="object"){let a=o.startsWith("&")?t.replace(/^([^:]+)/,`$1${o.substring(1)}`):o;te(e,a,n);}}else if(typeof r=="string")try{let n=S$1.parse(`.temp{${r}}`).first;n&&n.nodes&&n.nodes.forEach(a=>{if(a.type==="decl"){let s=a.clone();s.raws.before=`
|
|
47
|
-
`,i?.append(s);}});}catch(o){throw console.error("Error parsing rule content:",t,r,o),o}}async function
|
|
47
|
+
`,i?.append(s);}});}catch(o){throw console.error("Error parsing rule content:",t,r,o),o}}async function Ue(e,t,r){if(!t.resolvedPaths.tailwindCss||!Object.keys(e??{}).length)return;r={cleanupDefaultNextStyles:!1,silent:!1,tailwindVersion:"v3",overwriteCssVars:!1,initIndex:!0,...r};let i=t.resolvedPaths.tailwindCss,o=x__default.relative(t.resolvedPaths.cwd,i),n=s(`Updating CSS variables in ${a.info(o)}`,{silent:r.silent}).start(),a$1=await promises.readFile(i,"utf8"),s$1=await Ir(a$1,e??{},t,{cleanupDefaultNextStyles:r.cleanupDefaultNextStyles,tailwindVersion:r.tailwindVersion,tailwindConfig:r.tailwindConfig,overwriteCssVars:r.overwriteCssVars,initIndex:r.initIndex});await promises.writeFile(i,s$1,"utf8"),n.succeed();}async function Ir(e,t,r,i={cleanupDefaultNextStyles:!1,tailwindVersion:"v3",tailwindConfig:void 0,overwriteCssVars:!1,initIndex:!0}){i={cleanupDefaultNextStyles:!1,tailwindVersion:"v3",tailwindConfig:void 0,overwriteCssVars:!1,initIndex:!0,...i};let o=[Cr(t)];if(i.cleanupDefaultNextStyles&&o.push(Ft()),i.tailwindVersion==="v4"){if(o=[],r.resolvedPaths?.cwd){let s=n(r.resolvedPaths.cwd);!s?.dependencies?.["tailwindcss-animate"]&&!s?.devDependencies?.["tailwindcss-animate"]&&i.initIndex&&o.push($r({params:"tw-animate-css"}));}o.push(Er({params:"dark (&:is(.dark *))"})),i.cleanupDefaultNextStyles&&o.push(Ft()),o.push(jr(t,{overwriteCssVars:i.overwriteCssVars})),o.push(Tr(t)),i.tailwindConfig&&(o.push(Or(i.tailwindConfig)),o.push(Ar(i.tailwindConfig)),o.push(Nr(i.tailwindConfig)));}r.tailwind.cssVariables&&i.initIndex&&o.push(Pr({tailwindVersion:i.tailwindVersion}));let a=(await S$1(o).process(e,{from:void 0})).css;return a=a.replace(/\/\* ---break--- \*\//g,""),i.tailwindVersion==="v4"&&(a=a.replace(/(\n\s*\n)+/g,`
|
|
48
48
|
|
|
49
49
|
`)),a}function Pr({tailwindVersion:e}){return {postcssPlugin:"update-base-layer",Once(t){let r=[{selector:"*",apply:e==="v4"?"border-border outline-ring/50":"border-border"},{selector:"body",apply:"bg-background text-foreground"}],i=t.nodes.find(o=>o.type==="atrule"&&o.name==="layer"&&o.params==="base"&&r.every(({selector:n,apply:a})=>o.nodes?.some(s=>s.type==="rule"&&s.selector===n&&s.nodes.some(c=>c.type==="atrule"&&c.name==="apply"&&c.params===a))));i||(i=S$1.atRule({name:"layer",params:"base",raws:{semicolon:!0,between:" ",before:`
|
|
50
50
|
`}}),t.append(i),t.insertBefore(i,S$1.comment({text:"---break---"}))),r.forEach(({selector:o,apply:n})=>{i?.nodes?.find(s=>s.type==="rule"&&s.selector===o)||i?.append(S$1.rule({selector:o,nodes:[S$1.atRule({name:"apply",params:n,raws:{semicolon:!0,before:`
|
|
@@ -63,22 +63,22 @@ Once configured, you can use the cli to add components.`),r.break(),process.exit
|
|
|
63
63
|
`}});r.append(c);}}}}function Dr(e){return e.nodes[0].toString().includes("'")?"single":"double"}function _t(e){if(e.startsWith("hsl")||e.startsWith("rgb")||e.startsWith("#")||e.startsWith("oklch"))return !1;let t=e.split(" ");return t.length===3&&t.slice(1,3).every(r=>r.includes("%"))}function Fr(e){return e.startsWith("hsl")||e.startsWith("rgb")||e.startsWith("#")||e.startsWith("oklch")}async function be(e,{withFallback:t}={withFallback:!1}){let r=await detect({programmatic:!0,cwd:e});if(r==="yarn@berry")return "yarn";if(r==="pnpm@6")return "pnpm";if(r==="bun")return "bun";if(r==="deno")return "deno";if(!t)return r??"npm";let i=process.env.npm_config_user_agent||"";return i.startsWith("yarn")?"yarn":i.startsWith("pnpm")?"pnpm":i.startsWith("bun")?"bun":"npm"}async function H(e,t,r$1,i){if(e=Array.from(new Set(e)),t=Array.from(new Set(t)),!e?.length&&!t?.length)return;i={silent:!1,...i};let o=s("Installing dependencies.",{silent:i.silent})?.start(),n=await Mr(r$1),a="";if(Vr(r$1)&&n==="npm")if(i.silent)a="force";else {o.stopAndPersist(),r.warn(`
|
|
64
64
|
It looks like you are using React 19.
|
|
65
65
|
Some packages may fail to install due to peer dependency issues in npm (see https://ui.shadcn.com/react-19).
|
|
66
|
-
`);let s=await Ye([{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&&(a=s.flag);}o?.start(),await zr(n,e,t,r$1.resolvedPaths.cwd,a),o?.succeed();}function Vr(e){let t=n(e.resolvedPaths.cwd,!1);if(!t?.dependencies?.react)return !1;let r=/^(?:\^|~)?19(?:\.\d+)*(?:-.*)?$/.test(t.dependencies.react),i=t.dependencies["react-day-picker"]?.startsWith("8");return r&&i}async function Mr(e){return n(e.resolvedPaths.cwd,!1)?.dependencies?.expo?"expo":be(e.resolvedPaths.cwd)}async function zr(e,t,r,i,o){if(e==="npm")return Wr(t,r,i,o);if(e==="deno")return Br(t,r,i);if(e==="expo")return Ur(t,r,i);t?.length&&await execa(e,["add",...t],{cwd:i}),r?.length&&await execa(e,["add","-D",...r],{cwd:i});}async function Wr(e,t,r,i){e.length&&await execa("npm",["install",...i?[`--${i}`]:[],...e],{cwd:r}),t.length&&await execa("npm",["install",...i?[`--${i}`]:[],"-D",...t],{cwd:r});}async function Br(e,t,r){e?.length&&await execa("deno",["add",...e.map(i=>`npm:${i}`)],{cwd:r}),t?.length&&await execa("deno",["add","-D",...t.map(i=>`npm:${i}`)],{cwd:r});}async function Ur(e,t,r){e.length&&await execa("npx",["expo","install",...e],{cwd:r}),t.length&&await execa("npx",["expo","install","-- -D",...t],{cwd:r});}var Se=async({sourceFile:e,config:t,baseColor:r})=>(t.tailwind?.cssVariables||!r?.inlineColors||e.getDescendantsOfKind(SyntaxKind.StringLiteral).forEach(i=>{let o=i.getText();if(o){let n=Jr(o.replace(/"/g,""),r.inlineColors);i.replaceWithText(`"${n.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 o=r.split(":"),n=o.pop(),a=o.join(":");return t.push(a??null,n??null,i??null),t}var Gr=["bg-","text-","border-","ring-offset-","ring-"];function Jr(e,t){e.includes(" border ")&&(e=e.replace(" border "," border border-border "));let r=e.split(" "),i=new Set,o=new Set;for(let n of r){let[a,s,c]=Ue(n),l=Gr.find(m=>s?.startsWith(m));if(!l){i.has(n)||i.add(n);continue}let f=s?.replace(l,"");if(f&&f in t.light){i.add([a,`${l}${t.light[f]}`].filter(Boolean).join(":")+(c?`/${c}`:"")),o.add(["dark",a,`${l}${t.dark[f]}`].filter(Boolean).join(":")+(c?`/${c}`:""));continue}i.has(n)||i.add(n);}return [...Array.from(i),...Array.from(o)].join(" ").trim()}var F={lucide:{name:"lucide-react",package:"lucide-react",import:"lucide-react"},radix:{name:"@radix-ui/react-icons",package:"@radix-ui/react-icons",import:"@radix-ui/react-icons"}};var Lt="lucide",Re=async({sourceFile:e,config:t})=>{if(!t.iconLibrary||!(t.iconLibrary in F))return e;let r=await Q$1(),i=Lt,o=t.iconLibrary;if(i===o)return e;let n=[];for(let a of e.getImportDeclarations()??[])if(a.getModuleSpecifier()?.getText()===`"${F[Lt].import}"`){for(let s of a.getNamedImports()??[]){let c=s.getName(),l=r[c]?.[o];!l||n.includes(l)||(n.push(l),s.remove(),e.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement).filter(f=>f.getTagNameNode()?.getText()===c).forEach(f=>f.getTagNameNode()?.replaceWithText(l)));}a.getNamedImports()?.length===0&&a.remove();}if(n.length>0){let a=e.addImportDeclaration({moduleSpecifier:F[o]?.import,namedImports:n.map(s=>({name:s}))});qr(e)||a.replaceWithText(a.getText().replace(";",""));}return e};function qr(e){return e.getImportDeclarations()?.[0]?.getText().endsWith(";")??!1}var ve=async({sourceFile:e,config:t,isRemote:r})=>{let o=`@${t.aliases?.utils?.split("/")[0]?.slice(1)}/lib/utils`,n=e.getImportDeclarations();if(![".tsx",".ts",".jsx",".js"].includes(e.getExtension()))return e;for(let a of n){let s=Hr(a.getModuleSpecifierValue(),t,r);a.setModuleSpecifier(s),(o===s||s==="@/lib/utils")&&a.getNamedImports().find(f=>f.getName()==="cn")&&a.setModuleSpecifier(o===s?s.replace(o,t.aliases.utils):t.aliases.utils);}return e};function Hr(e,t,r=!1){if(!e.startsWith("@/")&&!r)return e;if(r&&e.startsWith("@/")&&(e=e.replace(/^@\//,"@/registry/new-york/")),!e.startsWith("@/registry/")){let i=t.aliases.components.split("/")[0];return e.replace(/^@\//,`${i}/`)}return e.match(/^@\/registry\/(.+)\/ui/)?e.replace(/^@\/registry\/(.+)\/ui/,t.aliases.ui??`${t.aliases.components}/ui`):t.aliases.components&&e.match(/^@\/registry\/(.+)\/components/)?e.replace(/^@\/registry\/(.+)\/components/,t.aliases.components):t.aliases.lib&&e.match(/^@\/registry\/(.+)\/lib/)?e.replace(/^@\/registry\/(.+)\/lib/,t.aliases.lib):t.aliases.hooks&&e.match(/^@\/registry\/(.+)\/hooks/)?e.replace(/^@\/registry\/(.+)\/hooks/,t.aliases.hooks):e.replace(/^@\/registry\/[^/]+/,t.aliases.components)}var ei={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"]},Vt=async({sourceFile:e,config:t})=>{let r=e.getFullText();if(t.tsx)return r;let i=Ie.parse(r,{parser:{parse:n=>parse(n,ei)}}),o=transformFromAstSync(i,r,{cloneInputAst:!1,code:!1,ast:!0,plugins:[Zr],configFile:!1});if(!o||!o.ast)throw new Error("Failed to transform JSX");return Ie.print(o.ast).code};var ri=/^["']use client["']$/g,Pe=async({sourceFile:e,config:t})=>{if(t.rsc)return e;let r=e.getFirstChildByKind(SyntaxKind.ExpressionStatement);return r&&ri.test(r.getText())&&r.remove(),e};var Ce=async({sourceFile:e,config:t})=>{if(!t.tailwind?.prefix)return e;let r=await q$1(t);return e.getDescendantsOfKind(SyntaxKind.CallExpression).filter(i=>i.getExpression().getText()==="cva").forEach(i=>{if(i.getArguments()[0]?.isKind(SyntaxKind.StringLiteral)){let o=i.getArguments()[0];o&&o.replaceWithText(`"${B(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix,r)}"`);}i.getArguments()[1]?.isKind(SyntaxKind.ObjectLiteralExpression)&&i.getArguments()[1]?.getDescendantsOfKind(SyntaxKind.PropertyAssignment).find(o=>o.getName()==="variants")?.getDescendantsOfKind(SyntaxKind.PropertyAssignment).forEach(o=>{o.getDescendantsOfKind(SyntaxKind.PropertyAssignment).forEach(n=>{let a=n.getInitializerIfKind(SyntaxKind.StringLiteral);a&&a?.replaceWithText(`"${B(a.getText()?.replace(/"|'/g,""),t.tailwind.prefix,r)}"`);});});}),e.getDescendantsOfKind(SyntaxKind.JsxAttribute).forEach(i=>{if(i.getName()==="className"){if(i.getInitializer()?.isKind(SyntaxKind.StringLiteral)){let o=i.getInitializer();o&&o.replaceWithText(`"${B(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix,r)}"`);}if(i.getInitializer()?.isKind(SyntaxKind.JsxExpression)){let o=i.getInitializer()?.getDescendantsOfKind(SyntaxKind.CallExpression).find(n=>n.getExpression().getText()==="cn");o&&o.getArguments().forEach(n=>{(n.isKind(SyntaxKind.ConditionalExpression)||n.isKind(SyntaxKind.BinaryExpression))&&n.getChildrenOfKind(SyntaxKind.StringLiteral).forEach(a=>{a.replaceWithText(`"${B(a.getText()?.replace(/"|'/g,""),t.tailwind.prefix,r)}"`);}),n.isKind(SyntaxKind.StringLiteral)&&n.replaceWithText(`"${B(n.getText()?.replace(/"|'/g,""),t.tailwind.prefix,r)}"`);});}}i.getName()==="classNames"&&i.getInitializer()?.isKind(SyntaxKind.JsxExpression)&&i.getDescendantsOfKind(SyntaxKind.PropertyAssignment).forEach(o=>{if(o.getInitializer()?.isKind(SyntaxKind.CallExpression)){let n=o.getInitializerIfKind(SyntaxKind.CallExpression);n&&n.getArguments().forEach(a=>{a.isKind(SyntaxKind.ConditionalExpression)&&a.getChildrenOfKind(SyntaxKind.StringLiteral).forEach(s=>{s.replaceWithText(`"${B(s.getText()?.replace(/"|'/g,""),t.tailwind.prefix,r)}"`);}),a.isKind(SyntaxKind.StringLiteral)&&a.replaceWithText(`"${B(a.getText()?.replace(/"|'/g,""),t.tailwind.prefix,r)}"`);});}if(o.getInitializer()?.isKind(SyntaxKind.StringLiteral)&&o.getName()!=="variant"){let n=o.getInitializer();n&&n.replaceWithText(`"${B(n.getText()?.replace(/"|'/g,""),t.tailwind.prefix,r)}"`);}});}),e};function B(e,t="",r){return r==="v3"?e.split(" ").map(i=>{let[o,n,a]=Ue(i);return o?a?`${o}:${t}${n}/${a}`:`${o}:${t}${n}`:a?`${t}${n}/${a}`:`${t}${n}`}).join(" "):e.split(" ").map(i=>i.indexOf(`${t}:`)===0?i:`${t}:${i.trim()}`).join(" ")}var ai=new Project({compilerOptions:{}});async function ci(e){let t=await promises.mkdtemp(x__default.join(tmpdir(),"shadcn-"));return x__default.join(t,e)}async function ke(e,t=[ve,Pe,Se,Ce,Re]){let r=await ci(e.filename),i=ai.createSourceFile(r,e.raw,{scriptKind:ScriptKind.TSX});for(let o of t)await o({sourceFile:i,...e});return e.transformJsx?await Vt({sourceFile:i,...e}):i.getText()}async function Ke(e,t,r$1){if(!e?.length)return {filesCreated:[],filesUpdated:[],filesSkipped:[]};r$1={overwrite:!1,force:!1,silent:!1,isRemote:!1,...r$1};let i=s("Updating files.",{silent:r$1.silent})?.start(),[o$1,n]=await Promise.all([o(t.resolvedPaths.cwd),t.tailwind.baseColor?T(t.tailwind.baseColor):Promise.resolve(void 0)]),a$1=[],s$1=[],c=[];for(let u of e){if(!u.content)continue;let h=ui(u,t,{isSrcDir:o$1?.isSrcDir,framework:o$1?.framework.name,commonRoot:hi(e.map(k=>k.path),u.path)});if(!h)continue;let y=basename(u.path),R=x__default.dirname(h);t.tsx||(h=h.replace(/\.tsx?$/,k=>k===".tsx"?".jsx":".js"));let g=existsSync(h),b=await ke({filename:u.path,raw:u.content,config:t,baseColor:n,transformJsx:!t.tsx,isRemote:r$1.isRemote},[ve,Pe,Se,Ce,Re]);if(g){let k=await promises.readFile(h,"utf-8"),[v,E]=await Promise.all([zt(k),zt(b)]);if(v===E){c.push(x__default.relative(t.resolvedPaths.cwd,h));continue}}if(g&&!r$1.overwrite){i.stop(),r$1.rootSpinner&&r$1.rootSpinner.stop();let{overwrite:k}=await Ye({type:"confirm",name:"overwrite",message:`The file ${a.info(y)} already exists. Would you like to overwrite?`,initial:!1});if(!k){c.push(x__default.relative(t.resolvedPaths.cwd,h)),r$1.rootSpinner&&r$1.rootSpinner.start();continue}i?.start(),r$1.rootSpinner&&r$1.rootSpinner.start();}existsSync(R)||await promises.mkdir(R,{recursive:!0}),await promises.writeFile(h,b,"utf-8"),g?s$1.push(x__default.relative(t.resolvedPaths.cwd,h)):a$1.push(x__default.relative(t.resolvedPaths.cwd,h));}let l=[...a$1,...s$1,...c],f=await xi(l,t);if(s$1.push(...f),s$1=s$1.filter(u=>!a$1.includes(u)),!(a$1.length||s$1.length)&&!c.length&&i?.info("No files updated."),a$1=Array.from(new Set(a$1)),s$1=Array.from(new Set(s$1)),c=Array.from(new Set(c)),a$1.length){if(i?.succeed(`Created ${a$1.length} ${a$1.length===1?"file":"files"}:`),!r$1.silent)for(let u of a$1)r.log(` - ${u}`);}else i?.stop();if(s$1.length&&(s(`Updated ${s$1.length} ${s$1.length===1?"file":"files"}:`,{silent:r$1.silent})?.info(),!r$1.silent))for(let u of s$1)r.log(` - ${u}`);if(c.length&&(s(`Skipped ${c.length} ${s$1.length===1?"file":"files"}: (files might be identical, use --overwrite to overwrite)`,{silent:r$1.silent})?.info(),!r$1.silent))for(let u of c)r.log(` - ${u}`);return r$1.silent||r.break(),{filesCreated:a$1,filesUpdated:s$1,filesSkipped:c}}function ui(e,t,r){if(e.target){if(e.target.startsWith("~/"))return x__default.join(t.resolvedPaths.cwd,e.target.replace("~/",""));let n=e.target;return e.type==="registry:page"&&(n=wi(n,r.framework),!n)?"":r.isSrcDir?x__default.join(t.resolvedPaths.cwd,"src",n.replace("src/","")):x__default.join(t.resolvedPaths.cwd,n.replace("src/",""))}let i=gi(e,t),o=yi(e.path,i);return x__default.join(i,o)}function gi(e,t){return e.type==="registry:ui"?t.resolvedPaths.ui:e.type==="registry:lib"?t.resolvedPaths.lib:e.type==="registry:block"||e.type==="registry:component"?t.resolvedPaths.components:e.type==="registry:hook"?t.resolvedPaths.hooks:t.resolvedPaths.components}function hi(e,t){let r=e.map(a=>a.replace(/^\//,"")),i=t.replace(/^\//,""),o=i.split("/").slice(0,-1).join("/");if(!o)return "";let n=o.split("/");for(let a=n.length;a>0;a--){let s=n.slice(0,a).join("/");if(r.some(l=>l!==i&&l.startsWith(s+"/")))return "/"+s}return "/"+o}function yi(e,t){let r=e.replace(/^\/|\/$/g,""),i=t.replace(/^\/|\/$/g,""),o=r.split("/"),n=i.split("/"),a=n[n.length-1],s=o.findIndex(c=>c===a);return s===-1?o[o.length-1]:o.slice(s+1).join("/")}async function zt(e){return e.replace(/\r\n/g,`
|
|
67
|
-
`).trim()}function wi(e,t){if(!t)return "";if(t==="next-app")return e;if(t==="next-pages"){let r=e.replace(/^app\//,"pages/");return r=r.replace(/\/page(\.[jt]sx?)$/,"$1"),r}if(t==="react-router"){let r=e.replace(/^app\//,"app/routes/");return r=r.replace(/\/page(\.[jt]sx?)$/,"$1"),r}if(t==="laravel"){let r=e.replace(/^app\//,"resources/js/pages/");return r=r.replace(/\/page(\.[jt]sx?)$/,"$1"),r}return ""}async function xi(e,t){let r=new Project({compilerOptions:{}}),i=await o(t.resolvedPaths.cwd),o$1=await loadConfig(t.resolvedPaths.cwd),n=[];if(!i||o$1.resultType==="failed")return [];for(let a of e){let s=x__default.resolve(t.resolvedPaths.cwd,a);if(!existsSync(s))continue;let c=await promises.readFile(s,"utf-8"),l=await promises.mkdtemp(x__default.join(tmpdir(),"shadcn-")),f=r.createSourceFile(x__default.join(l,basename(s)),c,{scriptKind:ScriptKind.TSX});if(![".tsx",".ts",".jsx",".js"].includes(f.getExtension()))continue;let m=f.getImportDeclarations();for(let u of m){let h=u.getModuleSpecifierValue();if(i?.aliasPrefix&&!h.startsWith(`${i.aliasPrefix}/`))continue;let y=await b(h,o$1);if(!y)continue;let R=bi(y,e,t);if(!R)continue;let g=Si(R,t,i);!g||g===h||(u.setModuleSpecifier(g),await promises.writeFile(s,f.getFullText(),"utf-8"),n.push(a));}}return n}function bi(e,t,r,i=[".tsx",".ts",".js",".jsx",".css"]){let o=x__default.normalize(r.resolvedPaths.cwd),n=t.map(g=>g.split(x__default.sep).join(x__default.posix.sep)),a=new Set(n),s=x__default.extname(e),c=s!=="",l=c?e.slice(0,-s.length):e,m=x__default.relative(o,l).split(x__default.sep).join(x__default.posix.sep),u=c?[s]:i,h=new Set;for(let g of u){let b=l+g,k=x__default.posix.normalize(x__default.relative(o,b));(a.has(k)||existsSync(b))&&h.add(k);let v=x__default.join(l,`index${g}`),E=x__default.posix.normalize(x__default.relative(o,v));(a.has(E)||existsSync(v))&&h.add(E);}let y=x__default.basename(l);for(let g of n)u.some(b=>g.endsWith(`/${y}${b}`))&&h.add(g);return h.size===0?null:Array.from(h).sort((g,b)=>{let k=x__default.posix.extname(g),v=x__default.posix.extname(b),E=u.indexOf(k)-u.indexOf(v);if(E!==0)return E;let j=m&&g.startsWith(m)?-1:1,_=m&&b.startsWith(m)?-1:1;return j-_})[0]}function Si(e,t,r){let i=x__default.normalize(x__default.join(t.resolvedPaths.cwd,e)),o=Object.entries(t.resolvedPaths).filter(([,y])=>y&&i.startsWith(x__default.normalize(y+x__default.sep))).sort((y,R)=>R[1].length-y[1].length);if(o.length===0)return null;let[n,a]=o[0],s=x__default.relative(a,i);s=s.split(x__default.sep).join("/");let c=x__default.posix.extname(s),f=[".ts",".tsx",".js",".jsx"].includes(c)?"":c,m=s.slice(0,s.length-c.length);m.endsWith("/index")&&(m=m.slice(0,-6));let u=n==="cwd"?r.aliasPrefix:t.aliases[n];if(!u)return null;let h=m===""?"":`/${m}`;return h=h.replace("/src",""),`${u}${h}${f}`}async function ce(e,t,r){r={overwrite:!1,silent:!1,isNewProject:!1,style:"index",...r};let i=await j(t);return i&&i.ui&&i.ui.resolvedPaths.cwd!==t.resolvedPaths.cwd?await vi(e,t,i,{...r,isRemote:e?.length===1&&!!e[0].match(/\/chat\/b\//)}):await Ri(e,t,r)}async function Ri(e,t,r$1){let i=s("Checking registry.",{silent:r$1.silent})?.start(),o=await Z(e,t);if(!o)return i?.fail(),x$1(new Error("Failed to fetch components from registry."));try{Kt(o.files??[],t.resolvedPaths.cwd);}catch(s){return i?.fail(),x$1(s)}i?.succeed();let n=await q$1(t);await y(o.tailwind?.config,t,{silent:r$1.silent,tailwindVersion:n});let a=await Ut(e);await
|
|
66
|
+
`);let s=await qe([{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&&(a=s.flag);}o?.start(),await zr(n,e,t,r$1.resolvedPaths.cwd,a),o?.succeed();}function Vr(e){let t=n(e.resolvedPaths.cwd,!1);if(!t?.dependencies?.react)return !1;let r=/^(?:\^|~)?19(?:\.\d+)*(?:-.*)?$/.test(t.dependencies.react),i=t.dependencies["react-day-picker"]?.startsWith("8");return r&&i}async function Mr(e){return n(e.resolvedPaths.cwd,!1)?.dependencies?.expo?"expo":be(e.resolvedPaths.cwd)}async function zr(e,t,r,i,o){if(e==="npm")return Wr(t,r,i,o);if(e==="deno")return Br(t,r,i);if(e==="expo")return Ur(t,r,i);t?.length&&await execa(e,["add",...t],{cwd:i}),r?.length&&await execa(e,["add","-D",...r],{cwd:i});}async function Wr(e,t,r,i){e.length&&await execa("npm",["install",...i?[`--${i}`]:[],...e],{cwd:r}),t.length&&await execa("npm",["install",...i?[`--${i}`]:[],"-D",...t],{cwd:r});}async function Br(e,t,r){e?.length&&await execa("deno",["add",...e.map(i=>`npm:${i}`)],{cwd:r}),t?.length&&await execa("deno",["add","-D",...t.map(i=>`npm:${i}`)],{cwd:r});}async function Ur(e,t,r){e.length&&await execa("npx",["expo","install",...e],{cwd:r}),t.length&&await execa("npx",["expo","install","-- -D",...t],{cwd:r});}var Se=async({sourceFile:e,config:t,baseColor:r})=>(t.tailwind?.cssVariables||!r?.inlineColors||e.getDescendantsOfKind(SyntaxKind.StringLiteral).forEach(i=>{let o=i.getText();if(o){let n=Jr(o.replace(/"/g,""),r.inlineColors);i.replaceWithText(`"${n.trim()}"`);}}),e);function Ke(e){if(!e.includes("/")&&!e.includes(":"))return [null,e,null];let t=[],[r,i]=e.split("/");if(!r.includes(":"))return [null,r,i];let o=r.split(":"),n=o.pop(),a=o.join(":");return t.push(a??null,n??null,i??null),t}var Gr=["bg-","text-","border-","ring-offset-","ring-"];function Jr(e,t){e.includes(" border ")&&(e=e.replace(" border "," border border-border "));let r=e.split(" "),i=new Set,o=new Set;for(let n of r){let[a,s,c]=Ke(n),l=Gr.find(m=>s?.startsWith(m));if(!l){i.has(n)||i.add(n);continue}let f=s?.replace(l,"");if(f&&f in t.light){i.add([a,`${l}${t.light[f]}`].filter(Boolean).join(":")+(c?`/${c}`:"")),o.add(["dark",a,`${l}${t.dark[f]}`].filter(Boolean).join(":")+(c?`/${c}`:""));continue}i.has(n)||i.add(n);}return [...Array.from(i),...Array.from(o)].join(" ").trim()}var F={lucide:{name:"lucide-react",package:"lucide-react",import:"lucide-react"},radix:{name:"@radix-ui/react-icons",package:"@radix-ui/react-icons",import:"@radix-ui/react-icons"}};var Lt="lucide",Re=async({sourceFile:e,config:t})=>{if(!t.iconLibrary||!(t.iconLibrary in F))return e;let r=await Q$1(),i=Lt,o=t.iconLibrary;if(i===o)return e;let n=[];for(let a of e.getImportDeclarations()??[])if(a.getModuleSpecifier()?.getText()===`"${F[Lt].import}"`){for(let s of a.getNamedImports()??[]){let c=s.getName(),l=r[c]?.[o];!l||n.includes(l)||(n.push(l),s.remove(),e.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement).filter(f=>f.getTagNameNode()?.getText()===c).forEach(f=>f.getTagNameNode()?.replaceWithText(l)));}a.getNamedImports()?.length===0&&a.remove();}if(n.length>0){let a=e.addImportDeclaration({moduleSpecifier:F[o]?.import,namedImports:n.map(s=>({name:s}))});qr(e)||a.replaceWithText(a.getText().replace(";",""));}return e};function qr(e){return e.getImportDeclarations()?.[0]?.getText().endsWith(";")??!1}var ve=async({sourceFile:e,config:t,isRemote:r})=>{let o=`@${t.aliases?.utils?.split("/")[0]?.slice(1)}/lib/utils`,n=e.getImportDeclarations();if(![".tsx",".ts",".jsx",".js"].includes(e.getExtension()))return e;for(let a of n){let s=Hr(a.getModuleSpecifierValue(),t,r);a.setModuleSpecifier(s),(o===s||s==="@/lib/utils")&&a.getNamedImports().find(f=>f.getName()==="cn")&&a.setModuleSpecifier(o===s?s.replace(o,t.aliases.utils):t.aliases.utils);}return e};function Hr(e,t,r=!1){if(!e.startsWith("@/")&&!r)return e;if(r&&e.startsWith("@/")&&(e=e.replace(/^@\//,"@/registry/new-york/")),!e.startsWith("@/registry/")){let i=t.aliases.components.split("/")[0];return e.replace(/^@\//,`${i}/`)}return e.match(/^@\/registry\/(.+)\/ui/)?e.replace(/^@\/registry\/(.+)\/ui/,t.aliases.ui??`${t.aliases.components}/ui`):t.aliases.components&&e.match(/^@\/registry\/(.+)\/components/)?e.replace(/^@\/registry\/(.+)\/components/,t.aliases.components):t.aliases.lib&&e.match(/^@\/registry\/(.+)\/lib/)?e.replace(/^@\/registry\/(.+)\/lib/,t.aliases.lib):t.aliases.hooks&&e.match(/^@\/registry\/(.+)\/hooks/)?e.replace(/^@\/registry\/(.+)\/hooks/,t.aliases.hooks):e.replace(/^@\/registry\/[^/]+/,t.aliases.components)}var ei={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"]},Vt=async({sourceFile:e,config:t})=>{let r=e.getFullText();if(t.tsx)return r;let i=Ie.parse(r,{parser:{parse:n=>parse(n,ei)}}),o=transformFromAstSync(i,r,{cloneInputAst:!1,code:!1,ast:!0,plugins:[Zr],configFile:!1});if(!o||!o.ast)throw new Error("Failed to transform JSX");return Ie.print(o.ast).code};var ri=/^["']use client["']$/g,Pe=async({sourceFile:e,config:t})=>{if(t.rsc)return e;let r=e.getFirstChildByKind(SyntaxKind.ExpressionStatement);return r&&ri.test(r.getText())&&r.remove(),e};var Ce=async({sourceFile:e,config:t})=>{if(!t.tailwind?.prefix)return e;let r=await q$1(t);return e.getDescendantsOfKind(SyntaxKind.CallExpression).filter(i=>i.getExpression().getText()==="cva").forEach(i=>{if(i.getArguments()[0]?.isKind(SyntaxKind.StringLiteral)){let o=i.getArguments()[0];o&&o.replaceWithText(`"${B(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix,r)}"`);}i.getArguments()[1]?.isKind(SyntaxKind.ObjectLiteralExpression)&&i.getArguments()[1]?.getDescendantsOfKind(SyntaxKind.PropertyAssignment).find(o=>o.getName()==="variants")?.getDescendantsOfKind(SyntaxKind.PropertyAssignment).forEach(o=>{o.getDescendantsOfKind(SyntaxKind.PropertyAssignment).forEach(n=>{let a=n.getInitializerIfKind(SyntaxKind.StringLiteral);a&&a?.replaceWithText(`"${B(a.getText()?.replace(/"|'/g,""),t.tailwind.prefix,r)}"`);});});}),e.getDescendantsOfKind(SyntaxKind.JsxAttribute).forEach(i=>{if(i.getName()==="className"){if(i.getInitializer()?.isKind(SyntaxKind.StringLiteral)){let o=i.getInitializer();o&&o.replaceWithText(`"${B(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix,r)}"`);}if(i.getInitializer()?.isKind(SyntaxKind.JsxExpression)){let o=i.getInitializer()?.getDescendantsOfKind(SyntaxKind.CallExpression).find(n=>n.getExpression().getText()==="cn");o&&o.getArguments().forEach(n=>{(n.isKind(SyntaxKind.ConditionalExpression)||n.isKind(SyntaxKind.BinaryExpression))&&n.getChildrenOfKind(SyntaxKind.StringLiteral).forEach(a=>{a.replaceWithText(`"${B(a.getText()?.replace(/"|'/g,""),t.tailwind.prefix,r)}"`);}),n.isKind(SyntaxKind.StringLiteral)&&n.replaceWithText(`"${B(n.getText()?.replace(/"|'/g,""),t.tailwind.prefix,r)}"`);});}}i.getName()==="classNames"&&i.getInitializer()?.isKind(SyntaxKind.JsxExpression)&&i.getDescendantsOfKind(SyntaxKind.PropertyAssignment).forEach(o=>{if(o.getInitializer()?.isKind(SyntaxKind.CallExpression)){let n=o.getInitializerIfKind(SyntaxKind.CallExpression);n&&n.getArguments().forEach(a=>{a.isKind(SyntaxKind.ConditionalExpression)&&a.getChildrenOfKind(SyntaxKind.StringLiteral).forEach(s=>{s.replaceWithText(`"${B(s.getText()?.replace(/"|'/g,""),t.tailwind.prefix,r)}"`);}),a.isKind(SyntaxKind.StringLiteral)&&a.replaceWithText(`"${B(a.getText()?.replace(/"|'/g,""),t.tailwind.prefix,r)}"`);});}if(o.getInitializer()?.isKind(SyntaxKind.StringLiteral)&&o.getName()!=="variant"){let n=o.getInitializer();n&&n.replaceWithText(`"${B(n.getText()?.replace(/"|'/g,""),t.tailwind.prefix,r)}"`);}});}),e};function B(e,t="",r){return r==="v3"?e.split(" ").map(i=>{let[o,n,a]=Ke(i);return o?a?`${o}:${t}${n}/${a}`:`${o}:${t}${n}`:a?`${t}${n}/${a}`:`${t}${n}`}).join(" "):e.split(" ").map(i=>i.indexOf(`${t}:`)===0?i:`${t}:${i.trim()}`).join(" ")}var ai=new Project({compilerOptions:{}});async function ci(e){let t=await promises.mkdtemp(x__default.join(tmpdir(),"shadcn-"));return x__default.join(t,e)}async function ke(e,t=[ve,Pe,Se,Ce,Re]){let r=await ci(e.filename),i=ai.createSourceFile(r,e.raw,{scriptKind:ScriptKind.TSX});for(let o of t)await o({sourceFile:i,...e});return e.transformJsx?await Vt({sourceFile:i,...e}):i.getText()}async function Ge(e,t,r$1){if(!e?.length)return {filesCreated:[],filesUpdated:[],filesSkipped:[]};r$1={overwrite:!1,force:!1,silent:!1,isRemote:!1,...r$1};let i=s("Updating files.",{silent:r$1.silent})?.start(),[o$1,n]=await Promise.all([o(t.resolvedPaths.cwd),t.tailwind.baseColor?T(t.tailwind.baseColor):Promise.resolve(void 0)]),a$1=[],s$1=[],c=[];for(let u of e){if(!u.content)continue;let h=ui(u,t,{isSrcDir:o$1?.isSrcDir,framework:o$1?.framework.name,commonRoot:hi(e.map(k=>k.path),u.path)});if(!h)continue;let y=basename(u.path),R=x__default.dirname(h);t.tsx||(h=h.replace(/\.tsx?$/,k=>k===".tsx"?".jsx":".js"));let g=existsSync(h),b=await ke({filename:u.path,raw:u.content,config:t,baseColor:n,transformJsx:!t.tsx,isRemote:r$1.isRemote},[ve,Pe,Se,Ce,Re]);if(g){let k=await promises.readFile(h,"utf-8"),[v,E]=await Promise.all([zt(k),zt(b)]);if(v===E){c.push(x__default.relative(t.resolvedPaths.cwd,h));continue}}if(g&&!r$1.overwrite){i.stop(),r$1.rootSpinner&&r$1.rootSpinner.stop();let{overwrite:k}=await qe({type:"confirm",name:"overwrite",message:`The file ${a.info(y)} already exists. Would you like to overwrite?`,initial:!1});if(!k){c.push(x__default.relative(t.resolvedPaths.cwd,h)),r$1.rootSpinner&&r$1.rootSpinner.start();continue}i?.start(),r$1.rootSpinner&&r$1.rootSpinner.start();}existsSync(R)||await promises.mkdir(R,{recursive:!0}),await promises.writeFile(h,b,"utf-8"),g?s$1.push(x__default.relative(t.resolvedPaths.cwd,h)):a$1.push(x__default.relative(t.resolvedPaths.cwd,h));}let l=[...a$1,...s$1,...c],f=await xi(l,t);if(s$1.push(...f),s$1=s$1.filter(u=>!a$1.includes(u)),!(a$1.length||s$1.length)&&!c.length&&i?.info("No files updated."),a$1=Array.from(new Set(a$1)),s$1=Array.from(new Set(s$1)),c=Array.from(new Set(c)),a$1.length){if(i?.succeed(`Created ${a$1.length} ${a$1.length===1?"file":"files"}:`),!r$1.silent)for(let u of a$1)r.log(` - ${u}`);}else i?.stop();if(s$1.length&&(s(`Updated ${s$1.length} ${s$1.length===1?"file":"files"}:`,{silent:r$1.silent})?.info(),!r$1.silent))for(let u of s$1)r.log(` - ${u}`);if(c.length&&(s(`Skipped ${c.length} ${s$1.length===1?"file":"files"}: (files might be identical, use --overwrite to overwrite)`,{silent:r$1.silent})?.info(),!r$1.silent))for(let u of c)r.log(` - ${u}`);return r$1.silent||r.break(),{filesCreated:a$1,filesUpdated:s$1,filesSkipped:c}}function ui(e,t,r){if(e.target){if(e.target.startsWith("~/"))return x__default.join(t.resolvedPaths.cwd,e.target.replace("~/",""));let n=e.target;return e.type==="registry:page"&&(n=wi(n,r.framework),!n)?"":r.isSrcDir?x__default.join(t.resolvedPaths.cwd,"src",n.replace("src/","")):x__default.join(t.resolvedPaths.cwd,n.replace("src/",""))}let i=gi(e,t),o=yi(e.path,i);return x__default.join(i,o)}function gi(e,t){return e.type==="registry:ui"?t.resolvedPaths.ui:e.type==="registry:lib"?t.resolvedPaths.lib:e.type==="registry:block"||e.type==="registry:component"?t.resolvedPaths.components:e.type==="registry:hook"?t.resolvedPaths.hooks:t.resolvedPaths.components}function hi(e,t){let r=e.map(a=>a.replace(/^\//,"")),i=t.replace(/^\//,""),o=i.split("/").slice(0,-1).join("/");if(!o)return "";let n=o.split("/");for(let a=n.length;a>0;a--){let s=n.slice(0,a).join("/");if(r.some(l=>l!==i&&l.startsWith(s+"/")))return "/"+s}return "/"+o}function yi(e,t){let r=e.replace(/^\/|\/$/g,""),i=t.replace(/^\/|\/$/g,""),o=r.split("/"),n=i.split("/"),a=n[n.length-1],s=o.findIndex(c=>c===a);return s===-1?o[o.length-1]:o.slice(s+1).join("/")}async function zt(e){return e.replace(/\r\n/g,`
|
|
67
|
+
`).trim()}function wi(e,t){if(!t)return "";if(t==="next-app")return e;if(t==="next-pages"){let r=e.replace(/^app\//,"pages/");return r=r.replace(/\/page(\.[jt]sx?)$/,"$1"),r}if(t==="react-router"){let r=e.replace(/^app\//,"app/routes/");return r=r.replace(/\/page(\.[jt]sx?)$/,"$1"),r}if(t==="laravel"){let r=e.replace(/^app\//,"resources/js/pages/");return r=r.replace(/\/page(\.[jt]sx?)$/,"$1"),r}return ""}async function xi(e,t){let r=new Project({compilerOptions:{}}),i=await o(t.resolvedPaths.cwd),o$1=await loadConfig(t.resolvedPaths.cwd),n=[];if(!i||o$1.resultType==="failed")return [];for(let a of e){let s=x__default.resolve(t.resolvedPaths.cwd,a);if(!existsSync(s))continue;let c=await promises.readFile(s,"utf-8"),l=await promises.mkdtemp(x__default.join(tmpdir(),"shadcn-")),f=r.createSourceFile(x__default.join(l,basename(s)),c,{scriptKind:ScriptKind.TSX});if(![".tsx",".ts",".jsx",".js"].includes(f.getExtension()))continue;let m=f.getImportDeclarations();for(let u of m){let h=u.getModuleSpecifierValue();if(i?.aliasPrefix&&!h.startsWith(`${i.aliasPrefix}/`))continue;let y=await b(h,o$1);if(!y)continue;let R=bi(y,e,t);if(!R)continue;let g=Si(R,t,i);!g||g===h||(u.setModuleSpecifier(g),await promises.writeFile(s,f.getFullText(),"utf-8"),n.push(a));}}return n}function bi(e,t,r,i=[".tsx",".ts",".js",".jsx",".css"]){let o=x__default.normalize(r.resolvedPaths.cwd),n=t.map(g=>g.split(x__default.sep).join(x__default.posix.sep)),a=new Set(n),s=x__default.extname(e),c=s!=="",l=c?e.slice(0,-s.length):e,m=x__default.relative(o,l).split(x__default.sep).join(x__default.posix.sep),u=c?[s]:i,h=new Set;for(let g of u){let b=l+g,k=x__default.posix.normalize(x__default.relative(o,b));(a.has(k)||existsSync(b))&&h.add(k);let v=x__default.join(l,`index${g}`),E=x__default.posix.normalize(x__default.relative(o,v));(a.has(E)||existsSync(v))&&h.add(E);}let y=x__default.basename(l);for(let g of n)u.some(b=>g.endsWith(`/${y}${b}`))&&h.add(g);return h.size===0?null:Array.from(h).sort((g,b)=>{let k=x__default.posix.extname(g),v=x__default.posix.extname(b),E=u.indexOf(k)-u.indexOf(v);if(E!==0)return E;let j=m&&g.startsWith(m)?-1:1,_=m&&b.startsWith(m)?-1:1;return j-_})[0]}function Si(e,t,r){let i=x__default.normalize(x__default.join(t.resolvedPaths.cwd,e)),o=Object.entries(t.resolvedPaths).filter(([,y])=>y&&i.startsWith(x__default.normalize(y+x__default.sep))).sort((y,R)=>R[1].length-y[1].length);if(o.length===0)return null;let[n,a]=o[0],s=x__default.relative(a,i);s=s.split(x__default.sep).join("/");let c=x__default.posix.extname(s),f=[".ts",".tsx",".js",".jsx"].includes(c)?"":c,m=s.slice(0,s.length-c.length);m.endsWith("/index")&&(m=m.slice(0,-6));let u=n==="cwd"?r.aliasPrefix:t.aliases[n];if(!u)return null;let h=m===""?"":`/${m}`;return h=h.replace("/src",""),`${u}${h}${f}`}async function ce(e,t,r){r={overwrite:!1,silent:!1,isNewProject:!1,style:"index",...r};let i=await j(t);return i&&i.ui&&i.ui.resolvedPaths.cwd!==t.resolvedPaths.cwd?await vi(e,t,i,{...r,isRemote:e?.length===1&&!!e[0].match(/\/chat\/b\//)}):await Ri(e,t,r)}async function Ri(e,t,r$1){let i=s("Checking registry.",{silent:r$1.silent})?.start(),o=await Z(e,t);if(!o)return i?.fail(),x$1(new Error("Failed to fetch components from registry."));try{Kt(o.files??[],t.resolvedPaths.cwd);}catch(s){return i?.fail(),x$1(s)}i?.succeed();let n=await q$1(t);await y(o.tailwind?.config,t,{silent:r$1.silent,tailwindVersion:n});let a=await Ut(e,t);await Ue(o.cssVars,t,{cleanupDefaultNextStyles:r$1.isNewProject,silent:r$1.silent,tailwindVersion:n,tailwindConfig:o.tailwind?.config,overwriteCssVars:a,initIndex:r$1.style?r$1.style==="index":!1}),await Be(o.css,t,{silent:r$1.silent}),await H(o.dependencies,o.devDependencies,t,{silent:r$1.silent}),await Ge(o.files,t,{overwrite:r$1.overwrite,silent:r$1.silent}),o.docs&&r.info(o.docs);}async function vi(e,t,r$1,i){let o=s("Checking registry.",{silent:i.silent})?.start(),n=await aa(e,t),a=await X$1(n),s$1=z.array(G).parse(a);if(!s$1)return o?.fail(),x$1(new Error("Failed to fetch components from registry."));o?.succeed();let c=ca(s$1),l$1=ba(),f=[],m=[],u=[],h=s$1.flatMap(g=>g.files??[]);try{Kt(h,t.resolvedPaths.cwd);}catch(g){return x$1(g)}let y$1=s("Installing components.")?.start();for(let g of s$1){let b=l$1.get(g.type),k$1=c.get(g.name);if(!b)continue;let v=g.type==="registry:ui"||k$1?.type==="registry:ui"?r$1.ui:t,E=await q$1(v),j=l(t.resolvedPaths.cwd,v.resolvedPaths.ui),_=await k(j,v.resolvedPaths.cwd)??v.resolvedPaths.cwd;if(g.tailwind?.config&&(await y(g.tailwind?.config,v,{silent:!0,tailwindVersion:E}),m.push(x__default.relative(j,v.resolvedPaths.tailwindConfig))),g.cssVars){let K=await Ut(e,t);await Ue(g.cssVars,v,{silent:!0,tailwindVersion:E,tailwindConfig:g.tailwind?.config,overwriteCssVars:K}),m.push(x__default.relative(j,v.resolvedPaths.tailwindCss));}g.css&&(await Be(g.css,v,{silent:!0}),m.push(x__default.relative(j,v.resolvedPaths.tailwindCss))),await H(g.dependencies,g.devDependencies,v,{silent:!0});let oe=await Ge(g.files,v,{overwrite:i.overwrite,silent:!0,rootSpinner:y$1,isRemote:i.isRemote});f.push(...oe.filesCreated.map(K=>x__default.relative(j,x__default.join(_,K)))),m.push(...oe.filesUpdated.map(K=>x__default.relative(j,x__default.join(_,K)))),u.push(...oe.filesSkipped.map(K=>x__default.relative(j,x__default.join(_,K))));}if(y$1?.succeed(),f.sort(),m.sort(),u.sort(),!(f.length||m.length)&&!u.length&&s("No files updated.",{silent:i.silent})?.info(),f.length){s(`Created ${f.length} ${f.length===1?"file":"files"}:`,{silent:i.silent})?.succeed();for(let g of f)r.log(` - ${g}`);}if(m.length){s(`Updated ${m.length} ${m.length===1?"file":"files"}:`,{silent:i.silent})?.info();for(let g of m)r.log(` - ${g}`);}if(u.length){s(`Skipped ${u.length} ${m.length===1?"file":"files"}: (use --overwrite to overwrite)`,{silent:i.silent})?.info();for(let g of u)r.log(` - ${g}`);}}async function Ut(e,t){let r=await aa(e,t),i=await X$1(r);return z.array(G).parse(i).some(n=>n.type==="registry:theme"||n.type==="registry:style")}function Kt(e,t){for(let r of e)if(r?.target&&!$t(r.target,t))throw new Error(`We found an unsafe file path "${r.target} in the registry item. Installation aborted.`)}var Ci="https://codeload.github.com/shadcn-ui/ui/tar.gz/main",X={next:"next","next-monorepo":"next-monorepo"};async function Te(e){e={srcDir:!1,...e};let t=e.template&&X[e.template]?e.template:"next",r$1=t===X.next?"my-app":"my-monorepo",i="latest",o=e.components?.length===1&&!!e.components[0].match(/\/chat\/b\//);if(e.components&&o)try{let[s]=await X$1(e.components),{meta:c}=z.object({meta:z.object({nextVersion:z.string()})}).parse(s);i=c.nextVersion,t=X.next;}catch(s){r.break(),x$1(s);}if(!e.force){let{type:s,name:c}=await qe([{type:e.template||o?null:"select",name:"type",message:`The path ${a.info(e.cwd)} does not contain a package.json file.
|
|
68
68
|
Would you like to start a new project?`,choices:[{title:"Next.js",value:"next"},{title:"Next.js (Monorepo)",value:"next-monorepo"}],initial:0},{type:"text",name:"name",message:"What is your project named?",initial:r$1,format:l=>l.trim(),validate:l=>l.length>128?"Name should be less than 128 characters.":!0}]);t=s??t,r$1=c;}let n=await be(e.cwd,{withFallback:!0}),a$1=`${e.cwd}/${r$1}`;try{await Q.access(e.cwd,Q.constants.W_OK);}catch{r.break(),r.error(`The path ${a.info(e.cwd)} is not writable.`),r.error(`It is likely you do not have write permissions for this folder or the path ${a.info(e.cwd)} does not exist.`),r.break(),process.exit(1);}return Q.existsSync(x__default.resolve(e.cwd,r$1,"package.json"))&&(r.break(),r.error(`A project with the name ${a.info(r$1)} already exists.`),r.error("Please choose a different name and try again."),r.break(),process.exit(1)),t===X.next&&await ki(a$1,{version:i,cwd:e.cwd,packageManager:n,srcDir:!!e.srcDir}),t===X["next-monorepo"]&&await ji(a$1,{packageManager:n}),{projectPath:a$1,projectName:r$1,template:t}}async function ki(e,t){let r$1=s("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")||t.version.startsWith("latest")||t.version.startsWith("canary"))&&i.push("--turbopack");try{await execa("npx",[`create-next-app@${t.version}`,e,"--silent",...i],{cwd:t.cwd});}catch{r.break(),r.error("Something went wrong creating a new Next.js project. Please try again."),process.exit(1);}r$1?.succeed("Creating a new Next.js project.");}async function ji(e,t){let r=s("Creating a new Next.js monorepo. This may take a few minutes.").start();try{let i=x__default.join(Ii.tmpdir(),`shadcn-template-${Date.now()}`);await Q.ensureDir(i);let o=await fetch(Ci);if(!o.ok)throw new Error(`Failed to download template: ${o.statusText}`);let n=x__default.resolve(i,"template.tar.gz");await Q.writeFile(n,Buffer.from(await o.arrayBuffer())),await execa("tar",["-xzf",n,"-C",i,"--strip-components=2","ui-main/templates/monorepo-next"]);let a=x__default.resolve(i,"monorepo-next");await Q.move(a,e),await Q.remove(i),await execa(t.packageManager,["install"],{cwd:e});let s=process.cwd();await execa("git",["--version"],{cwd:e}),await execa("git",["init"],{cwd:e}),await execa("git",["add","-A"],{cwd:e}),await execa("git",["commit","-m","Initial commit"],{cwd:e}),await execa("cd",[s]),r?.succeed("Creating a new Next.js monorepo.");}catch(i){r?.fail("Something went wrong creating a new Next.js monorepo."),x$1(i);}}async function Jt(e,t,r){if(!e)return;r={silent:!1,...r};let i=x__default.relative(t.resolvedPaths.cwd,t.resolvedPaths.tailwindConfig),o=s(`Updating ${a.info(i)}`,{silent:r.silent}).start(),n=await promises.readFile(t.resolvedPaths.tailwindConfig,"utf8"),a$1=await Ei(n,e,t);await promises.writeFile(t.resolvedPaths.tailwindConfig,a$1,"utf8"),o?.succeed();}async function Ei(e,t,r){let i=await z$1(e,r),o=i.getDescendantsOfKind(SyntaxKind.ObjectLiteralExpression).find(n=>n.getProperties().some(a=>a.isKind(SyntaxKind.PropertyAssignment)&&a.getName()==="content"));return o?($i(o,t),i.getFullText()):e}async function $i(e,t){let r=A$1(e),i=e.getProperty("content");if(!i){let o={name:"content",initializer:`[${r}${t.join(`${r}, ${r}`)}${r}]`};return e.addPropertyAssignment(o),e}if(i.isKind(SyntaxKind.PropertyAssignment)){let o=i.getInitializer();if(o?.isKind(SyntaxKind.ArrayLiteralExpression))for(let n of t){let a=`${r}${n}${r}`;o.getElements().map(s=>s.getText()).includes(a)||o.addElement(a);}return e}return e}var Ai=z.object({cwd:z.string(),components:z.array(z.string()).optional(),yes:z.boolean(),defaults:z.boolean(),force:z.boolean(),silent:z.boolean(),isNewProject:z.boolean(),srcDir:z.boolean().optional(),cssVariables:z.boolean(),template:z.string().optional().refine(e=>e?X[e]:!0,{message:"Invalid template. Please use 'next' or 'next-monorepo'."}),baseColor:z.string().optional().refine(e=>e?N.find(t=>t.name===e):!0,{message:`Invalid base color. Please use '${N.map(e=>e.name).join("', '")}'`}),style:z.string()}),Yt=new Command().name("init").description("initialize your project and install dependencies").argument("[components...]","names, url or local path to component").option("-t, --template <template>","the template to use. (next, next-monorepo)").option("-b, --base-color <base-color>","the base color to use. (neutral, gray, zinc, stone, slate)",void 0).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).option("--no-src-dir","do not use the src directory when creating a new project.").option("--css-variables","use css variables for theming.",!0).option("--no-css-variables","do not use css variables for theming.").action(async(e,t)=>{try{let r$1=Ai.parse({cwd:x__default.resolve(t.cwd),isNewProject:!1,components:e,style:"index",...t});if(e.length>0&&(u(e[0])||v(e[0]))){let i=await R(e[0],"");i?.type==="registry:style"&&(r$1.baseColor="neutral",r$1.style=i.extends??"index");}await $e(r$1),r.log(`${a.success("Success!")} Project initialization completed.
|
|
69
|
-
You may now add components.`),r.break();}catch(r$1){r.break(),x$1(r$1);}});async function $e(e){let t,r;if(e.skipPreflight)t=await o(e.cwd);else {let l=await Et(e);if(l.errors[A]){let{projectPath:f,template:m}=await Te(e);f||process.exit(1),e.cwd=f,e.isNewProject=!0,r=m;}t=l.projectInfo;}if(r==="next-monorepo")return e.cwd=x__default.resolve(e.cwd,"apps/web"),await h(e.cwd);let i$1=await p(e.cwd,t),o$1=i$1?await Fi(i$1,e):await Di(await h(e.cwd));if(!e.yes){let{proceed:l}=await
|
|
69
|
+
You may now add components.`),r.break();}catch(r$1){r.break(),x$1(r$1);}});async function $e(e){let t,r;if(e.skipPreflight)t=await o(e.cwd);else {let l=await Et(e);if(l.errors[A]){let{projectPath:f,template:m}=await Te(e);f||process.exit(1),e.cwd=f,e.isNewProject=!0,r=m;}t=l.projectInfo;}if(r==="next-monorepo")return e.cwd=x__default.resolve(e.cwd,"apps/web"),await h(e.cwd);let i$1=await p(e.cwd,t),o$1=i$1?await Fi(i$1,e):await Di(await h(e.cwd));if(!e.yes){let{proceed:l}=await qe({type:"confirm",name:"proceed",message:`Write configuration to ${a.info("components.json")}. Proceed?`,initial:!0});l||process.exit(0);}let n=s("Writing components.json.").start(),a$1=x__default.resolve(e.cwd,"components.json");await promises.writeFile(a$1,JSON.stringify(o$1,null,2),"utf8"),n.succeed();let s$1=await i(e.cwd,o$1),c=[...e.style==="none"?[]:[e.style],...e.components??[]];return await ce(c,s$1,{overwrite:!0,silent:e.silent,style:e.style,isNewProject:e.isNewProject||t?.framework.name==="next-app"}),e.isNewProject&&e.srcDir&&await Jt(["./src/**/*.{js,ts,jsx,tsx,mdx}"],s$1,{silent:e.silent}),s$1}async function Di(e$1=null){let[t,r$1]=await Promise.all([P(),S()]);r.info("");let i=await qe([{type:"toggle",name:"typescript",message:`Would you like to use ${a.info("TypeScript")} (recommended)?`,initial:e$1?.tsx??!0,active:"yes",inactive:"no"},{type:"select",name:"style",message:`Which ${a.info("style")} would you like to use?`,choices:t.map(o=>({title:o.label,value:o.name}))},{type:"select",name:"tailwindBaseColor",message:`Which color would you like to use as the ${a.info("base color")}?`,choices:r$1.map(o=>({title:o.label,value:o.name}))},{type:"text",name:"tailwindCss",message:`Where is your ${a.info("global CSS")} file?`,initial:e$1?.tailwind.css??e},{type:"toggle",name:"tailwindCssVariables",message:`Would you like to use ${a.info("CSS variables")} for theming?`,initial:e$1?.tailwind.cssVariables??!0,active:"yes",inactive:"no"},{type:"text",name:"tailwindPrefix",message:`Are you using a custom ${a.info("tailwind prefix eg. tw-")}? (Leave blank if not)`,initial:""},{type:"text",name:"tailwindConfig",message:`Where is your ${a.info("tailwind.config.js")} located?`,initial:e$1?.tailwind.config??f},{type:"text",name:"components",message:`Configure the import alias for ${a.info("components")}:`,initial:e$1?.aliases.components??c},{type:"text",name:"utils",message:`Configure the import alias for ${a.info("utils")}:`,initial:e$1?.aliases.utils??d},{type:"toggle",name:"rsc",message:`Are you using ${a.info("React Server Components")}?`,initial:e$1?.rsc??!0,active:"yes",inactive:"no"}]);return g.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 Fi(e,t){let r=e.style,i=t.baseColor,o=e.tailwind.cssVariables;if(!t.defaults){let[n,a$1,s]=await Promise.all([P(),S(),q$1(e)]),c=await qe([{type:s==="v4"?null:"select",name:"style",message:`Which ${a.info("style")} would you like to use?`,choices:n.map(l=>({title:l.name==="new-york"?"New York (Recommended)":l.label,value:l.name})),initial:0},{type:t.baseColor?null:"select",name:"tailwindBaseColor",message:`Which color would you like to use as the ${a.info("base color")}?`,choices:a$1.map(l=>({title:l.label,value:l.name}))}]);r=c.style??"new-york",i=c.tailwindBaseColor??i,o=t.cssVariables;}return g.parse({$schema:e?.$schema,style:r,tailwind:{...e?.tailwind,baseColor:i,cssVariables:o},rsc:e?.rsc,tsx:e?.tsx,aliases:e?.aliases,iconLibrary:e?.iconLibrary})}async function Ht(e){let t={};if(!Q.existsSync(e.cwd)||!Q.existsSync(x__default.resolve(e.cwd,"package.json")))return t[A]=!0,{errors:t,config:null};if(!Q.existsSync(x__default.resolve(e.cwd,"components.json")))return t[D]=!0,{errors:t,config:null};try{let r=await h(e.cwd);return {errors:t,config:r}}catch{r.break(),r.error(`An invalid ${a.info("components.json")} file was found at ${a.info(e.cwd)}.
|
|
70
70
|
Before you can add components, you must create a valid ${a.info("components.json")} file by running the ${a.info("init")} command.`),r.error(`Learn more at ${a.info("https://ui.shadcn.com/docs/components-json")}.`),r.break(),process.exit(1);}}async function Qt(e,t){let r=x__default.join(t.resolvedPaths.cwd,"app/page.tsx");if(!(await M__default.stat(r)).isFile())return;let i=await R(e,t.style);if(!i?.meta?.importSpecifier||!i?.meta?.moduleSpecifier)return;let o=`import { ${i?.meta?.importSpecifier} } from "${i.meta.moduleSpecifier}"
|
|
71
71
|
|
|
72
72
|
export default function Page() {
|
|
73
73
|
return <${i?.meta?.importSpecifier} />
|
|
74
|
-
}`;await M__default.writeFile(r,o,"utf8");}var
|
|
75
|
-
Existing CSS variables and components will be overwritten. Continue?`)});l||(r.break(),r.log("Installation cancelled."),r.break(),process.exit(1));}if(r$1.components?.length||(r$1.components=await zi(r$1)),(await o(r$1.cwd))?.tailwindVersion==="v4"){let l=Xe.filter(f=>r$1.components?.includes(f.name));l?.length&&(r.break(),l.forEach(f=>{r.warn(a.warn(f.message));}),r.break(),process.exit(1));}if(w(o$1)){if(!Li.existsSync(r$1.cwd))throw new Error(`Directory ${r$1.cwd} does not exist`);let l=m({resolvedPaths:{cwd:r$1.cwd}});await ce(r$1.components,l,r$1);return}let{errors:a$1,config:s}=await Ht(r$1);if(a$1[D]){let{proceed:l}=await Ye({type:"confirm",name:"proceed",message:`You need to create a ${a.info("components.json")} file to add components. Proceed?`,initial:!0});l||(r.break(),process.exit(1)),s=await $e({cwd:r$1.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!1,silent:!0,isNewProject:!1,srcDir:r$1.srcDir,cssVariables:r$1.cssVariables,style:"index"});}let c=!1;if(a$1[A]){let{projectPath:l,template:f}=await Te({cwd:r$1.cwd,force:r$1.overwrite,srcDir:r$1.srcDir,components:r$1.components});l||(r.break(),process.exit(1)),r$1.cwd=l,f==="next-monorepo"?(r$1.cwd=x__default.resolve(r$1.cwd,"apps/web"),s=await h(r$1.cwd)):(s=await $e({cwd:r$1.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!0,silent:!0,isNewProject:!0,srcDir:r$1.srcDir,cssVariables:r$1.cssVariables,style:"index"}),c=r$1.components?.length===1&&!!r$1.components[0].match(/\/chat\/b\//));}if(!s)throw new Error(`Failed to read config at ${a.info(r$1.cwd)}.`);await ce(r$1.components,s,r$1),c&&await Qt(r$1.components[0],s);}catch(r$1){r.break(),x$1(r$1);}});async function zi(e){let t=await O();if(!t)return r.break(),x$1(new Error("Failed to fetch registry index.")),[];if(e.all)return t.map(o=>o.name).filter(o=>!Xe.some(n=>n.name===o));if(e.components?.length)return e.components;let{components:r$1}=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(o=>o.type==="registry:ui"&&!Xe.some(n=>n.name===o.name)).map(o=>({title:o.name,value:o.name,selected:e.all?!0:e.components?.includes(o.name)}))});r$1?.length||(r.warn("No components selected. Exiting."),r.info(""),process.exit(1));let i=z.array(z.string()).safeParse(r$1);return i.success?i.data:(r.error(""),x$1(new Error("Something went wrong. Please try again.")),[])}async function ir(e){let t={},r$1={cwd:e.cwd,registryFile:x__default.resolve(e.cwd,e.registryFile),outputDir:x__default.resolve(e.cwd,e.outputDir)};return Q.existsSync(r$1.registryFile)||(t[q]=!0),await Q.mkdir(r$1.outputDir,{recursive:!0}),Object.keys(t).length>0&&(t[q]&&(r.break(),r.error(`The path ${a.info(r$1.registryFile)} does not exist.`)),r.break(),process.exit(1)),{errors:t,resolvePaths:r$1}}var Bi=z.object({cwd:z.string(),registryFile:z.string(),outputDir:z.string()}),or=new Command().name("build").description("build components for a shadcn registry").argument("[registry]","path to registry.json file","./registry.json").option("-o, --output <path>","destination directory for json files","./public/r").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async(e,t)=>{try{let r$1=Bi.parse({cwd:x.resolve(t.cwd),registryFile:e,outputDir:t.output}),{resolvePaths:i}=await ir(r$1),o=await M.readFile(i.registryFile,"utf-8"),n=H$1.safeParse(JSON.parse(o));n.success||(r.error(`Invalid registry file found at ${a.info(i.registryFile)}.`),process.exit(1));let a$1=s("Building registry...");for(let s of n.data.items){if(!s.files)continue;a$1.start(`Building ${s.name}...`),s.$schema="https://ui.shadcn.com/schema/registry-item.json";for(let l of s.files)l.content=await M.readFile(x.resolve(i.cwd,l.path),"utf-8");let c=G.safeParse(s);if(!c.success){r.error(`Invalid registry item found for ${a.info(s.name)}.`);continue}await M.writeFile(x.resolve(i.outputDir,`${c.data.name}.json`),JSON.stringify(c.data,null,2));}a$1.succeed("Building registry.");}catch(r$1){r.break(),x$1(r$1);}});var Ji=z.object({component:z.string().optional(),yes:z.boolean(),cwd:z.string(),path:z.string().optional()}),sr=new Command().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$1=Ji.parse({component:e,...t}),i=x__default.resolve(r$1.cwd);existsSync(i)||(r.error(`The path ${i} does not exist. Please try again.`),process.exit(1));let o=await h(i);o||(r.warn(`Configuration is missing. Please run ${a.success("init")} to create a components.json file.`),process.exit(1));let n=await O();if(n||(x$1(new Error("Failed to fetch registry index.")),process.exit(1)),!r$1.component){let c=o.resolvedPaths.components,l=n.filter(m=>{for(let u of m.files??[]){let h=x__default.resolve(c,typeof u=="string"?u:u.path);if(existsSync(h))return !0}return !1}),f=[];for(let m of l){let u=await nr(m,o);u.length&&f.push({name:m.name,changes:u});}f.length||(r.info("No updates found."),process.exit(0)),r.info("The following components have updates available:");for(let m of f){r.info(`- ${m.name}`);for(let u of m.changes)r.info(` - ${u.filePath}`);}r.break(),r.info(`Run ${a.success("diff <component>")} to see the changes.`),process.exit(0);}let a$1=n.find(c=>c.name===r$1.component);a$1||(r.error(`The component ${a.success(r$1.component)} does not exist.`),process.exit(1));let s=await nr(a$1,o);s.length||(r.info(`No updates found for ${r$1.component}.`),process.exit(0));for(let c of s)r.info(`- ${c.filePath}`),await Yi(c.patch),r.info("");}catch(r){x$1(r);}});async function nr(e,t){let r=await V(t.style,[e]),i=await T(t.tailwind.baseColor);if(!r)return [];let o=[];for(let n of r){let a=await W(t,n);if(a)for(let s of n.files??[]){let c=x__default.resolve(a,typeof s=="string"?s:s.path);if(!existsSync(c))continue;let l=await promises.readFile(c,"utf8");if(typeof s=="string"||!s.content)continue;let f=await ke({filename:s.path,raw:s.content,config:t,baseColor:i}),m=diffLines(f,l);m.length>1&&o.push({filePath:c,patch:m});}}return o}async function Yi(e){e.forEach(t=>{if(t)return t.added?process.stdout.write(a.success(t.value)):t.removed?process.stdout.write(a.error(t.value)):process.stdout.write(t.value)});}var ar=new Command().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=>{r.info("> project info"),console.log(await o(e.cwd)),r.break(),r.info("> components.json"),console.log(await h(e.cwd));});async function lr(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$1,i]=await Promise.all([Qi("**/*.{js,ts,jsx,tsx}",{cwd:t}),Q$1()]);if(Object.keys(i).length===0)throw new Error("Something went wrong fetching the registry icons.");let o=Object.entries(F).map(([f,m])=>({title:m.name,value:f})),n=await Ye([{type:"select",name:"sourceLibrary",message:`Which icon library would you like to ${a.info("migrate from")}?`,choices:o},{type:"select",name:"targetLibrary",message:`Which icon library would you like to ${a.info("migrate to")}?`,choices:o}]);if(n.sourceLibrary===n.targetLibrary)throw new Error("You cannot migrate to the same icon library. Please choose a different icon library.");if(!(n.sourceLibrary in F&&n.targetLibrary in F))throw new Error("Invalid icon library. Please choose a valid icon library.");let a$1=F[n.sourceLibrary],s$1=F[n.targetLibrary],{confirm:c}=await Ye({type:"confirm",name:"confirm",initial:!0,message:`We will migrate ${a.info(r$1.length)} files in ${a.info(`./${x__default.relative(e.resolvedPaths.cwd,t)}`)} from ${a.info(a$1.name)} to ${a.info(s$1.name)}. Continue?`});c||(r.info("Migration cancelled."),process.exit(0)),s$1.package&&await H([s$1.package],[],e,{silent:!1});let l=s("Migrating icons...")?.start();await Promise.all(r$1.map(async f=>{l.text=`Migrating ${f}...`;let m=x__default.join(t,f),u=await promises.readFile(m,"utf-8"),h=await ro(u,n.sourceLibrary,n.targetLibrary,i);await promises.writeFile(m,h);})),l.succeed("Migration complete.");}async function ro(e,t,r,i){let o=F[t]?.import,n=F[r]?.import,a=await promises.mkdtemp(x__default.join(tmpdir(),"shadcn-")),s=new Project({compilerOptions:{}}),c=x__default.join(a,`shadcn-icons-${randomBytes(4).toString("hex")}.tsx`),l=s.createSourceFile(c,e,{scriptKind:ScriptKind.TSX}),f=[];for(let m of l.getImportDeclarations()??[])if(m.getModuleSpecifier()?.getText()===`"${o}"`){for(let u of m.getNamedImports()??[]){let h=u.getName(),y=Object.values(i).find(R=>R[t]===h)?.[r];!y||f.includes(y)||(f.push(y),u.remove(),l.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement).filter(R=>R.getTagNameNode()?.getText()===h).forEach(R=>R.getTagNameNode()?.replaceWithText(y)));}m.getNamedImports()?.length===0&&m.remove();}return f.length>0&&l.addImportDeclaration({moduleSpecifier:n,namedImports:f.map(m=>({name:m}))}),await l.getText()}function no(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function so(e,t,r,i){let n=e.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").trim().split(",").map(a=>a.trim()).filter(Boolean);for(let a of n){let s=a.match(/^type\s+(\w+)(?:\s+as\s+(\w+))?$/),c=a.match(/^(\w+)\s+as\s+(\w+)$/);if(s){let l=s[1],f=s[2];i==="slot"&&l==="Slot"&&!f?r.push({name:"Slot",alias:"SlotPrimitive",isType:!0}):r.push({name:l,alias:f,isType:!0});}else if(c){let l=c[1],f=c[2];i==="slot"&&l==="Slot"&&f==="Slot"?r.push({name:"Slot",alias:"SlotPrimitive",isType:t}):r.push({name:l,alias:f,isType:t});}else i==="slot"&&a==="Slot"?r.push({name:"Slot",alias:"SlotPrimitive",isType:t}):r.push({name:a,isType:t});}}async function pr(e,t={}){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 r$1=e.resolvedPaths.ui,i=await Qi("**/*.{js,ts,jsx,tsx}",{cwd:r$1});if(!t.yes){let{confirm:s}=await Ye({type:"confirm",name:"confirm",initial:!0,message:`We will migrate ${a.info(i.length)} files in ${a.info(`./${x__default.relative(e.resolvedPaths.cwd,r$1)}`)} to ${a.info("radix-ui")}. Continue?`});s||(r.info("Migration cancelled."),process.exit(0));}let o=s("Migrating imports...")?.start(),n$1=new Set;await Promise.all(i.map(async s=>{o.text=`Migrating ${s}...`;let c=x__default.join(r$1,s),l=await promises.readFile(c,"utf-8"),{content:f,replacedPackages:m}=await ao(l);m.forEach(u=>n$1.add(u)),await promises.writeFile(c,f);})),o.succeed("Migrating imports.");let a$1=s("Updating package.json...")?.start();try{let s=n(e.resolvedPaths.cwd,!1);if(!s){a$1.fail("Could not read package.json"),r.warn("Could not update package.json. You may need to manually replace @radix-ui/react-* packages with radix-ui");return}let c=Array.from(n$1),l=["dependencies","devDependencies"];for(let f of l)if(s[f])for(let m of c)s[f][m]&&delete s[f][m];if(c.length>0){s.dependencies||(s.dependencies={}),s.dependencies["radix-ui"]="latest";let f=x__default.join(e.resolvedPaths.cwd,"package.json");await promises.writeFile(f,JSON.stringify(s,null,2)+`
|
|
74
|
+
}`;await M__default.writeFile(r,o,"utf8");}var Qe=[{name:"toast",deprecatedBy:"sonner",message:"The toast component is deprecated. Use the sonner component instead."},{name:"toaster",deprecatedBy:"sonner",message:"The toaster component is deprecated. Use the sonner component instead."}],Mi=z.object({components:z.array(z.string()).optional(),yes:z.boolean(),overwrite:z.boolean(),cwd:z.string(),all:z.boolean(),path:z.string().optional(),silent:z.boolean(),srcDir:z.boolean().optional(),cssVariables:z.boolean()}),er=new Command().name("add").description("add a component to your project").argument("[components...]","names, url or local path to 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).option("--no-src-dir","do not use the src directory when creating a new project.").option("--css-variables","use css variables for theming.",!0).option("--no-css-variables","do not use css variables for theming.").action(async(e,t)=>{try{let r$1=Mi.parse({components:e,cwd:x__default.resolve(t.cwd),...t}),i,o$1=null;if(e.length>0&&(u(e[0])||v(e[0]))&&(o$1=await R(e[0],""),i=o$1?.type),!r$1.yes&&(i==="registry:style"||i==="registry:theme")){r.break();let{confirm:l}=await qe({type:"confirm",name:"confirm",message:a.warn(`You are about to install a new ${i.replace("registry:","")}.
|
|
75
|
+
Existing CSS variables and components will be overwritten. Continue?`)});l||(r.break(),r.log("Installation cancelled."),r.break(),process.exit(1));}if(r$1.components?.length||(r$1.components=await zi(r$1)),(await o(r$1.cwd))?.tailwindVersion==="v4"){let l=Qe.filter(f=>r$1.components?.includes(f.name));l?.length&&(r.break(),l.forEach(f=>{r.warn(a.warn(f.message));}),r.break(),process.exit(1));}if(w(o$1)){if(!Li.existsSync(r$1.cwd))throw new Error(`Directory ${r$1.cwd} does not exist`);let l=m({resolvedPaths:{cwd:r$1.cwd}});await ce(r$1.components,l,r$1);return}let{errors:a$1,config:s}=await Ht(r$1);if(a$1[D]){let{proceed:l}=await qe({type:"confirm",name:"proceed",message:`You need to create a ${a.info("components.json")} file to add components. Proceed?`,initial:!0});l||(r.break(),process.exit(1)),s=await $e({cwd:r$1.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!1,silent:!0,isNewProject:!1,srcDir:r$1.srcDir,cssVariables:r$1.cssVariables,style:"index"});}let c=!1;if(a$1[A]){let{projectPath:l,template:f}=await Te({cwd:r$1.cwd,force:r$1.overwrite,srcDir:r$1.srcDir,components:r$1.components});l||(r.break(),process.exit(1)),r$1.cwd=l,f==="next-monorepo"?(r$1.cwd=x__default.resolve(r$1.cwd,"apps/web"),s=await h(r$1.cwd)):(s=await $e({cwd:r$1.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!0,silent:!0,isNewProject:!0,srcDir:r$1.srcDir,cssVariables:r$1.cssVariables,style:"index"}),c=r$1.components?.length===1&&!!r$1.components[0].match(/\/chat\/b\//));}if(!s)throw new Error(`Failed to read config at ${a.info(r$1.cwd)}.`);await ce(r$1.components,s,r$1),c&&await Qt(r$1.components[0],s);}catch(r$1){r.break(),x$1(r$1);}});async function zi(e){let t=await O();if(!t)return r.break(),x$1(new Error("Failed to fetch registry index.")),[];if(e.all)return t.map(o=>o.name).filter(o=>!Qe.some(n=>n.name===o));if(e.components?.length)return e.components;let{components:r$1}=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(o=>o.type==="registry:ui"&&!Qe.some(n=>n.name===o.name)).map(o=>({title:o.name,value:o.name,selected:e.all?!0:e.components?.includes(o.name)}))});r$1?.length||(r.warn("No components selected. Exiting."),r.info(""),process.exit(1));let i=z.array(z.string()).safeParse(r$1);return i.success?i.data:(r.error(""),x$1(new Error("Something went wrong. Please try again.")),[])}async function ir(e){let t={},r$1={cwd:e.cwd,registryFile:x__default.resolve(e.cwd,e.registryFile),outputDir:x__default.resolve(e.cwd,e.outputDir)};return Q.existsSync(r$1.registryFile)||(t[q]=!0),await Q.mkdir(r$1.outputDir,{recursive:!0}),Object.keys(t).length>0&&(t[q]&&(r.break(),r.error(`The path ${a.info(r$1.registryFile)} does not exist.`)),r.break(),process.exit(1)),{errors:t,resolvePaths:r$1}}var Bi=z.object({cwd:z.string(),registryFile:z.string(),outputDir:z.string()}),or=new Command().name("build").description("build components for a shadcn registry").argument("[registry]","path to registry.json file","./registry.json").option("-o, --output <path>","destination directory for json files","./public/r").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async(e,t)=>{try{let r$1=Bi.parse({cwd:x.resolve(t.cwd),registryFile:e,outputDir:t.output}),{resolvePaths:i}=await ir(r$1),o=await M.readFile(i.registryFile,"utf-8"),n=H$1.safeParse(JSON.parse(o));n.success||(r.error(`Invalid registry file found at ${a.info(i.registryFile)}.`),process.exit(1));let a$1=s("Building registry...");for(let s of n.data.items){if(!s.files)continue;a$1.start(`Building ${s.name}...`),s.$schema="https://ui.shadcn.com/schema/registry-item.json";for(let l of s.files)l.content=await M.readFile(x.resolve(i.cwd,l.path),"utf-8");let c=G.safeParse(s);if(!c.success){r.error(`Invalid registry item found for ${a.info(s.name)}.`);continue}await M.writeFile(x.resolve(i.outputDir,`${c.data.name}.json`),JSON.stringify(c.data,null,2));}a$1.succeed("Building registry.");}catch(r$1){r.break(),x$1(r$1);}});var Ji=z.object({component:z.string().optional(),yes:z.boolean(),cwd:z.string(),path:z.string().optional()}),sr=new Command().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$1=Ji.parse({component:e,...t}),i=x__default.resolve(r$1.cwd);existsSync(i)||(r.error(`The path ${i} does not exist. Please try again.`),process.exit(1));let o=await h(i);o||(r.warn(`Configuration is missing. Please run ${a.success("init")} to create a components.json file.`),process.exit(1));let n=await O();if(n||(x$1(new Error("Failed to fetch registry index.")),process.exit(1)),!r$1.component){let c=o.resolvedPaths.components,l=n.filter(m=>{for(let u of m.files??[]){let h=x__default.resolve(c,typeof u=="string"?u:u.path);if(existsSync(h))return !0}return !1}),f=[];for(let m of l){let u=await nr(m,o);u.length&&f.push({name:m.name,changes:u});}f.length||(r.info("No updates found."),process.exit(0)),r.info("The following components have updates available:");for(let m of f){r.info(`- ${m.name}`);for(let u of m.changes)r.info(` - ${u.filePath}`);}r.break(),r.info(`Run ${a.success("diff <component>")} to see the changes.`),process.exit(0);}let a$1=n.find(c=>c.name===r$1.component);a$1||(r.error(`The component ${a.success(r$1.component)} does not exist.`),process.exit(1));let s=await nr(a$1,o);s.length||(r.info(`No updates found for ${r$1.component}.`),process.exit(0));for(let c of s)r.info(`- ${c.filePath}`),await Yi(c.patch),r.info("");}catch(r){x$1(r);}});async function nr(e,t){let r=await V(t.style,[e]),i=await T(t.tailwind.baseColor);if(!r)return [];let o=[];for(let n of r){let a=await W(t,n);if(a)for(let s of n.files??[]){let c=x__default.resolve(a,typeof s=="string"?s:s.path);if(!existsSync(c))continue;let l=await promises.readFile(c,"utf8");if(typeof s=="string"||!s.content)continue;let f=await ke({filename:s.path,raw:s.content,config:t,baseColor:i}),m=diffLines(f,l);m.length>1&&o.push({filePath:c,patch:m});}}return o}async function Yi(e){e.forEach(t=>{if(t)return t.added?process.stdout.write(a.success(t.value)):t.removed?process.stdout.write(a.error(t.value)):process.stdout.write(t.value)});}var ar=new Command().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=>{r.info("> project info"),console.log(await o(e.cwd)),r.break(),r.info("> components.json"),console.log(await h(e.cwd));});async function lr(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$1,i]=await Promise.all([Qi("**/*.{js,ts,jsx,tsx}",{cwd:t}),Q$1()]);if(Object.keys(i).length===0)throw new Error("Something went wrong fetching the registry icons.");let o=Object.entries(F).map(([f,m])=>({title:m.name,value:f})),n=await qe([{type:"select",name:"sourceLibrary",message:`Which icon library would you like to ${a.info("migrate from")}?`,choices:o},{type:"select",name:"targetLibrary",message:`Which icon library would you like to ${a.info("migrate to")}?`,choices:o}]);if(n.sourceLibrary===n.targetLibrary)throw new Error("You cannot migrate to the same icon library. Please choose a different icon library.");if(!(n.sourceLibrary in F&&n.targetLibrary in F))throw new Error("Invalid icon library. Please choose a valid icon library.");let a$1=F[n.sourceLibrary],s$1=F[n.targetLibrary],{confirm:c}=await qe({type:"confirm",name:"confirm",initial:!0,message:`We will migrate ${a.info(r$1.length)} files in ${a.info(`./${x__default.relative(e.resolvedPaths.cwd,t)}`)} from ${a.info(a$1.name)} to ${a.info(s$1.name)}. Continue?`});c||(r.info("Migration cancelled."),process.exit(0)),s$1.package&&await H([s$1.package],[],e,{silent:!1});let l=s("Migrating icons...")?.start();await Promise.all(r$1.map(async f=>{l.text=`Migrating ${f}...`;let m=x__default.join(t,f),u=await promises.readFile(m,"utf-8"),h=await ro(u,n.sourceLibrary,n.targetLibrary,i);await promises.writeFile(m,h);})),l.succeed("Migration complete.");}async function ro(e,t,r,i){let o=F[t]?.import,n=F[r]?.import,a=await promises.mkdtemp(x__default.join(tmpdir(),"shadcn-")),s=new Project({compilerOptions:{}}),c=x__default.join(a,`shadcn-icons-${randomBytes(4).toString("hex")}.tsx`),l=s.createSourceFile(c,e,{scriptKind:ScriptKind.TSX}),f=[];for(let m of l.getImportDeclarations()??[])if(m.getModuleSpecifier()?.getText()===`"${o}"`){for(let u of m.getNamedImports()??[]){let h=u.getName(),y=Object.values(i).find(R=>R[t]===h)?.[r];!y||f.includes(y)||(f.push(y),u.remove(),l.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement).filter(R=>R.getTagNameNode()?.getText()===h).forEach(R=>R.getTagNameNode()?.replaceWithText(y)));}m.getNamedImports()?.length===0&&m.remove();}return f.length>0&&l.addImportDeclaration({moduleSpecifier:n,namedImports:f.map(m=>({name:m}))}),await l.getText()}function no(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function so(e,t,r,i){let n=e.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").trim().split(",").map(a=>a.trim()).filter(Boolean);for(let a of n){let s=a.match(/^type\s+(\w+)(?:\s+as\s+(\w+))?$/),c=a.match(/^(\w+)\s+as\s+(\w+)$/);if(s){let l=s[1],f=s[2];i==="slot"&&l==="Slot"&&!f?r.push({name:"Slot",alias:"SlotPrimitive",isType:!0}):r.push({name:l,alias:f,isType:!0});}else if(c){let l=c[1],f=c[2];i==="slot"&&l==="Slot"&&f==="Slot"?r.push({name:"Slot",alias:"SlotPrimitive",isType:t}):r.push({name:l,alias:f,isType:t});}else i==="slot"&&a==="Slot"?r.push({name:"Slot",alias:"SlotPrimitive",isType:t}):r.push({name:a,isType:t});}}async function pr(e,t={}){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 r$1=e.resolvedPaths.ui,i=await Qi("**/*.{js,ts,jsx,tsx}",{cwd:r$1});if(!t.yes){let{confirm:s}=await qe({type:"confirm",name:"confirm",initial:!0,message:`We will migrate ${a.info(i.length)} files in ${a.info(`./${x__default.relative(e.resolvedPaths.cwd,r$1)}`)} to ${a.info("radix-ui")}. Continue?`});s||(r.info("Migration cancelled."),process.exit(0));}let o=s("Migrating imports...")?.start(),n$1=new Set;await Promise.all(i.map(async s=>{o.text=`Migrating ${s}...`;let c=x__default.join(r$1,s),l=await promises.readFile(c,"utf-8"),{content:f,replacedPackages:m}=await ao(l);m.forEach(u=>n$1.add(u)),await promises.writeFile(c,f);})),o.succeed("Migrating imports.");let a$1=s("Updating package.json...")?.start();try{let s=n(e.resolvedPaths.cwd,!1);if(!s){a$1.fail("Could not read package.json"),r.warn("Could not update package.json. You may need to manually replace @radix-ui/react-* packages with radix-ui");return}let c=Array.from(n$1),l=["dependencies","devDependencies"];for(let f of l)if(s[f])for(let m of c)s[f][m]&&delete s[f][m];if(c.length>0){s.dependencies||(s.dependencies={}),s.dependencies["radix-ui"]="latest";let f=x__default.join(e.resolvedPaths.cwd,"package.json");await promises.writeFile(f,JSON.stringify(s,null,2)+`
|
|
76
76
|
`),a$1.succeed("Updated package.json."),await H(["radix-ui"],[],e,{silent:!1});}else a$1.succeed("No packages found in source files.");}catch{a$1.fail("Failed to update package.json"),r.warn("You may need to manually replace @radix-ui/react-* packages with radix-ui");}}async function ao(e){let t=/import\s+(?:(type)\s+)?(?:\*\s+as\s+(\w+)|{([^}]+)})\s+from\s+(["'])@radix-ui\/react-([^"']+)\4(;?)/g,r=[],i=[],o=[],n='"',a=!1,s=e,c;for(;(c=t.exec(e))!==null;){let[y,R,g,b,k,v,E]=c;if(v==="icons"||v.startsWith("icons/"))continue;i.push(y),i.length===1&&(n=k,a=E===";"),o.push(`@radix-ui/react-${v}`);let j=!!R;if(g){let _=no(v);r.push({name:_,alias:g,isType:j});}else b&&so(b,j,r,v);}if(r.length===0)return {content:e,replacedPackages:[]};let l=r.filter((y,R,g)=>R===g.findIndex(b=>b.name===y.name&&b.alias===y.alias&&b.isType===y.isType)),m=`import { ${l.map(y=>{let R=y.isType?"type ":"";return y.alias?`${R}${y.name} as ${y.alias}`:`${R}${y.name}`}).join(", ")} } from ${n}radix-ui${n}${a?";":""}`;s=i.reduce((y,R,g)=>y.replace(R,g===0?m:""),s),s=s.replace(/\n\s*\n\s*\n/g,`
|
|
77
77
|
|
|
78
78
|
`),l.some(y=>y.name==="Slot"&&y.alias==="SlotPrimitive")&&(s=s.split(`
|
|
79
79
|
`).map(g=>{if(g.trim().startsWith("import "))return g;let b=g;return b=b.replace(/\b(asChild\s*\?\s*)Slot(\s*:)/g,"$1__SLOT_PLACEHOLDER__$2"),b=b.replace(/\bReact\.ComponentProps<typeof\s+Slot>/g,"React.ComponentProps<typeof __SLOT_PLACEHOLDER__>"),b=b.replace(/\bComponentProps<typeof\s+Slot>/g,"ComponentProps<typeof __SLOT_PLACEHOLDER__>"),b=b.replace(/(<\/?)Slot(\s*\/?>)/g,"$1__SLOT_PLACEHOLDER__$2"),b=b.replace(/\bSlot\b/g,(k,v,E)=>{let j=E.substring(0,v),_=(j.match(/"/g)||[]).length,oe=(j.match(/'/g)||[]).length;return _%2!==0||oe%2!==0?k:"__SLOT_PLACEHOLDER__"}),b=b.replace(/__SLOT_PLACEHOLDER__/g,"SlotPrimitive.Slot"),b}).join(`
|
|
80
80
|
`));let h=Array.from(new Set(o));return {content:s,replacedPackages:h}}async function mr(e){let t={};if(!Q.existsSync(e.cwd)||!Q.existsSync(x__default.resolve(e.cwd,"package.json")))return t[A]=!0,{errors:t,config:null};if(!Q.existsSync(x__default.resolve(e.cwd,"components.json")))return t[D]=!0,{errors:t,config:null};try{let r=await h(e.cwd);return {errors:t,config:r}}catch{r.break(),r.error(`An invalid ${a.info("components.json")} file was found at ${a.info(e.cwd)}.
|
|
81
81
|
Before you can run a migration, you must create a valid ${a.info("components.json")} file by running the ${a.info("init")} command.`),r.error(`Learn more at ${a.info("https://ui.shadcn.com/docs/components-json")}.`),r.break(),process.exit(1);}}var dr=[{name:"icons",description:"migrate your ui components to a different icon library."},{name:"radix",description:"migrate to radix-ui."}],po=z.object({cwd:z.string(),list:z.boolean(),yes:z.boolean(),migration:z.string().refine(e=>e&&dr.some(t=>t.name===e),{message:"You must specify a valid migration. Run `shadcn migrate --list` to see available migrations."}).optional()}),ur=new Command().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).option("-y, --yes","skip confirmation prompt.",!1).action(async(e,t)=>{try{let r$1=po.parse({cwd:x__default.resolve(t.cwd),migration:e,list:t.list,yes:t.yes});if(r$1.list||!r$1.migration){r.info("Available migrations:");for(let n of dr)r.info(`- ${n.name}: ${n.description}`);return}if(!r$1.migration)throw new Error("You must specify a migration. Run `shadcn migrate --list` to see available migrations.");let{errors:i,config:o}=await mr(r$1);if(i[A]||i[D])throw new Error("No `components.json` file found. Ensure you are at the root of your project.");if(!o)throw new Error("Something went wrong reading your `components.json` file. Please ensure you have a valid `components.json` file.");r$1.migration==="icons"&&await lr(o),r$1.migration==="radix"&&await pr(o,{yes:r$1.yes});}catch(r$1){r.break(),x$1(r$1);}});async function gr(e){let t={},r$1={cwd:e.cwd,registryFile:x__default.resolve(e.cwd,e.registryFile),outputDir:x__default.resolve(e.cwd,e.outputDir)};if(!Q.existsSync(r$1.registryFile))return t[q]=!0,{errors:t,resolvePaths:null,config:null};if(!Q.existsSync(x__default.resolve(e.cwd,"components.json")))return t[D]=!0,{errors:t,resolvePaths:null,config:null};await Q.mkdir(r$1.outputDir,{recursive:!0});try{let i=await h(e.cwd);return {errors:t,config:i,resolvePaths:r$1}}catch{r.break(),r.error(`An invalid ${a.info("components.json")} file was found at ${a.info(e.cwd)}.
|
|
82
|
-
Before you can build the registry, you must create a valid ${a.info("components.json")} file by running the ${a.info("init")} command.`),r.break(),process.exit(1);}}var mo=z.object({cwd:z.string(),registryFile:z.string(),outputDir:z.string(),verbose:z.boolean().optional().default(!1)}),hr=new Command().name("registry:build").description("builds the registry [EXPERIMENTAL]").argument("[registry]","path to registry.json file","./registry.json").option("-o, --output <path>","destination directory for json files","./public/r").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-v, --verbose","verbose output").action(async(e,t)=>{await uo({cwd:x.resolve(t.cwd),registryFile:e,outputDir:t.output,verbose:t.verbose});});async function uo(e){try{let t=mo.parse(e),[{errors:r$1,resolvePaths:i,config:o$1},n]=await Promise.all([gr(t),o(t.cwd)]);(r$1[D]||!o$1||!n)&&(r.error(`A ${a.info("components.json")} file is required to build the registry. Run ${a.info("shadcn init")} to create one.`),r.break(),process.exit(1)),(r$1[q]||!i)&&(r.error(`We could not find a registry file at ${a.info(x.resolve(t.cwd,t.registryFile))}.`),r.break(),process.exit(1));let a$1=await M.readFile(i.registryFile,"utf-8"),s$1=H$1.safeParse(JSON.parse(a$1));s$1.success||(r.error(`Invalid registry file found at ${a.info(i.registryFile)}.`),r.break(),process.exit(1));let c=s("Building registry..."),l=await go(s$1.data,o$1,n);for(let f of l.items)f.files=f.files?.filter((m,u,h)=>u===h.findIndex(y=>y.path===m.path)),f.dependencies&&(f.dependencies=f.dependencies.filter((m,u,h)=>u===h.findIndex(y=>y===m)));for(let f of l.items){if(!f.files)continue;c.start(`Building ${f.name}...`),f.$schema="https://ui.shadcn.com/schema/registry-item.json";for(let u of f.files){let h=x.resolve(i.cwd,u.path);try{if(!(await M.stat(h)).isFile())continue;u.content=await M.readFile(h,"utf-8");}catch(y){console.error("Error reading file in registry build:",h,y);continue}}let m=G.safeParse(f);if(!m.success){r.error(`Invalid registry item found for ${a.info(f.name)}.`);continue}await M.writeFile(x.resolve(i.outputDir,`${m.data.name}.json`),JSON.stringify(m.data,null,2));}if(await M.copyFile(i.registryFile,x.resolve(i.outputDir,"registry.json")),c.succeed("Building registry."),t.verbose){s(`The registry has ${a.info(l.items.length.toString())} items:`).succeed();for(let f of l.items){r.log(` - ${f.name} (${a.info(f.type)})`);for(let m of f.files??[])r.log(` - ${m.path}`);}}}catch(t){r.break(),x$1(t);}}async function go(e,t$1,r){for(let i of e.items)if(i.files?.length)for(let o of i.files){let n=await t(o.path,t$1,r);n.files=n.files?.filter(a=>a.path!==o.path),n.files&&i.files.push(...n.files),n.dependencies&&(i.dependencies=i.dependencies?i.dependencies.concat(n.dependencies):n.dependencies);}return e}var yr=new Command().name("registry:mcp").description("starts the registry MCP server [EXPERIMENTAL]").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async()=>{try{let e=new StdioServerTransport;await a$1.connect(e);}catch(e){r.break(),x$1(e);}});var wr={name:"shadcn",version:"2.9.
|
|
82
|
+
Before you can build the registry, you must create a valid ${a.info("components.json")} file by running the ${a.info("init")} command.`),r.break(),process.exit(1);}}var mo=z.object({cwd:z.string(),registryFile:z.string(),outputDir:z.string(),verbose:z.boolean().optional().default(!1)}),hr=new Command().name("registry:build").description("builds the registry [EXPERIMENTAL]").argument("[registry]","path to registry.json file","./registry.json").option("-o, --output <path>","destination directory for json files","./public/r").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-v, --verbose","verbose output").action(async(e,t)=>{await uo({cwd:x.resolve(t.cwd),registryFile:e,outputDir:t.output,verbose:t.verbose});});async function uo(e){try{let t=mo.parse(e),[{errors:r$1,resolvePaths:i,config:o$1},n]=await Promise.all([gr(t),o(t.cwd)]);(r$1[D]||!o$1||!n)&&(r.error(`A ${a.info("components.json")} file is required to build the registry. Run ${a.info("shadcn init")} to create one.`),r.break(),process.exit(1)),(r$1[q]||!i)&&(r.error(`We could not find a registry file at ${a.info(x.resolve(t.cwd,t.registryFile))}.`),r.break(),process.exit(1));let a$1=await M.readFile(i.registryFile,"utf-8"),s$1=H$1.safeParse(JSON.parse(a$1));s$1.success||(r.error(`Invalid registry file found at ${a.info(i.registryFile)}.`),r.break(),process.exit(1));let c=s("Building registry..."),l=await go(s$1.data,o$1,n);for(let f of l.items)f.files=f.files?.filter((m,u,h)=>u===h.findIndex(y=>y.path===m.path)),f.dependencies&&(f.dependencies=f.dependencies.filter((m,u,h)=>u===h.findIndex(y=>y===m)));for(let f of l.items){if(!f.files)continue;c.start(`Building ${f.name}...`),f.$schema="https://ui.shadcn.com/schema/registry-item.json";for(let u of f.files){let h=x.resolve(i.cwd,u.path);try{if(!(await M.stat(h)).isFile())continue;u.content=await M.readFile(h,"utf-8");}catch(y){console.error("Error reading file in registry build:",h,y);continue}}let m=G.safeParse(f);if(!m.success){r.error(`Invalid registry item found for ${a.info(f.name)}.`);continue}await M.writeFile(x.resolve(i.outputDir,`${m.data.name}.json`),JSON.stringify(m.data,null,2));}if(await M.copyFile(i.registryFile,x.resolve(i.outputDir,"registry.json")),c.succeed("Building registry."),t.verbose){s(`The registry has ${a.info(l.items.length.toString())} items:`).succeed();for(let f of l.items){r.log(` - ${f.name} (${a.info(f.type)})`);for(let m of f.files??[])r.log(` - ${m.path}`);}}}catch(t){r.break(),x$1(t);}}async function go(e,t$1,r){for(let i of e.items)if(i.files?.length)for(let o of i.files){let n=await t(o.path,t$1,r);n.files=n.files?.filter(a=>a.path!==o.path),n.files&&i.files.push(...n.files),n.dependencies&&(i.dependencies=i.dependencies?i.dependencies.concat(n.dependencies):n.dependencies);}return e}var yr=new Command().name("registry:mcp").description("starts the registry MCP server [EXPERIMENTAL]").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async()=>{try{let e=new StdioServerTransport;await a$1.connect(e);}catch(e){r.break(),x$1(e);}});var wr={name:"shadcn",version:"2.9.2",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:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./registry":{types:"./dist/registry/index.d.ts",default:"./dist/registry/index.js"},"./mcp":{types:"./dist/mcp/index.d.ts",default:"./dist/mcp/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:4000/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:4000/r vitest run"},dependencies:{"@antfu/ni":"^23.2.0","@babel/core":"^7.22.1","@babel/parser":"^7.22.6","@babel/plugin-transform-typescript":"^7.22.5","@modelcontextprotocol/sdk":"^1.10.2",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",msw:"^2.7.1","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","zod-to-json-schema":"^3.24.5"},devDependencies:{"@types/babel__core":"^7.20.1","@types/diff":"^5.0.3","@types/fs-extra":"^11.0.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 bo(){let e=new Command().name("shadcn").description("add components and dependencies to your project").version(wr.version,"-v, --version","display the version number");e.addCommand(Yt).addCommand(er).addCommand(sr).addCommand(ur).addCommand(ar).addCommand(or),e.addCommand(hr).addCommand(yr),e.parse();}bo();
|
|
83
83
|
//# sourceMappingURL=out.js.map
|
|
84
84
|
//# sourceMappingURL=index.js.map
|