@foundrykit/cli 0.1.0 → 0.1.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.
@@ -1,99 +1,51 @@
1
+ /**
2
+ * Add command for FoundryKit CLI
3
+ * Handles adding components to projects
4
+ */
5
+
1
6
  import { Command } from 'commander';
2
7
  import chalk from 'chalk';
3
8
  import fs from 'fs-extra';
4
9
  import path from 'path';
5
- import fetch from 'node-fetch';
6
10
  import inquirer from 'inquirer';
11
+ import type {
12
+ ComponentMeta,
13
+ ComponentData,
14
+ ComponentCategory,
15
+ } from '@foundrykit/types';
16
+ import { getRegistry } from '../lib/registry.js';
7
17
 
8
18
  interface AddOptions {
9
19
  withAnimation?: boolean;
10
20
  path?: string;
11
- force?: boolean;
12
- }
13
-
14
- interface ComponentFile {
15
- path: string;
16
- content: string;
17
- type: 'component' | 'hook' | 'util' | 'style';
18
- }
19
-
20
- interface ComponentData {
21
- name: string;
22
- category: 'primitives' | 'components' | 'blocks';
23
- description: string;
24
- dependencies?: string[];
25
- files: ComponentFile[];
26
- registryDependencies?: string[];
21
+ overwrite?: boolean;
27
22
  }
28
23
 
29
24
  export function addCommand() {
30
25
  return new Command('add')
31
26
  .description('Add a component or block to your project')
32
- .argument('<id>', 'Component or block ID')
27
+ .argument('[id]', 'Component or block ID (optional for interactive mode)')
33
28
  .option('--with-animation', 'Include animation variants')
34
- .option('--path <path>', 'Custom installation path')
35
- .option('--force', 'Force overwrite existing files')
36
- .action(async (id: string, options: AddOptions) => {
29
+ .option('-p, --path <path>', 'Custom installation path')
30
+ .option('-o, --overwrite', 'Overwrite existing files')
31
+ .action(async (id: string | undefined, options: AddOptions) => {
37
32
  try {
38
- console.log(chalk.blue(`šŸ“¦ Adding ${id} to your project...`));
39
-
40
- // Validate FoundryKit is initialized
41
- await validateFoundryKitProject();
42
-
43
- // Get component data
44
- const componentData = await getComponentData(id);
45
-
46
- if (!componentData) {
47
- console.error(chalk.red(`āŒ Component "${id}" not found.`));
48
- console.log(
49
- chalk.gray('\nUse "foundrykit list" to see available components.')
50
- );
51
- return;
52
- }
53
-
54
- // Check for existing files
55
- if (
56
- !options.force &&
57
- (await hasConflictingFiles(componentData, options))
58
- ) {
59
- const { shouldContinue } = await inquirer.prompt([
60
- {
61
- type: 'confirm',
62
- name: 'shouldContinue',
63
- message: 'Some files already exist. Continue and overwrite?',
64
- default: false,
65
- },
66
- ]);
67
-
68
- if (!shouldContinue) {
69
- console.log(chalk.yellow('āŒ Installation cancelled.'));
33
+ // If no ID provided, show interactive selector
34
+ if (!id) {
35
+ const selectedIds = await selectComponentsInteractively();
36
+ if (selectedIds.length === 0) {
37
+ console.log(chalk.yellow('No components selected.'));
70
38
  return;
71
39
  }
72
- }
73
40
 
74
- // Install registry dependencies first
75
- if (
76
- componentData.registryDependencies &&
77
- componentData.registryDependencies.length > 0
78
- ) {
79
- console.log(chalk.blue('šŸ“¦ Installing required components...'));
80
- for (const dep of componentData.registryDependencies) {
81
- await addComponent(dep, { ...options, force: true });
41
+ // Add each selected component
42
+ for (const componentId of selectedIds) {
43
+ await addSingleComponent(componentId, options);
82
44
  }
45
+ } else {
46
+ // Add single component
47
+ await addSingleComponent(id, options);
83
48
  }
84
-
85
- // Install the component files
86
- await installComponentFiles(componentData, options);
87
-
88
- // Update imports if needed
89
- await updateImports(componentData);
90
-
91
- console.log(
92
- chalk.green(`\nāœ… ${componentData.name} added successfully!`)
93
- );
94
-
95
- // Show usage example
96
- showUsageExample(componentData);
97
49
  } catch (error) {
98
50
  console.error(chalk.red('āŒ Failed to add component:'));
99
51
  console.error(
@@ -104,197 +56,197 @@ export function addCommand() {
104
56
  });
105
57
  }
106
58
 
107
- async function validateFoundryKitProject(): Promise<void> {
108
- const tailwindConfigPath = path.join(process.cwd(), 'tailwind.config.ts');
109
- const tailwindConfigJsPath = path.join(process.cwd(), 'tailwind.config.js');
59
+ /**
60
+ * Interactive component selection
61
+ */
62
+ async function selectComponentsInteractively(): Promise<string[]> {
63
+ console.log(chalk.blue('šŸ“¦ Select components to add:'));
64
+ console.log(
65
+ chalk.gray(' Use arrow keys to navigate, space to select, a to toggle all')
66
+ );
67
+ console.log(chalk.gray(' Press enter when done\n'));
110
68
 
111
- if (
112
- !fs.existsSync(tailwindConfigPath) &&
113
- !fs.existsSync(tailwindConfigJsPath)
114
- ) {
115
- throw new Error('FoundryKit not initialized. Run "foundrykit init" first.');
116
- }
69
+ const registry = getRegistry();
117
70
 
118
- // Check if config includes FoundryKit
119
- const configPath = fs.existsSync(tailwindConfigPath)
120
- ? tailwindConfigPath
121
- : tailwindConfigJsPath;
122
- const config = await fs.readFile(configPath, 'utf-8');
71
+ try {
72
+ // Fetch all available components from registry
73
+ console.log(chalk.gray('Fetching components from registry...'));
74
+ const allComponents = await registry.getComponents();
123
75
 
124
- if (!config.includes('@foundrykit/tailwind-config')) {
125
- throw new Error(
126
- 'FoundryKit not properly configured. Run "foundrykit init" first.'
76
+ if (allComponents.length === 0) {
77
+ console.log(chalk.yellow('No components available in the registry.'));
78
+ return [];
79
+ }
80
+
81
+ // Group components by category
82
+ const groupedChoices = createGroupedChoices(allComponents);
83
+
84
+ const { selectedComponents } = await inquirer.prompt([
85
+ {
86
+ type: 'checkbox',
87
+ name: 'selectedComponents',
88
+ message: 'Which components would you like to add?',
89
+ choices: groupedChoices,
90
+ pageSize: 20,
91
+ loop: false,
92
+ },
93
+ ]);
94
+
95
+ return selectedComponents;
96
+ } catch (error) {
97
+ console.error(chalk.red('Failed to fetch components from registry:'));
98
+ console.error(
99
+ chalk.red(error instanceof Error ? error.message : String(error))
127
100
  );
101
+ throw error;
128
102
  }
129
103
  }
130
104
 
131
- async function getComponentData(id: string): Promise<ComponentData | null> {
132
- try {
133
- // Try to fetch from registry API
134
- const response = await fetch(`http://localhost:3001/api/components/${id}`);
135
- if (response.ok) {
136
- const data = await response.json();
137
- return data as ComponentData;
105
+ /**
106
+ * Create grouped choices for the interactive selector
107
+ */
108
+ function createGroupedChoices(components: ComponentMeta[]) {
109
+ const categories: ComponentCategory[] = [
110
+ 'primitives',
111
+ 'components',
112
+ 'blocks',
113
+ 'animations',
114
+ ];
115
+
116
+ const choices: any[] = [];
117
+
118
+ for (const category of categories) {
119
+ const categoryComponents = components.filter(c => c.category === category);
120
+
121
+ if (categoryComponents.length === 0) continue;
122
+
123
+ // Add category separator
124
+ choices.push({
125
+ name: chalk.bold.cyan(`─── ${category.toUpperCase()} ───`),
126
+ disabled: true,
127
+ value: `separator-${category}`,
128
+ });
129
+
130
+ // Add components in this category
131
+ for (const component of categoryComponents) {
132
+ choices.push({
133
+ name: `${component.name} - ${chalk.gray(component.description)}`,
134
+ value: component.id,
135
+ short: component.name,
136
+ });
138
137
  }
139
- } catch (error) {
140
- // Fall back to local registry
141
138
  }
142
139
 
143
- // Return local component data
144
- return getLocalComponentData(id);
140
+ return choices;
145
141
  }
146
142
 
147
- function getLocalComponentData(id: string): ComponentData | null {
148
- const components: Record<string, ComponentData> = {
149
- button: {
150
- name: 'Button',
151
- category: 'primitives',
152
- description: 'A button component with multiple variants.',
153
- files: [
143
+ /**
144
+ * Add a single component to the project
145
+ */
146
+ async function addSingleComponent(
147
+ id: string,
148
+ options: AddOptions
149
+ ): Promise<void> {
150
+ console.log(chalk.blue(`\nšŸ“¦ Adding ${id} to your project...`));
151
+
152
+ // Validate project is initialized
153
+ await validateProject();
154
+
155
+ const registry = getRegistry();
156
+
157
+ try {
158
+ // Fetch component data from registry
159
+ const componentData = await registry.getComponent(id);
160
+
161
+ // Check for existing files
162
+ if (
163
+ !options.overwrite &&
164
+ (await hasConflictingFiles(componentData, options))
165
+ ) {
166
+ const { shouldContinue } = await inquirer.prompt([
154
167
  {
155
- path: 'components/ui/button.tsx',
156
- type: 'component',
157
- content: `import * as React from "react"
158
- import { Slot } from "@radix-ui/react-slot"
159
- import { cva, type VariantProps } from "class-variance-authority"
160
-
161
- import { cn } from "@/lib/utils"
162
-
163
- const buttonVariants = cva(
164
- "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
165
- {
166
- variants: {
167
- variant: {
168
- default:
169
- "bg-primary text-primary-foreground shadow hover:bg-primary/90",
170
- destructive:
171
- "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
172
- outline:
173
- "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
174
- secondary:
175
- "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
176
- ghost: "hover:bg-accent hover:text-accent-foreground",
177
- link: "text-primary underline-offset-4 hover:underline",
178
- },
179
- size: {
180
- default: "h-9 px-4 py-2",
181
- sm: "h-8 rounded-md px-3 text-xs",
182
- lg: "h-10 rounded-md px-8",
183
- icon: "h-9 w-9",
184
- },
185
- },
186
- defaultVariants: {
187
- variant: "default",
188
- size: "default",
189
- },
190
- }
191
- )
168
+ type: 'confirm',
169
+ name: 'shouldContinue',
170
+ message: `Some files for ${componentData.name} already exist. Overwrite?`,
171
+ default: false,
172
+ },
173
+ ]);
192
174
 
193
- export interface ButtonProps
194
- extends React.ButtonHTMLAttributes<HTMLButtonElement>,
195
- VariantProps<typeof buttonVariants> {
196
- asChild?: boolean
197
- }
175
+ if (!shouldContinue) {
176
+ console.log(chalk.yellow(`ā­ļø Skipping ${componentData.name}.`));
177
+ return;
178
+ }
179
+ }
180
+
181
+ // Install registry dependencies first
182
+ if (componentData.registryDependencies?.length) {
183
+ console.log(chalk.blue('šŸ“¦ Installing required dependencies...'));
184
+ for (const dep of componentData.registryDependencies) {
185
+ // Check if dependency is already installed
186
+ const depData = await registry.getComponent(dep);
187
+ if (!(await hasConflictingFiles(depData, options))) {
188
+ await installComponentFiles(depData, options);
189
+ console.log(chalk.green(` āœ“ Installed ${dep}`));
190
+ }
191
+ }
192
+ }
193
+
194
+ // Install the component files
195
+ await installComponentFiles(componentData, options);
196
+
197
+ console.log(chalk.green(`āœ… ${componentData.name} added successfully!`));
198
+
199
+ // Show usage example
200
+ showUsageExample(componentData);
198
201
 
199
- const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
200
- ({ className, variant, size, asChild = false, ...props }, ref) => {
201
- const Comp = asChild ? Slot : "button"
202
- return (
203
- <Comp
204
- className={cn(buttonVariants({ variant, size, className }))}
205
- ref={ref}
206
- {...props}
207
- />
208
- )
202
+ // Show package dependencies if any
203
+ if (componentData.packageDependencies?.length) {
204
+ console.log(chalk.yellow('\nšŸ“¦ Required npm packages:'));
205
+ console.log(
206
+ chalk.gray(` ${componentData.packageDependencies.join(', ')}`)
207
+ );
208
+ console.log(chalk.gray(' Install them with:'));
209
+ console.log(
210
+ chalk.cyan(` pnpm add ${componentData.packageDependencies.join(' ')}`)
211
+ );
212
+ }
213
+ } catch (error) {
214
+ console.error(chalk.red(`Failed to add ${id}:`));
215
+ throw error;
209
216
  }
210
- )
211
- Button.displayName = "Button"
217
+ }
212
218
 
213
- export { Button, buttonVariants }
214
- `,
215
- },
216
- ],
217
- },
218
- input: {
219
- name: 'Input',
220
- category: 'primitives',
221
- description: 'A form input component.',
222
- files: [
223
- {
224
- path: 'components/ui/input.tsx',
225
- type: 'component',
226
- content: `import * as React from "react"
227
-
228
- import { cn } from "@/lib/utils"
229
-
230
- export interface InputProps
231
- extends React.InputHTMLAttributes<HTMLInputElement> {}
232
-
233
- const Input = React.forwardRef<HTMLInputElement, InputProps>(
234
- ({ className, type, ...props }, ref) => {
235
- return (
236
- <input
237
- type={type}
238
- className={cn(
239
- "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
240
- className
241
- )}
242
- ref={ref}
243
- {...props}
244
- />
245
- )
219
+ /**
220
+ * Validate that the project is properly initialized
221
+ */
222
+ async function validateProject(): Promise<void> {
223
+ const packageJsonPath = path.join(process.cwd(), 'package.json');
224
+
225
+ if (!fs.existsSync(packageJsonPath)) {
226
+ throw new Error(
227
+ 'No package.json found. Please run this command in a project root.'
228
+ );
246
229
  }
247
- )
248
- Input.displayName = "Input"
249
230
 
250
- export { Input }
251
- `,
252
- },
253
- ],
254
- },
255
- 'hero-minimal': {
256
- name: 'Hero Minimal',
257
- category: 'blocks',
258
- description: 'A minimal hero section with heading, description, and CTA.',
259
- registryDependencies: ['button'],
260
- files: [
261
- {
262
- path: 'components/blocks/hero-minimal.tsx',
263
- type: 'component',
264
- content: `import { Button } from "@/components/ui/button"
265
-
266
- export function HeroMinimal() {
267
- return (
268
- <section className="w-full py-12 md:py-24 lg:py-32">
269
- <div className="container px-4 md:px-6">
270
- <div className="flex flex-col items-center space-y-4 text-center">
271
- <div className="space-y-2">
272
- <h1 className="text-3xl font-bold tracking-tighter sm:text-4xl md:text-5xl lg:text-6xl/none">
273
- Welcome to FoundryKit
274
- </h1>
275
- <p className="mx-auto max-w-[700px] text-gray-500 md:text-xl dark:text-gray-400">
276
- Build beautiful, accessible React components with our comprehensive design system.
277
- Fast, flexible, and ready for production.
278
- </p>
279
- </div>
280
- <div className="space-x-4">
281
- <Button>Get Started</Button>
282
- <Button variant="outline">Learn More</Button>
283
- </div>
284
- </div>
285
- </div>
286
- </section>
287
- )
288
- }
289
- `,
290
- },
291
- ],
292
- },
231
+ const packageJson = await fs.readJson(packageJsonPath);
232
+ const dependencies = {
233
+ ...packageJson.dependencies,
234
+ ...packageJson.devDependencies,
293
235
  };
294
236
 
295
- return components[id] || null;
237
+ // Check for Next.js or FoundryKit packages
238
+ const hasFoundryKit = Object.keys(dependencies).some(dep =>
239
+ dep.startsWith('@foundrykit/')
240
+ );
241
+
242
+ if (!hasFoundryKit && !dependencies.next) {
243
+ throw new Error('FoundryKit not initialized. Run "foundrykit init" first.');
244
+ }
296
245
  }
297
246
 
247
+ /**
248
+ * Check if component files already exist
249
+ */
298
250
  async function hasConflictingFiles(
299
251
  componentData: ComponentData,
300
252
  options: AddOptions
@@ -311,6 +263,9 @@ async function hasConflictingFiles(
311
263
  return false;
312
264
  }
313
265
 
266
+ /**
267
+ * Install component files to the project
268
+ */
314
269
  async function installComponentFiles(
315
270
  componentData: ComponentData,
316
271
  options: AddOptions
@@ -332,44 +287,54 @@ async function installComponentFiles(
332
287
  }
333
288
  }
334
289
 
335
- async function updateImports(componentData: ComponentData): Promise<void> {
336
- // This would handle updating import maps, index files, etc.
337
- // For now, we'll skip this step
338
- }
339
-
340
- async function addComponent(id: string, options: AddOptions): Promise<void> {
341
- const componentData = await getComponentData(id);
342
- if (!componentData) {
343
- throw new Error(`Dependency component "${id}" not found.`);
344
- }
345
-
346
- await installComponentFiles(componentData, options);
347
- }
348
-
290
+ /**
291
+ * Show usage example for the installed component
292
+ */
349
293
  function showUsageExample(componentData: ComponentData): void {
350
294
  console.log(chalk.cyan('\nšŸ’” Usage:'));
351
295
 
352
- if (componentData.category === 'primitives') {
296
+ const componentName = componentData.name.replace(/\s+/g, '');
297
+
298
+ if (
299
+ componentData.category === 'primitives' ||
300
+ componentData.category === 'components'
301
+ ) {
353
302
  console.log(
354
303
  chalk.gray(
355
- `import { ${componentData.name} } from "@/components/ui/${componentData.name.toLowerCase()}"`
304
+ `import { ${componentName} } from "@/components/ui/${componentData.id}"`
356
305
  )
357
306
  );
358
307
  } else if (componentData.category === 'blocks') {
359
308
  console.log(
360
309
  chalk.gray(
361
- `import { ${componentData.name.replace(/\s+/g, '')} } from "@/components/blocks/${componentData.name.toLowerCase().replace(/\s+/g, '-')}"`
310
+ `import { ${componentName} } from "@/components/blocks/${componentData.id}"`
311
+ )
312
+ );
313
+ } else if (componentData.category === 'animations') {
314
+ console.log(
315
+ chalk.gray(
316
+ `import { ${componentName} } from "@/components/animations/${componentData.id}"`
362
317
  )
363
318
  );
364
319
  }
365
320
 
366
- // Show a basic usage example
367
- if (componentData.name === 'Button') {
321
+ // Show basic usage examples based on component type
322
+ if (componentData.id === 'button') {
368
323
  console.log(chalk.gray('\n<Button>Click me</Button>'));
369
324
  console.log(chalk.gray('<Button variant="outline">Outline</Button>'));
370
- } else if (componentData.name === 'Input') {
325
+ } else if (componentData.id === 'input') {
371
326
  console.log(chalk.gray('\n<Input placeholder="Enter text..." />'));
372
- } else if (componentData.name === 'Hero Minimal') {
373
- console.log(chalk.gray('\n<HeroMinimal />'));
327
+ } else if (componentData.id.includes('hero')) {
328
+ console.log(chalk.gray(`\n<${componentName} />`));
329
+ } else if (componentData.id === 'card') {
330
+ console.log(chalk.gray('\n<Card>'));
331
+ console.log(chalk.gray(' <CardHeader>'));
332
+ console.log(chalk.gray(' <CardTitle>Title</CardTitle>'));
333
+ console.log(
334
+ chalk.gray(' <CardDescription>Description</CardDescription>')
335
+ );
336
+ console.log(chalk.gray(' </CardHeader>'));
337
+ console.log(chalk.gray(' <CardContent>Content</CardContent>'));
338
+ console.log(chalk.gray('</Card>'));
374
339
  }
375
340
  }