@foundrykit/cli 2.0.12 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1069 +0,0 @@
1
- /**
2
- * Add command for FoundryKit CLI
3
- * Handles adding components to projects
4
- */
5
-
6
- import { exec } from 'node:child_process';
7
- import path from 'node:path';
8
- import { promisify } from 'node:util';
9
- import type {
10
- ComponentCategory,
11
- ComponentData,
12
- ComponentMeta,
13
- Config,
14
- } from '@foundrykit/types';
15
- import chalk from 'chalk';
16
- import { Command } from 'commander';
17
- import fs from 'fs-extra';
18
- import inquirer from 'inquirer';
19
- import { CLI_VERSION, REGISTRY_CATEGORY_ORDER } from '../lib/constants.js';
20
- import { getRegistry } from '../lib/registry.js';
21
-
22
- const execAsync = promisify(exec);
23
-
24
- interface AddOptions {
25
- withAnimation?: boolean;
26
- path?: string;
27
- overwrite?: boolean;
28
- force?: boolean;
29
- }
30
-
31
- export type { AddOptions };
32
-
33
- export function addCommand() {
34
- return new Command('add')
35
- .description('Add a component or block to your project')
36
- .argument('[id]', 'Component or block ID (optional for interactive mode)')
37
- .option('--with-animation', 'Include animation variants')
38
- .option('-p, --path <path>', 'Custom installation path')
39
- .option('-o, --overwrite', 'Overwrite existing files')
40
- .action(async (id: string | undefined, options: AddOptions) => {
41
- try {
42
- // If no ID provided, show interactive selector
43
- if (!id) {
44
- const selectedIds = await selectComponentsInteractively();
45
- if (selectedIds.length === 0) {
46
- console.log(chalk.yellow('No components selected.'));
47
- return;
48
- }
49
-
50
- // Add each selected component
51
- for (const componentId of selectedIds) {
52
- await addSingleComponent(componentId, options);
53
- }
54
- } else {
55
- // Add single component
56
- await addSingleComponent(id, options);
57
- }
58
- } catch (error) {
59
- console.error(chalk.red('❌ Failed to add component:'));
60
- console.error(
61
- chalk.red(error instanceof Error ? error.message : String(error))
62
- );
63
- process.exit(1);
64
- }
65
- });
66
- }
67
-
68
- /**
69
- * Interactive component selection
70
- */
71
- async function selectComponentsInteractively(): Promise<string[]> {
72
- console.log(chalk.blue('📦 Select components to add:'));
73
- console.log(
74
- chalk.gray(' Use arrow keys to navigate, space to select, a to toggle all')
75
- );
76
- console.log(chalk.gray(' Press enter when done\n'));
77
-
78
- const registry = getRegistry();
79
-
80
- try {
81
- // Fetch all available components from registry
82
- console.log(chalk.gray('Fetching components from registry...'));
83
- const allComponents = await registry.getComponents();
84
-
85
- if (allComponents.length === 0) {
86
- console.log(chalk.yellow('No components available in the registry.'));
87
- return [];
88
- }
89
-
90
- // Group components by category
91
- const groupedChoices = createGroupedChoices(allComponents);
92
-
93
- const { selectedComponents } = await inquirer.prompt([
94
- {
95
- type: 'checkbox',
96
- name: 'selectedComponents',
97
- message: 'Which components would you like to add?',
98
- choices: groupedChoices,
99
- pageSize: 20,
100
- loop: false,
101
- },
102
- ]);
103
-
104
- return selectedComponents;
105
- } catch (error) {
106
- console.error(chalk.red('Failed to fetch components from registry:'));
107
- console.error(
108
- chalk.red(error instanceof Error ? error.message : String(error))
109
- );
110
- throw error;
111
- }
112
- }
113
-
114
- /**
115
- * Create grouped choices for the interactive selector
116
- */
117
- function createGroupedChoices(components: ComponentMeta[]) {
118
- const knownCategories = new Set<ComponentCategory>(
119
- REGISTRY_CATEGORY_ORDER as readonly ComponentCategory[]
120
- );
121
- const categories: ComponentCategory[] = [
122
- ...(REGISTRY_CATEGORY_ORDER as readonly ComponentCategory[]),
123
- ...components
124
- .map(component => component.category)
125
- .filter(category => !knownCategories.has(category)),
126
- ];
127
-
128
- const choices: Array<{
129
- name: string;
130
- value: string;
131
- short?: string;
132
- disabled?: boolean;
133
- }> = [];
134
-
135
- for (const category of categories) {
136
- const categoryComponents = components.filter(c => c.category === category);
137
-
138
- if (categoryComponents.length === 0) continue;
139
-
140
- // Add category separator
141
- choices.push({
142
- name: chalk.bold.cyan(`─── ${category.toUpperCase()} ───`),
143
- disabled: true,
144
- value: `separator-${category}`,
145
- });
146
-
147
- // Add components in this category
148
- for (const component of categoryComponents) {
149
- choices.push({
150
- name: `${component.name} - ${chalk.gray(component.description)}`,
151
- value: component.id,
152
- short: component.name,
153
- });
154
- }
155
- }
156
-
157
- return choices;
158
- }
159
-
160
- /**
161
- * Add a single component to the project
162
- */
163
- export async function addSingleComponent(
164
- id: string,
165
- options: AddOptions
166
- ): Promise<void> {
167
- console.log(chalk.blue(`\n📦 Adding ${id} to your project...`));
168
-
169
- // Validate project is initialized
170
- await validateProject();
171
-
172
- const registry = getRegistry();
173
-
174
- try {
175
- // Fetch component data from registry
176
- const componentData = await registry.getComponent(id, options.force);
177
-
178
- // Check for existing files
179
- if (
180
- !options.overwrite &&
181
- (await hasConflictingFiles(componentData, options))
182
- ) {
183
- const { shouldContinue } = await inquirer.prompt([
184
- {
185
- type: 'confirm',
186
- name: 'shouldContinue',
187
- message: `Some files for ${componentData.name} already exist. Overwrite?`,
188
- default: false,
189
- },
190
- ]);
191
-
192
- if (!shouldContinue) {
193
- console.log(chalk.yellow(`⏭️ Skipping ${componentData.name}.`));
194
- return;
195
- }
196
- }
197
-
198
- // Install registry dependencies first
199
- if (componentData.registryDependencies?.length) {
200
- console.log(chalk.blue('📦 Installing required dependencies...'));
201
- for (const dep of componentData.registryDependencies) {
202
- try {
203
- // Fetch dependency from registry
204
- const depData = await registry.getComponent(dep);
205
-
206
- // Handle package dependencies (hooks, types) differently
207
- if (['hooks', 'types'].includes(dep)) {
208
- console.log(chalk.green(` ✓ ${dep} package is available`));
209
- continue;
210
- }
211
-
212
- // Check if dependency files already exist
213
- const hasExisting = await hasConflictingFiles(depData, options);
214
-
215
- if (!hasExisting) {
216
- await installComponentFiles(depData, options);
217
- console.log(chalk.green(` ✓ Installed ${dep}`));
218
- } else {
219
- console.log(chalk.gray(` ⏭ ${dep} already exists`));
220
- }
221
- } catch (error) {
222
- // If dependency fetch fails, log warning but continue
223
- console.log(
224
- chalk.yellow(
225
- ` ⚠ Could not install dependency "${dep}": ${
226
- error instanceof Error ? error.message : 'Unknown error'
227
- }`
228
- )
229
- );
230
- }
231
- }
232
- }
233
-
234
- // Install the component files
235
- await installComponentFiles(componentData, options);
236
-
237
- // Track the installed component in config
238
- await trackInstalledComponent(componentData);
239
-
240
- console.log(chalk.green(`✅ ${componentData.name} added successfully!`));
241
-
242
- // Show usage example
243
- showUsageExample(componentData);
244
-
245
- // Handle package dependencies
246
- await handlePackageDependencies(componentData, options);
247
- } catch (error) {
248
- console.error(chalk.red(`Failed to add ${id}:`));
249
- throw error;
250
- }
251
- }
252
-
253
- /**
254
- * Update config version to match CLI version
255
- */
256
- export async function updateConfigVersion(): Promise<void> {
257
- const configPath = path.join(process.cwd(), 'foundrykit.config.json');
258
- if (fs.existsSync(configPath)) {
259
- const config = await fs.readJson(configPath);
260
- if (config.version !== CLI_VERSION) {
261
- config.version = CLI_VERSION;
262
- await fs.writeJson(configPath, config, { spaces: 2 });
263
- }
264
- }
265
- }
266
-
267
- /**
268
- * Validate that the project is properly initialized
269
- */
270
- export async function validateProject(): Promise<void> {
271
- const packageJsonPath = path.join(process.cwd(), 'package.json');
272
-
273
- if (!fs.existsSync(packageJsonPath)) {
274
- throw new Error(
275
- 'No package.json found. Please run this command in a project root.'
276
- );
277
- }
278
-
279
- // Check for configuration file
280
- const configPath = path.join(process.cwd(), 'foundrykit.config.json');
281
- if (!fs.existsSync(configPath)) {
282
- throw new Error('FoundryKit not initialized. Run "foundrykit init" first.');
283
- }
284
-
285
- // Update config version if needed
286
- await updateConfigVersion();
287
- }
288
-
289
- /**
290
- * Check if component files already exist
291
- */
292
- export async function hasConflictingFiles(
293
- componentData: ComponentData,
294
- options: AddOptions
295
- ): Promise<boolean> {
296
- const config = await loadConfig();
297
- const basePath = options.path || process.cwd();
298
-
299
- for (const file of componentData.files) {
300
- // Special handling for utils to ensure it always goes to the right place
301
- let resolvedPath: string;
302
- if (componentData.id === 'utils' || file.path === 'lib/utils.ts') {
303
- resolvedPath = config.paths.utils || 'lib/utils.ts';
304
- } else {
305
- resolvedPath = resolveComponentPath(
306
- file.path,
307
- componentData.category,
308
- config
309
- );
310
- }
311
- const filePath = path.join(basePath, resolvedPath);
312
- if (fs.existsSync(filePath)) {
313
- return true;
314
- }
315
- }
316
-
317
- return false;
318
- }
319
-
320
- /**
321
- * Install component files to the project
322
- */
323
- export async function installComponentFiles(
324
- componentData: ComponentData,
325
- options: AddOptions
326
- ): Promise<void> {
327
- const config = await loadConfig();
328
- const basePath = options.path || process.cwd();
329
-
330
- if (componentData.files.length === 0) {
331
- return;
332
- }
333
-
334
- console.log(chalk.blue('📝 Installing component files...'));
335
-
336
- for (const file of componentData.files) {
337
- // Special handling for utils to ensure it always goes to the right place
338
- let resolvedPath: string;
339
- if (componentData.id === 'utils' || file.path === 'lib/utils.ts') {
340
- resolvedPath = config.paths.utils || 'lib/utils.ts';
341
- } else {
342
- resolvedPath = resolveComponentPath(
343
- file.path,
344
- componentData.category,
345
- config
346
- );
347
- }
348
-
349
- const filePath = path.join(basePath, resolvedPath);
350
-
351
- // Ensure directory exists
352
- await fs.ensureDir(path.dirname(filePath));
353
-
354
- // Check if file has content before writing
355
- if (!file.content || file.content.trim() === '') {
356
- console.log(
357
- chalk.yellow(` ⚠ Skipping ${resolvedPath} - no content available`)
358
- );
359
- continue;
360
- }
361
-
362
- // Transform imports based on config
363
- const transformedContent = transformImportsForConfig(file.content, config);
364
-
365
- // Write the file
366
- await fs.writeFile(filePath, transformedContent);
367
- console.log(chalk.gray(` ✓ Created ${resolvedPath}`));
368
- }
369
-
370
- // Update config version after successful installation
371
- await updateConfigVersion();
372
- }
373
-
374
- /**
375
- * Record an installed component in foundrykit.config.json
376
- */
377
- export async function trackInstalledComponent(
378
- componentData: ComponentData
379
- ): Promise<void> {
380
- const configPath = path.join(process.cwd(), 'foundrykit.config.json');
381
- if (!fs.existsSync(configPath)) return;
382
-
383
- const config = await fs.readJson(configPath);
384
- config.installedComponents = config.installedComponents ?? {};
385
- config.installedComponents[componentData.id] = {
386
- id: componentData.id,
387
- version: componentData.version ?? null,
388
- installedAt: new Date().toISOString(),
389
- };
390
- await fs.writeJson(configPath, config, { spaces: 2 });
391
- }
392
-
393
- /**
394
- * Handle package dependencies - check and auto-install if needed
395
- */
396
- export async function handlePackageDependencies(
397
- componentData: ComponentData,
398
- options: AddOptions = {}
399
- ): Promise<void> {
400
- // Only use the package dependencies specified by the component
401
- const allDependencies = new Set<string>();
402
-
403
- if (componentData.packageDependencies?.length) {
404
- for (const dep of componentData.packageDependencies)
405
- allDependencies.add(dep);
406
- }
407
-
408
- if (allDependencies.size === 0) {
409
- return;
410
- }
411
-
412
- const dependencies = Array.from(allDependencies);
413
- const forcePackageUpdate =
414
- componentData.files.length === 0 && (options.force || options.overwrite);
415
- const missingPackages = forcePackageUpdate
416
- ? dependencies
417
- : await getMissingPackages(dependencies);
418
-
419
- if (missingPackages.length === 0) {
420
- console.log(chalk.green('✅ All required packages are already installed'));
421
- return;
422
- }
423
-
424
- const packagesToInstall = missingPackages.map(pkg =>
425
- forcePackageUpdate ? getPackageInstallSpec(pkg, componentData.version) : pkg
426
- );
427
-
428
- console.log(
429
- chalk.yellow(
430
- forcePackageUpdate
431
- ? '\n📦 Updating required packages...'
432
- : '\n📦 Installing required packages...'
433
- )
434
- );
435
- console.log(chalk.gray(` ${packagesToInstall.join(', ')}`));
436
-
437
- // Try to detect package manager
438
- const packageManager = await detectPackageManager();
439
-
440
- try {
441
- const installCommand = `${packageManager} add ${packagesToInstall.join(' ')}`;
442
- console.log(chalk.blue(` Running: ${installCommand}`));
443
-
444
- const { stderr } = await execAsync(installCommand);
445
-
446
- if (stderr && !stderr.includes('warning')) {
447
- console.error(chalk.yellow(` Warning: ${stderr}`));
448
- }
449
-
450
- console.log(chalk.green('✅ Packages installed successfully'));
451
- } catch {
452
- console.log(chalk.yellow('\n⚠️ Could not install packages automatically'));
453
- console.log(chalk.gray(' Please install them manually:'));
454
- console.log(
455
- chalk.cyan(` ${packageManager} add ${packagesToInstall.join(' ')}`)
456
- );
457
- }
458
- }
459
-
460
- function getPackageInstallSpec(packageName: string, version?: string): string {
461
- if (!packageName.startsWith('@foundrykit/')) {
462
- return packageName;
463
- }
464
-
465
- return `${packageName}@${version ?? 'latest'}`;
466
- }
467
-
468
- /**
469
- * Check which packages are missing from the project
470
- */
471
- export async function getMissingPackages(
472
- packages: string[]
473
- ): Promise<string[]> {
474
- const packageJsonPath = path.join(process.cwd(), 'package.json');
475
-
476
- try {
477
- const packageJson = await fs.readJson(packageJsonPath);
478
- const installedPackages = {
479
- ...packageJson.dependencies,
480
- ...packageJson.devDependencies,
481
- };
482
-
483
- return packages.filter(pkg => !installedPackages[pkg]);
484
- } catch {
485
- // If we can't read package.json, assume all packages are missing
486
- return packages;
487
- }
488
- }
489
-
490
- /**
491
- * Detect which package manager is being used
492
- */
493
- export async function detectPackageManager(): Promise<string> {
494
- // Check for lock files
495
- if (await fs.pathExists(path.join(process.cwd(), 'pnpm-lock.yaml'))) {
496
- return 'pnpm';
497
- }
498
- if (await fs.pathExists(path.join(process.cwd(), 'yarn.lock'))) {
499
- return 'yarn';
500
- }
501
- if (await fs.pathExists(path.join(process.cwd(), 'package-lock.json'))) {
502
- return 'npm';
503
- }
504
- if (await fs.pathExists(path.join(process.cwd(), 'bun.lockb'))) {
505
- return 'bun';
506
- }
507
-
508
- // Default to pnpm as it's what FoundryKit uses
509
- return 'pnpm';
510
- }
511
-
512
- /**
513
- * Show usage example for the installed component
514
- */
515
- export async function showUsageExample(
516
- componentData: ComponentData
517
- ): Promise<void> {
518
- const config = await loadConfig();
519
- console.log(chalk.cyan('\n💡 Usage:'));
520
-
521
- if (componentData.files.length === 0) {
522
- const packageName = componentData.packageDependencies?.find(dep =>
523
- dep.startsWith('@foundrykit/')
524
- );
525
- if (packageName) {
526
- console.log(chalk.gray(`import { ... } from "${packageName}"`));
527
- }
528
- return;
529
- }
530
-
531
- const componentName = componentData.name.replace(/\s+/g, '');
532
- const importPath = getImportPath(componentData, config);
533
-
534
- console.log(chalk.gray(`import { ${componentName} } from "${importPath}"`));
535
-
536
- // Show usage example if provided in component data
537
- if (componentData.usageExample) {
538
- console.log(chalk.gray(`\n${componentData.usageExample}`));
539
- }
540
- }
541
-
542
- /**
543
- * Load FoundryKit configuration
544
- */
545
- export async function loadConfig(): Promise<Config> {
546
- const configPath = path.join(process.cwd(), 'foundrykit.config.json');
547
- if (!fs.existsSync(configPath)) {
548
- throw new Error(
549
- 'Configuration file not found. Run "foundrykit init" first.'
550
- );
551
- }
552
- return fs.readJson(configPath);
553
- }
554
-
555
- /**
556
- * Transform imports in file content based on config
557
- */
558
- export function transformImportsForConfig(
559
- content: string,
560
- config: Config
561
- ): string {
562
- let transformed = content;
563
-
564
- const importPaths = getConfiguredImportPaths(config);
565
-
566
- transformed = transformRegistryBarrelImports(
567
- transformed,
568
- ['@foundrykit/primitives', '@/components/primitives', '@/components/ui'],
569
- importPaths.primitives,
570
- config,
571
- 'primitives'
572
- );
573
-
574
- transformed = transformRegistryBarrelImports(
575
- transformed,
576
- ['@foundrykit/components', '@/components/components'],
577
- importPaths.components,
578
- config,
579
- 'components'
580
- );
581
-
582
- transformed = transformRegistryBarrelImports(
583
- transformed,
584
- ['@foundrykit/blocks', '@/components/blocks'],
585
- importPaths.blocks,
586
- config,
587
- 'blocks'
588
- );
589
-
590
- transformed = transformRegistryBarrelImports(
591
- transformed,
592
- ['@foundrykit/animation', '@/components/animations'],
593
- importPaths.animations,
594
- config,
595
- 'animations'
596
- );
597
-
598
- transformed = transformRegistryBarrelImports(
599
- transformed,
600
- ['@foundrykit/maps', '@/components/maps'],
601
- importPaths.maps,
602
- config,
603
- 'maps'
604
- );
605
-
606
- transformed = transformRegistryBarrelImports(
607
- transformed,
608
- ['@foundrykit/hooks', '@/hooks'],
609
- importPaths.hooks,
610
- config,
611
- 'hooks'
612
- );
613
-
614
- // Handle utils imports
615
- transformed = transformed
616
- .replace(/@foundrykit\/utils/g, importPaths.utils)
617
- .replace(/@\/lib\/utils/g, importPaths.utils);
618
-
619
- return transformed;
620
- }
621
-
622
- function getConfiguredImportPaths(
623
- config: Config
624
- ): Record<ComponentCategory | 'utils', string> {
625
- const paths = config?.paths || {
626
- primitives: 'components/primitives',
627
- components: 'components',
628
- blocks: 'components/blocks',
629
- animations: 'components/animations',
630
- hooks: 'hooks',
631
- maps: 'components/maps',
632
- utils: 'lib/utils',
633
- };
634
-
635
- return {
636
- primitives: resolveImportBasePath(paths.primitives, config, {
637
- preferRootAlias: true,
638
- }),
639
- components: resolveImportBasePath(paths.components, config, {
640
- preferRootAlias: true,
641
- }),
642
- blocks: resolveImportBasePath(paths.blocks, config, {
643
- preferRootAlias: true,
644
- }),
645
- animations: resolveImportBasePath(paths.animations, config, {
646
- preferRootAlias: true,
647
- }),
648
- maps: resolveImportBasePath(
649
- paths.maps ?? joinImportPath(paths.components, 'maps'),
650
- config,
651
- {
652
- preferRootAlias: true,
653
- }
654
- ),
655
- hooks: resolveImportBasePath(paths.hooks ?? 'hooks', config, {
656
- preferRootAlias: true,
657
- }),
658
- packages: resolveImportBasePath(paths.components, config, {
659
- preferRootAlias: true,
660
- }),
661
- utils: resolveImportBasePath(paths.utils, config).replace(
662
- /\.(ts|js)x?$/,
663
- ''
664
- ),
665
- };
666
- }
667
-
668
- function resolveImportBasePath(
669
- filePath: string,
670
- config: Config,
671
- options: { preferRootAlias?: boolean } = {}
672
- ): string {
673
- if (isPackageImportSpecifier(filePath)) {
674
- return filePath.replace(/\/$/, '');
675
- }
676
-
677
- const normalizedPath = normalizeConfigPath(filePath).replace(
678
- /\.(ts|js)x?$/,
679
- ''
680
- );
681
- const aliases = config?.aliases ?? {};
682
-
683
- if (options.preferRootAlias && aliases['@']) {
684
- const rootTarget = normalizeConfigPath(aliases['@']);
685
- const matchesRoot =
686
- normalizedPath === rootTarget ||
687
- (rootTarget !== '' && normalizedPath.startsWith(`${rootTarget}/`)) ||
688
- rootTarget === '';
689
-
690
- if (matchesRoot) {
691
- const relativePath =
692
- rootTarget === ''
693
- ? normalizedPath
694
- : normalizedPath.slice(rootTarget.length).replace(/^\//, '');
695
- return joinImportPath('@', relativePath);
696
- }
697
- }
698
-
699
- const aliasMatches = Object.entries(aliases)
700
- .map(([alias, target]) => ({
701
- alias,
702
- target: normalizeConfigPath(target),
703
- }))
704
- .filter(({ target }) => {
705
- return (
706
- normalizedPath === target ||
707
- (target !== '' && normalizedPath.startsWith(`${target}/`)) ||
708
- target === ''
709
- );
710
- })
711
- .sort((a, b) => b.target.length - a.target.length);
712
-
713
- const bestMatch = aliasMatches[0];
714
- if (bestMatch) {
715
- const relativePath =
716
- bestMatch.target === ''
717
- ? normalizedPath
718
- : normalizedPath.slice(bestMatch.target.length).replace(/^\//, '');
719
- return joinImportPath(bestMatch.alias, relativePath);
720
- }
721
-
722
- return joinImportPath('@', normalizedPath);
723
- }
724
-
725
- function normalizeConfigPath(filePath: string): string {
726
- return filePath
727
- .replace(/\\/g, '/')
728
- .replace(/^\.\//, '')
729
- .replace(/^\.\/?$/, '')
730
- .replace(/\/$/, '');
731
- }
732
-
733
- function isPackageImportSpecifier(importPath: string): boolean {
734
- return importPath.startsWith('@') && !importPath.startsWith('@/');
735
- }
736
-
737
- function joinImportPath(basePath: string, childPath: string): string {
738
- const normalizedBase = basePath.replace(/\/$/, '');
739
- const normalizedChild = childPath.replace(/^\//, '').replace(/\/$/, '');
740
-
741
- if (!normalizedChild) {
742
- return normalizedBase;
743
- }
744
-
745
- return `${normalizedBase}/${normalizedChild}`;
746
- }
747
-
748
- function transformRegistryBarrelImports(
749
- content: string,
750
- sources: string[],
751
- destinationBasePath: string,
752
- config: Config,
753
- category: ComponentCategory
754
- ): string {
755
- const sourcePattern = sources
756
- .map(source => source.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
757
- .join('|');
758
- const importPattern = new RegExp(
759
- `import\\s+{([^}]+)}\\s+from\\s+["'](${sourcePattern})["'];?`,
760
- 'g'
761
- );
762
-
763
- return content.replace(
764
- importPattern,
765
- (match, imports: string, source: string) => {
766
- if (isPackageImportSpecifier(destinationBasePath)) {
767
- return match.replace(source, destinationBasePath);
768
- }
769
-
770
- const groupedImports = groupImportsByComponent(imports, config, category);
771
-
772
- return Array.from(groupedImports.entries())
773
- .map(([componentPath, specifiers]) => {
774
- return `import { ${specifiers.join(', ')} } from "${destinationBasePath}/${componentPath}";`;
775
- })
776
- .join('\n');
777
- }
778
- );
779
- }
780
-
781
- function groupImportsByComponent(
782
- imports: string,
783
- config: Config,
784
- category: ComponentCategory
785
- ): Map<string, string[]> {
786
- const groupedImports = new Map<string, string[]>();
787
- const exportMap = getInstalledComponentExportMap(config, category);
788
- const specifiers = imports
789
- .split(',')
790
- .map(specifier => specifier.trim())
791
- .filter(Boolean);
792
- const exportNames = specifiers.map(getExportNameFromSpecifier);
793
-
794
- for (const specifier of specifiers) {
795
- const componentPath = getComponentPathForSpecifier(
796
- specifier,
797
- exportNames,
798
- exportMap
799
- );
800
- const existing = groupedImports.get(componentPath) ?? [];
801
- existing.push(specifier);
802
- groupedImports.set(componentPath, existing);
803
- }
804
-
805
- return groupedImports;
806
- }
807
-
808
- function getComponentPathForSpecifier(
809
- specifier: string,
810
- importExportNames: string[],
811
- exportMap: Map<string, string>
812
- ): string {
813
- const exportName = getExportNameFromSpecifier(specifier);
814
-
815
- const mappedPath = exportMap.get(exportName);
816
- if (mappedPath) {
817
- return mappedPath;
818
- }
819
-
820
- const siblingOwnerName = importExportNames
821
- .filter(name => name !== exportName)
822
- .sort((a, b) => a.length - b.length)
823
- .find(name => exportName.toLowerCase().startsWith(name.toLowerCase()));
824
-
825
- if (siblingOwnerName) {
826
- return exportMap.get(siblingOwnerName) ?? toKebabCase(siblingOwnerName);
827
- }
828
-
829
- const variantsOwnerName = exportName.replace(/Variants$/, '');
830
- if (variantsOwnerName !== exportName) {
831
- return exportMap.get(variantsOwnerName) ?? toKebabCase(variantsOwnerName);
832
- }
833
-
834
- return toKebabCase(exportName);
835
- }
836
-
837
- function getExportNameFromSpecifier(specifier: string): string {
838
- return (
839
- specifier
840
- .replace(/^type\s+/, '')
841
- .split(/\s+as\s+/)[0]
842
- ?.trim() || specifier
843
- );
844
- }
845
-
846
- function getInstalledComponentExportMap(
847
- config: Config,
848
- category: ComponentCategory
849
- ): Map<string, string> {
850
- const exportMap = new Map<string, string>();
851
- const categoryPath = getConfiguredCategoryPath(config, category);
852
- if (!categoryPath) {
853
- return exportMap;
854
- }
855
-
856
- const absoluteCategoryPath = path.resolve(
857
- process.cwd(),
858
- normalizeConfigPath(categoryPath)
859
- );
860
-
861
- if (!fs.existsSync(absoluteCategoryPath)) {
862
- return exportMap;
863
- }
864
-
865
- for (const entry of fs.readdirSync(absoluteCategoryPath, {
866
- withFileTypes: true,
867
- })) {
868
- if (!entry.isDirectory()) continue;
869
-
870
- const componentPath = entry.name;
871
- const componentDir = path.join(absoluteCategoryPath, componentPath);
872
- const entryFiles = ['index.tsx', 'index.ts', 'index.jsx', 'index.js']
873
- .map(fileName => path.join(componentDir, fileName))
874
- .filter(filePath => fs.existsSync(filePath));
875
-
876
- for (const filePath of entryFiles) {
877
- const content = fs.readFileSync(filePath, 'utf-8');
878
- for (const exportName of parseExportNames(content)) {
879
- exportMap.set(exportName, componentPath);
880
- }
881
- }
882
- }
883
-
884
- return exportMap;
885
- }
886
-
887
- function parseExportNames(content: string): string[] {
888
- const exportNames = new Set<string>();
889
- const namedExportPattern = /export\s*{\s*([^}]+)\s*}/g;
890
- const declarationExportPattern =
891
- /export\s+(?:declare\s+)?(?:const|let|var|function|class|interface|type|enum)\s+([A-Za-z_$][\w$]*)/g;
892
-
893
- for (const match of content.matchAll(namedExportPattern)) {
894
- const exports = match[1] ?? '';
895
- for (const rawExport of exports.split(',')) {
896
- const exportName = rawExport
897
- .trim()
898
- .replace(/^type\s+/, '')
899
- .split(/\s+as\s+/)
900
- .pop()
901
- ?.trim();
902
-
903
- if (exportName) {
904
- exportNames.add(exportName);
905
- }
906
- }
907
- }
908
-
909
- for (const match of content.matchAll(declarationExportPattern)) {
910
- if (match[1]) {
911
- exportNames.add(match[1]);
912
- }
913
- }
914
-
915
- return Array.from(exportNames);
916
- }
917
-
918
- function toKebabCase(value: string): string {
919
- return value
920
- .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
921
- .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
922
- .toLowerCase();
923
- }
924
-
925
- /**
926
- * Resolve component path based on category and configuration
927
- */
928
- export function resolveComponentPath(
929
- originalPath: string,
930
- category: ComponentCategory,
931
- config: Config
932
- ): string {
933
- // Ensure config.paths exists with fallbacks
934
- const paths = config?.paths || {
935
- primitives: 'components/primitives',
936
- components: 'components',
937
- blocks: 'components/blocks',
938
- animations: 'components/animations',
939
- hooks: 'hooks',
940
- maps: 'components/maps',
941
- utils: 'lib/utils',
942
- };
943
-
944
- // Special handling for utils files - they should go directly to lib/utils.ts
945
- if (originalPath === 'lib/utils.ts') {
946
- return paths.utils || 'lib/utils.ts';
947
- }
948
-
949
- // Get the base path for the category from config
950
- const categoryPath =
951
- getConfiguredCategoryPath(config, category) || paths.components;
952
-
953
- // Extract just the filename from the original path
954
- const fileName = path.basename(originalPath);
955
- const componentName = path.dirname(originalPath).split('/').pop() || '';
956
-
957
- // Build the resolved path based on category
958
- if (category === 'primitives') {
959
- return path.join(categoryPath, componentName, fileName);
960
- } else if (category === 'components') {
961
- return path.join(paths.components, componentName, fileName);
962
- } else if (category === 'blocks') {
963
- return path.join(
964
- paths.blocks || path.join(paths.components, 'blocks'),
965
- componentName,
966
- fileName
967
- );
968
- } else if (category === 'animations') {
969
- return path.join(
970
- paths.animations || path.join(paths.components, 'animations'),
971
- componentName,
972
- fileName
973
- );
974
- } else if (category === 'maps') {
975
- return path.join(
976
- paths.maps || path.join(paths.components, 'maps'),
977
- componentName,
978
- fileName
979
- );
980
- } else if (category === 'hooks') {
981
- return path.join(paths.hooks || 'hooks', componentName, fileName);
982
- } else if (category === 'packages') {
983
- return path.join(paths.components, componentName, fileName);
984
- }
985
-
986
- // Default to original path if category not recognized
987
- return originalPath;
988
- }
989
-
990
- function getConfiguredCategoryPath(
991
- config: Config,
992
- category: ComponentCategory
993
- ): string | undefined {
994
- const paths = config.paths;
995
-
996
- switch (category) {
997
- case 'primitives':
998
- return paths.primitives;
999
- case 'components':
1000
- return paths.components;
1001
- case 'blocks':
1002
- return paths.blocks;
1003
- case 'animations':
1004
- return paths.animations;
1005
- case 'maps':
1006
- return paths.maps ?? path.join(paths.components, 'maps');
1007
- case 'hooks':
1008
- return paths.hooks ?? 'hooks';
1009
- case 'packages':
1010
- return paths.components;
1011
- default:
1012
- return undefined;
1013
- }
1014
- }
1015
-
1016
- /**
1017
- * Get import path for a component
1018
- */
1019
- export function getImportPath(
1020
- componentData: ComponentData,
1021
- config: Config
1022
- ): string {
1023
- // Ensure config.paths exists with fallbacks
1024
- const paths = config?.paths || {
1025
- primitives: 'components/primitives',
1026
- components: 'components',
1027
- blocks: 'components/blocks',
1028
- animations: 'components/animations',
1029
- hooks: 'hooks',
1030
- maps: 'components/maps',
1031
- utils: 'lib/utils',
1032
- };
1033
-
1034
- const componentName = path.basename(
1035
- path.dirname(componentData.files[0]?.path || '')
1036
- );
1037
-
1038
- if (componentData.category === 'primitives') {
1039
- return `${resolveImportBasePath(paths.primitives, config, {
1040
- preferRootAlias: true,
1041
- })}/${componentName}`;
1042
- } else if (componentData.category === 'components') {
1043
- return `${resolveImportBasePath(paths.components, config, {
1044
- preferRootAlias: true,
1045
- })}/${componentName}`;
1046
- } else if (componentData.category === 'blocks') {
1047
- return `${resolveImportBasePath(paths.blocks, config, {
1048
- preferRootAlias: true,
1049
- })}/${componentName}`;
1050
- } else if (componentData.category === 'animations') {
1051
- return `${resolveImportBasePath(paths.animations, config, {
1052
- preferRootAlias: true,
1053
- })}/${componentName}`;
1054
- } else if (componentData.category === 'maps') {
1055
- return `${resolveImportBasePath(
1056
- paths.maps || path.join(paths.components, 'maps'),
1057
- config,
1058
- {
1059
- preferRootAlias: true,
1060
- }
1061
- )}/${componentName}`;
1062
- } else if (componentData.category === 'hooks') {
1063
- return `${resolveImportBasePath(paths.hooks || 'hooks', config, {
1064
- preferRootAlias: true,
1065
- })}/${componentName}`;
1066
- }
1067
-
1068
- return `@/components/${componentName}`;
1069
- }