@foundrykit/cli 1.0.5 → 1.0.7

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.
@@ -2,12 +2,43 @@ import { Command } from 'commander';
2
2
  import chalk from 'chalk';
3
3
  import fs from 'fs-extra';
4
4
  import path from 'path';
5
- import { execSync } from 'child_process';
6
5
  import inquirer from 'inquirer';
6
+ import { exec, execSync } from 'child_process';
7
+ import { promisify } from 'util';
7
8
 
8
9
  interface InitOptions {
9
10
  force?: boolean;
10
11
  skipInstall?: boolean;
12
+ skipPrompts?: boolean;
13
+ }
14
+
15
+ interface ProjectStructure {
16
+ hasSrc: boolean;
17
+ hasApp: boolean;
18
+ hasComponents: boolean;
19
+ hasLib: boolean;
20
+ hasHooks: boolean;
21
+ hasStyles: boolean;
22
+ baseDir: string;
23
+ framework: string;
24
+ isTypeScript: boolean;
25
+ packageManager: string;
26
+ appPath?: string;
27
+ componentsPath?: string;
28
+ libPath?: string;
29
+ hooksPath?: string;
30
+ stylesPath?: string;
31
+ }
32
+
33
+ interface PathConfig {
34
+ utils: string;
35
+ primitives: string;
36
+ components: string;
37
+ blocks: string;
38
+ hooks: string;
39
+ animations: string;
40
+ styles: string;
41
+ lib: string;
11
42
  }
12
43
 
13
44
  export function initCommand() {
@@ -15,6 +46,7 @@ export function initCommand() {
15
46
  .description('Initialize FoundryKit in your project')
16
47
  .option('-f, --force', 'overwrite existing files')
17
48
  .option('--skip-install', 'skip installing dependencies')
49
+ .option('--skip-prompts', 'use default paths without prompting')
18
50
  .action(async (options: InitOptions) => {
19
51
  try {
20
52
  console.log(chalk.blue('🚀 Initializing FoundryKit...'));
@@ -39,25 +71,43 @@ export function initCommand() {
39
71
  }
40
72
  }
41
73
 
74
+ // Detect project structure
75
+ const projectStructure = await detectProjectStructure();
76
+ console.log(
77
+ chalk.gray(
78
+ `Detected project structure: ${projectStructure.hasSrc ? 'src/' : 'root'} based`
79
+ )
80
+ );
81
+
82
+ // Get path configuration (with prompts or defaults)
83
+ const pathConfig = await getPathConfiguration(
84
+ projectStructure,
85
+ options.skipPrompts
86
+ );
87
+
42
88
  // Install dependencies
43
89
  if (!options.skipInstall) {
44
90
  await installDependencies();
45
91
  }
46
92
 
47
- // Create configuration file
48
- await createConfigFile(options);
93
+ // Create configuration file with custom paths
94
+ await createConfigFile(options, projectStructure, pathConfig);
49
95
 
50
- // Install utils
51
- await installUtils();
96
+ // Install utils with custom path
97
+ await installUtils(pathConfig);
52
98
 
53
99
  // Setup CSS with Tailwind v4
54
- await setupTailwindV4();
100
+ await setupTailwindV4(
101
+ pathConfig,
102
+ projectStructure,
103
+ options.skipPrompts
104
+ );
55
105
 
56
- // Create components directory
57
- await createDirectories();
106
+ // Create components directory with custom paths
107
+ await createDirectories(pathConfig);
58
108
 
59
- // Create example files
60
- await createExampleFiles();
109
+ // Create example files with custom paths
110
+ await createExampleFiles(pathConfig, projectStructure);
61
111
 
62
112
  // Update package.json scripts
63
113
  await updatePackageScripts();
@@ -94,19 +144,19 @@ async function validateProject(): Promise<void> {
94
144
 
95
145
  if (!fs.existsSync(packageJsonPath)) {
96
146
  throw new Error(
97
- 'No package.json found. Please run this command in a Next.js project root.'
147
+ 'No package.json found. Please run this command in a project directory.'
98
148
  );
99
149
  }
100
150
 
101
151
  const packageJson = await fs.readJson(packageJsonPath);
102
- const dependencies = {
152
+ const deps = {
103
153
  ...packageJson.dependencies,
104
154
  ...packageJson.devDependencies,
105
155
  };
106
156
 
107
- if (!dependencies.next) {
157
+ if (!deps.next) {
108
158
  throw new Error(
109
- 'Next.js not detected. This command should be run in a Next.js project.'
159
+ 'Next.js not detected. FoundryKit currently requires Next.js.'
110
160
  );
111
161
  }
112
162
 
@@ -114,97 +164,299 @@ async function validateProject(): Promise<void> {
114
164
  }
115
165
 
116
166
  async function isFoundryKitInitialized(): Promise<boolean> {
117
- // Check for foundrykit.config.json
118
- const configPath = path.join(process.cwd(), 'foundrykit.config.json');
119
- return fs.existsSync(configPath);
167
+ return fs.existsSync(path.join(process.cwd(), 'foundrykit.config.json'));
120
168
  }
121
169
 
122
- async function installDependencies(): Promise<void> {
123
- console.log(chalk.blue('📦 Installing base dependencies...'));
170
+ async function detectProjectStructure(): Promise<ProjectStructure> {
171
+ const cwd = process.cwd();
172
+
173
+ // Check for src directory
174
+ const hasSrc = fs.existsSync(path.join(cwd, 'src'));
175
+
176
+ // Determine base directory
177
+ let baseDir = './';
178
+ let appPath: string | undefined;
179
+ let componentsPath: string | undefined;
180
+ let libPath: string | undefined;
181
+ let hooksPath: string | undefined;
182
+ let stylesPath: string | undefined;
183
+
184
+ if (hasSrc) {
185
+ // Check if src contains app directory
186
+ const srcHasApp = fs.existsSync(path.join(cwd, 'src/app'));
187
+ if (srcHasApp) {
188
+ baseDir = './src/';
189
+ appPath = './src/app';
190
+ } else {
191
+ // Check if there's an app directory in root
192
+ const rootHasApp = fs.existsSync(path.join(cwd, 'app'));
193
+ if (rootHasApp) {
194
+ // Mixed structure - app in root, other dirs might be in src
195
+ appPath = './app';
196
+ baseDir = './src/';
197
+ }
198
+ }
124
199
 
125
- const dependencies = ['clsx', 'tailwind-merge'];
200
+ // Check for existing directories in src
201
+ if (fs.existsSync(path.join(cwd, 'src/components'))) {
202
+ componentsPath = './src/components';
203
+ }
204
+ if (fs.existsSync(path.join(cwd, 'src/lib'))) {
205
+ libPath = './src/lib';
206
+ }
207
+ if (fs.existsSync(path.join(cwd, 'src/hooks'))) {
208
+ hooksPath = './src/hooks';
209
+ }
210
+ if (fs.existsSync(path.join(cwd, 'src/styles'))) {
211
+ stylesPath = './src/styles';
212
+ }
213
+ } else {
214
+ // No src directory - check for app directory in root
215
+ const hasApp = fs.existsSync(path.join(cwd, 'app'));
216
+ if (hasApp) {
217
+ appPath = './app';
218
+ }
126
219
 
127
- try {
128
- // Detect package manager
129
- const packageManager = detectPackageManager();
130
- console.log(chalk.gray(`Using ${packageManager}...`));
131
-
132
- const installCmd =
133
- packageManager === 'npm'
134
- ? `npm install ${dependencies.join(' ')}`
135
- : packageManager === 'yarn'
136
- ? `yarn add ${dependencies.join(' ')}`
137
- : packageManager === 'bun'
138
- ? `bun add ${dependencies.join(' ')}`
139
- : `pnpm add ${dependencies.join(' ')}`;
140
-
141
- execSync(installCmd, { stdio: 'inherit' });
142
- console.log(chalk.green('✅ Dependencies installed'));
143
- } catch (error) {
144
- console.log(
145
- chalk.yellow('⚠️ Could not install dependencies automatically')
146
- );
147
- console.log(chalk.gray('Please install them manually:'));
220
+ // Check for existing directories in root
221
+ if (fs.existsSync(path.join(cwd, 'components'))) {
222
+ componentsPath = './components';
223
+ }
224
+ if (fs.existsSync(path.join(cwd, 'lib'))) {
225
+ libPath = './lib';
226
+ }
227
+ if (fs.existsSync(path.join(cwd, 'hooks'))) {
228
+ hooksPath = './hooks';
229
+ }
230
+ if (fs.existsSync(path.join(cwd, 'styles'))) {
231
+ stylesPath = './styles';
232
+ }
233
+ }
234
+
235
+ // Detect TypeScript
236
+ const isTypeScript = fs.existsSync(path.join(cwd, 'tsconfig.json'));
237
+
238
+ // Detect package manager
239
+ const packageManager = detectPackageManager();
240
+
241
+ return {
242
+ hasSrc,
243
+ hasApp: !!appPath,
244
+ hasComponents: !!componentsPath,
245
+ hasLib: !!libPath,
246
+ hasHooks: !!hooksPath,
247
+ hasStyles: !!stylesPath,
248
+ baseDir,
249
+ framework: 'next',
250
+ isTypeScript,
251
+ packageManager,
252
+ appPath,
253
+ componentsPath,
254
+ libPath,
255
+ hooksPath,
256
+ stylesPath,
257
+ };
258
+ }
259
+
260
+ async function getPathConfiguration(
261
+ structure: ProjectStructure,
262
+ skipPrompts?: boolean
263
+ ): Promise<PathConfig> {
264
+ const ext = structure.isTypeScript ? '.ts' : '.js';
265
+ const jsxExt = structure.isTypeScript ? '.tsx' : '.jsx';
266
+
267
+ // Smart defaults based on existing structure
268
+ const defaults: PathConfig = {
269
+ utils: path.join(
270
+ structure.libPath || path.join(structure.baseDir, 'lib'),
271
+ `utils${ext}`
272
+ ),
273
+ primitives: path.join(
274
+ structure.componentsPath || path.join(structure.baseDir, 'components'),
275
+ 'primitives'
276
+ ),
277
+ components: path.join(
278
+ structure.componentsPath || path.join(structure.baseDir, 'components'),
279
+ 'ui'
280
+ ),
281
+ blocks: path.join(
282
+ structure.componentsPath || path.join(structure.baseDir, 'components'),
283
+ 'blocks'
284
+ ),
285
+ animations: path.join(
286
+ structure.componentsPath || path.join(structure.baseDir, 'components'),
287
+ 'animations'
288
+ ),
289
+ hooks: structure.hooksPath || path.join(structure.baseDir, 'hooks'),
290
+ lib: structure.libPath || path.join(structure.baseDir, 'lib'),
291
+ styles: path.join(structure.appPath || structure.baseDir, 'globals.css'),
292
+ };
293
+
294
+ // If app directory exists, look for existing globals.css
295
+ if (structure.appPath) {
296
+ const possibleStylePaths = [
297
+ path.join(structure.appPath, 'globals.css'),
298
+ path.join(structure.appPath, 'global.css'),
299
+ path.join(structure.stylesPath || '', 'globals.css'),
300
+ path.join(structure.stylesPath || '', 'global.css'),
301
+ ];
302
+
303
+ for (const stylePath of possibleStylePaths) {
304
+ if (fs.existsSync(path.join(process.cwd(), stylePath))) {
305
+ defaults.styles = stylePath;
306
+ break;
307
+ }
308
+ }
309
+ }
310
+
311
+ if (skipPrompts) {
148
312
  console.log(
149
- chalk.cyan(` ${detectPackageManager()} add ${dependencies.join(' ')}`)
313
+ chalk.gray('Using smart defaults based on project structure...')
150
314
  );
315
+ return defaults;
151
316
  }
317
+
318
+ console.log(chalk.blue('\n📂 Configure installation paths:'));
319
+ console.log(
320
+ chalk.gray('Press enter to use the default value shown in parentheses\n')
321
+ );
322
+
323
+ const answers = await inquirer.prompt([
324
+ {
325
+ type: 'input',
326
+ name: 'utils',
327
+ message: 'Utils file path:',
328
+ default: defaults.utils,
329
+ validate: (input: string) => {
330
+ if (!input) return 'Path cannot be empty';
331
+ return true;
332
+ },
333
+ },
334
+ {
335
+ type: 'input',
336
+ name: 'components',
337
+ message: 'Components directory:',
338
+ default: defaults.components,
339
+ },
340
+ {
341
+ type: 'input',
342
+ name: 'primitives',
343
+ message: 'Primitives directory:',
344
+ default: defaults.primitives,
345
+ },
346
+ {
347
+ type: 'input',
348
+ name: 'blocks',
349
+ message: 'Blocks directory:',
350
+ default: defaults.blocks,
351
+ },
352
+ {
353
+ type: 'input',
354
+ name: 'hooks',
355
+ message: 'Hooks directory:',
356
+ default: defaults.hooks,
357
+ },
358
+ {
359
+ type: 'input',
360
+ name: 'animations',
361
+ message: 'Animations directory:',
362
+ default: defaults.animations,
363
+ },
364
+ {
365
+ type: 'input',
366
+ name: 'styles',
367
+ message: 'Global styles file:',
368
+ default: defaults.styles,
369
+ },
370
+ {
371
+ type: 'input',
372
+ name: 'lib',
373
+ message: 'Lib directory:',
374
+ default: defaults.lib,
375
+ },
376
+ ]);
377
+
378
+ return answers as PathConfig;
152
379
  }
153
380
 
154
- async function checkIfWorkspace(): Promise<boolean> {
381
+ async function installDependencies(): Promise<void> {
382
+ console.log(chalk.blue('📦 Installing dependencies...'));
383
+
384
+ const packageManager = detectPackageManager();
385
+ const execAsync = promisify(exec);
386
+
387
+ const dependencies = [
388
+ 'clsx',
389
+ 'tailwind-merge',
390
+ 'framer-motion',
391
+ 'lucide-react',
392
+ 'next-themes',
393
+ 'cmdk',
394
+ '@foundrykit/tailwind',
395
+ '@radix-ui/react-dialog',
396
+ '@radix-ui/react-dropdown-menu',
397
+ '@radix-ui/react-label',
398
+ '@radix-ui/react-popover',
399
+ '@radix-ui/react-select',
400
+ '@radix-ui/react-separator',
401
+ '@radix-ui/react-slot',
402
+ '@radix-ui/react-switch',
403
+ '@radix-ui/react-tabs',
404
+ '@radix-ui/react-tooltip',
405
+ ];
406
+
407
+ const devDependencies = ['tailwindcss', 'autoprefixer', 'postcss'];
408
+
155
409
  try {
156
- // Check for pnpm workspace
157
- const pnpmWorkspacePath = path.join(
158
- process.cwd(),
159
- '../../pnpm-workspace.yaml'
410
+ // Install regular dependencies
411
+ const installCmd = packageManager === 'npm' ? 'install' : 'add';
412
+ await execAsync(
413
+ `${packageManager} ${installCmd} ${dependencies.join(' ')}`
160
414
  );
161
- if (fs.existsSync(pnpmWorkspacePath)) {
162
- return true;
163
- }
164
415
 
165
- // Check package.json for workspace packages
166
- const packageJsonPath = path.join(process.cwd(), 'package.json');
167
- if (fs.existsSync(packageJsonPath)) {
168
- const packageJson = await fs.readJson(packageJsonPath);
169
- const allDeps = {
170
- ...packageJson.dependencies,
171
- ...packageJson.devDependencies,
172
- };
173
-
174
- // Check if any FoundryKit packages use workspace protocol
175
- const foundryKitPackages = Object.keys(allDeps).filter(key =>
176
- key.startsWith('@foundrykit/')
177
- );
178
- for (const pkg of foundryKitPackages) {
179
- if (allDeps[pkg]?.includes('workspace:')) {
180
- return true;
181
- }
182
- }
183
- }
416
+ // Install dev dependencies
417
+ const devFlag = packageManager === 'npm' ? '--save-dev' : '-D';
418
+ await execAsync(
419
+ `${packageManager} ${installCmd} ${devFlag} ${devDependencies.join(' ')}`
420
+ );
184
421
 
185
- return false;
186
- } catch {
187
- return false;
422
+ console.log(chalk.green('✅ Dependencies installed'));
423
+ } catch (error) {
424
+ console.error(chalk.yellow('⚠️ Failed to install some dependencies'));
425
+ console.error(chalk.gray('You may need to install them manually'));
188
426
  }
189
427
  }
190
428
 
191
429
  function detectPackageManager(): string {
192
- if (fs.existsSync('pnpm-lock.yaml')) return 'pnpm';
193
- if (fs.existsSync('yarn.lock')) return 'yarn';
194
- if (fs.existsSync('bun.lockb')) return 'bun';
430
+ if (fs.existsSync(path.join(process.cwd(), 'pnpm-lock.yaml'))) return 'pnpm';
431
+ if (fs.existsSync(path.join(process.cwd(), 'yarn.lock'))) return 'yarn';
432
+ if (fs.existsSync(path.join(process.cwd(), 'bun.lockb'))) return 'bun';
195
433
  return 'npm';
196
434
  }
197
435
 
198
- async function setupTailwindV4(): Promise<void> {
199
- console.log(chalk.blue('⚙️ Setting up Tailwind CSS v4...'));
436
+ async function setupTailwindV4(
437
+ pathConfig: PathConfig,
438
+ projectStructure: ProjectStructure,
439
+ skipPrompts?: boolean
440
+ ): Promise<void> {
441
+ console.log(chalk.blue('🎨 Setting up Tailwind CSS v4...'));
200
442
 
201
443
  // First check if layout already imports FoundryKit styles
202
- const layoutInfo = await findLayoutFile();
203
- if (layoutInfo) {
204
- const layoutContent = await fs.readFile(layoutInfo.path, 'utf-8');
444
+ const layoutPath = await findLayoutFile(projectStructure);
445
+
446
+ if (layoutPath) {
447
+ const layoutContent = await fs.readFile(layoutPath, 'utf-8');
205
448
 
206
449
  // Check if already importing FoundryKit styles directly
207
450
  if (layoutContent.includes('@foundrykit/tailwind/globals.css')) {
451
+ if (skipPrompts) {
452
+ console.log(
453
+ chalk.green(
454
+ '✅ Keeping existing import from @foundrykit/tailwind/globals.css'
455
+ )
456
+ );
457
+ return;
458
+ }
459
+
208
460
  const { importPreference } = await inquirer.prompt([
209
461
  {
210
462
  type: 'list',
@@ -235,36 +487,23 @@ async function setupTailwindV4(): Promise<void> {
235
487
  }
236
488
 
237
489
  // User wants to switch to local globals.css
238
- await createLocalGlobalsAndUpdateLayout(layoutInfo.path, layoutContent);
490
+ await createOrUpdateGlobalsCss(pathConfig, projectStructure);
491
+ await updateLayoutImport(layoutPath, pathConfig);
239
492
  return;
240
493
  }
241
494
 
242
495
  // Check if importing a local globals.css
243
496
  const globalsCssImportMatch = layoutContent.match(
244
- /import\s+['"]([^'"]*globals\.css)['"]/
497
+ /import\s+['"]([^'"]*globals?\.css)['"]/
245
498
  );
499
+
246
500
  if (globalsCssImportMatch && globalsCssImportMatch[1]) {
247
- // Local globals.css is imported, check if it needs updating
501
+ // Local globals.css is imported, update it
248
502
  const importPath = globalsCssImportMatch[1];
249
- const resolvedPath = importPath.startsWith('.')
250
- ? path.join(path.dirname(layoutInfo.path), importPath)
251
- : path.join(process.cwd(), importPath.replace(/^@\//, 'app/'));
503
+ const resolvedPath = resolveImportPath(layoutPath, importPath);
252
504
 
253
505
  if (fs.existsSync(resolvedPath)) {
254
- const globalsCssContent = await fs.readFile(resolvedPath, 'utf-8');
255
- if (globalsCssContent.includes('@foundrykit/tailwind/globals.css')) {
256
- console.log(chalk.green('✅ FoundryKit styles already configured'));
257
- return;
258
- }
259
-
260
- // Update existing globals.css
261
- const updatedContent = `/* Import FoundryKit's Tailwind CSS v4 styles */
262
- @import "@foundrykit/tailwind/globals.css";
263
-
264
- /* Your custom styles below */
265
- ${globalsCssContent}`;
266
-
267
- await fs.writeFile(resolvedPath, updatedContent);
506
+ await updateExistingGlobalsCss(resolvedPath);
268
507
  console.log(
269
508
  chalk.green('✅ Updated existing globals.css with FoundryKit styles')
270
509
  );
@@ -273,280 +512,261 @@ ${globalsCssContent}`;
273
512
  }
274
513
  }
275
514
 
276
- // No existing setup found, ask user preference
277
- const { setupPreference } = await inquirer.prompt([
278
- {
279
- type: 'list',
280
- name: 'setupPreference',
281
- message: 'How would you like to import FoundryKit styles?',
282
- choices: [
283
- {
284
- name: 'Create a local globals.css file (recommended for customization)',
285
- value: 'local',
286
- },
287
- {
288
- name: 'Import directly from @foundrykit/tailwind/globals.css',
289
- value: 'direct',
290
- },
291
- ],
292
- default: 'local',
293
- },
294
- ]);
515
+ // No existing setup found, use default preference or ask user
516
+ let setupPreference = 'local';
517
+
518
+ if (!skipPrompts) {
519
+ const answer = await inquirer.prompt([
520
+ {
521
+ type: 'list',
522
+ name: 'setupPreference',
523
+ message: 'How would you like to import FoundryKit styles?',
524
+ choices: [
525
+ {
526
+ name: 'Create/update a local globals.css file (recommended for customization)',
527
+ value: 'local',
528
+ },
529
+ {
530
+ name: 'Import directly from @foundrykit/tailwind/globals.css',
531
+ value: 'direct',
532
+ },
533
+ ],
534
+ default: 'local',
535
+ },
536
+ ]);
537
+ setupPreference = answer.setupPreference;
538
+ }
295
539
 
296
540
  if (setupPreference === 'direct') {
297
- // Add direct import to layout
298
- await addDirectImportToLayout();
541
+ await addDirectImportToLayout(layoutPath!, pathConfig);
299
542
  } else {
300
- // Create local globals.css and update layout
301
- await createLocalGlobalsAndUpdateLayout();
302
- }
303
- }
304
-
305
- async function createLocalGlobalsAndUpdateLayout(
306
- existingLayoutPath?: string,
307
- existingLayoutContent?: string
308
- ): Promise<void> {
309
- // Find or create globals.css
310
- const possiblePaths = [
311
- 'app/globals.css',
312
- 'src/app/globals.css',
313
- 'styles/globals.css',
314
- 'src/styles/globals.css',
315
- ];
316
-
317
- let globalCssPath: string | null = null;
318
- for (const p of possiblePaths) {
319
- const fullPath = path.join(process.cwd(), p);
320
- if (fs.existsSync(fullPath)) {
321
- globalCssPath = fullPath;
322
- break;
543
+ await createOrUpdateGlobalsCss(pathConfig, projectStructure);
544
+ if (layoutPath) {
545
+ await updateLayoutImport(layoutPath, pathConfig);
323
546
  }
324
547
  }
325
548
 
326
- if (!globalCssPath) {
327
- // Create in app directory by default
328
- globalCssPath = path.join(process.cwd(), 'app/globals.css');
329
- await fs.ensureDir(path.dirname(globalCssPath));
330
- }
549
+ console.log(chalk.green('✅ Tailwind CSS v4 configured'));
550
+ }
331
551
 
332
- // Check if the file already imports FoundryKit styles
333
- const existingContent = fs.existsSync(globalCssPath)
334
- ? await fs.readFile(globalCssPath, 'utf-8')
335
- : '';
552
+ async function createOrUpdateGlobalsCss(
553
+ pathConfig: PathConfig,
554
+ projectStructure: ProjectStructure
555
+ ): Promise<void> {
556
+ const globalsCssPath = path.join(process.cwd(), pathConfig.styles);
336
557
 
337
- if (!existingContent.includes('@foundrykit/tailwind/globals.css')) {
338
- // Add FoundryKit import to globals.css
558
+ // Check if file already exists
559
+ if (fs.existsSync(globalsCssPath)) {
560
+ await updateExistingGlobalsCss(globalsCssPath);
561
+ } else {
562
+ // Create new globals.css
339
563
  const cssContent = `/* Import FoundryKit's Tailwind CSS v4 styles */
340
564
  @import "@foundrykit/tailwind/globals.css";
341
565
 
342
566
  /* Your custom styles below */
343
- ${existingContent}`;
344
-
345
- await fs.writeFile(globalCssPath, cssContent);
346
- console.log(
347
- chalk.green('✅ Created/updated globals.css with FoundryKit styles')
348
- );
349
- }
350
-
351
- // Update layout file
352
- if (existingLayoutPath && existingLayoutContent) {
353
- // Replace direct import with local globals.css
354
- const layoutDir = path.dirname(existingLayoutPath);
355
- const cssRelativePath = path
356
- .relative(layoutDir, globalCssPath)
357
- .replace(/\\/g, '/');
358
- const importPath = cssRelativePath.startsWith('.')
359
- ? cssRelativePath
360
- : `./${cssRelativePath}`;
361
-
362
- const updatedContent = existingLayoutContent.replace(
363
- /@foundrykit\/tailwind\/globals\.css/g,
364
- importPath
365
- );
567
+ `;
366
568
 
367
- await fs.writeFile(existingLayoutPath, updatedContent);
368
- console.log(chalk.green('✅ Updated layout to use local globals.css'));
369
- } else {
370
- // Add import to layout
371
- await updateLayoutImport(globalCssPath);
569
+ await fs.ensureDir(path.dirname(globalsCssPath));
570
+ await fs.writeFile(globalsCssPath, cssContent);
571
+ console.log(chalk.green(`✅ Created ${pathConfig.styles}`));
372
572
  }
373
573
  }
374
574
 
375
- async function addDirectImportToLayout(): Promise<void> {
376
- const layoutInfo = await findLayoutFile();
575
+ async function updateExistingGlobalsCss(globalsCssPath: string): Promise<void> {
576
+ const content = await fs.readFile(globalsCssPath, 'utf-8');
377
577
 
378
- if (!layoutInfo) {
379
- console.log(
380
- chalk.yellow(
381
- '⚠️ No layout file found. Please add this import to your layout manually:'
382
- )
383
- );
384
- console.log(chalk.gray(` import '@foundrykit/tailwind/globals.css';`));
578
+ // Check if already has FoundryKit import
579
+ if (content.includes('@foundrykit/tailwind/globals.css')) {
580
+ console.log(chalk.gray('globals.css already imports FoundryKit styles'));
385
581
  return;
386
582
  }
387
583
 
388
- const layoutContent = await fs.readFile(layoutInfo.path, 'utf-8');
389
-
390
- // Check if already importing
391
- if (layoutContent.includes('@foundrykit/tailwind/globals.css')) {
392
- console.log(
393
- chalk.gray('Layout already imports FoundryKit styles directly')
584
+ // Check if it has @import "tailwindcss"
585
+ if (content.includes('@import "tailwindcss"')) {
586
+ // Replace the tailwindcss import with FoundryKit import but keep all other content
587
+ const updatedContent = content.replace(
588
+ '@import "tailwindcss"',
589
+ `/* Import FoundryKit's Tailwind CSS v4 styles */\n@import "@foundrykit/tailwind/globals.css"`
394
590
  );
395
- return;
396
- }
397
-
398
- // Add import statement after existing imports
399
- const importStatement = `import '@foundrykit/tailwind/globals.css';`;
400
591
 
401
- // Find a good place to insert the import (after other imports)
402
- const importRegex = /^import\s+.*$/gm;
403
- const imports = layoutContent.match(importRegex);
592
+ await fs.writeFile(globalsCssPath, updatedContent);
593
+ console.log(chalk.green('✅ Updated globals.css with FoundryKit styles'));
594
+ } else {
595
+ // Just prepend the FoundryKit import
596
+ const updatedContent = `/* Import FoundryKit's Tailwind CSS v4 styles */
597
+ @import "@foundrykit/tailwind/globals.css";
404
598
 
405
- let updatedContent: string;
406
- if (imports && imports.length > 0) {
407
- const lastImport = imports[imports.length - 1];
408
- const lastImportIndex = layoutContent.lastIndexOf(lastImport!);
409
- const insertPosition = lastImportIndex + lastImport!.length;
599
+ /* Your custom styles below */
600
+ ${content}`;
410
601
 
411
- updatedContent =
412
- layoutContent.slice(0, insertPosition) +
413
- '\n' +
414
- importStatement +
415
- layoutContent.slice(insertPosition);
416
- } else {
417
- // No imports found, add at the beginning
418
- updatedContent = importStatement + '\n' + layoutContent;
602
+ await fs.writeFile(globalsCssPath, updatedContent);
603
+ console.log(chalk.green('✅ Updated globals.css with FoundryKit styles'));
419
604
  }
420
-
421
- await fs.writeFile(layoutInfo.path, updatedContent);
422
- console.log(
423
- chalk.green('✅ Added direct import of FoundryKit styles to layout')
424
- );
425
605
  }
426
606
 
427
- async function findLayoutFile(): Promise<{ path: string } | null> {
428
- const layoutPaths = [
607
+ async function findLayoutFile(
608
+ projectStructure: ProjectStructure
609
+ ): Promise<string | null> {
610
+ const possiblePaths = [];
611
+
612
+ if (projectStructure.appPath) {
613
+ const ext = projectStructure.isTypeScript ? '.tsx' : '.jsx';
614
+ possiblePaths.push(
615
+ path.join(projectStructure.appPath, `layout${ext}`),
616
+ path.join(projectStructure.appPath, `layout.js`)
617
+ );
618
+ }
619
+
620
+ // Also check standard paths
621
+ possiblePaths.push(
429
622
  'app/layout.tsx',
430
623
  'app/layout.jsx',
431
624
  'app/layout.js',
432
625
  'src/app/layout.tsx',
433
626
  'src/app/layout.jsx',
434
- 'src/app/layout.js',
435
- ];
627
+ 'src/app/layout.js'
628
+ );
436
629
 
437
- for (const p of layoutPaths) {
438
- const fullPath = path.join(process.cwd(), p);
630
+ for (const layoutPath of possiblePaths) {
631
+ const fullPath = path.join(process.cwd(), layoutPath);
439
632
  if (fs.existsSync(fullPath)) {
440
- return { path: fullPath };
633
+ return fullPath;
441
634
  }
442
635
  }
443
636
 
444
637
  return null;
445
638
  }
446
639
 
447
- async function updateLayoutImport(globalCssPath: string): Promise<void> {
448
- const layoutInfo = await findLayoutFile();
640
+ async function updateLayoutImport(
641
+ layoutPath: string,
642
+ pathConfig: PathConfig
643
+ ): Promise<void> {
644
+ try {
645
+ let content = await fs.readFile(layoutPath, 'utf-8');
646
+
647
+ // Calculate relative import path from layout to styles
648
+ const fromPath = path.dirname(layoutPath);
649
+ const toPath = path.join(process.cwd(), pathConfig.styles);
650
+ const relativePath = path.relative(fromPath, toPath).replace(/\\/g, '/');
651
+ const importPath = relativePath.startsWith('.')
652
+ ? relativePath
653
+ : `./${relativePath}`;
654
+
655
+ // Check for existing global CSS imports
656
+ const globalImportRegex = /import\s+['"]([^'"]*globals?\.css)['"]/;
657
+ const match = content.match(globalImportRegex);
658
+
659
+ if (match) {
660
+ // Replace existing import
661
+ content = content.replace(globalImportRegex, `import '${importPath}'`);
662
+ } else if (!content.includes(importPath)) {
663
+ // Add new import after other imports
664
+ const importStatement = `import '${importPath}';\n`;
665
+ const importRegex = /^(import\s+.*?;\s*)+/m;
666
+ const importMatch = content.match(importRegex);
667
+
668
+ if (importMatch) {
669
+ const lastImportIndex = importMatch.index! + importMatch[0].length;
670
+ content =
671
+ content.slice(0, lastImportIndex) +
672
+ importStatement +
673
+ content.slice(lastImportIndex);
674
+ } else {
675
+ content = importStatement + content;
676
+ }
677
+ }
449
678
 
450
- if (!layoutInfo) {
679
+ await fs.writeFile(layoutPath, content);
451
680
  console.log(
452
- chalk.yellow(
453
- '⚠️ No layout file found. Please import globals.css manually in your layout.'
681
+ chalk.gray(
682
+ `Updated ${path.relative(process.cwd(), layoutPath)} with CSS import`
454
683
  )
455
684
  );
456
- return;
457
- }
458
-
459
- const layoutContent = await fs.readFile(layoutInfo.path, 'utf-8');
460
-
461
- // Check if already importing any globals.css
462
- if (layoutContent.match(/import\s+['"][^'"]*globals\.css['"]/)) {
463
- console.log(chalk.gray('Layout already has a globals.css import'));
464
- return;
685
+ } catch (error) {
686
+ console.error(chalk.yellow('⚠️ Failed to update layout with CSS import'));
465
687
  }
688
+ }
466
689
 
467
- // Check if already importing FoundryKit styles directly
468
- if (layoutContent.includes('@foundrykit/tailwind/globals.css')) {
469
- // Replace direct FoundryKit import with local globals.css
470
- const layoutDir = path.dirname(layoutInfo.path);
471
- const cssRelativePath = path
472
- .relative(layoutDir, globalCssPath)
473
- .replace(/\\/g, '/');
474
- const importPath = cssRelativePath.startsWith('.')
475
- ? cssRelativePath
476
- : `./${cssRelativePath}`;
477
-
478
- const updatedContent = layoutContent.replace(
479
- /@foundrykit\/tailwind\/globals\.css/g,
480
- importPath
481
- );
690
+ async function addDirectImportToLayout(
691
+ layoutPath: string,
692
+ pathConfig: PathConfig
693
+ ): Promise<void> {
694
+ try {
695
+ let content = await fs.readFile(layoutPath, 'utf-8');
696
+ const importStatement = `import '@foundrykit/tailwind/globals.css';\n`;
697
+
698
+ if (!content.includes('@foundrykit/tailwind/globals.css')) {
699
+ // Add import at the top of the file after any existing imports
700
+ const importRegex = /^(import\s+.*?;\s*)+/m;
701
+ const match = content.match(importRegex);
702
+
703
+ if (match) {
704
+ // Add after existing imports
705
+ const lastImportIndex = match.index! + match[0].length;
706
+ content =
707
+ content.slice(0, lastImportIndex) +
708
+ importStatement +
709
+ content.slice(lastImportIndex);
710
+ } else {
711
+ // Add at the very beginning
712
+ content = importStatement + content;
713
+ }
482
714
 
483
- await fs.writeFile(layoutInfo.path, updatedContent);
484
- console.log(
485
- chalk.green('✅ Updated layout import to use local globals.css')
486
- );
487
- return;
715
+ await fs.writeFile(layoutPath, content);
716
+ console.log(
717
+ chalk.green('✅ Added direct import of FoundryKit styles to layout')
718
+ );
719
+ }
720
+ } catch (error) {
721
+ console.error(chalk.yellow('⚠️ Failed to add CSS import to layout'));
488
722
  }
723
+ }
489
724
 
490
- // Calculate relative import path
491
- const layoutDir = path.dirname(layoutInfo.path);
492
- const cssRelativePath = path
493
- .relative(layoutDir, globalCssPath)
494
- .replace(/\\/g, '/');
495
- const importPath = cssRelativePath.startsWith('.')
496
- ? cssRelativePath
497
- : `./${cssRelativePath}`;
498
-
499
- // Add import statement after existing imports
500
- const importStatement = `import '${importPath}';`;
501
-
502
- // Find a good place to insert the import (after other imports)
503
- const importRegex = /^import\s+.*$/gm;
504
- const imports = layoutContent.match(importRegex);
505
-
506
- let updatedContent: string;
507
- if (imports && imports.length > 0) {
508
- const lastImport = imports[imports.length - 1];
509
- const lastImportIndex = layoutContent.lastIndexOf(lastImport!);
510
- const insertPosition = lastImportIndex + lastImport!.length;
511
-
512
- updatedContent =
513
- layoutContent.slice(0, insertPosition) +
514
- '\n' +
515
- importStatement +
516
- layoutContent.slice(insertPosition);
517
- } else {
518
- // No imports found, add at the beginning
519
- updatedContent = importStatement + '\n' + layoutContent;
725
+ function resolveImportPath(fromFile: string, importPath: string): string {
726
+ if (importPath.startsWith('.')) {
727
+ // Relative import
728
+ return path.join(path.dirname(fromFile), importPath);
729
+ } else if (importPath.startsWith('@/')) {
730
+ // Alias import
731
+ return path.join(process.cwd(), importPath.replace('@/', 'src/'));
732
+ } else if (importPath.startsWith('/')) {
733
+ // Absolute import from project root
734
+ return path.join(process.cwd(), importPath);
520
735
  }
521
736
 
522
- await fs.writeFile(layoutInfo.path, updatedContent);
523
- console.log(chalk.green('✅ Layout file updated with globals.css import'));
737
+ // Default to relative from project root
738
+ return path.join(process.cwd(), importPath);
524
739
  }
525
740
 
526
- async function createDirectories(): Promise<void> {
741
+ async function createDirectories(pathConfig: PathConfig): Promise<void> {
527
742
  console.log(chalk.blue('📁 Creating component directories...'));
528
743
 
529
744
  const dirs = [
530
- 'components/primitives',
531
- 'components/components',
532
- 'components/blocks',
533
- 'components/animations',
534
- 'lib',
535
- 'hooks',
745
+ pathConfig.primitives,
746
+ pathConfig.components,
747
+ pathConfig.blocks,
748
+ pathConfig.animations,
749
+ pathConfig.hooks,
750
+ pathConfig.lib,
536
751
  ];
537
752
 
538
753
  for (const dir of dirs) {
539
- await fs.ensureDir(path.join(process.cwd(), dir));
754
+ const fullPath = path.join(process.cwd(), dir);
755
+ await fs.ensureDir(fullPath);
756
+ console.log(chalk.gray(`Created ${dir}`));
540
757
  }
541
758
 
542
759
  console.log(chalk.green('✅ Directories created'));
543
760
  }
544
761
 
545
- async function createExampleFiles(): Promise<void> {
762
+ async function createExampleFiles(
763
+ pathConfig: PathConfig,
764
+ structure: ProjectStructure
765
+ ): Promise<void> {
546
766
  console.log(chalk.blue('📝 Creating example files...'));
547
767
 
548
- // Create lib/utils.ts
549
- const utilsPath = path.join(process.cwd(), 'lib/utils.ts');
768
+ // Create lib/utils.ts if it doesn't exist
769
+ const utilsPath = path.join(process.cwd(), pathConfig.utils);
550
770
  const utilsContent = `import { type ClassValue, clsx } from 'clsx';
551
771
  import { twMerge } from 'tailwind-merge';
552
772
 
@@ -555,18 +775,25 @@ export function cn(...inputs: ClassValue[]) {
555
775
  }
556
776
  `;
557
777
 
778
+ await fs.ensureDir(path.dirname(utilsPath));
779
+
558
780
  if (!fs.existsSync(utilsPath)) {
559
781
  await fs.writeFile(utilsPath, utilsContent);
560
- console.log(chalk.gray('Created lib/utils.ts'));
782
+ console.log(chalk.gray(`Created ${pathConfig.utils}`));
561
783
  }
562
784
 
563
- // Create providers.tsx if using theme support
564
- const providersPath = path.join(process.cwd(), 'components/providers.tsx');
785
+ // Create providers.tsx for Next.js projects
786
+ const providersPath = path.join(
787
+ process.cwd(),
788
+ path.dirname(pathConfig.components),
789
+ `theme-provider${structure.isTypeScript ? '.tsx' : '.jsx'}`
790
+ );
791
+
565
792
  const providersContent = `'use client';
566
793
 
567
794
  import { ThemeProvider } from 'next-themes';
568
795
 
569
- export function Providers({ children }: { children: React.ReactNode }) {
796
+ export function ThemeProvider({ children }: { children: React.ReactNode }) {
570
797
  return (
571
798
  <ThemeProvider attribute="class" defaultTheme="system" enableSystem>
572
799
  {children}
@@ -577,36 +804,38 @@ export function Providers({ children }: { children: React.ReactNode }) {
577
804
 
578
805
  if (!fs.existsSync(providersPath)) {
579
806
  await fs.writeFile(providersPath, providersContent);
580
- console.log(chalk.gray('Created components/providers.tsx'));
807
+ console.log(
808
+ chalk.gray(
809
+ `Created theme-provider.${structure.isTypeScript ? 'tsx' : 'jsx'}`
810
+ )
811
+ );
581
812
  }
582
813
 
583
814
  console.log(chalk.green('✅ Example files created'));
584
815
  }
585
816
 
586
817
  async function updatePackageScripts(): Promise<void> {
587
- console.log(chalk.blue('📋 Updating package.json scripts...'));
818
+ console.log(chalk.blue('📝 Updating package.json scripts...'));
588
819
 
589
820
  const packageJsonPath = path.join(process.cwd(), 'package.json');
590
821
  const packageJson = await fs.readJson(packageJsonPath);
591
822
 
592
- if (!packageJson.scripts) {
593
- packageJson.scripts = {};
594
- }
595
-
596
- // Add FoundryKit CLI scripts if they don't exist
597
- if (!packageJson.scripts['foundrykit']) {
598
- packageJson.scripts['foundrykit'] = 'foundrykit';
599
- }
600
-
601
- if (!packageJson.scripts['fk']) {
602
- packageJson.scripts['fk'] = 'foundrykit';
603
- }
823
+ // Add foundrykit scripts
824
+ packageJson.scripts = {
825
+ ...packageJson.scripts,
826
+ 'foundrykit:add': 'pnpm dlx @foundrykit/cli add',
827
+ 'foundrykit:update': 'pnpm dlx @foundrykit/cli update',
828
+ };
604
829
 
605
830
  await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });
606
831
  console.log(chalk.green('✅ Package scripts updated'));
607
832
  }
608
833
 
609
- async function createConfigFile(options: InitOptions): Promise<void> {
834
+ async function createConfigFile(
835
+ options: InitOptions,
836
+ structure: ProjectStructure,
837
+ pathConfig: PathConfig
838
+ ): Promise<void> {
610
839
  console.log(chalk.blue('📝 Creating configuration file...'));
611
840
 
612
841
  const configPath = path.join(process.cwd(), 'foundrykit.config.json');
@@ -616,88 +845,40 @@ async function createConfigFile(options: InitOptions): Promise<void> {
616
845
  return;
617
846
  }
618
847
 
619
- // Detect framework
620
- const framework = await detectFramework();
621
-
622
- // Detect TypeScript
623
- const isTypeScript = fs.existsSync(path.join(process.cwd(), 'tsconfig.json'));
624
-
625
- // Create configuration
848
+ // Create configuration with custom paths
626
849
  const config = {
627
850
  version: '1.0.0',
628
851
  registry: 'https://foundry.umiflow.com',
629
852
  paths: {
630
- utils: './src/lib/utils.ts',
631
- primitives: './src/components/primitives',
632
- components: './src/components/components',
633
- blocks: './src/components/blocks',
634
- hooks: './src/hooks',
635
- animations: './src/components/animations',
853
+ utils: pathConfig.utils,
854
+ primitives: pathConfig.primitives,
855
+ components: pathConfig.components,
856
+ blocks: pathConfig.blocks,
857
+ hooks: pathConfig.hooks,
858
+ animations: pathConfig.animations,
636
859
  },
637
- packageManager: detectPackageManager(),
638
- typescript: isTypeScript,
639
- framework,
860
+ packageManager: structure.packageManager,
861
+ typescript: structure.isTypeScript,
862
+ framework: structure.framework,
640
863
  tailwind: {
641
- config: './tailwind.config.js',
642
- css: './src/styles/globals.css',
864
+ css: pathConfig.styles,
643
865
  },
644
866
  aliases: {
645
- '@': './src',
646
- '@/components': './src/components',
647
- '@/lib': './src/lib',
648
- '@/hooks': './src/hooks',
867
+ '@': structure.baseDir.replace(/\/$/, '') || '.',
868
+ '@/components': path.dirname(pathConfig.components).replace(/\/$/, ''),
869
+ '@/lib': pathConfig.lib.replace(/\/$/, ''),
870
+ '@/hooks': pathConfig.hooks.replace(/\/$/, ''),
649
871
  },
650
872
  };
651
873
 
652
- // Adjust paths based on framework
653
- if (framework === 'next') {
654
- const hasAppDir = fs.existsSync(path.join(process.cwd(), 'app'));
655
- if (hasAppDir && !fs.existsSync(path.join(process.cwd(), 'src/app'))) {
656
- // Using app directory without src
657
- config.paths = {
658
- utils: './lib/utils.ts',
659
- primitives: './components/primitives',
660
- components: './components/components',
661
- blocks: './components/blocks',
662
- hooks: './hooks',
663
- animations: './components/animations',
664
- };
665
- config.tailwind.css = './app/globals.css';
666
- config.aliases = {
667
- '@': './',
668
- '@/components': './components',
669
- '@/lib': './lib',
670
- '@/hooks': './hooks',
671
- };
672
- }
673
- }
674
-
675
874
  await fs.writeJson(configPath, config, { spaces: 2 });
676
875
  console.log(chalk.green('✅ Created foundrykit.config.json'));
677
876
  }
678
877
 
679
- async function installUtils(): Promise<void> {
680
- console.log(chalk.blue('📦 Installing utils...'));
681
-
682
- // Read config to get utils path
683
- const configPath = path.join(process.cwd(), 'foundrykit.config.json');
684
- if (!fs.existsSync(configPath)) {
685
- console.log(chalk.yellow('⚠️ Configuration file not found'));
686
- return;
687
- }
688
-
689
- const config = await fs.readJson(configPath);
690
- const utilsPath = path.join(process.cwd(), config.paths.utils);
691
-
692
- // Check if utils already exists
693
- if (fs.existsSync(utilsPath)) {
694
- console.log(chalk.yellow('⚠️ Utils file already exists'));
695
- return;
696
- }
697
-
698
- // Create utils file
699
- await fs.ensureDir(path.dirname(utilsPath));
878
+ async function installUtils(pathConfig: PathConfig): Promise<void> {
879
+ console.log(chalk.blue('📦 Installing utility functions...'));
700
880
 
881
+ const utilsPath = path.join(process.cwd(), pathConfig.utils);
701
882
  const utilsContent = `import { type ClassValue, clsx } from 'clsx';
702
883
  import { twMerge } from 'tailwind-merge';
703
884
 
@@ -706,24 +887,14 @@ export function cn(...inputs: ClassValue[]) {
706
887
  }
707
888
  `;
708
889
 
709
- await fs.writeFile(utilsPath, utilsContent);
710
- console.log(chalk.green('✅ Created utils file'));
711
- }
890
+ // Ensure directory exists
891
+ const utilsDir = path.dirname(utilsPath);
892
+ await fs.ensureDir(utilsDir);
712
893
 
713
- async function detectFramework(): Promise<string> {
714
- const packageJsonPath = path.join(process.cwd(), 'package.json');
715
- if (fs.existsSync(packageJsonPath)) {
716
- const packageJson = await fs.readJson(packageJsonPath);
717
- const deps = {
718
- ...packageJson.dependencies,
719
- ...packageJson.devDependencies,
720
- };
721
-
722
- if (deps.next) return 'next';
723
- if (deps.remix) return 'remix';
724
- if (deps.vite) return 'vite';
725
- if (deps.react) return 'react';
894
+ if (!fs.existsSync(utilsPath)) {
895
+ await fs.writeFile(utilsPath, utilsContent);
896
+ console.log(chalk.green('✅ Utility functions installed'));
897
+ } else {
898
+ console.log(chalk.gray('Utils file already exists, skipping...'));
726
899
  }
727
-
728
- return 'react';
729
900
  }