@astralkit/cli 4.2.0 → 4.2.1

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,451 +1,565 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import pc from 'picocolors';
4
- import * as p from '@clack/prompts';
5
- import { getComponent, getBooster, getWorkflow, listComponents, listBoosters, listWorkflows } from '../lib/api.js';
6
- import {
7
- detectFramework,
8
- detectTypeScript,
9
- isAstralkitInstalled,
10
- findCssEntryFile,
11
- getMissingCssImports,
12
- } from '../lib/config.js';
13
- import { validateSlug, validateFramework, isSafePath, writeFiles } from '../lib/validators.js';
14
- import { detectPackageManager, getRunCommand, runInstall } from '../lib/pkg-manager.js';
15
- import { saveApiKey, getApiKey, getAuth } from '../lib/auth.js';
16
-
17
- const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React' };
18
-
19
- export async function addCommand(nameOrSlug, options) {
20
- if (options.apiKey) {
21
- if (!options.apiKey.startsWith('ak_')) {
22
- console.log(pc.red('Invalid API key format. Keys start with ak_'));
23
- process.exit(1);
24
- }
25
- saveApiKey(options.apiKey);
26
- }
27
-
28
- if (!getApiKey()) {
29
- const auth = getAuth();
30
- if (!auth.token) {
31
- p.log.warn('No API key found. Run ' + pc.cyan('astralkit init --api-key <key>') + ' first.');
32
- console.log(pc.gray('Get yours at ') + pc.cyan('https://astralkit.com/account'));
33
- process.exit(1);
34
- }
35
- }
36
-
37
- // If explicit type flag provided, skip smart detection
38
- if (options.booster) return addBooster(nameOrSlug, options);
39
- if (options.workflow) return addWorkflow(nameOrSlug, options);
40
-
41
- // ─── Smart detection: search all registries for the slug ───
42
- const ora = (await import('ora')).default;
43
- const spinner = ora('Searching registries...').start();
44
-
45
- try {
46
- // Search all three registries in parallel
47
- const [components, boosters, workflows] = await Promise.allSettled([
48
- listComponents({ search: nameOrSlug }).catch(() => ({ data: [] })),
49
- listBoosters({ search: nameOrSlug }).catch(() => ({ data: [] })),
50
- listWorkflows({ search: nameOrSlug }).catch(() => ({ data: [] })),
51
- ]);
52
-
53
- const compMatch = (components.status === 'fulfilled' ? components.value?.data : [])
54
- ?.find(c => c.slug === nameOrSlug);
55
- const boosterMatch = (boosters.status === 'fulfilled' ? boosters.value?.data : [])
56
- ?.find(b => b.slug === nameOrSlug);
57
- const workflowMatch = (workflows.status === 'fulfilled' ? workflows.value?.data : [])
58
- ?.find(w => w.slug === nameOrSlug);
59
-
60
- const matches = [];
61
- if (compMatch) matches.push({ type: 'component', name: compMatch.name || nameOrSlug, slug: nameOrSlug });
62
- if (boosterMatch) matches.push({ type: 'booster', name: boosterMatch.name || nameOrSlug, slug: nameOrSlug });
63
- if (workflowMatch) matches.push({ type: 'workflow', name: workflowMatch.name || nameOrSlug, slug: nameOrSlug });
64
-
65
- spinner.stop();
66
-
67
- if (matches.length === 0) {
68
- // No exact match — try fuzzy suggestions
69
- const allItems = [
70
- ...((components.status === 'fulfilled' ? components.value?.data : []) || []).map(c => ({ ...c, type: 'component' })),
71
- ...((boosters.status === 'fulfilled' ? boosters.value?.data : []) || []).map(b => ({ ...b, type: 'booster' })),
72
- ...((workflows.status === 'fulfilled' ? workflows.value?.data : []) || []).map(w => ({ ...w, type: 'workflow' })),
73
- ];
74
-
75
- const similar = allItems
76
- .filter(item => item.slug && (
77
- item.slug.includes(nameOrSlug) ||
78
- nameOrSlug.includes(item.slug) ||
79
- item.name?.toLowerCase().includes(nameOrSlug.toLowerCase())
80
- ))
81
- .slice(0, 5);
82
-
83
- if (similar.length > 0) {
84
- p.log.warn(`"${nameOrSlug}" not found.`);
85
- console.log();
86
- console.log(pc.gray(' Did you mean:'));
87
- for (const s of similar) {
88
- console.log(` ${pc.cyan(s.slug)} ${pc.gray(`(${s.type})`)}`);
89
- }
90
- console.log();
91
- } else {
92
- p.log.error(`"${nameOrSlug}" not found in any registry.`);
93
- p.log.info('Run ' + pc.cyan('astralkit search "' + nameOrSlug + '"') + ' to browse available content.');
94
- }
95
- return;
96
- }
97
-
98
- if (matches.length === 1) {
99
- // Exact match in one registry — install directly
100
- const match = matches[0];
101
- p.log.step(`Found ${pc.cyan(match.name)} as a ${pc.bold(match.type)}`);
102
-
103
- if (match.type === 'booster') return addBooster(nameOrSlug, options);
104
- if (match.type === 'workflow') return addWorkflow(nameOrSlug, options);
105
- return addComponent(nameOrSlug, options);
106
- }
107
-
108
- // Found in multiple registries — prompt user to choose
109
- const choice = await p.select({
110
- message: `"${nameOrSlug}" found in multiple registries. What would you like to install?`,
111
- options: matches.map(m => ({
112
- value: m.type,
113
- label: `${m.name} (${m.type === 'component' ? 'UI component' : m.type === 'booster' ? 'feature module' : 'app scaffold'})`,
114
- })),
115
- });
116
-
117
- if (p.isCancel(choice)) { p.cancel('Cancelled.'); process.exit(0); }
118
-
119
- if (choice === 'booster') return addBooster(nameOrSlug, options);
120
- if (choice === 'workflow') return addWorkflow(nameOrSlug, options);
121
- return addComponent(nameOrSlug, options);
122
-
123
- } catch (err) {
124
- spinner.stop();
125
- // If registry search fails, fall back to component (original behavior)
126
- return addComponent(nameOrSlug, options);
127
- }
128
- }
129
-
130
- function resolveFramework(options) {
131
- if (options.framework) {
132
- if (!validateFramework(options.framework)) process.exit(1);
133
- return options.framework;
134
- }
135
- const detected = detectFramework();
136
- if (detected === 'nextjs' || detected === 'react') return detected;
137
- return 'react';
138
- }
139
-
140
- function resolveExtension(framework) {
141
- const isTS = detectTypeScript();
142
- if (framework === 'nextjs') return '.tsx';
143
- return isTS ? '.tsx' : '.jsx';
144
- }
145
-
146
- async function addComponent(componentSlug, options) {
147
- if (!validateSlug(componentSlug)) process.exit(1);
148
- if (!fs.existsSync(path.join(process.cwd(), 'package.json'))) {
149
- p.log.warn('No package.json found. Run this inside a project directory.');
150
- return;
151
- }
152
-
153
- const ora = (await import('ora')).default;
154
- const framework = resolveFramework(options);
155
- const ext = resolveExtension(framework);
156
- const componentsDir = options.dir || 'src/components/ui';
157
- const targetFile = path.resolve(process.cwd(), componentsDir, `${componentSlug}${ext}`);
158
-
159
- if (fs.existsSync(targetFile) && !options.overwrite) {
160
- p.log.warn(`Already exists: ${componentsDir}/${componentSlug}${ext}`);
161
- console.log(pc.gray('Use --overwrite to replace.'));
162
- return;
163
- }
164
-
165
- const spinner = ora(`Fetching ${pc.cyan(componentSlug)} (${FRAMEWORK_LABELS[framework]})...`).start();
166
-
167
- try {
168
- const data = await getComponent(componentSlug, framework);
169
-
170
- if (!data.files?.length) {
171
- spinner.fail(`No ${framework} code available for "${componentSlug}".`);
172
- if (data.supported_frameworks?.length) {
173
- console.log(pc.gray(`Available: ${data.supported_frameworks.map(f => FRAMEWORK_LABELS[f] || f).join(', ')}`));
174
- }
175
- return;
176
- }
177
-
178
- if (options.dryRun) {
179
- spinner.stop();
180
- console.log(pc.bold('\nDry run — no files will be written:\n'));
181
- for (const file of data.files) {
182
- const exists = fs.existsSync(path.resolve(process.cwd(), componentsDir, file.path));
183
- console.log(` ${exists ? pc.yellow('overwrite') : pc.green('+ create')} ${componentsDir}/${file.path}`);
184
- }
185
- return;
186
- }
187
-
188
- const dir = path.resolve(process.cwd(), componentsDir);
189
- fs.mkdirSync(dir, { recursive: true });
190
-
191
- for (const file of data.files) {
192
- if (!isSafePath(dir, file.path)) {
193
- console.log(pc.red(` Skipping suspicious path: ${file.path}`));
194
- continue;
195
- }
196
- const filePath = path.resolve(dir, file.path);
197
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
198
- fs.writeFileSync(filePath, file.content);
199
- }
200
-
201
- spinner.succeed(`Added ${pc.cyan(data.name || componentSlug)} (${FRAMEWORK_LABELS[framework]})`);
202
- console.log(pc.gray(` ${componentsDir}/`));
203
- for (const file of data.files) console.log(pc.gray(` ${file.path}`));
204
-
205
- if (!isAstralkitInstalled()) {
206
- p.log.warn('Run ' + pc.cyan('astralkit init') + ' to set up design tokens.');
207
- }
208
-
209
- const cssEntry = findCssEntryFile();
210
- if (cssEntry) {
211
- const missing = getMissingCssImports(cssEntry.path);
212
- if (missing.length > 0) {
213
- p.log.warn(`Missing CSS imports in ${cssEntry.relative}. Run ${pc.cyan('astralkit init')} to fix.`);
214
- }
215
- }
216
-
217
- if (data.dependencies?.length) {
218
- const pm = detectPackageManager();
219
- const depList = data.dependencies.filter(d => d !== 'astralkit' && d !== 'clsx' && d !== 'tailwind-merge');
220
- if (depList.length > 0) {
221
- const s = ora(`Installing ${depList.join(', ')}...`).start();
222
- const result = await runInstall(pm, process.cwd(), depList);
223
- if (result.success) s.succeed(`Installed ${depList.join(', ')}`);
224
- else { s.fail(result.error); if (result.hint) console.log(pc.gray(` ${result.hint}`)); }
225
- }
226
- }
227
-
228
- } catch (err) {
229
- spinner.fail('Failed to add component.');
230
- handleAddError(err, componentSlug, framework);
231
- }
232
- }
233
-
234
- async function addBooster(slug, options) {
235
- if (!validateSlug(slug, 'booster name')) process.exit(1);
236
-
237
- const ora = (await import('ora')).default;
238
- const framework = resolveFramework(options);
239
- const pm = detectPackageManager();
240
- const spinner = ora(`Fetching booster ${pc.cyan(slug)} (${FRAMEWORK_LABELS[framework] || framework})...`).start();
241
-
242
- try {
243
- const data = await getBooster(slug, framework);
244
- const coreFiles = data.core_files || [];
245
- const adapterFiles = data.adapter_files || [];
246
-
247
- if (coreFiles.length === 0 && adapterFiles.length === 0) {
248
- spinner.fail(`No files available for booster "${slug}" (${framework}).`);
249
- return;
250
- }
251
-
252
- const corePath = options.dir || data.install_paths?.core || `src/lib/${slug}`;
253
- const adapterPath = data.install_paths?.adapter || `src/components/${slug}`;
254
- const coreDir = path.resolve(process.cwd(), corePath);
255
- const adapterDir = path.resolve(process.cwd(), adapterPath);
256
-
257
- if (options.dryRun) {
258
- spinner.stop();
259
- console.log(pc.bold('\nDry run — no files will be written:\n'));
260
- if (coreFiles.length > 0) {
261
- console.log(pc.gray(` Core: ${corePath}/`));
262
- for (const f of coreFiles) {
263
- const exists = fs.existsSync(path.resolve(coreDir, f.path));
264
- console.log(` ${exists ? pc.yellow('overwrite') : pc.green('+ create')} ${f.path}`);
265
- }
266
- }
267
- if (adapterFiles.length > 0) {
268
- console.log(pc.gray(` Adapter: ${adapterPath}/`));
269
- for (const f of adapterFiles) {
270
- const exists = fs.existsSync(path.resolve(adapterDir, f.path));
271
- console.log(` ${exists ? pc.yellow('overwrite') : pc.green('+ create')} ${f.path}`);
272
- }
273
- }
274
- return;
275
- }
276
-
277
- if (!options.overwrite) {
278
- const conflicts = [
279
- ...coreFiles.filter(f => fs.existsSync(path.resolve(coreDir, f.path))).map(f => `${corePath}/${f.path}`),
280
- ...adapterFiles.filter(f => fs.existsSync(path.resolve(adapterDir, f.path))).map(f => `${adapterPath}/${f.path}`),
281
- ];
282
- if (conflicts.length > 0) {
283
- spinner.stop();
284
- console.log(pc.yellow('\nThese files already exist:'));
285
- conflicts.forEach(c => console.log(pc.gray(` ${c}`)));
286
- const overwrite = await p.confirm({ message: 'Overwrite existing files?', initialValue: false });
287
- if (p.isCancel(overwrite) || !overwrite) return;
288
- }
289
- }
290
-
291
- writeFiles(coreDir, coreFiles);
292
- writeFiles(adapterDir, adapterFiles);
293
-
294
- spinner.succeed(`Added booster ${pc.cyan(data.name || slug)} (${FRAMEWORK_LABELS[framework] || framework})`);
295
-
296
- if (coreFiles.length > 0) {
297
- console.log(pc.gray(` Core: ${corePath}/`));
298
- coreFiles.forEach(f => console.log(pc.gray(` ${f.path}`)));
299
- }
300
- if (adapterFiles.length > 0) {
301
- console.log(pc.gray(` Adapter: ${adapterPath}/`));
302
- adapterFiles.forEach(f => console.log(pc.gray(` ${f.path}`)));
303
- }
304
-
305
- if (data.dependencies?.npm?.length) {
306
- console.log();
307
- const install = await p.confirm({
308
- message: `Install dependencies? (${data.dependencies.npm.join(', ')})`,
309
- initialValue: true,
310
- });
311
- if (!p.isCancel(install) && install) {
312
- const s = ora('Installing dependencies...').start();
313
- const result = await runInstall(pm, process.cwd(), data.dependencies.npm);
314
- if (result.success) s.succeed('Dependencies installed');
315
- else { s.fail(result.error); if (result.hint) console.log(pc.gray(` ${result.hint}`)); }
316
- }
317
- }
318
-
319
- if (data.dependencies?.env?.length) {
320
- console.log();
321
- p.log.warn('Add these to your .env:');
322
- data.dependencies.env.forEach(v => console.log(pc.gray(` ${v}=`)));
323
- }
324
-
325
- if (data.post_install) { console.log(); console.log(pc.gray(data.post_install)); }
326
-
327
- } catch (err) {
328
- spinner.fail('Failed to add booster.');
329
- handleAddError(err, slug, framework);
330
- }
331
- }
332
-
333
- async function addWorkflow(slug, options) {
334
- if (!validateSlug(slug, 'workflow name')) process.exit(1);
335
-
336
- const ora = (await import('ora')).default;
337
- const framework = resolveFramework(options);
338
- const spinner = ora(`Fetching workflow ${pc.cyan(slug)} (${FRAMEWORK_LABELS[framework] || framework})...`).start();
339
-
340
- try {
341
- const data = await getWorkflow(slug, framework);
342
-
343
- if (!data.files?.length) {
344
- spinner.fail(`No files available for workflow "${slug}" (${framework}).`);
345
- return;
346
- }
347
-
348
- let targetDir;
349
- if (options.overlay) {
350
- targetDir = path.resolve(process.cwd());
351
- } else {
352
- let dirName = options.dir || slug;
353
-
354
- if (fs.existsSync(path.resolve(process.cwd(), dirName)) && !options.overwrite) {
355
- spinner.stop();
356
- const action = await p.select({
357
- message: `Directory "${dirName}/" already exists.`,
358
- options: [
359
- { label: 'Overwrite it', value: 'overwrite' },
360
- { label: 'Use a different name', value: 'rename' },
361
- { label: 'Cancel', value: 'cancel' },
362
- ],
363
- });
364
- if (p.isCancel(action) || action === 'cancel') return;
365
- if (action === 'rename') {
366
- const newDir = await p.text({ message: 'Enter a directory name:', placeholder: `${slug}-app` });
367
- if (p.isCancel(newDir)) return;
368
- dirName = newDir;
369
- }
370
- }
371
- targetDir = path.resolve(process.cwd(), dirName);
372
- }
373
-
374
- if (options.overlay && !options.overwrite) {
375
- const conflicts = data.files.filter(f => fs.existsSync(path.resolve(targetDir, f.path))).map(f => f.path);
376
- if (conflicts.length > 0) {
377
- spinner.stop();
378
- console.log(pc.yellow(`${conflicts.length} file(s) would be overwritten:`));
379
- conflicts.slice(0, 10).forEach(c => console.log(pc.gray(` ${c}`)));
380
- if (conflicts.length > 10) console.log(pc.gray(` ... and ${conflicts.length - 10} more`));
381
- const overwrite = await p.confirm({ message: 'Overwrite these files?', initialValue: false });
382
- if (p.isCancel(overwrite) || !overwrite) return;
383
- }
384
- }
385
-
386
- if (options.dryRun) {
387
- spinner.stop();
388
- const label = options.overlay ? './' : `${path.basename(targetDir)}/`;
389
- console.log(pc.bold(`\nDry run — no files will be written to ${label}:\n`));
390
- data.files.forEach(f => {
391
- const exists = fs.existsSync(path.resolve(targetDir, f.path));
392
- console.log(` ${exists ? pc.yellow('overwrite') : pc.green('+ create')} ${f.path}`);
393
- });
394
- return;
395
- }
396
-
397
- const pm = detectPackageManager(options.overlay ? process.cwd() : targetDir);
398
- const fileCount = writeFiles(targetDir, data.files);
399
- const label = options.overlay ? './' : `${path.basename(targetDir)}/`;
400
-
401
- spinner.succeed(`Scaffolded workflow ${pc.cyan(data.name || slug)} in ${label}`);
402
- console.log(pc.gray(` ${fileCount} files written`));
403
-
404
- if (!options.overlay) {
405
- console.log();
406
- const install = await p.confirm({ message: `Install dependencies with ${pm}?`, initialValue: true });
407
- if (!p.isCancel(install) && install) {
408
- const s = ora(`Installing with ${pm}...`).start();
409
- const result = await runInstall(pm, targetDir);
410
- if (result.success) s.succeed('Dependencies installed');
411
- else { s.fail(result.error); if (result.hint) console.log(pc.gray(` ${result.hint}`)); }
412
- }
413
- }
414
-
415
- console.log();
416
- if (!options.overlay) console.log(pc.white(` cd ${path.basename(targetDir)}`));
417
- console.log(pc.white(` ${getRunCommand(pm, 'dev')}`));
418
-
419
- if (data.dependencies?.env?.length) {
420
- console.log();
421
- p.log.warn('Set up your environment variables:');
422
- data.dependencies.env.forEach(v => console.log(pc.gray(` ${v}=`)));
423
- }
424
-
425
- if (data.post_install) { console.log(); console.log(pc.gray(data.post_install)); }
426
-
427
- } catch (err) {
428
- spinner.fail('Failed to add workflow.');
429
- handleAddError(err, slug, framework);
430
- }
431
- }
432
-
433
- function handleAddError(err, slug, framework) {
434
- if (err.code === 'AUTH_REQUIRED') {
435
- p.log.warn(err.message);
436
- } else if (err.code === 'PRO_REQUIRED') {
437
- p.log.warn(`${FRAMEWORK_LABELS[framework] || framework} version requires a Pro subscription.`);
438
- console.log(pc.gray(' Upgrade at ') + pc.cyan('https://astralkit.com/pricing'));
439
- } else {
440
- try {
441
- const body = JSON.parse(err.message.replace(/^API error \d+: /, ''));
442
- if (body.supported_frameworks) {
443
- p.log.warn(`No ${framework} version available for "${slug}".`);
444
- console.log(pc.gray(`Available: ${body.supported_frameworks.map(f => FRAMEWORK_LABELS[f] || f).join(', ')}`));
445
- process.exit(1);
446
- }
447
- } catch { /* not json */ }
448
- console.error(pc.red(err.message));
449
- }
450
- process.exit(1);
451
- }
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import pc from 'picocolors';
4
+ import * as p from '@clack/prompts';
5
+ import { getComponent, getBooster, getWorkflow, listComponents, listBoosters, listWorkflows } from '../lib/api.js';
6
+ import {
7
+ detectFramework,
8
+ detectTypeScript,
9
+ isAstralkitInstalled,
10
+ findCssEntryFile,
11
+ getMissingCssImports,
12
+ } from '../lib/config.js';
13
+ import { validateSlug, validateFramework, isSafePath, writeFiles, isSafeInstallDir, filterSafePackages, sanitizeForTerminal } from '../lib/validators.js';
14
+ import { detectPackageManager, getRunCommand, runInstall } from '../lib/pkg-manager.js';
15
+ import { saveApiKey, getApiKey, getAuth } from '../lib/auth.js';
16
+
17
+ const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React' };
18
+
19
+ export async function addCommand(nameOrSlug, options) {
20
+ if (options.apiKey) {
21
+ if (!options.apiKey.startsWith('ak_')) {
22
+ console.log(pc.red('Invalid API key format. Keys start with ak_'));
23
+ process.exit(1);
24
+ }
25
+ saveApiKey(options.apiKey);
26
+ }
27
+
28
+ if (!getApiKey()) {
29
+ const auth = getAuth();
30
+ if (!auth.token) {
31
+ p.log.warn('No API key found. Run ' + pc.cyan('astralkit init --api-key <key>') + ' first.');
32
+ console.log(pc.gray('Get yours at ') + pc.cyan('https://astralkit.com/account'));
33
+ process.exit(1);
34
+ }
35
+ }
36
+
37
+ // If explicit type flag provided, skip smart detection
38
+ if (options.booster) return addBooster(nameOrSlug, options);
39
+ if (options.workflow) return addWorkflow(nameOrSlug, options);
40
+
41
+ // ─── Smart detection: search all registries for the slug ───
42
+ const ora = (await import('ora')).default;
43
+ const spinner = ora('Searching registries...').start();
44
+
45
+ try {
46
+ // Search all three registries in parallel
47
+ const [components, boosters, workflows] = await Promise.allSettled([
48
+ listComponents({ search: nameOrSlug }).catch(() => ({ data: [] })),
49
+ listBoosters({ search: nameOrSlug }).catch(() => ({ data: [] })),
50
+ listWorkflows({ search: nameOrSlug }).catch(() => ({ data: [] })),
51
+ ]);
52
+
53
+ const compMatch = (components.status === 'fulfilled' ? (components.value?.components || components.value?.data || []) : [])
54
+ ?.find(c => c.slug === nameOrSlug);
55
+ const boosterMatch = (boosters.status === 'fulfilled' ? (boosters.value?.boosters || boosters.value?.data || []) : [])
56
+ ?.find(b => b.slug === nameOrSlug);
57
+ const workflowMatch = (workflows.status === 'fulfilled' ? (workflows.value?.workflows || workflows.value?.data || []) : [])
58
+ ?.find(w => w.slug === nameOrSlug);
59
+
60
+ const matches = [];
61
+ if (compMatch) matches.push({ type: 'component', name: compMatch.name || nameOrSlug, slug: nameOrSlug });
62
+ if (boosterMatch) matches.push({ type: 'booster', name: boosterMatch.name || nameOrSlug, slug: nameOrSlug });
63
+ if (workflowMatch) matches.push({ type: 'workflow', name: workflowMatch.name || nameOrSlug, slug: nameOrSlug });
64
+
65
+ spinner.stop();
66
+
67
+ if (matches.length === 0) {
68
+ // No exact match — try fuzzy suggestions
69
+ const allItems = [
70
+ ...((components.status === 'fulfilled' ? (components.value?.components || components.value?.data || []) : []) || []).map(c => ({ ...c, type: 'component' })),
71
+ ...((boosters.status === 'fulfilled' ? (boosters.value?.boosters || boosters.value?.data || []) : []) || []).map(b => ({ ...b, type: 'booster' })),
72
+ ...((workflows.status === 'fulfilled' ? (workflows.value?.workflows || workflows.value?.data || []) : []) || []).map(w => ({ ...w, type: 'workflow' })),
73
+ ];
74
+
75
+ const similar = allItems
76
+ .filter(item => item.slug && (
77
+ item.slug.includes(nameOrSlug) ||
78
+ nameOrSlug.includes(item.slug) ||
79
+ item.name?.toLowerCase().includes(nameOrSlug.toLowerCase())
80
+ ))
81
+ .slice(0, 5);
82
+
83
+ if (similar.length > 0) {
84
+ p.log.warn(`"${nameOrSlug}" not found.`);
85
+ console.log();
86
+ console.log(pc.gray(' Did you mean:'));
87
+ for (const s of similar) {
88
+ console.log(` ${pc.cyan(s.slug)} ${pc.gray(`(${s.type})`)}`);
89
+ }
90
+ console.log();
91
+ } else {
92
+ p.log.error(`"${nameOrSlug}" not found in any registry.`);
93
+ p.log.info('Run ' + pc.cyan('astralkit search "' + nameOrSlug + '"') + ' to browse available content.');
94
+ }
95
+ return;
96
+ }
97
+
98
+ if (matches.length === 1) {
99
+ // Exact match in one registry — install directly
100
+ const match = matches[0];
101
+ p.log.step(`Found ${pc.cyan(match.name)} as a ${pc.bold(match.type)}`);
102
+
103
+ if (match.type === 'booster') return addBooster(nameOrSlug, options);
104
+ if (match.type === 'workflow') return addWorkflow(nameOrSlug, options);
105
+ return addComponent(nameOrSlug, options);
106
+ }
107
+
108
+ // Found in multiple registries — prompt user to choose
109
+ const choice = await p.select({
110
+ message: `"${nameOrSlug}" found in multiple registries. What would you like to install?`,
111
+ options: matches.map(m => ({
112
+ value: m.type,
113
+ label: `${m.name} (${m.type === 'component' ? 'UI component' : m.type === 'booster' ? 'feature module' : 'app scaffold'})`,
114
+ })),
115
+ });
116
+
117
+ if (p.isCancel(choice)) { p.cancel('Cancelled.'); process.exit(0); }
118
+
119
+ if (choice === 'booster') return addBooster(nameOrSlug, options);
120
+ if (choice === 'workflow') return addWorkflow(nameOrSlug, options);
121
+ return addComponent(nameOrSlug, options);
122
+
123
+ } catch (err) {
124
+ spinner.stop();
125
+ // If registry search fails, fall back to component (original behavior)
126
+ return addComponent(nameOrSlug, options);
127
+ }
128
+ }
129
+
130
+ function resolveFramework(options) {
131
+ if (options.framework) {
132
+ if (!validateFramework(options.framework)) process.exit(1);
133
+ return options.framework;
134
+ }
135
+ const detected = detectFramework();
136
+ if (detected === 'nextjs' || detected === 'react') return detected;
137
+ return 'react';
138
+ }
139
+
140
+ function resolveExtension(framework) {
141
+ const isTS = detectTypeScript();
142
+ if (framework === 'nextjs') return '.tsx';
143
+ return isTS ? '.tsx' : '.jsx';
144
+ }
145
+
146
+ async function addComponent(componentSlug, options) {
147
+ if (!validateSlug(componentSlug)) process.exit(1);
148
+ if (!fs.existsSync(path.join(process.cwd(), 'package.json'))) {
149
+ p.log.warn('No package.json found. Run this inside a project directory.');
150
+ return;
151
+ }
152
+
153
+ const ora = (await import('ora')).default;
154
+ const framework = resolveFramework(options);
155
+ const ext = resolveExtension(framework);
156
+ const componentsDir = options.dir || 'src/components/ui';
157
+ // Refuse absolute / traversal values of --dir.
158
+ if (!isSafeInstallDir(process.cwd(), componentsDir)) {
159
+ console.log(pc.red(`Refusing install: unsafe --dir value "${componentsDir}"`));
160
+ process.exit(1);
161
+ }
162
+ const targetFile = path.resolve(process.cwd(), componentsDir, `${componentSlug}${ext}`);
163
+
164
+ if (fs.existsSync(targetFile) && !options.overwrite) {
165
+ p.log.warn(`Already exists: ${componentsDir}/${componentSlug}${ext}`);
166
+ console.log(pc.gray('Use --overwrite to replace.'));
167
+ return;
168
+ }
169
+
170
+ const spinner = ora(`Fetching ${pc.cyan(componentSlug)} (${FRAMEWORK_LABELS[framework]})...`).start();
171
+
172
+ try {
173
+ const data = await getComponent(componentSlug, framework);
174
+
175
+ if (!data.files?.length) {
176
+ spinner.fail(`No ${framework} code available for "${componentSlug}".`);
177
+ if (data.supported_frameworks?.length) {
178
+ console.log(pc.gray(`Available: ${data.supported_frameworks.map(f => FRAMEWORK_LABELS[f] || f).join(', ')}`));
179
+ }
180
+ return;
181
+ }
182
+
183
+ if (options.dryRun) {
184
+ spinner.stop();
185
+ console.log(pc.bold('\nDry run — no files will be written:\n'));
186
+ for (const file of data.files) {
187
+ const exists = fs.existsSync(path.resolve(process.cwd(), componentsDir, file.path));
188
+ console.log(` ${exists ? pc.yellow('overwrite') : pc.green('+ create')} ${componentsDir}/${file.path}`);
189
+ }
190
+ return;
191
+ }
192
+
193
+ const dir = path.resolve(process.cwd(), componentsDir);
194
+ fs.mkdirSync(dir, { recursive: true });
195
+
196
+ // Filter out supplementary files that aren't needed for React/Next.js
197
+ // (styles.css and script.js are for HTML standalone components only)
198
+ const filesToWrite = framework === 'html'
199
+ ? data.files
200
+ : data.files.filter(f => f.path !== 'styles.css' && f.path !== 'script.js');
201
+
202
+ for (const file of filesToWrite) {
203
+ if (!isSafePath(dir, file.path)) {
204
+ console.log(pc.red(` Skipping suspicious path: ${file.path}`));
205
+ continue;
206
+ }
207
+ const filePath = path.resolve(dir, file.path);
208
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
209
+ fs.writeFileSync(filePath, file.content);
210
+ }
211
+
212
+ spinner.succeed(`Added ${pc.cyan(data.name || componentSlug)} (${FRAMEWORK_LABELS[framework]})`);
213
+ console.log(pc.gray(` ${componentsDir}/`));
214
+ for (const file of filesToWrite) console.log(pc.gray(` ${file.path}`));
215
+
216
+ if (!isAstralkitInstalled()) {
217
+ p.log.warn('Run ' + pc.cyan('astralkit init') + ' to set up design tokens.');
218
+ }
219
+
220
+ const cssEntry = findCssEntryFile();
221
+ if (cssEntry) {
222
+ const missing = getMissingCssImports(cssEntry.path);
223
+ if (missing.length > 0) {
224
+ p.log.warn(`Missing CSS imports in ${cssEntry.relative}. Run ${pc.cyan('astralkit init')} to fix.`);
225
+ }
226
+ }
227
+
228
+ // Detect if component uses Phosphor Icons (CSS class-based icons)
229
+ const componentCode = data.files?.map(f => f.content).join('') || '';
230
+ const usesPhosphorCss = componentCode.includes('class="ph ') || componentCode.includes("class='ph ") || componentCode.includes('"ph ph-') || componentCode.includes("'ph ph-");
231
+
232
+ if (data.dependencies?.length || usesPhosphorCss) {
233
+ const pm = detectPackageManager();
234
+ const rawDepList = (data.dependencies || []).filter(d => d !== 'astralkit' && d !== 'clsx' && d !== 'tailwind-merge');
235
+
236
+ // Auto-add @phosphor-icons/web if component uses CSS-based Phosphor icons
237
+ if (usesPhosphorCss && !rawDepList.includes('@phosphor-icons/web')) {
238
+ rawDepList.push('@phosphor-icons/web');
239
+ }
240
+
241
+ // SECURITY: validate package names before passing to npm install — a
242
+ // malicious server response could inject "-S", "--registry=evil.com",
243
+ // "git+ssh://...", or a tarball URL. We only accept bare npm names.
244
+ const { accepted: depList, rejected } = filterSafePackages(rawDepList);
245
+ if (rejected.length > 0) {
246
+ console.log(pc.yellow(` Skipping invalid package names: ${rejected.map(sanitizeForTerminal).join(', ')}`));
247
+ }
248
+
249
+ if (depList.length > 0) {
250
+ // Always ask before running npm install — mirrors the booster flow.
251
+ const install = await p.confirm({
252
+ message: `Install dependencies? (${depList.join(', ')})`,
253
+ initialValue: true,
254
+ });
255
+ if (!p.isCancel(install) && install) {
256
+ const s = ora(`Installing ${depList.join(', ')}...`).start();
257
+ const result = await runInstall(pm, process.cwd(), depList);
258
+ if (result.success) s.succeed(`Installed ${depList.join(', ')}`);
259
+ else { s.fail(sanitizeForTerminal(result.error || 'Install failed')); if (result.hint) console.log(pc.gray(` ${sanitizeForTerminal(result.hint)}`)); }
260
+ }
261
+ }
262
+
263
+ // Auto-add JS imports for icon/font packages in layout file
264
+ // (CSS @import doesn't resolve node_modules exports in Next.js PostCSS)
265
+ const JS_DEPENDENCY_IMPORTS = {
266
+ '@phosphor-icons/web': [
267
+ "import '@phosphor-icons/web/regular'",
268
+ "import '@phosphor-icons/web/fill'",
269
+ ],
270
+ };
271
+
272
+ for (const [pkg, imports] of Object.entries(JS_DEPENDENCY_IMPORTS)) {
273
+ if (!depList.includes(pkg)) continue;
274
+
275
+ // Find the layout file
276
+ const layoutCandidates = [
277
+ 'src/app/layout.tsx', 'src/app/layout.jsx', 'src/app/layout.js',
278
+ 'app/layout.tsx', 'app/layout.jsx', 'app/layout.js',
279
+ 'src/pages/_app.tsx', 'src/pages/_app.jsx', 'src/pages/_app.js',
280
+ 'pages/_app.tsx', 'pages/_app.jsx', 'pages/_app.js',
281
+ ];
282
+ let layoutFile = null;
283
+ for (const candidate of layoutCandidates) {
284
+ const fullPath = path.join(process.cwd(), candidate);
285
+ if (fs.existsSync(fullPath)) {
286
+ layoutFile = { path: fullPath, relative: candidate };
287
+ break;
288
+ }
289
+ }
290
+ if (!layoutFile) continue;
291
+
292
+ const layoutContent = fs.readFileSync(layoutFile.path, 'utf8');
293
+ const missing = imports.filter(imp => !layoutContent.includes(imp));
294
+ if (missing.length > 0) {
295
+ // Add after the first import line
296
+ const lines = layoutContent.split('\n');
297
+ let lastImportIdx = -1;
298
+ for (let i = 0; i < lines.length; i++) {
299
+ if (lines[i].trim().startsWith('import ')) lastImportIdx = i;
300
+ }
301
+ if (lastImportIdx >= 0) {
302
+ lines.splice(lastImportIdx + 1, 0, ...missing);
303
+ } else {
304
+ lines.unshift(...missing);
305
+ }
306
+ fs.writeFileSync(layoutFile.path, lines.join('\n'));
307
+ p.log.success(`Added ${pc.cyan(pkg)} imports to ${pc.cyan(layoutFile.relative)}`);
308
+ }
309
+ }
310
+ }
311
+
312
+ } catch (err) {
313
+ spinner.fail('Failed to add component.');
314
+ handleAddError(err, componentSlug, framework);
315
+ }
316
+ }
317
+
318
+ async function addBooster(slug, options) {
319
+ if (!validateSlug(slug, 'booster name')) process.exit(1);
320
+
321
+ const ora = (await import('ora')).default;
322
+ const framework = resolveFramework(options);
323
+ const pm = detectPackageManager();
324
+ const spinner = ora(`Fetching booster ${pc.cyan(slug)} (${FRAMEWORK_LABELS[framework] || framework})...`).start();
325
+
326
+ try {
327
+ const data = await getBooster(slug, framework);
328
+ const coreFiles = data.core_files || [];
329
+ const adapterFiles = data.adapter_files || [];
330
+
331
+ if (coreFiles.length === 0 && adapterFiles.length === 0) {
332
+ spinner.fail(`No files available for booster "${slug}" (${framework}).`);
333
+ return;
334
+ }
335
+
336
+ // SECURITY: Server-supplied install_paths must stay inside cwd. Otherwise
337
+ // a compromised API could write to /etc, ~/.ssh, %APPDATA%, etc.
338
+ // options.dir comes from the user's own CLI invocation, so it's trusted.
339
+ const serverCore = data.install_paths?.core;
340
+ const serverAdapter = data.install_paths?.adapter;
341
+ if (serverCore && !isSafeInstallDir(process.cwd(), serverCore)) {
342
+ spinner.fail(pc.red(`Refusing install: server returned unsafe core path "${serverCore}"`));
343
+ return;
344
+ }
345
+ if (serverAdapter && !isSafeInstallDir(process.cwd(), serverAdapter)) {
346
+ spinner.fail(pc.red(`Refusing install: server returned unsafe adapter path "${serverAdapter}"`));
347
+ return;
348
+ }
349
+ const corePath = options.dir || serverCore || `src/lib/${slug}`;
350
+ const adapterPath = serverAdapter || `src/components/${slug}`;
351
+ // Final defense: even if options.dir came from the user, reject absolute/traversal
352
+ // values so --dir "/" or --dir "../.." can't be weaponized.
353
+ if (!isSafeInstallDir(process.cwd(), corePath) || !isSafeInstallDir(process.cwd(), adapterPath)) {
354
+ spinner.fail(pc.red(`Refusing install: unsafe install path`));
355
+ return;
356
+ }
357
+ const coreDir = path.resolve(process.cwd(), corePath);
358
+ const adapterDir = path.resolve(process.cwd(), adapterPath);
359
+
360
+ if (options.dryRun) {
361
+ spinner.stop();
362
+ console.log(pc.bold('\nDry run — no files will be written:\n'));
363
+ if (coreFiles.length > 0) {
364
+ console.log(pc.gray(` Core: ${corePath}/`));
365
+ for (const f of coreFiles) {
366
+ const exists = fs.existsSync(path.resolve(coreDir, f.path));
367
+ console.log(` ${exists ? pc.yellow('overwrite') : pc.green('+ create')} ${f.path}`);
368
+ }
369
+ }
370
+ if (adapterFiles.length > 0) {
371
+ console.log(pc.gray(` Adapter: ${adapterPath}/`));
372
+ for (const f of adapterFiles) {
373
+ const exists = fs.existsSync(path.resolve(adapterDir, f.path));
374
+ console.log(` ${exists ? pc.yellow('overwrite') : pc.green('+ create')} ${f.path}`);
375
+ }
376
+ }
377
+ return;
378
+ }
379
+
380
+ if (!options.overwrite) {
381
+ const conflicts = [
382
+ ...coreFiles.filter(f => fs.existsSync(path.resolve(coreDir, f.path))).map(f => `${corePath}/${f.path}`),
383
+ ...adapterFiles.filter(f => fs.existsSync(path.resolve(adapterDir, f.path))).map(f => `${adapterPath}/${f.path}`),
384
+ ];
385
+ if (conflicts.length > 0) {
386
+ spinner.stop();
387
+ console.log(pc.yellow('\nThese files already exist:'));
388
+ conflicts.forEach(c => console.log(pc.gray(` ${c}`)));
389
+ const overwrite = await p.confirm({ message: 'Overwrite existing files?', initialValue: false });
390
+ if (p.isCancel(overwrite) || !overwrite) return;
391
+ }
392
+ }
393
+
394
+ writeFiles(coreDir, coreFiles);
395
+ writeFiles(adapterDir, adapterFiles);
396
+
397
+ spinner.succeed(`Added booster ${pc.cyan(data.name || slug)} (${FRAMEWORK_LABELS[framework] || framework})`);
398
+
399
+ if (coreFiles.length > 0) {
400
+ console.log(pc.gray(` Core: ${corePath}/`));
401
+ coreFiles.forEach(f => console.log(pc.gray(` ${f.path}`)));
402
+ }
403
+ if (adapterFiles.length > 0) {
404
+ console.log(pc.gray(` Adapter: ${adapterPath}/`));
405
+ adapterFiles.forEach(f => console.log(pc.gray(` ${f.path}`)));
406
+ }
407
+
408
+ if (data.dependencies?.npm?.length) {
409
+ // SECURITY: filter out anything that isn't a bare npm package name.
410
+ const { accepted: safeDeps, rejected } = filterSafePackages(data.dependencies.npm);
411
+ if (rejected.length > 0) {
412
+ console.log(pc.yellow(` Skipping invalid package names: ${rejected.map(sanitizeForTerminal).join(', ')}`));
413
+ }
414
+ if (safeDeps.length > 0) {
415
+ console.log();
416
+ const install = await p.confirm({
417
+ message: `Install dependencies? (${safeDeps.join(', ')})`,
418
+ initialValue: true,
419
+ });
420
+ if (!p.isCancel(install) && install) {
421
+ const s = ora('Installing dependencies...').start();
422
+ const result = await runInstall(pm, process.cwd(), safeDeps);
423
+ if (result.success) s.succeed('Dependencies installed');
424
+ else { s.fail(sanitizeForTerminal(result.error || 'Install failed')); if (result.hint) console.log(pc.gray(` ${sanitizeForTerminal(result.hint)}`)); }
425
+ }
426
+ }
427
+ }
428
+
429
+ if (data.dependencies?.env?.length) {
430
+ console.log();
431
+ p.log.warn('Add these to your .env:');
432
+ data.dependencies.env.forEach(v => console.log(pc.gray(` ${v}=`)));
433
+ }
434
+
435
+ if (data.post_install) { console.log(); console.log(pc.gray(data.post_install)); }
436
+
437
+ } catch (err) {
438
+ spinner.fail('Failed to add booster.');
439
+ handleAddError(err, slug, framework);
440
+ }
441
+ }
442
+
443
+ async function addWorkflow(slug, options) {
444
+ if (!validateSlug(slug, 'workflow name')) process.exit(1);
445
+
446
+ const ora = (await import('ora')).default;
447
+ const framework = resolveFramework(options);
448
+ const spinner = ora(`Fetching workflow ${pc.cyan(slug)} (${FRAMEWORK_LABELS[framework] || framework})...`).start();
449
+
450
+ try {
451
+ const data = await getWorkflow(slug, framework);
452
+
453
+ if (!data.files?.length) {
454
+ spinner.fail(`No files available for workflow "${slug}" (${framework}).`);
455
+ return;
456
+ }
457
+
458
+ let targetDir;
459
+ if (options.overlay) {
460
+ targetDir = path.resolve(process.cwd());
461
+ } else {
462
+ let dirName = options.dir || slug;
463
+ if (!isSafeInstallDir(process.cwd(), dirName)) {
464
+ spinner.fail(pc.red(`Refusing install: unsafe --dir value`));
465
+ return;
466
+ }
467
+
468
+ if (fs.existsSync(path.resolve(process.cwd(), dirName)) && !options.overwrite) {
469
+ spinner.stop();
470
+ const action = await p.select({
471
+ message: `Directory "${dirName}/" already exists.`,
472
+ options: [
473
+ { label: 'Overwrite it', value: 'overwrite' },
474
+ { label: 'Use a different name', value: 'rename' },
475
+ { label: 'Cancel', value: 'cancel' },
476
+ ],
477
+ });
478
+ if (p.isCancel(action) || action === 'cancel') return;
479
+ if (action === 'rename') {
480
+ const newDir = await p.text({ message: 'Enter a directory name:', placeholder: `${slug}-app` });
481
+ if (p.isCancel(newDir)) return;
482
+ dirName = newDir;
483
+ }
484
+ }
485
+ targetDir = path.resolve(process.cwd(), dirName);
486
+ }
487
+
488
+ if (options.overlay && !options.overwrite) {
489
+ const conflicts = data.files.filter(f => fs.existsSync(path.resolve(targetDir, f.path))).map(f => f.path);
490
+ if (conflicts.length > 0) {
491
+ spinner.stop();
492
+ console.log(pc.yellow(`${conflicts.length} file(s) would be overwritten:`));
493
+ conflicts.slice(0, 10).forEach(c => console.log(pc.gray(` ${c}`)));
494
+ if (conflicts.length > 10) console.log(pc.gray(` ... and ${conflicts.length - 10} more`));
495
+ const overwrite = await p.confirm({ message: 'Overwrite these files?', initialValue: false });
496
+ if (p.isCancel(overwrite) || !overwrite) return;
497
+ }
498
+ }
499
+
500
+ if (options.dryRun) {
501
+ spinner.stop();
502
+ const label = options.overlay ? './' : `${path.basename(targetDir)}/`;
503
+ console.log(pc.bold(`\nDry run — no files will be written to ${label}:\n`));
504
+ data.files.forEach(f => {
505
+ const exists = fs.existsSync(path.resolve(targetDir, f.path));
506
+ console.log(` ${exists ? pc.yellow('overwrite') : pc.green('+ create')} ${f.path}`);
507
+ });
508
+ return;
509
+ }
510
+
511
+ const pm = detectPackageManager(options.overlay ? process.cwd() : targetDir);
512
+ const fileCount = writeFiles(targetDir, data.files);
513
+ const label = options.overlay ? './' : `${path.basename(targetDir)}/`;
514
+
515
+ spinner.succeed(`Scaffolded workflow ${pc.cyan(data.name || slug)} in ${label}`);
516
+ console.log(pc.gray(` ${fileCount} files written`));
517
+
518
+ if (!options.overlay) {
519
+ console.log();
520
+ const install = await p.confirm({ message: `Install dependencies with ${pm}?`, initialValue: true });
521
+ if (!p.isCancel(install) && install) {
522
+ const s = ora(`Installing with ${pm}...`).start();
523
+ const result = await runInstall(pm, targetDir);
524
+ if (result.success) s.succeed('Dependencies installed');
525
+ else { s.fail(result.error); if (result.hint) console.log(pc.gray(` ${result.hint}`)); }
526
+ }
527
+ }
528
+
529
+ console.log();
530
+ if (!options.overlay) console.log(pc.white(` cd ${path.basename(targetDir)}`));
531
+ console.log(pc.white(` ${getRunCommand(pm, 'dev')}`));
532
+
533
+ if (data.dependencies?.env?.length) {
534
+ console.log();
535
+ p.log.warn('Set up your environment variables:');
536
+ data.dependencies.env.forEach(v => console.log(pc.gray(` ${v}=`)));
537
+ }
538
+
539
+ if (data.post_install) { console.log(); console.log(pc.gray(data.post_install)); }
540
+
541
+ } catch (err) {
542
+ spinner.fail('Failed to add workflow.');
543
+ handleAddError(err, slug, framework);
544
+ }
545
+ }
546
+
547
+ function handleAddError(err, slug, framework) {
548
+ if (err.code === 'AUTH_REQUIRED') {
549
+ p.log.warn(err.message);
550
+ } else if (err.code === 'PRO_REQUIRED') {
551
+ p.log.warn(`${FRAMEWORK_LABELS[framework] || framework} version requires a Pro subscription.`);
552
+ console.log(pc.gray(' Upgrade at ') + pc.cyan('https://astralkit.com/pricing'));
553
+ } else {
554
+ try {
555
+ const body = JSON.parse(err.message.replace(/^API error \d+: /, ''));
556
+ if (body.supported_frameworks) {
557
+ p.log.warn(`No ${framework} version available for "${slug}".`);
558
+ console.log(pc.gray(`Available: ${body.supported_frameworks.map(f => FRAMEWORK_LABELS[f] || f).join(', ')}`));
559
+ process.exit(1);
560
+ }
561
+ } catch { /* not json */ }
562
+ console.error(pc.red(err.message));
563
+ }
564
+ process.exit(1);
565
+ }