@foundrykit/cli 1.0.4 → 1.0.6

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,298 @@ 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
+ 'components'
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
+ '@radix-ui/react-dialog',
395
+ '@radix-ui/react-dropdown-menu',
396
+ '@radix-ui/react-label',
397
+ '@radix-ui/react-popover',
398
+ '@radix-ui/react-select',
399
+ '@radix-ui/react-separator',
400
+ '@radix-ui/react-slot',
401
+ '@radix-ui/react-switch',
402
+ '@radix-ui/react-tabs',
403
+ '@radix-ui/react-tooltip',
404
+ ];
405
+
406
+ const devDependencies = ['tailwindcss', 'autoprefixer', 'postcss'];
407
+
155
408
  try {
156
- // Check for pnpm workspace
157
- const pnpmWorkspacePath = path.join(
158
- process.cwd(),
159
- '../../pnpm-workspace.yaml'
409
+ // Install regular dependencies
410
+ const installCmd = packageManager === 'npm' ? 'install' : 'add';
411
+ await execAsync(
412
+ `${packageManager} ${installCmd} ${dependencies.join(' ')}`
160
413
  );
161
- if (fs.existsSync(pnpmWorkspacePath)) {
162
- return true;
163
- }
164
414
 
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
- }
415
+ // Install dev dependencies
416
+ const devFlag = packageManager === 'npm' ? '--save-dev' : '-D';
417
+ await execAsync(
418
+ `${packageManager} ${installCmd} ${devFlag} ${devDependencies.join(' ')}`
419
+ );
184
420
 
185
- return false;
186
- } catch {
187
- return false;
421
+ console.log(chalk.green('✅ Dependencies installed'));
422
+ } catch (error) {
423
+ console.error(chalk.yellow('⚠️ Failed to install some dependencies'));
424
+ console.error(chalk.gray('You may need to install them manually'));
188
425
  }
189
426
  }
190
427
 
191
428
  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';
429
+ if (fs.existsSync(path.join(process.cwd(), 'pnpm-lock.yaml'))) return 'pnpm';
430
+ if (fs.existsSync(path.join(process.cwd(), 'yarn.lock'))) return 'yarn';
431
+ if (fs.existsSync(path.join(process.cwd(), 'bun.lockb'))) return 'bun';
195
432
  return 'npm';
196
433
  }
197
434
 
198
- async function setupTailwindV4(): Promise<void> {
199
- console.log(chalk.blue('⚙️ Setting up Tailwind CSS v4...'));
435
+ async function setupTailwindV4(
436
+ pathConfig: PathConfig,
437
+ projectStructure: ProjectStructure,
438
+ skipPrompts?: boolean
439
+ ): Promise<void> {
440
+ console.log(chalk.blue('🎨 Setting up Tailwind CSS v4...'));
200
441
 
201
442
  // 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');
443
+ const layoutPath = await findLayoutFile(projectStructure);
444
+
445
+ if (layoutPath) {
446
+ const layoutContent = await fs.readFile(layoutPath, 'utf-8');
205
447
 
206
448
  // Check if already importing FoundryKit styles directly
207
449
  if (layoutContent.includes('@foundrykit/tailwind/globals.css')) {
450
+ if (skipPrompts) {
451
+ console.log(
452
+ chalk.green(
453
+ '✅ Keeping existing import from @foundrykit/tailwind/globals.css'
454
+ )
455
+ );
456
+ return;
457
+ }
458
+
208
459
  const { importPreference } = await inquirer.prompt([
209
460
  {
210
461
  type: 'list',
@@ -235,36 +486,23 @@ async function setupTailwindV4(): Promise<void> {
235
486
  }
236
487
 
237
488
  // User wants to switch to local globals.css
238
- await createLocalGlobalsAndUpdateLayout(layoutInfo.path, layoutContent);
489
+ await createOrUpdateGlobalsCss(pathConfig, projectStructure);
490
+ await updateLayoutImport(layoutPath, pathConfig);
239
491
  return;
240
492
  }
241
493
 
242
494
  // Check if importing a local globals.css
243
495
  const globalsCssImportMatch = layoutContent.match(
244
- /import\s+['"]([^'"]*globals\.css)['"]/
496
+ /import\s+['"]([^'"]*globals?\.css)['"]/
245
497
  );
498
+
246
499
  if (globalsCssImportMatch && globalsCssImportMatch[1]) {
247
- // Local globals.css is imported, check if it needs updating
500
+ // Local globals.css is imported, update it
248
501
  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/'));
502
+ const resolvedPath = resolveImportPath(layoutPath, importPath);
252
503
 
253
504
  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);
505
+ await updateExistingGlobalsCss(resolvedPath);
268
506
  console.log(
269
507
  chalk.green('✅ Updated existing globals.css with FoundryKit styles')
270
508
  );
@@ -273,280 +511,261 @@ ${globalsCssContent}`;
273
511
  }
274
512
  }
275
513
 
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
- ]);
514
+ // No existing setup found, use default preference or ask user
515
+ let setupPreference = 'local';
516
+
517
+ if (!skipPrompts) {
518
+ const answer = await inquirer.prompt([
519
+ {
520
+ type: 'list',
521
+ name: 'setupPreference',
522
+ message: 'How would you like to import FoundryKit styles?',
523
+ choices: [
524
+ {
525
+ name: 'Create/update a local globals.css file (recommended for customization)',
526
+ value: 'local',
527
+ },
528
+ {
529
+ name: 'Import directly from @foundrykit/tailwind/globals.css',
530
+ value: 'direct',
531
+ },
532
+ ],
533
+ default: 'local',
534
+ },
535
+ ]);
536
+ setupPreference = answer.setupPreference;
537
+ }
295
538
 
296
539
  if (setupPreference === 'direct') {
297
- // Add direct import to layout
298
- await addDirectImportToLayout();
540
+ await addDirectImportToLayout(layoutPath!, pathConfig);
299
541
  } 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;
542
+ await createOrUpdateGlobalsCss(pathConfig, projectStructure);
543
+ if (layoutPath) {
544
+ await updateLayoutImport(layoutPath, pathConfig);
323
545
  }
324
546
  }
325
547
 
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
- }
548
+ console.log(chalk.green('✅ Tailwind CSS v4 configured'));
549
+ }
331
550
 
332
- // Check if the file already imports FoundryKit styles
333
- const existingContent = fs.existsSync(globalCssPath)
334
- ? await fs.readFile(globalCssPath, 'utf-8')
335
- : '';
551
+ async function createOrUpdateGlobalsCss(
552
+ pathConfig: PathConfig,
553
+ projectStructure: ProjectStructure
554
+ ): Promise<void> {
555
+ const globalsCssPath = path.join(process.cwd(), pathConfig.styles);
336
556
 
337
- if (!existingContent.includes('@foundrykit/tailwind/globals.css')) {
338
- // Add FoundryKit import to globals.css
557
+ // Check if file already exists
558
+ if (fs.existsSync(globalsCssPath)) {
559
+ await updateExistingGlobalsCss(globalsCssPath);
560
+ } else {
561
+ // Create new globals.css
339
562
  const cssContent = `/* Import FoundryKit's Tailwind CSS v4 styles */
340
563
  @import "@foundrykit/tailwind/globals.css";
341
564
 
342
565
  /* 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
- );
566
+ `;
366
567
 
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);
568
+ await fs.ensureDir(path.dirname(globalsCssPath));
569
+ await fs.writeFile(globalsCssPath, cssContent);
570
+ console.log(chalk.green(`✅ Created ${pathConfig.styles}`));
372
571
  }
373
572
  }
374
573
 
375
- async function addDirectImportToLayout(): Promise<void> {
376
- const layoutInfo = await findLayoutFile();
574
+ async function updateExistingGlobalsCss(globalsCssPath: string): Promise<void> {
575
+ const content = await fs.readFile(globalsCssPath, 'utf-8');
377
576
 
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';`));
577
+ // Check if already has FoundryKit import
578
+ if (content.includes('@foundrykit/tailwind/globals.css')) {
579
+ console.log(chalk.gray('globals.css already imports FoundryKit styles'));
385
580
  return;
386
581
  }
387
582
 
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')
583
+ // Check if it has @import "tailwindcss"
584
+ if (content.includes('@import "tailwindcss"')) {
585
+ // Replace the tailwindcss import with FoundryKit import but keep all other content
586
+ const updatedContent = content.replace(
587
+ '@import "tailwindcss"',
588
+ `/* Import FoundryKit's Tailwind CSS v4 styles */\n@import "@foundrykit/tailwind/globals.css"`
394
589
  );
395
- return;
396
- }
397
-
398
- // Add import statement after existing imports
399
- const importStatement = `import '@foundrykit/tailwind/globals.css';`;
400
590
 
401
- // Find a good place to insert the import (after other imports)
402
- const importRegex = /^import\s+.*$/gm;
403
- const imports = layoutContent.match(importRegex);
591
+ await fs.writeFile(globalsCssPath, updatedContent);
592
+ console.log(chalk.green('✅ Updated globals.css with FoundryKit styles'));
593
+ } else {
594
+ // Just prepend the FoundryKit import
595
+ const updatedContent = `/* Import FoundryKit's Tailwind CSS v4 styles */
596
+ @import "@foundrykit/tailwind/globals.css";
404
597
 
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;
598
+ /* Your custom styles below */
599
+ ${content}`;
410
600
 
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;
601
+ await fs.writeFile(globalsCssPath, updatedContent);
602
+ console.log(chalk.green('✅ Updated globals.css with FoundryKit styles'));
419
603
  }
420
-
421
- await fs.writeFile(layoutInfo.path, updatedContent);
422
- console.log(
423
- chalk.green('✅ Added direct import of FoundryKit styles to layout')
424
- );
425
604
  }
426
605
 
427
- async function findLayoutFile(): Promise<{ path: string } | null> {
428
- const layoutPaths = [
606
+ async function findLayoutFile(
607
+ projectStructure: ProjectStructure
608
+ ): Promise<string | null> {
609
+ const possiblePaths = [];
610
+
611
+ if (projectStructure.appPath) {
612
+ const ext = projectStructure.isTypeScript ? '.tsx' : '.jsx';
613
+ possiblePaths.push(
614
+ path.join(projectStructure.appPath, `layout${ext}`),
615
+ path.join(projectStructure.appPath, `layout.js`)
616
+ );
617
+ }
618
+
619
+ // Also check standard paths
620
+ possiblePaths.push(
429
621
  'app/layout.tsx',
430
622
  'app/layout.jsx',
431
623
  'app/layout.js',
432
624
  'src/app/layout.tsx',
433
625
  'src/app/layout.jsx',
434
- 'src/app/layout.js',
435
- ];
626
+ 'src/app/layout.js'
627
+ );
436
628
 
437
- for (const p of layoutPaths) {
438
- const fullPath = path.join(process.cwd(), p);
629
+ for (const layoutPath of possiblePaths) {
630
+ const fullPath = path.join(process.cwd(), layoutPath);
439
631
  if (fs.existsSync(fullPath)) {
440
- return { path: fullPath };
632
+ return fullPath;
441
633
  }
442
634
  }
443
635
 
444
636
  return null;
445
637
  }
446
638
 
447
- async function updateLayoutImport(globalCssPath: string): Promise<void> {
448
- const layoutInfo = await findLayoutFile();
639
+ async function updateLayoutImport(
640
+ layoutPath: string,
641
+ pathConfig: PathConfig
642
+ ): Promise<void> {
643
+ try {
644
+ let content = await fs.readFile(layoutPath, 'utf-8');
645
+
646
+ // Calculate relative import path from layout to styles
647
+ const fromPath = path.dirname(layoutPath);
648
+ const toPath = path.join(process.cwd(), pathConfig.styles);
649
+ const relativePath = path.relative(fromPath, toPath).replace(/\\/g, '/');
650
+ const importPath = relativePath.startsWith('.')
651
+ ? relativePath
652
+ : `./${relativePath}`;
653
+
654
+ // Check for existing global CSS imports
655
+ const globalImportRegex = /import\s+['"]([^'"]*globals?\.css)['"]/;
656
+ const match = content.match(globalImportRegex);
657
+
658
+ if (match) {
659
+ // Replace existing import
660
+ content = content.replace(globalImportRegex, `import '${importPath}'`);
661
+ } else if (!content.includes(importPath)) {
662
+ // Add new import after other imports
663
+ const importStatement = `import '${importPath}';\n`;
664
+ const importRegex = /^(import\s+.*?;\s*)+/m;
665
+ const importMatch = content.match(importRegex);
666
+
667
+ if (importMatch) {
668
+ const lastImportIndex = importMatch.index! + importMatch[0].length;
669
+ content =
670
+ content.slice(0, lastImportIndex) +
671
+ importStatement +
672
+ content.slice(lastImportIndex);
673
+ } else {
674
+ content = importStatement + content;
675
+ }
676
+ }
449
677
 
450
- if (!layoutInfo) {
678
+ await fs.writeFile(layoutPath, content);
451
679
  console.log(
452
- chalk.yellow(
453
- '⚠️ No layout file found. Please import globals.css manually in your layout.'
680
+ chalk.gray(
681
+ `Updated ${path.relative(process.cwd(), layoutPath)} with CSS import`
454
682
  )
455
683
  );
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;
684
+ } catch (error) {
685
+ console.error(chalk.yellow('⚠️ Failed to update layout with CSS import'));
465
686
  }
687
+ }
466
688
 
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
- );
689
+ async function addDirectImportToLayout(
690
+ layoutPath: string,
691
+ pathConfig: PathConfig
692
+ ): Promise<void> {
693
+ try {
694
+ let content = await fs.readFile(layoutPath, 'utf-8');
695
+ const importStatement = `import '@foundrykit/tailwind/globals.css';\n`;
696
+
697
+ if (!content.includes('@foundrykit/tailwind/globals.css')) {
698
+ // Add import at the top of the file after any existing imports
699
+ const importRegex = /^(import\s+.*?;\s*)+/m;
700
+ const match = content.match(importRegex);
701
+
702
+ if (match) {
703
+ // Add after existing imports
704
+ const lastImportIndex = match.index! + match[0].length;
705
+ content =
706
+ content.slice(0, lastImportIndex) +
707
+ importStatement +
708
+ content.slice(lastImportIndex);
709
+ } else {
710
+ // Add at the very beginning
711
+ content = importStatement + content;
712
+ }
482
713
 
483
- await fs.writeFile(layoutInfo.path, updatedContent);
484
- console.log(
485
- chalk.green('✅ Updated layout import to use local globals.css')
486
- );
487
- return;
714
+ await fs.writeFile(layoutPath, content);
715
+ console.log(
716
+ chalk.green('✅ Added direct import of FoundryKit styles to layout')
717
+ );
718
+ }
719
+ } catch (error) {
720
+ console.error(chalk.yellow('⚠️ Failed to add CSS import to layout'));
488
721
  }
722
+ }
489
723
 
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;
724
+ function resolveImportPath(fromFile: string, importPath: string): string {
725
+ if (importPath.startsWith('.')) {
726
+ // Relative import
727
+ return path.join(path.dirname(fromFile), importPath);
728
+ } else if (importPath.startsWith('@/')) {
729
+ // Alias import
730
+ return path.join(process.cwd(), importPath.replace('@/', 'src/'));
731
+ } else if (importPath.startsWith('/')) {
732
+ // Absolute import from project root
733
+ return path.join(process.cwd(), importPath);
520
734
  }
521
735
 
522
- await fs.writeFile(layoutInfo.path, updatedContent);
523
- console.log(chalk.green('✅ Layout file updated with globals.css import'));
736
+ // Default to relative from project root
737
+ return path.join(process.cwd(), importPath);
524
738
  }
525
739
 
526
- async function createDirectories(): Promise<void> {
740
+ async function createDirectories(pathConfig: PathConfig): Promise<void> {
527
741
  console.log(chalk.blue('📁 Creating component directories...'));
528
742
 
529
743
  const dirs = [
530
- 'components/primitives',
531
- 'components/components',
532
- 'components/blocks',
533
- 'components/animations',
534
- 'lib',
535
- 'hooks',
744
+ pathConfig.primitives,
745
+ pathConfig.components,
746
+ pathConfig.blocks,
747
+ pathConfig.animations,
748
+ pathConfig.hooks,
749
+ pathConfig.lib,
536
750
  ];
537
751
 
538
752
  for (const dir of dirs) {
539
- await fs.ensureDir(path.join(process.cwd(), dir));
753
+ const fullPath = path.join(process.cwd(), dir);
754
+ await fs.ensureDir(fullPath);
755
+ console.log(chalk.gray(`Created ${dir}`));
540
756
  }
541
757
 
542
758
  console.log(chalk.green('✅ Directories created'));
543
759
  }
544
760
 
545
- async function createExampleFiles(): Promise<void> {
761
+ async function createExampleFiles(
762
+ pathConfig: PathConfig,
763
+ structure: ProjectStructure
764
+ ): Promise<void> {
546
765
  console.log(chalk.blue('📝 Creating example files...'));
547
766
 
548
- // Create lib/utils.ts
549
- const utilsPath = path.join(process.cwd(), 'lib/utils.ts');
767
+ // Create lib/utils.ts if it doesn't exist
768
+ const utilsPath = path.join(process.cwd(), pathConfig.utils);
550
769
  const utilsContent = `import { type ClassValue, clsx } from 'clsx';
551
770
  import { twMerge } from 'tailwind-merge';
552
771
 
@@ -555,18 +774,25 @@ export function cn(...inputs: ClassValue[]) {
555
774
  }
556
775
  `;
557
776
 
777
+ await fs.ensureDir(path.dirname(utilsPath));
778
+
558
779
  if (!fs.existsSync(utilsPath)) {
559
780
  await fs.writeFile(utilsPath, utilsContent);
560
- console.log(chalk.gray('Created lib/utils.ts'));
781
+ console.log(chalk.gray(`Created ${pathConfig.utils}`));
561
782
  }
562
783
 
563
- // Create providers.tsx if using theme support
564
- const providersPath = path.join(process.cwd(), 'components/providers.tsx');
784
+ // Create providers.tsx for Next.js projects
785
+ const providersPath = path.join(
786
+ process.cwd(),
787
+ path.dirname(pathConfig.components),
788
+ `theme-provider${structure.isTypeScript ? '.tsx' : '.jsx'}`
789
+ );
790
+
565
791
  const providersContent = `'use client';
566
792
 
567
793
  import { ThemeProvider } from 'next-themes';
568
794
 
569
- export function Providers({ children }: { children: React.ReactNode }) {
795
+ export function ThemeProvider({ children }: { children: React.ReactNode }) {
570
796
  return (
571
797
  <ThemeProvider attribute="class" defaultTheme="system" enableSystem>
572
798
  {children}
@@ -577,36 +803,38 @@ export function Providers({ children }: { children: React.ReactNode }) {
577
803
 
578
804
  if (!fs.existsSync(providersPath)) {
579
805
  await fs.writeFile(providersPath, providersContent);
580
- console.log(chalk.gray('Created components/providers.tsx'));
806
+ console.log(
807
+ chalk.gray(
808
+ `Created theme-provider.${structure.isTypeScript ? 'tsx' : 'jsx'}`
809
+ )
810
+ );
581
811
  }
582
812
 
583
813
  console.log(chalk.green('✅ Example files created'));
584
814
  }
585
815
 
586
816
  async function updatePackageScripts(): Promise<void> {
587
- console.log(chalk.blue('📋 Updating package.json scripts...'));
817
+ console.log(chalk.blue('📝 Updating package.json scripts...'));
588
818
 
589
819
  const packageJsonPath = path.join(process.cwd(), 'package.json');
590
820
  const packageJson = await fs.readJson(packageJsonPath);
591
821
 
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
- }
822
+ // Add foundrykit scripts
823
+ packageJson.scripts = {
824
+ ...packageJson.scripts,
825
+ 'foundrykit:add': 'pnpm dlx @foundrykit/cli add',
826
+ 'foundrykit:update': 'pnpm dlx @foundrykit/cli update',
827
+ };
604
828
 
605
829
  await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });
606
830
  console.log(chalk.green('✅ Package scripts updated'));
607
831
  }
608
832
 
609
- async function createConfigFile(options: InitOptions): Promise<void> {
833
+ async function createConfigFile(
834
+ options: InitOptions,
835
+ structure: ProjectStructure,
836
+ pathConfig: PathConfig
837
+ ): Promise<void> {
610
838
  console.log(chalk.blue('📝 Creating configuration file...'));
611
839
 
612
840
  const configPath = path.join(process.cwd(), 'foundrykit.config.json');
@@ -616,88 +844,40 @@ async function createConfigFile(options: InitOptions): Promise<void> {
616
844
  return;
617
845
  }
618
846
 
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
847
+ // Create configuration with custom paths
626
848
  const config = {
627
849
  version: '1.0.0',
628
850
  registry: 'https://foundry.umiflow.com',
629
851
  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',
852
+ utils: pathConfig.utils,
853
+ primitives: pathConfig.primitives,
854
+ components: pathConfig.components,
855
+ blocks: pathConfig.blocks,
856
+ hooks: pathConfig.hooks,
857
+ animations: pathConfig.animations,
636
858
  },
637
- packageManager: detectPackageManager(),
638
- typescript: isTypeScript,
639
- framework,
859
+ packageManager: structure.packageManager,
860
+ typescript: structure.isTypeScript,
861
+ framework: structure.framework,
640
862
  tailwind: {
641
- config: './tailwind.config.js',
642
- css: './src/styles/globals.css',
863
+ css: pathConfig.styles,
643
864
  },
644
865
  aliases: {
645
- '@': './src',
646
- '@/components': './src/components',
647
- '@/lib': './src/lib',
648
- '@/hooks': './src/hooks',
866
+ '@': structure.baseDir.replace(/\/$/, '') || '.',
867
+ '@/components': path.dirname(pathConfig.components).replace(/\/$/, ''),
868
+ '@/lib': pathConfig.lib.replace(/\/$/, ''),
869
+ '@/hooks': pathConfig.hooks.replace(/\/$/, ''),
649
870
  },
650
871
  };
651
872
 
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
873
  await fs.writeJson(configPath, config, { spaces: 2 });
676
874
  console.log(chalk.green('✅ Created foundrykit.config.json'));
677
875
  }
678
876
 
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));
877
+ async function installUtils(pathConfig: PathConfig): Promise<void> {
878
+ console.log(chalk.blue('📦 Installing utility functions...'));
700
879
 
880
+ const utilsPath = path.join(process.cwd(), pathConfig.utils);
701
881
  const utilsContent = `import { type ClassValue, clsx } from 'clsx';
702
882
  import { twMerge } from 'tailwind-merge';
703
883
 
@@ -706,24 +886,14 @@ export function cn(...inputs: ClassValue[]) {
706
886
  }
707
887
  `;
708
888
 
709
- await fs.writeFile(utilsPath, utilsContent);
710
- console.log(chalk.green('✅ Created utils file'));
711
- }
889
+ // Ensure directory exists
890
+ const utilsDir = path.dirname(utilsPath);
891
+ await fs.ensureDir(utilsDir);
712
892
 
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';
893
+ if (!fs.existsSync(utilsPath)) {
894
+ await fs.writeFile(utilsPath, utilsContent);
895
+ console.log(chalk.green('✅ Utility functions installed'));
896
+ } else {
897
+ console.log(chalk.gray('Utils file already exists, skipping...'));
726
898
  }
727
-
728
- return 'react';
729
899
  }