create-shadcn-js 0.0.0-stage → 1.2.0

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.
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Generates jsconfig.json content for path alias support in Vite + React JS.
3
+ */
4
+ export function getJsConfig() {
5
+ return JSON.stringify(
6
+ {
7
+ compilerOptions: {
8
+ baseUrl: ".",
9
+ paths: {
10
+ "@/*": ["./src/*"]
11
+ }
12
+ }
13
+ },
14
+ null,
15
+ 2
16
+ ) + "\n"
17
+ }
18
+
19
+ /**
20
+ * Generates vite.config.js content.
21
+ * @param {'v4' | 'v3'} tailwindVersion
22
+ */
23
+ export function getViteConfig(tailwindVersion = "v4") {
24
+ if (tailwindVersion === "v4") {
25
+ return `import path from "node:path"
26
+ import { fileURLToPath } from "node:url"
27
+ import tailwindcss from "@tailwindcss/vite"
28
+ import react from "@vitejs/plugin-react"
29
+ import { defineConfig } from "vite"
30
+
31
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
32
+
33
+ // https://vite.dev/config/
34
+ export default defineConfig({
35
+ plugins: [react(), tailwindcss()],
36
+ resolve: {
37
+ alias: {
38
+ "@": path.resolve(__dirname, "./src"),
39
+ },
40
+ },
41
+ })
42
+ `
43
+ }
44
+
45
+ // Tailwind v3 (uses PostCSS plugin)
46
+ return `import path from "node:path"
47
+ import { fileURLToPath } from "node:url"
48
+ import react from "@vitejs/plugin-react"
49
+ import { defineConfig } from "vite"
50
+
51
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
52
+
53
+ // https://vite.dev/config/
54
+ export default defineConfig({
55
+ plugins: [react()],
56
+ resolve: {
57
+ alias: {
58
+ "@": path.resolve(__dirname, "./src"),
59
+ },
60
+ },
61
+ })
62
+ `
63
+ }
64
+
65
+ /**
66
+ * Generates tailwind.config.js for Tailwind CSS v3.
67
+ *
68
+ * This is intentionally self-contained: shadcn@2.3.0 writes v4-flavoured
69
+ * variables (oklch) that do not work with the v3 `hsl(var(--token))` theme,
70
+ * so the scaffold owns the v3 theme instead of relying on the legacy CLI.
71
+ */
72
+ export function getTailwindConfigV3() {
73
+ return `import animate from "tailwindcss-animate"
74
+
75
+ /** @type {import('tailwindcss').Config} */
76
+ export default {
77
+ darkMode: ["class"],
78
+ content: ["./index.html", "./src/**/*.{js,jsx}"],
79
+ theme: {
80
+ container: {
81
+ center: true,
82
+ padding: "2rem",
83
+ screens: {
84
+ "2xl": "1400px",
85
+ },
86
+ },
87
+ extend: {
88
+ colors: {
89
+ border: "hsl(var(--border))",
90
+ input: "hsl(var(--input))",
91
+ ring: "hsl(var(--ring))",
92
+ background: "hsl(var(--background))",
93
+ foreground: "hsl(var(--foreground))",
94
+ primary: {
95
+ DEFAULT: "hsl(var(--primary))",
96
+ foreground: "hsl(var(--primary-foreground))",
97
+ },
98
+ secondary: {
99
+ DEFAULT: "hsl(var(--secondary))",
100
+ foreground: "hsl(var(--secondary-foreground))",
101
+ },
102
+ destructive: {
103
+ DEFAULT: "hsl(var(--destructive))",
104
+ foreground: "hsl(var(--destructive-foreground))",
105
+ },
106
+ muted: {
107
+ DEFAULT: "hsl(var(--muted))",
108
+ foreground: "hsl(var(--muted-foreground))",
109
+ },
110
+ accent: {
111
+ DEFAULT: "hsl(var(--accent))",
112
+ foreground: "hsl(var(--accent-foreground))",
113
+ },
114
+ popover: {
115
+ DEFAULT: "hsl(var(--popover))",
116
+ foreground: "hsl(var(--popover-foreground))",
117
+ },
118
+ card: {
119
+ DEFAULT: "hsl(var(--card))",
120
+ foreground: "hsl(var(--card-foreground))",
121
+ },
122
+ sidebar: {
123
+ DEFAULT: "hsl(var(--sidebar-background))",
124
+ foreground: "hsl(var(--sidebar-foreground))",
125
+ primary: "hsl(var(--sidebar-primary))",
126
+ "primary-foreground": "hsl(var(--sidebar-primary-foreground))",
127
+ accent: "hsl(var(--sidebar-accent))",
128
+ "accent-foreground": "hsl(var(--sidebar-accent-foreground))",
129
+ border: "hsl(var(--sidebar-border))",
130
+ ring: "hsl(var(--sidebar-ring))",
131
+ },
132
+ },
133
+ borderRadius: {
134
+ lg: "var(--radius)",
135
+ md: "calc(var(--radius) - 2px)",
136
+ sm: "calc(var(--radius) - 4px)",
137
+ },
138
+ keyframes: {
139
+ "accordion-down": {
140
+ from: { height: "0" },
141
+ to: { height: "var(--radix-accordion-content-height)" },
142
+ },
143
+ "accordion-up": {
144
+ from: { height: "var(--radix-accordion-content-height)" },
145
+ to: { height: "0" },
146
+ },
147
+ },
148
+ animation: {
149
+ "accordion-down": "accordion-down 0.2s ease-out",
150
+ "accordion-up": "accordion-up 0.2s ease-out",
151
+ },
152
+ },
153
+ },
154
+ plugins: [animate],
155
+ }
156
+ `
157
+ }
158
+
159
+ /**
160
+ * Generates components.json for the legacy Tailwind CSS v3 + shadcn CLI 2.x setup.
161
+ */
162
+ export function getComponentsJsonV3() {
163
+ return `{
164
+ "$schema": "https://ui.shadcn.com/schema.json",
165
+ "style": "new-york",
166
+ "rsc": false,
167
+ "tsx": false,
168
+ "tailwind": {
169
+ "config": "tailwind.config.js",
170
+ "css": "src/index.css",
171
+ "baseColor": "zinc",
172
+ "cssVariables": true,
173
+ "prefix": ""
174
+ },
175
+ "aliases": {
176
+ "components": "@/components",
177
+ "utils": "@/lib/utils",
178
+ "ui": "@/components/ui",
179
+ "lib": "@/lib",
180
+ "hooks": "@/hooks"
181
+ },
182
+ "iconLibrary": "lucide"
183
+ }
184
+ `
185
+ }
186
+
187
+ /**
188
+ * Generates the JavaScript cn() helper used by shadcn components.
189
+ */
190
+ export function getShadcnUtilsJs() {
191
+ return `import { clsx } from "clsx"
192
+ import { twMerge } from "tailwind-merge"
193
+
194
+ export function cn(...inputs) {
195
+ return twMerge(clsx(inputs))
196
+ }
197
+ `
198
+ }
199
+
200
+ /**
201
+ * Generates postcss.config.js for Tailwind CSS v3.
202
+ */
203
+ export function getPostcssConfigV3() {
204
+ return `export default {
205
+ plugins: {
206
+ tailwindcss: {},
207
+ autoprefixer: {},
208
+ },
209
+ }
210
+ `
211
+ }
212
+
213
+ /**
214
+ * Generates a clean index.html with nice typography and titles.
215
+ * @param {string} title
216
+ */
217
+ export function getIndexHtml(title = "shadcn/ui + Vite") {
218
+ return `<!doctype html>
219
+ <html lang="en">
220
+ <head>
221
+ <meta charset="UTF-8" />
222
+ <link rel="icon" type="image/svg+xml" href="/vite.svg" />
223
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
224
+ <title>${title}</title>
225
+ <link rel="preconnect" href="https://fonts.googleapis.com">
226
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
227
+ <link href="https://fonts.googleapis.com/css2?family=Geist:wght@100..900&family=Geist+Mono:wght@100..900&display=swap" rel="stylesheet">
228
+ </head>
229
+ <body class="min-h-screen bg-background font-sans antialiased text-foreground">
230
+ <div id="root"></div>
231
+ <script type="module" src="/src/main.jsx"></script>
232
+ </body>
233
+ </html>
234
+ `
235
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Generates initial index.css based on Tailwind version.
3
+ * @param {'v4' | 'v3'} tailwindVersion
4
+ */
5
+ export function getIndexCss(tailwindVersion = "v4") {
6
+ if (tailwindVersion === "v4") {
7
+ return `@import "tailwindcss";
8
+ `
9
+ }
10
+
11
+ return `@tailwind base;
12
+ @tailwind components;
13
+ @tailwind utilities;
14
+
15
+ @layer base {
16
+ :root {
17
+ --background: 0 0% 100%;
18
+ --foreground: 240 10% 3.9%;
19
+ --card: 0 0% 100%;
20
+ --card-foreground: 240 10% 3.9%;
21
+ --popover: 0 0% 100%;
22
+ --popover-foreground: 240 10% 3.9%;
23
+ --primary: 240 5.9% 10%;
24
+ --primary-foreground: 0 0% 98%;
25
+ --secondary: 240 4.8% 95.9%;
26
+ --secondary-foreground: 240 5.9% 10%;
27
+ --muted: 240 4.8% 95.9%;
28
+ --muted-foreground: 240 3.8% 46.1%;
29
+ --accent: 240 4.8% 95.9%;
30
+ --accent-foreground: 240 5.9% 10%;
31
+ --destructive: 0 84.2% 60.2%;
32
+ --destructive-foreground: 0 0% 98%;
33
+ --border: 240 5.9% 90%;
34
+ --input: 240 5.9% 90%;
35
+ --ring: 240 10% 3.9%;
36
+ --chart-1: 12 76% 61%;
37
+ --chart-2: 173 58% 39%;
38
+ --chart-3: 197 37% 24%;
39
+ --chart-4: 43 74% 66%;
40
+ --chart-5: 27 87% 67%;
41
+ --radius: 0.5rem;
42
+ --sidebar-background: 0 0% 98%;
43
+ --sidebar-foreground: 240 5.3% 26.1%;
44
+ --sidebar-primary: 240 5.9% 10%;
45
+ --sidebar-primary-foreground: 0 0% 98%;
46
+ --sidebar-accent: 240 4.8% 95.9%;
47
+ --sidebar-accent-foreground: 240 5.9% 10%;
48
+ --sidebar-border: 220 13% 91%;
49
+ --sidebar-ring: 217.2 91.2% 59.8%;
50
+ }
51
+
52
+ .dark {
53
+ --background: 240 10% 3.9%;
54
+ --foreground: 0 0% 98%;
55
+ --card: 240 10% 3.9%;
56
+ --card-foreground: 0 0% 98%;
57
+ --popover: 240 10% 3.9%;
58
+ --popover-foreground: 0 0% 98%;
59
+ --primary: 0 0% 98%;
60
+ --primary-foreground: 240 5.9% 10%;
61
+ --secondary: 240 3.7% 15.9%;
62
+ --secondary-foreground: 0 0% 98%;
63
+ --muted: 240 3.7% 15.9%;
64
+ --muted-foreground: 240 5% 64.9%;
65
+ --accent: 240 3.7% 15.9%;
66
+ --accent-foreground: 0 0% 98%;
67
+ --destructive: 0 62.8% 30.6%;
68
+ --destructive-foreground: 0 0% 98%;
69
+ --border: 240 3.7% 15.9%;
70
+ --input: 240 3.7% 15.9%;
71
+ --ring: 240 4.9% 83.9%;
72
+ --chart-1: 220 70% 50%;
73
+ --chart-2: 160 60% 45%;
74
+ --chart-3: 30 80% 55%;
75
+ --chart-4: 280 65% 60%;
76
+ --chart-5: 340 75% 55%;
77
+ --sidebar-background: 240 5.9% 10%;
78
+ --sidebar-foreground: 240 4.8% 95.9%;
79
+ --sidebar-primary: 224.3 76.3% 48%;
80
+ --sidebar-primary-foreground: 0 0% 100%;
81
+ --sidebar-accent: 240 3.7% 15.9%;
82
+ --sidebar-accent-foreground: 240 4.8% 95.9%;
83
+ --sidebar-border: 240 3.7% 15.9%;
84
+ --sidebar-ring: 217.2 91.2% 59.8%;
85
+ }
86
+ }
87
+
88
+ @layer base {
89
+ * {
90
+ @apply border-border;
91
+ }
92
+
93
+ body {
94
+ @apply bg-background text-foreground;
95
+ }
96
+ }
97
+ `
98
+ }
package/src/utils.js ADDED
@@ -0,0 +1,370 @@
1
+ import fs from "fs-extra"
2
+ import path from "node:path"
3
+ import spawn from "cross-spawn"
4
+
5
+ const ALLOWED_PACKAGE_MANAGERS = new Set(["npm", "pnpm", "yarn", "bun"])
6
+ const ALLOWED_TAILWIND_VERSIONS = new Set(["v4", "v3"])
7
+ const ALLOWED_INIT_MODES = new Set(["interactive", "quickstart"])
8
+ const ALLOWED_BASE_LIBRARIES = new Set(["base", "radix", "aria"])
9
+ const SAFE_IDENTIFIER_REGEX = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/
10
+ const SAFE_PROJECT_NAME_REGEX = /^[a-zA-Z0-9@._-]+$/
11
+
12
+ /**
13
+ * CLI packages pinned by major so a future shadcn release cannot silently
14
+ * change the flags or component format used by the scaffolder.
15
+ */
16
+ export const SHADCN_CLI_V4 = "shadcn@4"
17
+ export const SHADCN_CLI_V3 = "shadcn@2.3.0"
18
+ export const CREATE_VITE_PACKAGE = "create-vite@8"
19
+
20
+ /**
21
+ * Builds the create-vite invocation with the selected package manager.
22
+ * @param {'npm' | 'pnpm' | 'yarn' | 'bun'} packageManager
23
+ * @param {string} folderName
24
+ * @returns {[string, string[]]}
25
+ */
26
+ export function getCreateViteCommand(packageManager, folderName) {
27
+ const valid = validateProjectName(folderName)
28
+ if (typeof valid === "string") {
29
+ throw new Error(valid)
30
+ }
31
+ return getPackageManagerCommands(packageManager).dlx(CREATE_VITE_PACKAGE, [
32
+ folderName,
33
+ "--template",
34
+ "react",
35
+ "-y",
36
+ ])
37
+ }
38
+
39
+ /**
40
+ * Returns the shadcn CLI package for the selected Tailwind version.
41
+ * Tailwind v3 must use the legacy 2.x CLI, which is the last release that
42
+ * ships Tailwind v3-compatible components.
43
+ * @param {'v4' | 'v3'} tailwindVersion
44
+ */
45
+ export function getShadcnCliPackage(tailwindVersion) {
46
+ return tailwindVersion === "v3" ? SHADCN_CLI_V3 : SHADCN_CLI_V4
47
+ }
48
+
49
+ /**
50
+ * Human-readable command for adding a component later.
51
+ * @param {'npm' | 'pnpm' | 'yarn' | 'bun'} packageManager
52
+ * @param {'v4' | 'v3'} tailwindVersion
53
+ */
54
+ export function getShadcnAddCommand(packageManager, tailwindVersion) {
55
+ const cli = getShadcnCliPackage(tailwindVersion)
56
+ // Reuse the same runner the CLI will actually execute. This keeps the
57
+ // copy-paste hint correct for Yarn 1, where `yarn dlx` does not exist and
58
+ // the scaffolder falls back to npx.
59
+ const { runner } = getPackageManagerCommands(packageManager)
60
+ return `${runner} ${cli} add <component>`
61
+ }
62
+
63
+ /**
64
+ * Detects the package manager used to run the CLI.
65
+ * @returns {'npm' | 'pnpm' | 'yarn' | 'bun'}
66
+ */
67
+ export function detectPackageManager() {
68
+ const userAgent = process.env.npm_config_user_agent || ""
69
+ if (userAgent.startsWith("pnpm")) return "pnpm"
70
+ if (userAgent.startsWith("yarn")) return "yarn"
71
+ if (userAgent.startsWith("bun")) return "bun"
72
+ return "npm"
73
+ }
74
+
75
+ /**
76
+ * Returns package manager execution commands.
77
+ * @param {'npm' | 'pnpm' | 'yarn' | 'bun'} pm
78
+ */
79
+ export function getPackageManagerCommands(pm) {
80
+ const safePm = sanitizePackageManager(pm)
81
+ switch (safePm) {
82
+ case "pnpm":
83
+ return {
84
+ install: ["pnpm", ["install", "--ignore-scripts=false"]],
85
+ add: (deps, isDev = false) => [
86
+ "pnpm",
87
+ ["add", ...(isDev ? ["-D"] : []), ...sanitizeDependencies(deps)],
88
+ ],
89
+ run: (script) => ["pnpm", [sanitizeIdentifier(script)]],
90
+ dlx: (pkg, args = []) => ["pnpm", ["dlx", pkg, ...args]],
91
+ runner: "pnpm dlx",
92
+ }
93
+ case "yarn": {
94
+ // `yarn dlx` only exists in Yarn 2+ (Berry). Yarn 1 projects need npx.
95
+ const isBerry = getYarnMajorVersion() >= 2
96
+ return {
97
+ install: ["yarn", ["install"]],
98
+ add: (deps, isDev = false) => [
99
+ "yarn",
100
+ ["add", ...(isDev ? ["-D"] : []), ...sanitizeDependencies(deps)],
101
+ ],
102
+ run: (script) => ["yarn", [sanitizeIdentifier(script)]],
103
+ dlx: isBerry
104
+ ? (pkg, args = []) => ["yarn", ["dlx", pkg, ...args]]
105
+ : (pkg, args = []) => ["npx", ["--yes", pkg, ...args]],
106
+ runner: isBerry ? "yarn dlx" : "npx",
107
+ }
108
+ }
109
+ case "bun":
110
+ return {
111
+ install: ["bun", ["install"]],
112
+ add: (deps, isDev = false) => [
113
+ "bun",
114
+ ["add", ...(isDev ? ["-d"] : []), ...sanitizeDependencies(deps)],
115
+ ],
116
+ run: (script) => ["bun", ["run", sanitizeIdentifier(script)]],
117
+ dlx: (pkg, args = []) => ["bunx", ["--bun", pkg, ...args]],
118
+ runner: "bunx --bun",
119
+ }
120
+ case "npm":
121
+ default:
122
+ return {
123
+ install: ["npm", ["install"]],
124
+ add: (deps, isDev = false) => [
125
+ "npm",
126
+ ["install", ...(isDev ? ["-D"] : []), ...sanitizeDependencies(deps)],
127
+ ],
128
+ run: (script) => ["npm", ["run", sanitizeIdentifier(script)]],
129
+ dlx: (pkg, args = []) => ["npx", ["--yes", pkg, ...args]],
130
+ runner: "npx",
131
+ }
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Executes a command synchronously with inherited stdio.
137
+ * @param {string} cmd
138
+ * @param {string[]} args
139
+ * @param {import('child_process').SpawnOptions} [options]
140
+ */
141
+ export function runCommandSync(cmd, args, options = {}) {
142
+ const result = spawn.sync(cmd, args, {
143
+ stdio: "inherit",
144
+ ...options,
145
+ })
146
+
147
+ if (result.error) {
148
+ throw result.error
149
+ }
150
+ if (result.status !== 0) {
151
+ throw new Error(`Command "${cmd} ${args.join(" ")}" failed with exit code ${result.status}`)
152
+ }
153
+ return result
154
+ }
155
+
156
+ /**
157
+ * Executes a command silently or with custom stdio, returning stdout string.
158
+ * @param {string} cmd
159
+ * @param {string[]} args
160
+ * @param {import('child_process').SpawnOptions} [options]
161
+ */
162
+ export function runCommandOutput(cmd, args, options = {}) {
163
+ const result = spawn.sync(cmd, args, {
164
+ encoding: "utf-8",
165
+ // Package-manager output can exceed Node's 1 MB default on large trees.
166
+ maxBuffer: 20 * 1024 * 1024,
167
+ ...options,
168
+ })
169
+
170
+ if (result.error) {
171
+ throw result.error
172
+ }
173
+ if (result.status !== 0) {
174
+ const details = [result.stderr, result.stdout]
175
+ .filter(Boolean)
176
+ .join("\n")
177
+ .trim()
178
+ const errorMsg = details || `exit code ${result.status}`
179
+ throw new Error(`Command "${cmd} ${args.join(" ")}" failed: ${errorMsg}`)
180
+ }
181
+ return result.stdout ? result.stdout.trim() : ""
182
+ }
183
+
184
+ /**
185
+ * Detects the installed Yarn major version.
186
+ * Returns 1 when Yarn is unavailable or its version cannot be parsed, which
187
+ * makes the caller fall back to npx instead of the Berry-only `yarn dlx`.
188
+ * @returns {number}
189
+ */
190
+ function getYarnMajorVersion() {
191
+ try {
192
+ const result = spawn.sync("yarn", ["--version"], { encoding: "utf-8" })
193
+ if (result.error || result.status !== 0 || !result.stdout) return 1
194
+ const major = Number.parseInt(result.stdout.trim().split(".")[0], 10)
195
+ return Number.isNaN(major) ? 1 : major
196
+ } catch {
197
+ return 1
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Validates a project directory name to prevent path traversal and argument injection.
203
+ * @param {string} name
204
+ * @returns {string | boolean} Returns error message if invalid, or true if valid
205
+ */
206
+ export function validateProjectName(name) {
207
+ if (!name || typeof name !== "string" || name.trim().length === 0) {
208
+ return "Project name cannot be empty."
209
+ }
210
+ const trimmed = name.trim()
211
+
212
+ // Prevent flag injection (e.g. --template, -v)
213
+ if (trimmed.startsWith("-")) {
214
+ return "Project name cannot start with a hyphen (-)."
215
+ }
216
+
217
+ // "." and ".." resolve to an existing directory. The scaffolder empties the
218
+ // target directory, so accepting them could delete the user's project.
219
+ if (trimmed === "." || trimmed === ".." || /^\.+$/.test(trimmed)) {
220
+ return 'Project name cannot be "." or "..".'
221
+ }
222
+
223
+ // Prevent path traversal
224
+ if (trimmed.includes("..") || trimmed.includes("/") || trimmed.includes("\\")) {
225
+ return "Project name cannot contain path separators (/ or \\) or path traversal (..)."
226
+ }
227
+
228
+ // Windows strips trailing dots, which can alias a different directory.
229
+ if (trimmed.endsWith(".")) {
230
+ return "Project name cannot end with a dot."
231
+ }
232
+
233
+ // Check valid characters
234
+ if (!SAFE_PROJECT_NAME_REGEX.test(trimmed)) {
235
+ return "Project name can only contain alphanumeric characters, hyphens, underscores, dots, and @."
236
+ }
237
+
238
+ // Prevent Windows reserved filenames
239
+ const baseUpper = trimmed.split(".")[0].toUpperCase()
240
+ const reserved = new Set([
241
+ "CON", "PRN", "AUX", "NUL",
242
+ "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
243
+ "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
244
+ ])
245
+ if (reserved.has(baseUpper)) {
246
+ return `"${trimmed}" is a reserved system filename. Please choose another name.`
247
+ }
248
+
249
+ return true
250
+ }
251
+
252
+ /**
253
+ * Sanitizes and validates package manager against strict allowlist.
254
+ * @param {string} pm
255
+ * @returns {'npm' | 'pnpm' | 'yarn' | 'bun'}
256
+ */
257
+ export function sanitizePackageManager(pm) {
258
+ if (pm === undefined || pm === null || pm === "") return "npm"
259
+ const normalized = String(pm).toLowerCase()
260
+ if (ALLOWED_PACKAGE_MANAGERS.has(normalized)) {
261
+ return normalized
262
+ }
263
+ throw new Error(
264
+ `Invalid package manager: "${pm}". Allowed values: npm, pnpm, yarn, bun.`
265
+ )
266
+ }
267
+
268
+ /**
269
+ * Sanitizes and validates Tailwind CSS version.
270
+ * @param {string} tw
271
+ * @returns {'v4' | 'v3'}
272
+ */
273
+ export function sanitizeTailwindVersion(tw) {
274
+ if (tw === undefined || tw === null || tw === "") return "v4"
275
+ const normalized = String(tw).toLowerCase()
276
+ if (ALLOWED_TAILWIND_VERSIONS.has(normalized)) {
277
+ return normalized
278
+ }
279
+ throw new Error(`Invalid Tailwind CSS version: "${tw}". Allowed values: v4, v3.`)
280
+ }
281
+
282
+ /**
283
+ * Sanitizes and validates init mode.
284
+ * @param {string} mode
285
+ * @returns {'interactive' | 'quickstart'}
286
+ */
287
+ export function sanitizeInitMode(mode) {
288
+ if (mode === undefined || mode === null || mode === "") return "interactive"
289
+ const normalized = String(mode).toLowerCase()
290
+ if (ALLOWED_INIT_MODES.has(normalized)) {
291
+ return normalized
292
+ }
293
+ throw new Error(
294
+ `Invalid init mode: "${mode}". Allowed values: interactive, quickstart.`
295
+ )
296
+ }
297
+
298
+ /**
299
+ * Sanitizes and validates base library.
300
+ * @param {string} [base]
301
+ * @returns {string | undefined}
302
+ */
303
+ export function sanitizeBaseLibrary(base) {
304
+ if (!base) return undefined
305
+ const lower = base.toLowerCase()
306
+ if (ALLOWED_BASE_LIBRARIES.has(lower)) {
307
+ return lower
308
+ }
309
+ throw new Error(`Invalid base library: "${base}". Allowed values: base, radix, aria.`)
310
+ }
311
+
312
+ /**
313
+ * Sanitizes and validates preset name against injection.
314
+ * @param {string} [preset]
315
+ * @returns {string | undefined}
316
+ */
317
+ export function sanitizePreset(preset) {
318
+ if (!preset) return undefined
319
+ if (SAFE_IDENTIFIER_REGEX.test(preset)) {
320
+ return preset
321
+ }
322
+ throw new Error(`Invalid preset name: "${preset}". Must contain only alphanumeric characters, hyphens, and underscores.`)
323
+ }
324
+
325
+ /**
326
+ * Sanitizes an array of dependencies or components.
327
+ * @param {string[]} deps
328
+ * @returns {string[]}
329
+ */
330
+ export function sanitizeDependencies(deps) {
331
+ if (!Array.isArray(deps)) return []
332
+ return deps.map((d) => {
333
+ const isSafe =
334
+ typeof d === "string" &&
335
+ /^[a-zA-Z0-9@/._-]+$/.test(d) &&
336
+ // Reject flag injection and filesystem escapes: arguments are passed
337
+ // to npm/npx as an argv array, but "-x", "/abs" and "../x" are still
338
+ // interpreted as options or out-of-project paths.
339
+ !d.startsWith("-") &&
340
+ !d.startsWith("/") &&
341
+ !d.startsWith("./") &&
342
+ d !== "." &&
343
+ !d.includes("..")
344
+ if (!isSafe) {
345
+ throw new Error(`Invalid package identifier: "${d}"`)
346
+ }
347
+ return d
348
+ })
349
+ }
350
+
351
+ /**
352
+ * Sanitizes a generic single identifier.
353
+ * @param {string} id
354
+ * @returns {string}
355
+ */
356
+ export function sanitizeIdentifier(id) {
357
+ if (typeof id !== "string" || !SAFE_IDENTIFIER_REGEX.test(id)) {
358
+ throw new Error(`Invalid identifier: "${id}"`)
359
+ }
360
+ return id
361
+ }
362
+
363
+ /**
364
+ * Formats a path to display nicely to the user.
365
+ * @param {string} targetPath
366
+ * @returns {string}
367
+ */
368
+ export function formatPath(targetPath) {
369
+ return path.relative(process.cwd(), targetPath) || "."
370
+ }