basuicn 0.1.1 → 0.1.4

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/scripts/ui-cli.ts CHANGED
@@ -1,485 +1,760 @@
1
- #!/usr/bin/env node
2
- import fs from 'fs';
3
- import path from 'path';
4
- import { execSync } from 'child_process';
5
-
6
- const REGISTRY_LOCAL = './registry.json';
7
- const REGISTRY_REMOTE = 'https://raw.githubusercontent.com/huy14032003/ui-component/main/registry.json';
8
-
9
- const log = (msg: string) => console.log(`[basuicn] ${msg}`);
10
- const warn = (msg: string) => console.warn(`[basuicn] WARN: ${msg}`);
11
- const error = (msg: string) => console.error(`[basuicn] ERROR: ${msg}`);
12
-
13
- const getTargetProjectDir = () => process.cwd();
14
-
15
- interface Registry {
16
- core?: { dependencies: string[]; files: { path: string; content: string }[] };
17
- components: Record<string, { dependencies: string[]; internalDependencies?: string[]; files: { path: string; content: string }[] }>;
18
- }
19
-
20
- const validateRegistry = (data: unknown): data is Registry => {
21
- if (!data || typeof data !== 'object') return false;
22
- const reg = data as Record<string, unknown>;
23
- return 'components' in reg && typeof reg.components === 'object' && reg.components !== null;
24
- };
25
-
26
- const getRegistry = async (isLocal: boolean): Promise<Registry> => {
27
- if (isLocal && fs.existsSync(REGISTRY_LOCAL)) {
28
- log('Using local registry...');
29
- try {
30
- const data = JSON.parse(fs.readFileSync(REGISTRY_LOCAL, 'utf-8'));
31
- if (!validateRegistry(data)) {
32
- error('Invalid local registry format — missing "components" field.');
33
- process.exit(1);
34
- }
35
- return data;
36
- } catch (err) {
37
- error(`Failed to parse local registry: ${err instanceof Error ? err.message : err}`);
38
- process.exit(1);
39
- }
40
- }
41
-
42
- log('Fetching registry from remote...');
43
- try {
44
- const response = await fetch(REGISTRY_REMOTE);
45
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
46
- const data = await response.json();
47
- if (!validateRegistry(data)) {
48
- error('Invalid remote registry format — missing "components" field.');
49
- process.exit(1);
50
- }
51
- return data;
52
- } catch (err: unknown) {
53
- const message = err instanceof Error ? err.message : String(err);
54
- error(`Cannot fetch registry: ${message}`);
55
- process.exit(1);
56
- }
57
- };
58
-
59
- const installNpmPackages = (packages: string[], cwd: string, dev = false) => {
60
- if (packages.length === 0) return;
61
-
62
- const pkgJsonPath = path.join(cwd, 'package.json');
63
- let toInstall = packages;
64
-
65
- if (fs.existsSync(pkgJsonPath)) {
66
- const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));
67
- const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
68
- toInstall = packages.filter((p) => !allDeps[p]);
69
- }
70
-
71
- if (toInstall.length === 0) return;
72
-
73
- log(`Installing: ${toInstall.join(', ')}...`);
74
- const flag = dev ? '--save-dev' : '--save';
75
- try {
76
- execSync(`npm install ${toInstall.join(' ')} ${flag}`, { stdio: 'inherit', cwd });
77
- } catch (err) {
78
- error(`Failed to install packages: ${toInstall.join(', ')}. ${err instanceof Error ? err.message : ''}`);
79
- }
80
- };
81
-
82
- const VITE_DEV_PACKAGES = ['tailwindcss', '@tailwindcss/vite', '@vitejs/plugin-react', 'vite-plugin-babel', 'babel-plugin-react-compiler', '@types/node'];
83
-
84
- // Runtime packages always required installed regardless of registry content
85
- const RUNTIME_PACKAGES = ['@base-ui/react', 'tailwind-variants', 'clsx', 'tailwind-merge', 'tailwindcss-animate'];
86
-
87
- const VITE_CONFIG_TEMPLATE = `import { defineConfig } from 'vite';
88
- import tailwindcss from '@tailwindcss/vite';
89
- import react from '@vitejs/plugin-react';
90
- import babel from 'vite-plugin-babel';
91
- import { reactCompilerPreset } from 'babel-plugin-react-compiler';
92
- import path from 'path';
93
-
94
- // https://vite.dev/config/
95
- export default defineConfig({
96
- plugins: [
97
- tailwindcss(),
98
- react(),
99
- babel({ presets: [reactCompilerPreset()] }),
100
- ],
101
- resolve: {
102
- alias: {
103
- '@': path.resolve(__dirname, './src'),
104
- '@lib': path.resolve(__dirname, './src/lib'),
105
- '@components': path.resolve(__dirname, './src/components'),
106
- '@assets': path.resolve(__dirname, './src/assets'),
107
- '@pages': path.resolve(__dirname, './src/pages'),
108
- '@styles': path.resolve(__dirname, './src/styles'),
109
- },
110
- },
111
- });
112
- `;
113
-
114
- const TSCONFIG_PATHS = {
115
- '@/*': ['./src/*'],
116
- '@lib/*': ['./src/lib/*'],
117
- '@components/*': ['./src/components/*'],
118
- '@assets/*': ['./src/assets/*'],
119
- '@pages/*': ['./src/pages/*'],
120
- '@styles/*': ['./src/styles/*'],
121
- };
122
-
123
- const setupViteConfig = (cwd: string) => {
124
- installNpmPackages(VITE_DEV_PACKAGES, cwd, true);
125
-
126
- const configTs = path.join(cwd, 'vite.config.ts');
127
- const configJs = path.join(cwd, 'vite.config.js');
128
-
129
- // No config exists — create from template
130
- if (!fs.existsSync(configTs) && !fs.existsSync(configJs)) {
131
- fs.writeFileSync(configTs, VITE_CONFIG_TEMPLATE);
132
- log('Created vite.config.ts with Tailwind + React Compiler setup.');
133
- return;
134
- }
135
-
136
- const existingPath = fs.existsSync(configTs) ? configTs : configJs;
137
- let content = fs.readFileSync(existingPath, 'utf-8');
138
-
139
- const missingImports: string[] = [];
140
- if (!content.includes('@tailwindcss/vite')) missingImports.push("import tailwindcss from '@tailwindcss/vite';");
141
- if (!content.includes('@vitejs/plugin-react')) missingImports.push("import react from '@vitejs/plugin-react';");
142
- if (!content.includes('vite-plugin-babel')) missingImports.push("import babel from 'vite-plugin-babel';");
143
- if (!content.includes('babel-plugin-react-compiler')) missingImports.push("import { reactCompilerPreset } from 'babel-plugin-react-compiler';");
144
- if (!content.includes("from 'path'") && !content.includes('from "path"')) missingImports.push("import path from 'path';");
145
-
146
- const missingPlugins: string[] = [];
147
- if (!content.includes('tailwindcss()')) missingPlugins.push('tailwindcss()');
148
- if (!content.includes('react()') && !content.includes('react({')) missingPlugins.push('react()');
149
- if (!content.includes('reactCompilerPreset')) missingPlugins.push("babel({ presets: [reactCompilerPreset()] })");
150
-
151
- const hasAlias = content.includes('alias:') || content.includes('alias(') || content.includes("'@'") || content.includes('"@"');
152
-
153
- if (missingImports.length === 0 && missingPlugins.length === 0 && hasAlias) {
154
- log('vite.config already configured — skipping.');
155
- return;
156
- }
157
-
158
- // --- Auto-patch the file ---
159
-
160
- // 1. Insert missing imports after the last import statement
161
- if (missingImports.length > 0) {
162
- const importBlock = missingImports.join('\n');
163
- const allImports = [...content.matchAll(/^import\s.+$/gm)];
164
- if (allImports.length > 0) {
165
- const last = allImports[allImports.length - 1];
166
- const pos = last.index! + last[0].length;
167
- content = content.slice(0, pos) + '\n' + importBlock + content.slice(pos);
168
- } else {
169
- content = importBlock + '\n' + content;
170
- }
171
- }
172
-
173
- // 2. Insert missing plugins into plugins: [...]
174
- if (missingPlugins.length > 0) {
175
- const match = content.match(/plugins:\s*\[/);
176
- if (match && match.index !== undefined) {
177
- const pos = match.index + match[0].length;
178
- const after = content.slice(pos);
179
- const pluginLines = missingPlugins.map((p) => `\n ${p},`).join('');
180
- // If existing content continues on the same line (e.g. `plugins: [react()],`),
181
- // push it to a new line so formatting stays clean
182
- const needsNewline = after.length > 0 && after[0] !== '\n' && after[0] !== '\r';
183
- content = content.slice(0, pos) + pluginLines + (needsNewline ? '\n ' : '') + after;
184
- }
185
- }
186
-
187
- // 3. Insert resolve.alias block if missing
188
- if (!hasAlias) {
189
- const aliasBlock = [
190
- ' resolve: {',
191
- ' alias: {',
192
- " '@': path.resolve(__dirname, './src'),",
193
- " '@lib': path.resolve(__dirname, './src/lib'),",
194
- " '@components': path.resolve(__dirname, './src/components'),",
195
- " '@assets': path.resolve(__dirname, './src/assets'),",
196
- " '@pages': path.resolve(__dirname, './src/pages'),",
197
- " '@styles': path.resolve(__dirname, './src/styles'),",
198
- ' },',
199
- ' },',
200
- ].join('\n');
201
-
202
- // Find end of plugins array, then insert after that line
203
- const pluginsStart = content.search(/plugins:\s*\[/);
204
- if (pluginsStart !== -1) {
205
- let depth = 0;
206
- let foundStart = false;
207
- for (let i = pluginsStart; i < content.length; i++) {
208
- if (content[i] === '[') { depth++; foundStart = true; }
209
- if (content[i] === ']') depth--;
210
- if (foundStart && depth === 0) {
211
- let lineEnd = content.indexOf('\n', i);
212
- if (lineEnd === -1) lineEnd = content.length;
213
- content = content.slice(0, lineEnd + 1) + aliasBlock + '\n' + content.slice(lineEnd + 1);
214
- break;
215
- }
216
- }
217
- }
218
- }
219
-
220
- fs.writeFileSync(existingPath, content);
221
- log(`Updated ${path.basename(existingPath)} with Tailwind + React Compiler + path aliases.`);
222
- };
223
-
224
- const ensureTailwindCss = (cwd: string) => {
225
- const candidates = ['src/index.css', 'src/App.css', 'src/main.css'];
226
- for (const cssFile of candidates) {
227
- const cssPath = path.join(cwd, cssFile);
228
- if (fs.existsSync(cssPath)) {
229
- const content = fs.readFileSync(cssPath, 'utf-8');
230
- if (!content.includes('@import "tailwindcss"') && !content.includes("@import 'tailwindcss'")) {
231
- fs.writeFileSync(cssPath, `@import "tailwindcss";\n\n${content}`);
232
- log(`Added @import "tailwindcss" to ${cssFile}`);
233
- } else {
234
- log(`${cssFile} already imports Tailwind — skipping.`);
235
- }
236
- return;
237
- }
238
- }
239
- // No CSS file found — create src/index.css
240
- const srcDir = path.join(cwd, 'src');
241
- if (!fs.existsSync(srcDir)) fs.mkdirSync(srcDir, { recursive: true });
242
- fs.writeFileSync(path.join(srcDir, 'index.css'), '@import "tailwindcss";\n');
243
- log('Created src/index.css with @import "tailwindcss"');
244
- };
245
-
246
- const setupTsConfig = (cwd: string) => {
247
- const candidates = ['tsconfig.app.json', 'tsconfig.json'];
248
-
249
- for (const candidate of candidates) {
250
- const configPath = path.join(cwd, candidate);
251
- if (!fs.existsSync(configPath)) continue;
252
-
253
- const raw = fs.readFileSync(configPath, 'utf-8');
254
-
255
- if (raw.includes('"@/*"') || raw.includes("'@/*'")) {
256
- log(`${candidate} already has path aliases — skipping.`);
257
- return;
258
- }
259
-
260
- try {
261
- // Strip comments safely: block comments first, then single-line comments
262
- // only when they appear outside of string values (preceded by whitespace or line start)
263
- const stripped = raw
264
- .replace(/\/\*[\s\S]*?\*\//g, '')
265
- .replace(/(^|[\s,{[\]])\/\/[^\n]*/g, '$1');
266
- const parsed = JSON.parse(stripped) as { compilerOptions?: Record<string, unknown> };
267
- if (!parsed.compilerOptions) parsed.compilerOptions = {};
268
- parsed.compilerOptions.baseUrl = '.';
269
- parsed.compilerOptions.paths = TSCONFIG_PATHS;
270
- fs.writeFileSync(configPath, JSON.stringify(parsed, null, 2));
271
- log(`Added path aliases to ${candidate}.`);
272
- } catch (err) {
273
- warn(`Could not auto-patch ${candidate}: ${err instanceof Error ? err.message : err}`);
274
- warn('Add these to compilerOptions manually:');
275
- console.log('\n "baseUrl": ".",');
276
- console.log(' "paths": {');
277
- for (const [alias, targets] of Object.entries(TSCONFIG_PATHS)) {
278
- console.log(` "${alias}": ["${targets[0]}"],`);
279
- }
280
- console.log(' }');
281
- console.log('');
282
- }
283
- return;
284
- }
285
-
286
- // No tsconfig found — create a minimal one
287
- const newConfig = { compilerOptions: { baseUrl: '.', paths: TSCONFIG_PATHS } };
288
- fs.writeFileSync(path.join(cwd, 'tsconfig.json'), JSON.stringify(newConfig, null, 2));
289
- log('Created tsconfig.json with path aliases.');
290
- };
291
-
292
- const ensureCore = (registry: { core?: { dependencies: string[]; files: { path: string; content: string }[] } }, cwd: string) => {
293
- const core = registry.core;
294
- if (!core) return;
295
-
296
- installNpmPackages(core.dependencies, cwd);
297
-
298
- for (const file of core.files) {
299
- const targetPath = path.join(cwd, file.path);
300
- const targetDir = path.dirname(targetPath);
301
-
302
- if (!fs.existsSync(targetDir)) {
303
- fs.mkdirSync(targetDir, { recursive: true });
304
- }
305
-
306
- if (!fs.existsSync(targetPath)) {
307
- fs.writeFileSync(targetPath, file.content);
308
- log(`Created core file: ${file.path}`);
309
- }
310
- }
311
- };
312
-
313
- const addComponent = (
314
- name: string,
315
- registry: { core?: unknown; components: Record<string, { dependencies: string[]; internalDependencies?: string[]; files: { path: string; content: string }[] }> },
316
- cwd: string,
317
- options: { force: boolean },
318
- added: Set<string> = new Set()
319
- ) => {
320
- if (added.has(name)) return;
321
- added.add(name);
322
-
323
- const component = registry.components[name];
324
- if (!component) {
325
- error(`Component "${name}" not found. Run 'list' to see available components.`);
326
- return;
327
- }
328
-
329
- log(`Adding: ${name}...`);
330
-
331
- ensureCore(registry as Parameters<typeof ensureCore>[0], cwd);
332
- installNpmPackages(component.dependencies, cwd);
333
-
334
- // Resolve internal dependencies first
335
- if (component.internalDependencies) {
336
- for (const dep of component.internalDependencies) {
337
- if (registry.components[dep]) {
338
- addComponent(dep, registry, cwd, options, added);
339
- }
340
- }
341
- }
342
-
343
- for (const file of component.files) {
344
- const targetPath = path.join(cwd, file.path);
345
- const targetDir = path.dirname(targetPath);
346
-
347
- if (!fs.existsSync(targetDir)) {
348
- fs.mkdirSync(targetDir, { recursive: true });
349
- }
350
-
351
- if (fs.existsSync(targetPath) && !options.force) {
352
- warn(`Skipped (exists): ${file.path} — use --force to overwrite`);
353
- continue;
354
- }
355
-
356
- fs.writeFileSync(targetPath, file.content);
357
- log(`Created: ${file.path}`);
358
- }
359
- };
360
-
361
- const removeComponent = (name: string, registry: { components: Record<string, { files: { path: string }[] }> }, cwd: string) => {
362
- const component = registry.components[name];
363
- if (!component) {
364
- error(`Component "${name}" not found.`);
365
- return;
366
- }
367
-
368
- log(`Removing: ${name}...`);
369
-
370
- for (const file of component.files) {
371
- const targetPath = path.join(cwd, file.path);
372
- if (fs.existsSync(targetPath)) {
373
- fs.unlinkSync(targetPath);
374
- log(`Deleted: ${file.path}`);
375
- }
376
- }
377
-
378
- // Clean up empty directories
379
- for (const file of component.files) {
380
- const targetDir = path.dirname(path.join(cwd, file.path));
381
- try {
382
- if (fs.existsSync(targetDir) && fs.readdirSync(targetDir).length === 0) {
383
- fs.rmdirSync(targetDir);
384
- log(`Removed empty dir: ${path.relative(cwd, targetDir)}`);
385
- }
386
- } catch (err) {
387
- warn(`Could not remove directory: ${err instanceof Error ? err.message : err}`);
388
- }
389
- }
390
- };
391
-
392
- const main = async () => {
393
- const args = process.argv.slice(2);
394
- const isLocal = args.includes('--local');
395
- const isForce = args.includes('--force');
396
- const filteredArgs = args.filter((a) => !a.startsWith('--'));
397
- const command = filteredArgs[0];
398
- const componentNames = filteredArgs.slice(1);
399
-
400
- const cwd = getTargetProjectDir();
401
- const registry = await getRegistry(isLocal);
402
-
403
- switch (command) {
404
- case 'add': {
405
- if (componentNames.length === 0) {
406
- error('Usage: npx basuicn add <component-name> [--force]');
407
- return;
408
- }
409
-
410
- // Auto-init if not yet initialized
411
- const cnPath = path.join(cwd, 'src/lib/utils/cn.ts');
412
- if (!fs.existsSync(cnPath)) {
413
- log('Project not initialized — running init first...');
414
- setupViteConfig(cwd);
415
- setupTsConfig(cwd);
416
- ensureTailwindCss(cwd);
417
- installNpmPackages(RUNTIME_PACKAGES, cwd);
418
- }
419
-
420
- for (const name of componentNames) {
421
- addComponent(name, registry, cwd, { force: isForce });
422
- }
423
- log('Done!');
424
- break;
425
- }
426
-
427
- case 'remove': {
428
- if (componentNames.length === 0) {
429
- error('Usage: npx basuicn remove <component-name>');
430
- return;
431
- }
432
- for (const name of componentNames) {
433
- removeComponent(name, registry, cwd);
434
- }
435
- log('Done!');
436
- break;
437
- }
438
-
439
- case 'list': {
440
- const components = Object.keys(registry.components).sort();
441
- log(`Available components (${components.length}):`);
442
- for (const k of components) {
443
- const deps = registry.components[k].internalDependencies;
444
- const depStr = deps?.length ? ` (requires: ${deps.join(', ')})` : '';
445
- console.log(` - ${k}${depStr}`);
446
- }
447
- break;
448
- }
449
-
450
- case 'init': {
451
- setupViteConfig(cwd);
452
- setupTsConfig(cwd);
453
- ensureTailwindCss(cwd);
454
- installNpmPackages(RUNTIME_PACKAGES, cwd);
455
- ensureCore(registry, cwd);
456
- log('Initialization complete.');
457
- break;
458
- }
459
-
460
- case 'tailwind': {
461
- console.log('\n--- Copy to tailwind.config.ts / tailwind.config.js ---\n');
462
- console.log('// See README_CLI.md for full theme config');
463
- break;
464
- }
465
-
466
- default: {
467
- console.log(`
468
- basuicn UI Component CLI
469
-
470
- Commands:
471
- init Initialize project (install core deps + files)
472
- add <name> [--force] Add component(s) to your project
473
- remove <name> Remove component(s) from your project
474
- list List all available components
475
- tailwind Show Tailwind config instructions
476
-
477
- Options:
478
- --local Use local registry.json instead of remote
479
- --force Overwrite existing files when adding
480
- `);
481
- }
482
- }
483
- };
484
-
485
- main();
1
+ #!/usr/bin/env node
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import { execSync } from 'child_process';
5
+
6
+ const REGISTRY_LOCAL = './registry.json';
7
+ const REGISTRY_REMOTE = 'https://raw.githubusercontent.com/huy14032003/ui-component/main/registry.json';
8
+
9
+ const log = (msg: string) => console.log(`[basuicn] ${msg}`);
10
+ const warn = (msg: string) => console.warn(`[basuicn] WARN: ${msg}`);
11
+ const error = (msg: string) => console.error(`[basuicn] ERROR: ${msg}`);
12
+
13
+ const getTargetProjectDir = () => process.cwd();
14
+
15
+ // ─── Registry ──────────────────────���─────────────────────────────���────────────
16
+
17
+ interface RegistryFile { path: string; content: string }
18
+ interface RegistryComponent {
19
+ dependencies: string[];
20
+ internalDependencies?: string[];
21
+ files: RegistryFile[];
22
+ }
23
+ interface Registry {
24
+ core?: { dependencies: string[]; files: RegistryFile[] };
25
+ components: Record<string, RegistryComponent>;
26
+ }
27
+
28
+ const validateRegistry = (data: unknown): data is Registry => {
29
+ if (!data || typeof data !== 'object') return false;
30
+ const reg = data as Record<string, unknown>;
31
+ return 'components' in reg && typeof reg.components === 'object' && reg.components !== null;
32
+ };
33
+
34
+ const getRegistry = async (isLocal: boolean): Promise<Registry> => {
35
+ if (isLocal && fs.existsSync(REGISTRY_LOCAL)) {
36
+ log('Using local registry...');
37
+ try {
38
+ const data = JSON.parse(fs.readFileSync(REGISTRY_LOCAL, 'utf-8'));
39
+ if (!validateRegistry(data)) {
40
+ error('Invalid local registry format — missing "components" field.');
41
+ process.exit(1);
42
+ }
43
+ return data;
44
+ } catch (err) {
45
+ error(`Failed to parse local registry: ${err instanceof Error ? err.message : err}`);
46
+ process.exit(1);
47
+ }
48
+ }
49
+
50
+ log('Fetching registry from remote...');
51
+ try {
52
+ const response = await fetch(REGISTRY_REMOTE);
53
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
54
+ const data = await response.json();
55
+ if (!validateRegistry(data)) {
56
+ error('Invalid remote registry format — missing "components" field.');
57
+ process.exit(1);
58
+ }
59
+ return data;
60
+ } catch (err: unknown) {
61
+ const message = err instanceof Error ? err.message : String(err);
62
+ error(`Cannot fetch registry: ${message}`);
63
+ process.exit(1);
64
+ }
65
+ };
66
+
67
+ // ─── npm ──────────────────────────────────────────────────────────────────────
68
+
69
+ const installNpmPackages = (packages: string[], cwd: string, dev = false) => {
70
+ if (packages.length === 0) return;
71
+
72
+ const pkgJsonPath = path.join(cwd, 'package.json');
73
+ let toInstall = packages;
74
+
75
+ if (fs.existsSync(pkgJsonPath)) {
76
+ const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));
77
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
78
+ toInstall = packages.filter((p) => !allDeps[p]);
79
+ }
80
+
81
+ if (toInstall.length === 0) return;
82
+
83
+ log(`Installing: ${toInstall.join(', ')}...`);
84
+ const flag = dev ? '--save-dev' : '--save';
85
+ try {
86
+ execSync(`npm install ${toInstall.join(' ')} ${flag}`, { stdio: 'inherit', cwd });
87
+ } catch (err) {
88
+ error(`Failed to install packages: ${toInstall.join(', ')}. ${err instanceof Error ? err.message : ''}`);
89
+ }
90
+ };
91
+
92
+ // ─── Packages ───────────────────────��─────────────────────────────��───────────
93
+
94
+ /** Build/dev tooling installed as devDependencies */
95
+ const VITE_DEV_PACKAGES = [
96
+ 'tailwindcss',
97
+ '@tailwindcss/vite',
98
+ '@vitejs/plugin-react',
99
+ '@types/node',
100
+ ];
101
+
102
+ /**
103
+ * Runtime packages every project using these components needs.
104
+ * Installed as regular dependencies.
105
+ */
106
+ const RUNTIME_PACKAGES = [
107
+ '@base-ui/react',
108
+ 'tailwind-variants',
109
+ 'clsx',
110
+ 'tailwind-merge',
111
+ 'tailwindcss-animate',
112
+ 'lucide-react',
113
+ ];
114
+
115
+ // ─── Vite config ────────────────────────────���──────────────────────────��──────
116
+
117
+ const VITE_CONFIG_TEMPLATE = `import { defineConfig } from 'vite';
118
+ import tailwindcss from '@tailwindcss/vite';
119
+ import react from '@vitejs/plugin-react';
120
+ import path from 'path';
121
+
122
+ export default defineConfig({
123
+ plugins: [tailwindcss(), react()],
124
+ resolve: {
125
+ alias: {
126
+ '@': path.resolve(__dirname, './src'),
127
+ '@lib': path.resolve(__dirname, './src/lib'),
128
+ '@components': path.resolve(__dirname, './src/components'),
129
+ '@assets': path.resolve(__dirname, './src/assets'),
130
+ '@pages': path.resolve(__dirname, './src/pages'),
131
+ '@styles': path.resolve(__dirname, './src/styles'),
132
+ },
133
+ },
134
+ });
135
+ `;
136
+
137
+ const TSCONFIG_PATHS = {
138
+ '@/*': ['./src/*'],
139
+ '@lib/*': ['./src/lib/*'],
140
+ '@components/*': ['./src/components/*'],
141
+ '@assets/*': ['./src/assets/*'],
142
+ '@pages/*': ['./src/pages/*'],
143
+ '@styles/*': ['./src/styles/*'],
144
+ };
145
+
146
+ const setupViteConfig = (cwd: string) => {
147
+ installNpmPackages(VITE_DEV_PACKAGES, cwd, true);
148
+
149
+ const configTs = path.join(cwd, 'vite.config.ts');
150
+ const configJs = path.join(cwd, 'vite.config.js');
151
+
152
+ if (!fs.existsSync(configTs) && !fs.existsSync(configJs)) {
153
+ fs.writeFileSync(configTs, VITE_CONFIG_TEMPLATE);
154
+ log('Created vite.config.ts.');
155
+ return;
156
+ }
157
+
158
+ const existingPath = fs.existsSync(configTs) ? configTs : configJs;
159
+ let content = fs.readFileSync(existingPath, 'utf-8');
160
+
161
+ const missingImports: string[] = [];
162
+ if (!content.includes('@tailwindcss/vite')) missingImports.push("import tailwindcss from '@tailwindcss/vite';");
163
+ if (!content.includes('@vitejs/plugin-react')) missingImports.push("import react from '@vitejs/plugin-react';");
164
+ if (!content.includes("from 'path'") && !content.includes('from "path"')) missingImports.push("import path from 'path';");
165
+
166
+ const missingPlugins: string[] = [];
167
+ if (!content.includes('tailwindcss()')) missingPlugins.push('tailwindcss()');
168
+ if (!content.includes('react()') && !content.includes('react({')) missingPlugins.push('react()');
169
+
170
+ const hasAlias = content.includes('alias:') || content.includes("'@'") || content.includes('"@"');
171
+
172
+ if (missingImports.length === 0 && missingPlugins.length === 0 && hasAlias) {
173
+ log('vite.config already configured skipping.');
174
+ return;
175
+ }
176
+
177
+ if (missingImports.length > 0) {
178
+ const importBlock = missingImports.join('\n');
179
+ const allImports = [...content.matchAll(/^import\s.+$/gm)];
180
+ if (allImports.length > 0) {
181
+ const last = allImports[allImports.length - 1];
182
+ const pos = last.index! + last[0].length;
183
+ content = content.slice(0, pos) + '\n' + importBlock + content.slice(pos);
184
+ } else {
185
+ content = importBlock + '\n' + content;
186
+ }
187
+ }
188
+
189
+ if (missingPlugins.length > 0) {
190
+ const match = content.match(/plugins:\s*\[/);
191
+ if (match && match.index !== undefined) {
192
+ const pos = match.index + match[0].length;
193
+ const after = content.slice(pos);
194
+ const pluginLines = missingPlugins.map((p) => `\n ${p},`).join('');
195
+ const needsNewline = after.length > 0 && after[0] !== '\n' && after[0] !== '\r';
196
+ content = content.slice(0, pos) + pluginLines + (needsNewline ? '\n ' : '') + after;
197
+ }
198
+ }
199
+
200
+ if (!hasAlias) {
201
+ const aliasBlock = [
202
+ ' resolve: {',
203
+ ' alias: {',
204
+ " '@': path.resolve(__dirname, './src'),",
205
+ " '@lib': path.resolve(__dirname, './src/lib'),",
206
+ " '@components': path.resolve(__dirname, './src/components'),",
207
+ " '@assets': path.resolve(__dirname, './src/assets'),",
208
+ " '@pages': path.resolve(__dirname, './src/pages'),",
209
+ " '@styles': path.resolve(__dirname, './src/styles'),",
210
+ ' },',
211
+ ' },',
212
+ ].join('\n');
213
+
214
+ const pluginsStart = content.search(/plugins:\s*\[/);
215
+ if (pluginsStart !== -1) {
216
+ let depth = 0;
217
+ let foundStart = false;
218
+ for (let i = pluginsStart; i < content.length; i++) {
219
+ if (content[i] === '[') { depth++; foundStart = true; }
220
+ if (content[i] === ']') depth--;
221
+ if (foundStart && depth === 0) {
222
+ let lineEnd = content.indexOf('\n', i);
223
+ if (lineEnd === -1) lineEnd = content.length;
224
+ content = content.slice(0, lineEnd + 1) + aliasBlock + '\n' + content.slice(lineEnd + 1);
225
+ break;
226
+ }
227
+ }
228
+ }
229
+ }
230
+
231
+ fs.writeFileSync(existingPath, content);
232
+ log(`Updated ${path.basename(existingPath)} with Tailwind + path aliases.`);
233
+ };
234
+
235
+ // ─── tsconfig ────────────────────────��────────────────────────────────���───────
236
+
237
+ const setupTsConfig = (cwd: string) => {
238
+ const candidates = ['tsconfig.app.json', 'tsconfig.json'];
239
+
240
+ for (const candidate of candidates) {
241
+ const configPath = path.join(cwd, candidate);
242
+ if (!fs.existsSync(configPath)) continue;
243
+
244
+ const raw = fs.readFileSync(configPath, 'utf-8');
245
+
246
+ if (raw.includes('"@/*"') || raw.includes("'@/*'")) {
247
+ log(`${candidate} already has path aliases — skipping.`);
248
+ return;
249
+ }
250
+
251
+ try {
252
+ const stripped = raw
253
+ .replace(/\/\*[\s\S]*?\*\//g, '')
254
+ .replace(/(^|[\s,{[\]])\/\/[^\n]*/g, '$1');
255
+ const parsed = JSON.parse(stripped) as { compilerOptions?: Record<string, unknown> };
256
+ if (!parsed.compilerOptions) parsed.compilerOptions = {};
257
+ parsed.compilerOptions.baseUrl = '.';
258
+ parsed.compilerOptions.paths = TSCONFIG_PATHS;
259
+ fs.writeFileSync(configPath, JSON.stringify(parsed, null, 2));
260
+ log(`Added path aliases to ${candidate}.`);
261
+ } catch (err) {
262
+ warn(`Could not auto-patch ${candidate}: ${err instanceof Error ? err.message : err}`);
263
+ warn('Add these to compilerOptions manually:');
264
+ console.log('\n "baseUrl": ".",');
265
+ console.log(' "paths": {');
266
+ for (const [alias, targets] of Object.entries(TSCONFIG_PATHS)) {
267
+ console.log(` "${alias}": ["${targets[0]}"],`);
268
+ }
269
+ console.log(' }');
270
+ console.log('');
271
+ }
272
+ return;
273
+ }
274
+
275
+ const newConfig = { compilerOptions: { baseUrl: '.', paths: TSCONFIG_PATHS } };
276
+ fs.writeFileSync(path.join(cwd, 'tsconfig.json'), JSON.stringify(newConfig, null, 2));
277
+ log('Created tsconfig.json with path aliases.');
278
+ };
279
+
280
+ // ─── Core files ────────────────────────────���─────────────────────────────��────
281
+
282
+ /**
283
+ * Copy core files (cn.ts, index.css, ThemeProvider, themes.ts) from registry.
284
+ * Pass force=true on `init` to always overwrite — keeps core up to date.
285
+ */
286
+ const ensureCore = (
287
+ registry: { core?: { dependencies: string[]; files: RegistryFile[] } },
288
+ cwd: string,
289
+ options: { force?: boolean } = {}
290
+ ) => {
291
+ const core = registry.core;
292
+ if (!core) return;
293
+
294
+ installNpmPackages(core.dependencies, cwd);
295
+
296
+ for (const file of core.files) {
297
+ const targetPath = path.join(cwd, file.path);
298
+ const targetDir = path.dirname(targetPath);
299
+
300
+ if (!fs.existsSync(targetDir)) fs.mkdirSync(targetDir, { recursive: true });
301
+
302
+ if (fs.existsSync(targetPath) && !options.force) {
303
+ log(`Core file exists (skipping): ${file.path}`);
304
+ continue;
305
+ }
306
+
307
+ fs.writeFileSync(targetPath, file.content);
308
+ log(`${fs.existsSync(targetPath) ? 'Updated' : 'Created'} core file: ${file.path}`);
309
+ }
310
+ };
311
+
312
+ // ─── main.tsx patching ────────────────────────────────────────────────────────
313
+
314
+ /**
315
+ * Components that need additional setup in the main entry file.
316
+ * Key = component name in registry, value = import + JSX to inject.
317
+ */
318
+ const MAIN_PATCH_COMPONENTS: Record<string, { import: string; jsx: string }> = {
319
+ toast: {
320
+ import: "import { Toaster } from '@/components/ui/toast/Toaster';",
321
+ jsx: '<Toaster position="top-center" expand={true} richColors />',
322
+ },
323
+ };
324
+
325
+ const MAIN_CANDIDATES = ['src/main.tsx', 'src/main.jsx', 'src/index.tsx', 'src/index.jsx'];
326
+
327
+ const findMainFile = (cwd: string): string | null => {
328
+ for (const c of MAIN_CANDIDATES) {
329
+ const p = path.join(cwd, c);
330
+ if (fs.existsSync(p)) return p;
331
+ }
332
+ return null;
333
+ };
334
+
335
+ const insertImport = (content: string, importLine: string): string => {
336
+ // Don't add duplicate
337
+ if (content.includes(importLine)) return content;
338
+ const allImports = [...content.matchAll(/^import\s.+$/gm)];
339
+ if (allImports.length > 0) {
340
+ const last = allImports[allImports.length - 1];
341
+ const pos = last.index! + last[0].length;
342
+ return content.slice(0, pos) + '\n' + importLine + content.slice(pos);
343
+ }
344
+ return importLine + '\n' + content;
345
+ };
346
+
347
+ /**
348
+ * Patches the main entry file to:
349
+ * 1. Import src/styles/index.css (theme variables + Tailwind)
350
+ * 2. Import ThemeProvider
351
+ * 3. Wrap <App /> with <ThemeProvider>
352
+ *
353
+ * Safe to call multiple times — skips sections that are already set up.
354
+ */
355
+ const patchMainTsx = (cwd: string) => {
356
+ const mainPath = findMainFile(cwd);
357
+ if (!mainPath) {
358
+ warn('Could not find entry file (src/main.tsx). Skipping main entry setup.');
359
+ return;
360
+ }
361
+
362
+ let content = fs.readFileSync(mainPath, 'utf-8');
363
+ let changed = false;
364
+
365
+ // 1. Ensure styles/index.css is imported
366
+ const cssImportLine = "import './styles/index.css';";
367
+ const hasCssImport = content.includes('styles/index.css') || content.includes('index.css');
368
+ if (!hasCssImport) {
369
+ // Insert at top before other imports
370
+ const firstImport = content.match(/^import\s/m);
371
+ if (firstImport?.index !== undefined) {
372
+ content = content.slice(0, firstImport.index) + cssImportLine + '\n' + content.slice(firstImport.index);
373
+ } else {
374
+ content = cssImportLine + '\n' + content;
375
+ }
376
+ changed = true;
377
+ } else if (!content.includes('styles/index.css')) {
378
+ // Has some CSS import but not our theme CSS — add it alongside
379
+ content = insertImport(content, cssImportLine);
380
+ changed = true;
381
+ }
382
+
383
+ // 2. ThemeProvider
384
+ if (!content.includes('ThemeProvider')) {
385
+ content = insertImport(content, "import { ThemeProvider } from '@/lib/theme/ThemeProvider';");
386
+
387
+ const wrapped = content.replace(/(<App\s*\/>)/g, '<ThemeProvider>\n $1\n </ThemeProvider>');
388
+ if (wrapped === content) {
389
+ warn('Could not locate <App /> in entry file — add <ThemeProvider> wrapper manually.');
390
+ } else {
391
+ content = wrapped;
392
+ }
393
+ changed = true;
394
+ }
395
+
396
+ if (changed) {
397
+ fs.writeFileSync(mainPath, content);
398
+ log(`Patched ${path.relative(cwd, mainPath)}.`);
399
+ } else {
400
+ log(`${path.relative(cwd, mainPath)} already configured — skipping.`);
401
+ }
402
+ };
403
+
404
+ /**
405
+ * Injects a component's bootstrap JSX (e.g. <Toaster />) into the main entry file.
406
+ * Places it inside <ThemeProvider> after <App />, falls back to right after <App />.
407
+ */
408
+ const patchMainTsxComponent = (cwd: string, componentName: string) => {
409
+ const patch = MAIN_PATCH_COMPONENTS[componentName];
410
+ if (!patch) return;
411
+
412
+ const mainPath = findMainFile(cwd);
413
+ if (!mainPath) return;
414
+
415
+ let content = fs.readFileSync(mainPath, 'utf-8');
416
+ // Check by component tag name (e.g. "Toaster")
417
+ const tagName = patch.jsx.match(/<(\w+)/)?.[1];
418
+ if (tagName && content.includes(`<${tagName}`)) return;
419
+
420
+ content = insertImport(content, patch.import);
421
+
422
+ const withProvider = content.replace(
423
+ /(<App\s*\/>)(\s*\n\s*<\/ThemeProvider>)/,
424
+ `$1\n ${patch.jsx}$2`
425
+ );
426
+
427
+ if (withProvider !== content) {
428
+ fs.writeFileSync(mainPath, withProvider);
429
+ } else {
430
+ const fallback = content.replace(/(<App\s*\/>)/, `$1\n ${patch.jsx}`);
431
+ if (fallback !== content) fs.writeFileSync(mainPath, fallback);
432
+ }
433
+
434
+ log(`Added <${tagName}> to ${path.relative(cwd, mainPath)}.`);
435
+ };
436
+
437
+ // ─── Component add/remove ──────────────────────────��──────────────────────────
438
+
439
+ const addComponent = (
440
+ name: string,
441
+ registry: { core?: unknown; components: Record<string, RegistryComponent> },
442
+ cwd: string,
443
+ options: { force: boolean },
444
+ added: Set<string> = new Set()
445
+ ) => {
446
+ if (added.has(name)) return;
447
+ added.add(name);
448
+
449
+ const component = registry.components[name];
450
+ if (!component) {
451
+ error(`Component "${name}" not found. Run 'list' to see available components.`);
452
+ return;
453
+ }
454
+
455
+ log(`Adding: ${name}...`);
456
+
457
+ ensureCore(registry as Parameters<typeof ensureCore>[0], cwd);
458
+ installNpmPackages(component.dependencies, cwd);
459
+
460
+ if (component.internalDependencies) {
461
+ for (const dep of component.internalDependencies) {
462
+ if (registry.components[dep]) {
463
+ addComponent(dep, registry, cwd, options, added);
464
+ }
465
+ }
466
+ }
467
+
468
+ for (const file of component.files) {
469
+ const targetPath = path.join(cwd, file.path);
470
+ const targetDir = path.dirname(targetPath);
471
+
472
+ if (!fs.existsSync(targetDir)) fs.mkdirSync(targetDir, { recursive: true });
473
+
474
+ if (fs.existsSync(targetPath) && !options.force) {
475
+ warn(`Skipped (exists): ${file.path} — use --force to overwrite`);
476
+ continue;
477
+ }
478
+
479
+ fs.writeFileSync(targetPath, file.content);
480
+ log(`Created: ${file.path}`);
481
+ }
482
+ };
483
+
484
+ const removeComponent = (
485
+ name: string,
486
+ registry: { components: Record<string, { files: { path: string }[] }> },
487
+ cwd: string
488
+ ) => {
489
+ const component = registry.components[name];
490
+ if (!component) {
491
+ error(`Component "${name}" not found.`);
492
+ return;
493
+ }
494
+
495
+ log(`Removing: ${name}...`);
496
+
497
+ for (const file of component.files) {
498
+ const targetPath = path.join(cwd, file.path);
499
+ if (fs.existsSync(targetPath)) {
500
+ fs.unlinkSync(targetPath);
501
+ log(`Deleted: ${file.path}`);
502
+ }
503
+ }
504
+
505
+ for (const file of component.files) {
506
+ const targetDir = path.dirname(path.join(cwd, file.path));
507
+ try {
508
+ if (fs.existsSync(targetDir) && fs.readdirSync(targetDir).length === 0) {
509
+ fs.rmdirSync(targetDir);
510
+ log(`Removed empty dir: ${path.relative(cwd, targetDir)}`);
511
+ }
512
+ } catch (err) {
513
+ warn(`Could not remove directory: ${err instanceof Error ? err.message : err}`);
514
+ }
515
+ }
516
+ };
517
+
518
+ // ─── Commands ─────────────────────────────────────────────────────────────────
519
+
520
+ const main = async () => {
521
+ const args = process.argv.slice(2);
522
+ const isLocal = args.includes('--local');
523
+ const isForce = args.includes('--force');
524
+ const filteredArgs = args.filter((a) => !a.startsWith('--'));
525
+ const command = filteredArgs[0];
526
+ const componentNames = filteredArgs.slice(1);
527
+
528
+ const cwd = getTargetProjectDir();
529
+ const registry = await getRegistry(isLocal);
530
+
531
+ switch (command) {
532
+
533
+ case 'init': {
534
+ log('Initializing project...');
535
+ setupViteConfig(cwd);
536
+ setupTsConfig(cwd);
537
+ installNpmPackages(RUNTIME_PACKAGES, cwd);
538
+ // force=true so init always refreshes core files to latest version
539
+ ensureCore(registry, cwd, { force: true });
540
+ patchMainTsx(cwd);
541
+ log('Initialization complete.');
542
+ break;
543
+ }
544
+
545
+ case 'add': {
546
+ if (componentNames.length === 0) {
547
+ error('Usage: npx basuicn add <component-name> [--force]');
548
+ return;
549
+ }
550
+
551
+ // Auto-init if project hasn't been initialized yet
552
+ const cnPath = path.join(cwd, 'src/lib/utils/cn.ts');
553
+ if (!fs.existsSync(cnPath)) {
554
+ log('Project not initialized — running init first...');
555
+ setupViteConfig(cwd);
556
+ setupTsConfig(cwd);
557
+ installNpmPackages(RUNTIME_PACKAGES, cwd);
558
+ ensureCore(registry, cwd, { force: true });
559
+ patchMainTsx(cwd);
560
+ }
561
+
562
+ for (const name of componentNames) {
563
+ addComponent(name, registry, cwd, { force: isForce });
564
+ patchMainTsxComponent(cwd, name);
565
+ }
566
+ log('Done!');
567
+ break;
568
+ }
569
+
570
+ case 'update': {
571
+ if (componentNames.length === 0) {
572
+ error('Usage: npx basuicn update <component-name> [...]');
573
+ return;
574
+ }
575
+ for (const name of componentNames) {
576
+ log(`Updating: ${name}...`);
577
+ addComponent(name, registry, cwd, { force: true });
578
+ }
579
+ log('Update complete.');
580
+ break;
581
+ }
582
+
583
+ case 'remove': {
584
+ if (componentNames.length === 0) {
585
+ error('Usage: npx basuicn remove <component-name>');
586
+ return;
587
+ }
588
+ for (const name of componentNames) {
589
+ removeComponent(name, registry, cwd);
590
+ }
591
+ log('Done!');
592
+ break;
593
+ }
594
+
595
+ case 'list': {
596
+ const components = Object.keys(registry.components).sort();
597
+ log(`Available components (${components.length}):`);
598
+ for (const k of components) {
599
+ const comp = registry.components[k];
600
+ const deps = comp.internalDependencies?.filter(Boolean);
601
+ const depStr = deps?.length ? ` (requires: ${deps.join(', ')})` : '';
602
+ console.log(` - ${k}${depStr}`);
603
+ }
604
+ break;
605
+ }
606
+
607
+ case 'diff': {
608
+ if (componentNames.length === 0) {
609
+ error('Usage: npx basuicn diff <component-name>');
610
+ return;
611
+ }
612
+ for (const name of componentNames) {
613
+ const component = registry.components[name];
614
+ if (!component) {
615
+ error(`Component "${name}" not found. Run 'list' to see available components.`);
616
+ continue;
617
+ }
618
+ let hasDiff = false;
619
+ console.log(`\n[diff] ${name}`);
620
+ for (const file of component.files) {
621
+ const targetPath = path.join(cwd, file.path);
622
+ if (!fs.existsSync(targetPath)) {
623
+ console.log(` + [new file] ${file.path}`);
624
+ hasDiff = true;
625
+ continue;
626
+ }
627
+ const localContent = fs.readFileSync(targetPath, 'utf-8');
628
+ if (localContent === file.content) continue;
629
+ hasDiff = true;
630
+ console.log(`\n ~ ${file.path}`);
631
+ const localLines = localContent.split('\n');
632
+ const remoteLines = file.content.split('\n');
633
+ const maxLen = Math.max(localLines.length, remoteLines.length);
634
+ let shownLines = 0;
635
+ for (let i = 0; i < maxLen; i++) {
636
+ if (localLines[i] !== remoteLines[i]) {
637
+ if (localLines[i] !== undefined) console.log(` - ${localLines[i]}`);
638
+ if (remoteLines[i] !== undefined) console.log(` + ${remoteLines[i]}`);
639
+ shownLines++;
640
+ if (shownLines >= 20) {
641
+ const remaining = maxLen - i - 1;
642
+ if (remaining > 0) console.log(` ... and ${remaining} more lines`);
643
+ break;
644
+ }
645
+ }
646
+ }
647
+ }
648
+ if (!hasDiff) log(`${name}: already up to date.`);
649
+ }
650
+ break;
651
+ }
652
+
653
+ case 'doctor': {
654
+ log('Running project health check...\n');
655
+ let issues = 0;
656
+ const check = (ok: boolean, msg: string, fix?: string) => {
657
+ console.log(`${ok ? ' ✓' : ' ✗'} ${msg}`);
658
+ if (!ok) { if (fix) console.log(` → ${fix}`); issues++; }
659
+ };
660
+
661
+ // ── Core files ──────────────────────────────────────────────────
662
+ check(fs.existsSync(path.join(cwd, 'src/lib/utils/cn.ts')),
663
+ 'src/lib/utils/cn.ts', 'run: npx basuicn init');
664
+ check(fs.existsSync(path.join(cwd, 'src/lib/theme/themes.ts')),
665
+ 'src/lib/theme/themes.ts', 'run: npx basuicn init');
666
+ check(fs.existsSync(path.join(cwd, 'src/lib/theme/ThemeProvider.tsx')),
667
+ 'src/lib/theme/ThemeProvider.tsx', 'run: npx basuicn init');
668
+ check(fs.existsSync(path.join(cwd, 'src/styles/index.css')),
669
+ 'src/styles/index.css (theme variables)', 'run: npx basuicn init');
670
+
671
+ // ── main entry ────────────────���──────────────────────────��──────
672
+ const mainPath = findMainFile(cwd);
673
+ if (mainPath) {
674
+ const mainContent = fs.readFileSync(mainPath, 'utf-8');
675
+ check(mainContent.includes('ThemeProvider'),
676
+ 'ThemeProvider in main entry', 'run: npx basuicn init');
677
+ check(mainContent.includes('styles/index.css') || mainContent.includes('index.css'),
678
+ 'CSS import in main entry', 'run: npx basuicn init');
679
+ } else {
680
+ check(false, 'main entry file (src/main.tsx)', 'create src/main.tsx');
681
+ }
682
+
683
+ // ── Runtime packages ─────────────────────────��──────────────────
684
+ const pkgPath = path.join(cwd, 'package.json');
685
+ if (fs.existsSync(pkgPath)) {
686
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
687
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
688
+ for (const dep of RUNTIME_PACKAGES) {
689
+ check(!!allDeps[dep], `package: ${dep}`, `run: npm install ${dep}`);
690
+ }
691
+ // Dev packages
692
+ for (const dep of VITE_DEV_PACKAGES) {
693
+ check(!!allDeps[dep], `package (dev): ${dep}`, `run: npm install -D ${dep}`);
694
+ }
695
+ } else {
696
+ check(false, 'package.json found', 'run: npm init -y');
697
+ }
698
+
699
+ // ── Config files ────────────────────���───────────────────────────
700
+ const hasTailwindInCss = (() => {
701
+ const candidates = ['src/styles/index.css', 'src/index.css', 'src/App.css'];
702
+ return candidates.some(f => {
703
+ const p = path.join(cwd, f);
704
+ if (!fs.existsSync(p)) return false;
705
+ const c = fs.readFileSync(p, 'utf-8');
706
+ return c.includes('@import "tailwindcss"') || c.includes("@import 'tailwindcss'");
707
+ });
708
+ })();
709
+ check(hasTailwindInCss, '@import "tailwindcss" in CSS', 'run: npx basuicn init');
710
+
711
+ const tsCandidates = ['tsconfig.app.json', 'tsconfig.json'];
712
+ const hasAlias = tsCandidates.some(f => {
713
+ const p = path.join(cwd, f);
714
+ if (!fs.existsSync(p)) return false;
715
+ const c = fs.readFileSync(p, 'utf-8');
716
+ return c.includes('"@/*"') || c.includes("'@/*'");
717
+ });
718
+ check(hasAlias, 'TypeScript path aliases (@/*)', 'run: npx basuicn init');
719
+
720
+ const hasViteConfig =
721
+ fs.existsSync(path.join(cwd, 'vite.config.ts')) ||
722
+ fs.existsSync(path.join(cwd, 'vite.config.js'));
723
+ check(hasViteConfig, 'vite.config.ts / vite.config.js', 'run: npx basuicn init');
724
+
725
+ console.log('');
726
+ if (issues === 0) {
727
+ log('All checks passed! Project is healthy.');
728
+ } else {
729
+ warn(`${issues} issue(s) found. Run "npx basuicn init" to fix most issues.`);
730
+ }
731
+ break;
732
+ }
733
+
734
+ default: {
735
+ console.log(`
736
+ basuicn — UI Component CLI
737
+
738
+ Commands:
739
+ init Set up project: install deps, copy core files, patch main entry
740
+ add <name> [--force] Add component(s) to your project
741
+ update <name> Update component(s) to latest registry version
742
+ diff <name> Show diff between local and registry version
743
+ remove <name> Remove component(s) from your project
744
+ list List all available components
745
+ doctor Check project health and configuration
746
+
747
+ Options:
748
+ --local Use local registry.json instead of remote
749
+ --force Overwrite existing files when adding
750
+
751
+ Quick start:
752
+ npx basuicn init
753
+ npx basuicn add button
754
+ npx basuicn add toast
755
+ `);
756
+ }
757
+ }
758
+ };
759
+
760
+ main();