@foundrykit/cli 1.0.16 → 2.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.
@@ -27,6 +27,8 @@ interface AddOptions {
27
27
  overwrite?: boolean;
28
28
  }
29
29
 
30
+ export type { AddOptions };
31
+
30
32
  export function addCommand() {
31
33
  return new Command('add')
32
34
  .description('Add a component or block to your project')
@@ -149,7 +151,7 @@ function createGroupedChoices(components: ComponentMeta[]) {
149
151
  /**
150
152
  * Add a single component to the project
151
153
  */
152
- async function addSingleComponent(
154
+ export async function addSingleComponent(
153
155
  id: string,
154
156
  options: AddOptions
155
157
  ): Promise<void> {
@@ -223,6 +225,9 @@ async function addSingleComponent(
223
225
  // Install the component files
224
226
  await installComponentFiles(componentData, options);
225
227
 
228
+ // Track the installed component in config
229
+ await trackInstalledComponent(componentData);
230
+
226
231
  console.log(chalk.green(`āœ… ${componentData.name} added successfully!`));
227
232
 
228
233
  // Show usage example
@@ -239,7 +244,7 @@ async function addSingleComponent(
239
244
  /**
240
245
  * Update config version to match CLI version
241
246
  */
242
- async function updateConfigVersion(): Promise<void> {
247
+ export async function updateConfigVersion(): Promise<void> {
243
248
  const configPath = path.join(process.cwd(), 'foundrykit.config.json');
244
249
  if (fs.existsSync(configPath)) {
245
250
  const config = await fs.readJson(configPath);
@@ -253,7 +258,7 @@ async function updateConfigVersion(): Promise<void> {
253
258
  /**
254
259
  * Validate that the project is properly initialized
255
260
  */
256
- async function validateProject(): Promise<void> {
261
+ export async function validateProject(): Promise<void> {
257
262
  const packageJsonPath = path.join(process.cwd(), 'package.json');
258
263
 
259
264
  if (!fs.existsSync(packageJsonPath)) {
@@ -275,7 +280,7 @@ async function validateProject(): Promise<void> {
275
280
  /**
276
281
  * Check if component files already exist
277
282
  */
278
- async function hasConflictingFiles(
283
+ export async function hasConflictingFiles(
279
284
  componentData: ComponentData,
280
285
  options: AddOptions
281
286
  ): Promise<boolean> {
@@ -306,7 +311,7 @@ async function hasConflictingFiles(
306
311
  /**
307
312
  * Install component files to the project
308
313
  */
309
- async function installComponentFiles(
314
+ export async function installComponentFiles(
310
315
  componentData: ComponentData,
311
316
  options: AddOptions
312
317
  ): Promise<void> {
@@ -353,10 +358,29 @@ async function installComponentFiles(
353
358
  await updateConfigVersion();
354
359
  }
355
360
 
361
+ /**
362
+ * Record an installed component in foundrykit.config.json
363
+ */
364
+ export async function trackInstalledComponent(
365
+ componentData: ComponentData
366
+ ): Promise<void> {
367
+ const configPath = path.join(process.cwd(), 'foundrykit.config.json');
368
+ if (!fs.existsSync(configPath)) return;
369
+
370
+ const config = await fs.readJson(configPath);
371
+ config.installedComponents = config.installedComponents ?? {};
372
+ config.installedComponents[componentData.id] = {
373
+ id: componentData.id,
374
+ version: componentData.version ?? null,
375
+ installedAt: new Date().toISOString(),
376
+ };
377
+ await fs.writeJson(configPath, config, { spaces: 2 });
378
+ }
379
+
356
380
  /**
357
381
  * Handle package dependencies - check and auto-install if needed
358
382
  */
359
- async function handlePackageDependencies(
383
+ export async function handlePackageDependencies(
360
384
  componentData: ComponentData
361
385
  ): Promise<void> {
362
386
  // Only use the package dependencies specified by the component
@@ -407,7 +431,7 @@ async function handlePackageDependencies(
407
431
  /**
408
432
  * Check which packages are missing from the project
409
433
  */
410
- async function getMissingPackages(packages: string[]): Promise<string[]> {
434
+ export async function getMissingPackages(packages: string[]): Promise<string[]> {
411
435
  const packageJsonPath = path.join(process.cwd(), 'package.json');
412
436
 
413
437
  try {
@@ -427,7 +451,7 @@ async function getMissingPackages(packages: string[]): Promise<string[]> {
427
451
  /**
428
452
  * Detect which package manager is being used
429
453
  */
430
- async function detectPackageManager(): Promise<string> {
454
+ export async function detectPackageManager(): Promise<string> {
431
455
  // Check for lock files
432
456
  if (await fs.pathExists(path.join(process.cwd(), 'pnpm-lock.yaml'))) {
433
457
  return 'pnpm';
@@ -449,7 +473,9 @@ async function detectPackageManager(): Promise<string> {
449
473
  /**
450
474
  * Show usage example for the installed component
451
475
  */
452
- async function showUsageExample(componentData: ComponentData): Promise<void> {
476
+ export async function showUsageExample(
477
+ componentData: ComponentData
478
+ ): Promise<void> {
453
479
  const config = await loadConfig();
454
480
  console.log(chalk.cyan('\nšŸ’” Usage:'));
455
481
 
@@ -467,7 +493,7 @@ async function showUsageExample(componentData: ComponentData): Promise<void> {
467
493
  /**
468
494
  * Load FoundryKit configuration
469
495
  */
470
- async function loadConfig(): Promise<Config> {
496
+ export async function loadConfig(): Promise<Config> {
471
497
  const configPath = path.join(process.cwd(), 'foundrykit.config.json');
472
498
  if (!fs.existsSync(configPath)) {
473
499
  throw new Error(
@@ -480,7 +506,7 @@ async function loadConfig(): Promise<Config> {
480
506
  /**
481
507
  * Transform imports in file content based on config
482
508
  */
483
- function transformImportsForConfig(content: string, config: Config): string {
509
+ export function transformImportsForConfig(content: string, config: Config): string {
484
510
  let transformed = content;
485
511
 
486
512
  // Ensure config.paths exists with fallbacks
@@ -613,7 +639,7 @@ function transformImportsForConfig(content: string, config: Config): string {
613
639
  /**
614
640
  * Resolve component path based on category and configuration
615
641
  */
616
- function resolveComponentPath(
642
+ export function resolveComponentPath(
617
643
  originalPath: string,
618
644
  category: ComponentCategory,
619
645
  config: any
@@ -665,7 +691,7 @@ function resolveComponentPath(
665
691
  /**
666
692
  * Get import path for a component
667
693
  */
668
- function getImportPath(componentData: ComponentData, config: any): string {
694
+ export function getImportPath(componentData: ComponentData, config: any): string {
669
695
  // Ensure config.paths exists with fallbacks
670
696
  const paths = config?.paths || {
671
697
  primitives: 'components/primitives',
@@ -1,11 +1,127 @@
1
1
  import { Command } from 'commander';
2
2
  import chalk from 'chalk';
3
+ import fs from 'fs-extra';
4
+ import path from 'path';
5
+ import { DEFAULT_REGISTRY_URL } from '../lib/constants.js';
6
+ import { loadConfig } from './add.js';
7
+
8
+ interface CheckResult {
9
+ label: string;
10
+ ok: boolean;
11
+ detail: string;
12
+ }
3
13
 
4
14
  export function doctorCommand() {
5
15
  return new Command('doctor')
6
16
  .description('Check project health and configuration')
7
17
  .action(async () => {
8
18
  console.log(chalk.blue('šŸ” Checking project health...'));
9
- console.log(chalk.green('āœ… All checks passed!'));
19
+
20
+ const results: CheckResult[] = [];
21
+
22
+ const packageJsonPath = path.join(process.cwd(), 'package.json');
23
+ const hasPackageJson = await fs.pathExists(packageJsonPath);
24
+ results.push({
25
+ label: 'package.json',
26
+ ok: hasPackageJson,
27
+ detail: hasPackageJson
28
+ ? 'Project manifest found'
29
+ : 'Run this command in a project root',
30
+ });
31
+
32
+ let packageJson: Record<string, any> | null = null;
33
+ if (hasPackageJson) {
34
+ packageJson = await fs.readJson(packageJsonPath);
35
+ }
36
+
37
+ const hasNext =
38
+ !!packageJson &&
39
+ !!(packageJson.dependencies?.next || packageJson.devDependencies?.next);
40
+ results.push({
41
+ label: 'Framework',
42
+ ok: hasNext,
43
+ detail: hasNext
44
+ ? 'Next.js dependency detected'
45
+ : 'FoundryKit currently expects a Next.js project',
46
+ });
47
+
48
+ const configPath = path.join(process.cwd(), 'foundrykit.config.json');
49
+ const hasConfig = await fs.pathExists(configPath);
50
+ results.push({
51
+ label: 'FoundryKit config',
52
+ ok: hasConfig,
53
+ detail: hasConfig
54
+ ? 'foundrykit.config.json found'
55
+ : 'Run "foundrykit init" to create the configuration file',
56
+ });
57
+
58
+ let config:
59
+ | Awaited<ReturnType<typeof loadConfig>>
60
+ | null = null;
61
+ if (hasConfig) {
62
+ try {
63
+ config = await loadConfig();
64
+ const hasRequiredPaths =
65
+ !!config.paths?.utils &&
66
+ !!config.paths?.primitives &&
67
+ !!config.paths?.components &&
68
+ !!config.paths?.blocks &&
69
+ !!config.paths?.animations;
70
+
71
+ results.push({
72
+ label: 'Config shape',
73
+ ok: hasRequiredPaths,
74
+ detail: hasRequiredPaths
75
+ ? 'Required install paths are configured'
76
+ : 'Configuration is missing one or more required install paths',
77
+ });
78
+
79
+ const registryUrl = config.registry || DEFAULT_REGISTRY_URL;
80
+ try {
81
+ const response = await fetch(`${registryUrl}/registry`, {
82
+ headers: { Accept: 'application/json' },
83
+ });
84
+
85
+ results.push({
86
+ label: 'Registry',
87
+ ok: response.ok,
88
+ detail: response.ok
89
+ ? `Registry reachable at ${registryUrl}`
90
+ : `Registry returned ${response.status} ${response.statusText}`,
91
+ });
92
+ } catch (error) {
93
+ results.push({
94
+ label: 'Registry',
95
+ ok: false,
96
+ detail: `Unable to reach ${registryUrl}: ${
97
+ error instanceof Error ? error.message : 'Unknown error'
98
+ }`,
99
+ });
100
+ }
101
+ } catch (error) {
102
+ results.push({
103
+ label: 'Config shape',
104
+ ok: false,
105
+ detail: `Failed to read foundrykit.config.json: ${
106
+ error instanceof Error ? error.message : 'Unknown error'
107
+ }`,
108
+ });
109
+ }
110
+ }
111
+
112
+ for (const result of results) {
113
+ const icon = result.ok ? chalk.green('āœ…') : chalk.red('āŒ');
114
+ console.log(`${icon} ${result.label}: ${result.detail}`);
115
+ }
116
+
117
+ const hasFailures = results.some(result => !result.ok);
118
+ if (hasFailures) {
119
+ console.log(
120
+ chalk.yellow('\nāš ļø Found issues that should be resolved before continuing.')
121
+ );
122
+ process.exit(1);
123
+ }
124
+
125
+ console.log(chalk.green('\nāœ… All checks passed!'));
10
126
  });
11
127
  }
@@ -1,12 +1,152 @@
1
1
  import { Command } from 'commander';
2
2
  import chalk from 'chalk';
3
+ import inquirer from 'inquirer';
4
+ import fs from 'fs-extra';
5
+ import path from 'path';
6
+ import { addSingleComponent, type AddOptions } from './add.js';
7
+ import { getRegistry } from '../lib/registry.js';
8
+ import type { InstalledComponent } from '@foundrykit/types';
9
+
10
+ interface UpdateOptions extends AddOptions {
11
+ opt?: boolean;
12
+ }
3
13
 
4
14
  export function updateCommand() {
5
15
  return new Command('update')
6
- .description('Update an existing component or block')
7
- .argument('<id>', 'Component or block ID')
8
- .action(async id => {
9
- console.log(chalk.blue(`šŸ”„ Updating ${id}...`));
10
- console.log(chalk.green(`āœ… ${id} updated successfully!`));
16
+ .description('Update installed components')
17
+ .argument('[id]', 'Component or block ID (omit to update all installed)')
18
+ .option('--opt', 'interactively select which components to update, showing available upgrades')
19
+ .option('-p, --path <path>', 'Custom installation path')
20
+ .action(async (id: string | undefined, options: UpdateOptions) => {
21
+ if (id) {
22
+ // Update single named component
23
+ try {
24
+ console.log(chalk.blue(`šŸ”„ Updating ${id}...`));
25
+ await addSingleComponent(id, { ...options, overwrite: true });
26
+ } catch (error) {
27
+ console.error(chalk.red(`āŒ Failed to update ${id}:`));
28
+ console.error(chalk.red(error instanceof Error ? error.message : String(error)));
29
+ process.exit(1);
30
+ }
31
+ return;
32
+ }
33
+
34
+ // Load installed components from config
35
+ const configPath = path.join(process.cwd(), 'foundrykit.config.json');
36
+ if (!fs.existsSync(configPath)) {
37
+ console.error(chalk.red('āŒ FoundryKit not initialized. Run "foundrykit init" first.'));
38
+ process.exit(1);
39
+ }
40
+
41
+ const config = await fs.readJson(configPath);
42
+ const installed: Record<string, InstalledComponent> = config.installedComponents ?? {};
43
+ const installedIds = Object.keys(installed);
44
+
45
+ if (installedIds.length === 0) {
46
+ console.log(chalk.yellow('No installed components found. Use "foundrykit add" to install components.'));
47
+ return;
48
+ }
49
+
50
+ if (options.opt) {
51
+ // --opt: fetch registry versions, show which have updates, let user pick
52
+ console.log(chalk.blue(`šŸ” Checking for updates across ${installedIds.length} installed component(s)...`));
53
+
54
+ const registry = getRegistry();
55
+ const withUpdates: Array<{ id: string; installed: string | null; latest: string | null }> = [];
56
+ const upToDate: string[] = [];
57
+
58
+ for (const compId of installedIds) {
59
+ try {
60
+ const data = await registry.getComponent(compId);
61
+ const installedVersion = installed[compId]?.version ?? null;
62
+ const latestVersion = data.version ?? null;
63
+
64
+ const hasUpdate =
65
+ latestVersion !== null &&
66
+ installedVersion !== null &&
67
+ latestVersion !== installedVersion;
68
+
69
+ const unknownVersion = installedVersion === null || latestVersion === null;
70
+
71
+ if (hasUpdate || unknownVersion) {
72
+ withUpdates.push({ id: compId, installed: installedVersion, latest: latestVersion });
73
+ } else {
74
+ upToDate.push(compId);
75
+ }
76
+ } catch {
77
+ // If we can't fetch, still offer the option to re-install
78
+ withUpdates.push({ id: compId, installed: installed[compId]?.version ?? null, latest: null });
79
+ }
80
+ }
81
+
82
+ if (upToDate.length > 0) {
83
+ console.log(chalk.gray(`\nāœ“ Already up to date: ${upToDate.join(', ')}`));
84
+ }
85
+
86
+ if (withUpdates.length === 0) {
87
+ console.log(chalk.green('\nāœ… All components are up to date.'));
88
+ return;
89
+ }
90
+
91
+ const choices = withUpdates.map(({ id: compId, installed: inst, latest }) => {
92
+ let versionLabel: string;
93
+ if (inst === null && latest === null) {
94
+ versionLabel = chalk.gray('(version unknown)');
95
+ } else if (latest === null) {
96
+ versionLabel = chalk.gray(`(installed: ${inst} — registry version unknown)`);
97
+ } else if (inst === null) {
98
+ versionLabel = chalk.cyan(`(latest: ${latest} — install version not tracked)`);
99
+ } else {
100
+ versionLabel = chalk.cyan(`(${inst} → ${latest})`);
101
+ }
102
+ return {
103
+ name: `${compId} ${versionLabel}`,
104
+ value: compId,
105
+ checked: true,
106
+ };
107
+ });
108
+
109
+ const { selectedIds } = await inquirer.prompt([
110
+ {
111
+ type: 'checkbox',
112
+ name: 'selectedIds',
113
+ message: 'Select components to update:',
114
+ choices,
115
+ pageSize: 20,
116
+ },
117
+ ]);
118
+
119
+ if (selectedIds.length === 0) {
120
+ console.log(chalk.yellow('No components selected.'));
121
+ return;
122
+ }
123
+
124
+ await runUpdates(selectedIds, options);
125
+ } else {
126
+ // No flag: update everything
127
+ console.log(chalk.blue(`šŸ”„ Updating all ${installedIds.length} installed component(s)...`));
128
+ await runUpdates(installedIds, options);
129
+ }
11
130
  });
12
131
  }
132
+
133
+ async function runUpdates(ids: string[], options: AddOptions): Promise<void> {
134
+ let failed = 0;
135
+ for (const compId of ids) {
136
+ try {
137
+ console.log(chalk.blue(`\nšŸ”„ Updating ${compId}...`));
138
+ await addSingleComponent(compId, { ...options, overwrite: true });
139
+ } catch (error) {
140
+ console.error(chalk.red(`āŒ Failed to update ${compId}:`));
141
+ console.error(chalk.red(error instanceof Error ? error.message : String(error)));
142
+ failed++;
143
+ }
144
+ }
145
+
146
+ if (failed > 0) {
147
+ console.log(chalk.yellow(`\n⚠ ${failed} component(s) failed to update.`));
148
+ process.exit(1);
149
+ } else {
150
+ console.log(chalk.green(`\nāœ… ${ids.length} component(s) updated successfully!`));
151
+ }
152
+ }
@@ -4,7 +4,7 @@
4
4
 
5
5
  // CLI version - update this when publishing new versions
6
6
  // This should match the version in package.json
7
- export const CLI_VERSION = '1.0.8';
7
+ export const CLI_VERSION = '1.0.16';
8
8
 
9
9
  // Default registry URL
10
10
  export const DEFAULT_REGISTRY_URL = 'https://foundry.umiflow.com';
@@ -96,6 +96,15 @@ export class RegistryService {
96
96
  return this.createSpecialDependency(id);
97
97
  }
98
98
 
99
+ const cache = await this.loadCache();
100
+ const cachedComponent = cache?.componentData?.[id];
101
+ const hasValidCache = cache ? this.isCacheValid(cache) : false;
102
+
103
+ if (cachedComponent && hasValidCache) {
104
+ console.log(chalk.gray(`Using cached data for component: ${id}`));
105
+ return cachedComponent;
106
+ }
107
+
99
108
  try {
100
109
  const url = `${this.config.registryUrl}/registry/${id}`;
101
110
  console.log(chalk.gray(`Fetching component: ${url}`));
@@ -118,11 +127,10 @@ export class RegistryService {
118
127
 
119
128
  return component;
120
129
  } catch (error) {
121
- // Try to load from cache
122
- const cache = await this.loadCache();
123
- if (cache?.componentData?.[id]) {
130
+ // Fall back to any cached component data, even if stale
131
+ if (cachedComponent) {
124
132
  console.log(chalk.yellow(`Using cached data for component: ${id}`));
125
- return cache.componentData[id];
133
+ return cachedComponent;
126
134
  }
127
135
 
128
136
  // No cached data, throw error
@@ -271,12 +279,17 @@ export function cn(...inputs: ClassValue[]) {
271
279
  */
272
280
  private async cacheComponent(component: ComponentData): Promise<void> {
273
281
  try {
274
- const cache = await this.loadCache();
275
- if (!cache) return;
282
+ const cache = (await this.loadCache()) ?? {
283
+ version: '1.0.0',
284
+ lastUpdated: new Date().toISOString(),
285
+ components: [],
286
+ componentData: {},
287
+ };
276
288
 
277
289
  cache.componentData[component.id] = component;
278
290
  cache.lastUpdated = new Date().toISOString();
279
291
 
292
+ await fs.ensureDir(this.config.cacheDir);
280
293
  await fs.writeJson(this.cacheFile, cache, { spaces: 2 });
281
294
  } catch (error) {
282
295
  // Cache update failed, but don't throw
@@ -6,7 +6,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
6
6
  import fs from 'fs-extra';
7
7
  import path from 'path';
8
8
  import os from 'os';
9
- import { RegistryService } from '../src/lib/registry';
9
+ import { RegistryService } from '../src/lib/registry.js';
10
10
  import type { ComponentData } from '@foundrykit/types';
11
11
 
12
12
  describe('Dependency Resolution', () => {
@@ -44,10 +44,10 @@ describe('Dependency Resolution', () => {
44
44
  expect(component).toBeDefined();
45
45
  expect(component.id).toBe('utils');
46
46
  expect(component.files).toHaveLength(1);
47
- expect(component.files[0].path).toBe('lib/utils.ts');
48
- expect(component.files[0].content).toContain('cn');
49
- expect(component.files[0].content).toContain('clsx');
50
- expect(component.files[0].content).toContain('twMerge');
47
+ expect(component.files[0]!.path).toBe('lib/utils.ts');
48
+ expect(component.files[0]!.content).toContain('cn');
49
+ expect(component.files[0]!.content).toContain('clsx');
50
+ expect(component.files[0]!.content).toContain('twMerge');
51
51
  });
52
52
 
53
53
  it('should handle lib alias for utils', async () => {
@@ -55,7 +55,7 @@ describe('Dependency Resolution', () => {
55
55
 
56
56
  expect(component).toBeDefined();
57
57
  expect(component.id).toBe('utils');
58
- expect(component.files[0].path).toBe('lib/utils.ts');
58
+ expect(component.files[0]!.path).toBe('lib/utils.ts');
59
59
  });
60
60
 
61
61
  it('should handle helpers alias for utils', async () => {
@@ -63,7 +63,7 @@ describe('Dependency Resolution', () => {
63
63
 
64
64
  expect(component).toBeDefined();
65
65
  expect(component.id).toBe('utils');
66
- expect(component.files[0].path).toBe('lib/utils.ts');
66
+ expect(component.files[0]!.path).toBe('lib/utils.ts');
67
67
  });
68
68
 
69
69
  it('should handle cn alias for utils', async () => {
@@ -71,7 +71,7 @@ describe('Dependency Resolution', () => {
71
71
 
72
72
  expect(component).toBeDefined();
73
73
  expect(component.id).toBe('utils');
74
- expect(component.files[0].path).toBe('lib/utils.ts');
74
+ expect(component.files[0]!.path).toBe('lib/utils.ts');
75
75
  });
76
76
  });
77
77
 
@@ -205,7 +205,7 @@ describe('Dependency Resolution', () => {
205
205
 
206
206
  // Simulate installation
207
207
  await fs.ensureDir(path.dirname(utilsPath));
208
- await fs.writeFile(utilsPath, utils.files[0].content);
208
+ await fs.writeFile(utilsPath, utils.files[0]!.content);
209
209
 
210
210
  expect(await fs.pathExists(utilsPath)).toBe(true);
211
211