@astralkit/cli 4.6.3 → 4.7.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,13 @@ All notable changes to the `@astralkit/cli` package.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [4.7.0] (2026-11-30)
9
+
10
+ ### Added
11
+ - **Several at once:** `astralkit add zest-navigation zest-hero zest-faq` installs each name in turn. One that fails does not stop the rest: the end of the run lists what was installed and what was not, and the exit code is 1 if any was not. Before, only the first name was installed and the others were dropped without a word.
12
+ - **A component's stylesheets are added for you.** A website template section keeps its palette and typefaces in the SDK (`astralkit/palettes`, `astralkit/template-fonts`), and a section with a date field or a map asks for `astralkit/datepicker.css` or `astralkit/maps.css`. `add`, `update` and `init` now put the imports a component names into your stylesheet, after the AstralKit theme, once. Before, the file was written and the line was left for you to read: the section drew without its colours or its typefaces.
13
+ - An import the installed `astralkit` cannot resolve is never written (it would break your build). The CLI offers to update `astralkit` once per run (accepted without a prompt in an agent or CI shell) and names anything it could not add.
14
+
8
15
  ## [4.6.3] (2026-11-24)
9
16
 
10
17
  ### Fixed
package/bin/index.js CHANGED
@@ -40,8 +40,8 @@ program
40
40
 
41
41
  // ─── add ─────────────────────────────────────────────
42
42
  program
43
- .command('add <name>')
44
- .description('Add a component, booster, or workflow to your project')
43
+ .command('add <names...>')
44
+ .description('Add one or more components, boosters, or workflows to your project')
45
45
  .option('--api-key <key>', 'Your API key')
46
46
  .option('-f, --framework <framework>', 'Framework version (html, react, nextjs)')
47
47
  .option('--dir <directory>', 'Override output directory')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astralkit/cli",
3
- "version": "4.6.3",
3
+ "version": "4.7.0",
4
4
  "description": "AstralKit CLI — Install and manage UI components in your project",
5
5
  "type": "module",
6
6
  "bin": {
@@ -14,16 +14,59 @@ import { validateSlug, validateFramework, isSafePath, writeFiles, isSafeInstallD
14
14
  import { detectPackageManager, getRunCommand, runInstall } from '../lib/pkg-manager.js';
15
15
  import { saveApiKey, getApiKey, getAuth } from '../lib/auth.js';
16
16
  import { applyMerges } from '../lib/merges.js';
17
+ import { ensureComponentStylesheets } from '../lib/stylesheets.js';
17
18
  import { setAssumeYes, confirm as askConfirm, select as askSelect, text as askText } from '../lib/ask.js';
18
19
 
19
20
  const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React' };
20
21
 
21
- export async function addCommand(nameOrSlug, options) {
22
+ // `astralkit add a b c` installs each name in turn. One name failing must not stop the rest, so inside a
23
+ // batch an exit becomes a throw that the loop catches; a single name exits as it always did.
24
+ class ExitSignal extends Error {
25
+ constructor(code) { super('exit'); this.code = code; }
26
+ }
27
+ let inBatch = false;
28
+ function exit(code) {
29
+ if (inBatch) throw new ExitSignal(code);
30
+ process.exit(code);
31
+ }
32
+
33
+ export async function addCommand(names, options) {
34
+ const list = [...new Set([].concat(names).filter(Boolean))];
35
+ if (list.length <= 1) return addOne(list[0], options);
36
+
37
+ const installed = [];
38
+ const notInstalled = [];
39
+ inBatch = true;
40
+ try {
41
+ for (const [index, name] of list.entries()) {
42
+ console.log();
43
+ p.log.step(`${pc.cyan(name)} (${index + 1} of ${list.length})`);
44
+ let done = false;
45
+ try {
46
+ done = (await addOne(name, options)) === true;
47
+ } catch (err) {
48
+ if (!(err instanceof ExitSignal)) throw err;
49
+ }
50
+ (done ? installed : notInstalled).push(name);
51
+ }
52
+ } finally {
53
+ inBatch = false;
54
+ }
55
+
56
+ console.log();
57
+ if (installed.length) p.log.success(`Installed ${installed.length} of ${list.length}: ${installed.join(', ')}`);
58
+ if (notInstalled.length) {
59
+ p.log.warn(`Not installed: ${notInstalled.join(', ')} (the reason for each is printed above)`);
60
+ process.exit(1);
61
+ }
62
+ }
63
+
64
+ async function addOne(nameOrSlug, options) {
22
65
  setAssumeYes(options.yes);
23
66
  if (options.apiKey) {
24
67
  if (!options.apiKey.startsWith('ak_')) {
25
68
  console.log(pc.red('Invalid API key format. Keys start with ak_'));
26
- process.exit(1);
69
+ exit(1);
27
70
  }
28
71
  saveApiKey(options.apiKey);
29
72
  }
@@ -36,7 +79,7 @@ export async function addCommand(nameOrSlug, options) {
36
79
  if (!auth.token) {
37
80
  p.log.warn('No API key found. Run ' + pc.cyan('astralkit init --api-key <key>') + ' first.');
38
81
  console.log(pc.gray('Get yours at ') + pc.cyan('https://astralkit.com/account'));
39
- process.exit(1);
82
+ exit(1);
40
83
  }
41
84
  }
42
85
 
@@ -123,7 +166,7 @@ export async function addCommand(nameOrSlug, options) {
123
166
  nonInteractive: componentMatch ? 'component' : matches[0].type,
124
167
  });
125
168
 
126
- if (p.isCancel(choice)) { p.cancel('Cancelled.'); process.exit(0); }
169
+ if (p.isCancel(choice)) { p.cancel('Cancelled.'); exit(0); }
127
170
 
128
171
  if (choice === 'booster') return addBooster(nameOrSlug, options);
129
172
  if (choice === 'workflow') return addWorkflow(nameOrSlug, options);
@@ -138,7 +181,7 @@ export async function addCommand(nameOrSlug, options) {
138
181
 
139
182
  function resolveFramework(options) {
140
183
  if (options.framework) {
141
- if (!validateFramework(options.framework)) process.exit(1);
184
+ if (!validateFramework(options.framework)) exit(1);
142
185
  return options.framework;
143
186
  }
144
187
  const detected = detectFramework();
@@ -174,7 +217,7 @@ function hostHasDep(pkg, name) {
174
217
  }
175
218
 
176
219
  async function addComponent(componentSlug, options) {
177
- if (!validateSlug(componentSlug)) process.exit(1);
220
+ if (!validateSlug(componentSlug)) exit(1);
178
221
  if (!fs.existsSync(path.join(process.cwd(), 'package.json'))) {
179
222
  p.log.warn('No package.json found. Run this inside a project directory.');
180
223
  return;
@@ -198,7 +241,7 @@ async function addComponent(componentSlug, options) {
198
241
  // Refuse absolute / traversal values of --dir.
199
242
  if (!isSafeInstallDir(process.cwd(), componentsDir)) {
200
243
  console.log(pc.red(`Refusing install: unsafe --dir value "${componentsDir}"`));
201
- process.exit(1);
244
+ exit(1);
202
245
  }
203
246
  const targetFile = path.resolve(process.cwd(), componentsDir, `${componentSlug}${ext}`);
204
247
 
@@ -268,6 +311,10 @@ async function addComponent(componentSlug, options) {
268
311
 
269
312
  // Detect if component uses Phosphor Icons (CSS class-based icons)
270
313
  const componentCode = data.files?.map(f => f.content).join('') || '';
314
+
315
+ // The stylesheets the component asks for (a template section's palette and typefaces, a date picker's dialog)
316
+ // go into the project's stylesheet. An HTML file loads its own from the CDN.
317
+ if (framework !== 'html') await ensureComponentStylesheets(filesToWrite.map(f => f.content).join('\n'), installSummary);
271
318
  let usesPhosphorCss = componentCode.includes('class="ph ') || componentCode.includes("class='ph ") || componentCode.includes('"ph ph-') || componentCode.includes("'ph ph-");
272
319
 
273
320
  // Phosphor conflict guard: @phosphor-icons/web and @phosphor-icons/react
@@ -462,6 +509,7 @@ async function addComponent(componentSlug, options) {
462
509
  }
463
510
 
464
511
  printInstallSummary(installSummary);
512
+ return true;
465
513
 
466
514
  } catch (err) {
467
515
  spinner.fail('Failed to add component.');
@@ -503,7 +551,7 @@ function printInstallSummary(s) {
503
551
  }
504
552
 
505
553
  async function addBooster(slug, options) {
506
- if (!validateSlug(slug, 'booster name')) process.exit(1);
554
+ if (!validateSlug(slug, 'booster name')) exit(1);
507
555
 
508
556
  const ora = (await import('ora')).default;
509
557
  const framework = resolveFramework(options);
@@ -652,6 +700,7 @@ async function addBooster(slug, options) {
652
700
  }
653
701
 
654
702
  if (data.post_install) { console.log(); console.log(pc.gray(data.post_install)); }
703
+ return true;
655
704
 
656
705
  } catch (err) {
657
706
  spinner.fail('Failed to add booster.');
@@ -660,7 +709,7 @@ async function addBooster(slug, options) {
660
709
  }
661
710
 
662
711
  async function addWorkflow(slug, options) {
663
- if (!validateSlug(slug, 'workflow name')) process.exit(1);
712
+ if (!validateSlug(slug, 'workflow name')) exit(1);
664
713
 
665
714
  const ora = (await import('ora')).default;
666
715
  const framework = resolveFramework(options);
@@ -761,6 +810,7 @@ async function addWorkflow(slug, options) {
761
810
  }
762
811
 
763
812
  if (data.post_install) { console.log(); console.log(pc.gray(data.post_install)); }
813
+ return true;
764
814
 
765
815
  } catch (err) {
766
816
  spinner.fail('Failed to add workflow.');
@@ -780,10 +830,10 @@ function handleAddError(err, slug, framework) {
780
830
  if (body.supported_frameworks) {
781
831
  p.log.warn(`No ${framework} version available for "${slug}".`);
782
832
  console.log(pc.gray(`Available: ${body.supported_frameworks.map(f => FRAMEWORK_LABELS[f] || f).join(', ')}`));
783
- process.exit(1);
833
+ exit(1);
784
834
  }
785
835
  } catch { /* not json */ }
786
836
  console.error(pc.red(err.message));
787
837
  }
788
- process.exit(1);
838
+ exit(1);
789
839
  }
@@ -13,6 +13,7 @@ import {
13
13
  getRequiredCssImports,
14
14
  } from '../lib/config.js';
15
15
  import { getAiRulesContent } from '../lib/ai-rules.js';
16
+ import { collectDeclaredCssImports, ensureComponentStylesheets } from '../lib/stylesheets.js';
16
17
  import { saveApiKey, getApiKey } from '../lib/auth.js';
17
18
  import { detectPackageManager, runInstall } from '../lib/pkg-manager.js';
18
19
  import { getStarterKit } from '../lib/api.js';
@@ -135,6 +136,11 @@ export async function initCommand(options) {
135
136
  p.log.success(`Created ${pc.cyan(defaultCssRelative)}`);
136
137
  }
137
138
 
139
+ // Components already in the project can ask for stylesheets of their own (a template section's palette and
140
+ // typefaces): `astralkit add` leaves them for this step when the SDK was not installed yet.
141
+ const declared = collectDeclaredCssImports();
142
+ if (declared.length) await ensureComponentStylesheets(declared.map(specifier => `@import "${specifier}";`).join('\n'));
143
+
138
144
  // ─── Step 4b: Tailwind v3 plugin registration ─────────
139
145
  //
140
146
  // In v3, the @theme directive doesn't exist, so ak-* utility classes
@@ -6,6 +6,7 @@ import { getComponent } from '../lib/api.js';
6
6
  import { getProjectConfig, detectFramework } from '../lib/config.js';
7
7
  import { isSafePath } from '../lib/validators.js';
8
8
  import { confirm as askConfirm } from '../lib/ask.js';
9
+ import { ensureComponentStylesheets } from '../lib/stylesheets.js';
9
10
 
10
11
  export async function updateCommand(componentSlug, options) {
11
12
  const ora = (await import('ora')).default;
@@ -80,6 +81,10 @@ export async function updateCommand(componentSlug, options) {
80
81
  fs.writeFileSync(filePath, file.content);
81
82
  }
82
83
 
84
+ // A newer version of a component can ask for stylesheets the older one carried in its own file
85
+ // (a template section's palette and typefaces): they go into the project's stylesheet.
86
+ if (framework !== 'html') await ensureComponentStylesheets([...toCreate, ...toUpdate].map(f => f.content).join('\n'));
87
+
83
88
  p.outro(pc.green(`✅ ${data.name || componentSlug} updated`));
84
89
 
85
90
  } catch (err) {
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Stylesheets a component asks for
3
+ * ────────────────────────────────
4
+ * A template section carries no stylesheet of its own: its palette is
5
+ * `astralkit/palettes` and its typefaces `astralkit/template-fonts`. A section
6
+ * with a date field asks for `astralkit/datepicker.css`, one with a map for
7
+ * `astralkit/maps.css`. The file says so in its header:
8
+ *
9
+ * Add once to your stylesheet, after the AstralKit theme:
10
+ * @import "astralkit/palettes"; @import "astralkit/template-fonts";
11
+ *
12
+ * Until 2026-11-30 the CLI wrote the file and left that line for the reader.
13
+ * A section installed that way draws without its palette or its typefaces
14
+ * (Zest's orange hero came out near-black, in a fallback face). Here the CLI
15
+ * reads the imports the file names and puts them in the project's stylesheet.
16
+ *
17
+ * The theme and utilities are the project's base setup (`astralkit init`),
18
+ * not these.
19
+ */
20
+
21
+ import fs from 'fs';
22
+ import path from 'path';
23
+ import pc from 'picocolors';
24
+ import * as p from '@clack/prompts';
25
+ import { findCssEntryFile, isAstralkitInstalled } from './config.js';
26
+ import { detectPackageManager, runInstall } from './pkg-manager.js';
27
+ import { confirm as askConfirm } from './ask.js';
28
+
29
+ const BASE = new Set(['astralkit/theme', 'astralkit/theme-v4', 'astralkit/utilities']);
30
+ /** Whether this run already tried to update astralkit. */
31
+ let updateTried = false;
32
+ const importLine = specifier => `@import "${specifier}";`;
33
+ const importPattern = specifier => new RegExp(`@import\\s+["']${specifier.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')}["']`);
34
+
35
+ /** The stylesheet imports a component's code names (`astralkit/palettes`), in the order it names them. */
36
+ export function getDeclaredCssImports(code) {
37
+ const found = new Set();
38
+ for (const match of String(code || '').matchAll(/@import\s+["'](astralkit\/[a-z0-9][a-z0-9./-]*)["']/g)) {
39
+ if (!BASE.has(match[1])) found.add(match[1]);
40
+ }
41
+ return [...found];
42
+ }
43
+
44
+ /** Of the imports asked for, the ones the stylesheet does not have yet. */
45
+ export function getMissingDeclaredImports(cssFilePath, specifiers) {
46
+ let content = '';
47
+ try { content = fs.readFileSync(cssFilePath, 'utf8'); } catch { /* no file: all are missing */ }
48
+ return specifiers.filter(specifier => !importPattern(specifier).test(content));
49
+ }
50
+
51
+ /**
52
+ * Whether the installed astralkit has the export a specifier names
53
+ * ("astralkit/template-fonts" is "./template-fonts"). null when astralkit is not installed.
54
+ */
55
+ export function sdkHasExport(specifier, dir = process.cwd()) {
56
+ try {
57
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'node_modules', 'astralkit', 'package.json'), 'utf8'));
58
+ if (!pkg.exports) return true;
59
+ return Object.prototype.hasOwnProperty.call(pkg.exports, `./${specifier.replace(/^astralkit\//, '')}`);
60
+ } catch {
61
+ return null;
62
+ }
63
+ }
64
+
65
+ export function installedSdkVersion(dir = process.cwd()) {
66
+ try {
67
+ return JSON.parse(fs.readFileSync(path.join(dir, 'node_modules', 'astralkit', 'package.json'), 'utf8')).version || null;
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Writes the imports into the stylesheet: after the AstralKit theme import, so a palette is read after the theme it
75
+ * builds on and every @import stays at the top of the file. With no theme import, after the last @import or
76
+ * @tailwind line; in an empty file, first. Imports already there are left alone. Returns the ones it added.
77
+ */
78
+ export function addDeclaredCssImports(cssFilePath, specifiers) {
79
+ const existing = fs.existsSync(cssFilePath) ? fs.readFileSync(cssFilePath, 'utf8') : '';
80
+ const missing = specifiers.filter(specifier => !importPattern(specifier).test(existing));
81
+ if (!missing.length) return [];
82
+ const eol = existing.includes('\r\n') ? '\r\n' : '\n';
83
+ const lines = existing.length ? existing.split(/\r?\n/) : [];
84
+ const lastWhere = test => lines.reduce((found, line, index) => (test(line.trim()) ? index : found), -1);
85
+ let at = lastWhere(line => /^@import\s+["']astralkit\/theme(-v4)?["']/.test(line));
86
+ if (at < 0) at = lastWhere(line => line.startsWith('@import') || line.startsWith('@tailwind'));
87
+ lines.splice(at + 1, 0, ...missing.map(importLine));
88
+ fs.writeFileSync(cssFilePath, lines.join(eol) + (existing.length ? '' : eol));
89
+ return missing;
90
+ }
91
+
92
+ /** The imports named by every component already in the project's component folders (for `astralkit init`). */
93
+ export function collectDeclaredCssImports(dir = process.cwd()) {
94
+ const found = new Set();
95
+ const read = folder => {
96
+ let entries = [];
97
+ try { entries = fs.readdirSync(folder, { withFileTypes: true }); } catch { return; }
98
+ for (const entry of entries) {
99
+ const file = path.join(folder, entry.name);
100
+ if (entry.isDirectory()) { if (entry.name !== 'node_modules') read(file); continue; }
101
+ if (!/\.(tsx|jsx)$/.test(entry.name)) continue;
102
+ try { getDeclaredCssImports(fs.readFileSync(file, 'utf8')).forEach(specifier => found.add(specifier)); } catch { /* unreadable: skip */ }
103
+ }
104
+ };
105
+ for (const folder of ['src/components', 'components']) read(path.join(dir, folder));
106
+ return [...found];
107
+ }
108
+
109
+ /**
110
+ * Puts the stylesheets a component asks for into the project's stylesheet, and says what it did.
111
+ * `summary` is the install summary of `astralkit add` ({ modified, skipped }); it may be left out.
112
+ *
113
+ * It never writes an import the installed astralkit cannot resolve: that would break the project's build. When the
114
+ * installed astralkit is too old it offers to update it (accepted without a prompt in an agent or CI shell, like the
115
+ * component's other dependencies), and if the import still cannot be resolved it is named as not added.
116
+ */
117
+ export async function ensureComponentStylesheets(code, summary) {
118
+ const wanted = getDeclaredCssImports(code);
119
+ if (!wanted.length) return;
120
+ const skip = (what, reason) => summary?.skipped?.push({ what, reason });
121
+
122
+ const cssEntry = findCssEntryFile();
123
+ if (!cssEntry) {
124
+ p.log.warn('This component needs these lines in your stylesheet, after the AstralKit theme:');
125
+ wanted.forEach(specifier => console.log(pc.gray(` ${importLine(specifier)}`)));
126
+ wanted.forEach(specifier => skip(importLine(specifier), 'no stylesheet found: add it by hand'));
127
+ return;
128
+ }
129
+
130
+ const missing = getMissingDeclaredImports(cssEntry.path, wanted);
131
+ if (!missing.length) return;
132
+
133
+ if (!isAstralkitInstalled()) {
134
+ // `astralkit init` installs the SDK and then adds these too (it reads the components already in the project).
135
+ p.log.warn(`This component also needs ${missing.map(s => pc.cyan(s)).join(' and ')} in ${cssEntry.relative}. ${pc.cyan('astralkit init')} adds them.`);
136
+ missing.forEach(specifier => skip(importLine(specifier), 'astralkit is not installed: run astralkit init'));
137
+ return;
138
+ }
139
+
140
+ let unavailable = missing.filter(specifier => sdkHasExport(specifier) === false);
141
+ // One update per run: `astralkit add a b c` asks once, not once per component.
142
+ if (unavailable.length && !updateTried) {
143
+ updateTried = true;
144
+ const before = installedSdkVersion();
145
+ p.log.warn(`This component needs a newer ${pc.cyan('astralkit')} than the ${before || 'one'} installed (for ${unavailable.join(', ')}).`);
146
+ const update = await askConfirm({ message: 'Update astralkit to the latest version?', initialValue: true, nonInteractive: true });
147
+ if (update === true) {
148
+ const ora = (await import('ora')).default;
149
+ const spinner = ora('Updating astralkit...').start();
150
+ const result = await runInstall(detectPackageManager(process.cwd()), process.cwd(), ['astralkit@latest']);
151
+ const after = installedSdkVersion();
152
+ if (!result.success) { spinner.fail('Could not update astralkit.'); if (result.hint || result.error) console.log(pc.gray(` ${result.hint || result.error}`)); }
153
+ else if (after === before) spinner.info(`astralkit ${after} is already the latest published version.`);
154
+ else spinner.succeed(`astralkit is now ${after}`);
155
+ unavailable = missing.filter(specifier => sdkHasExport(specifier) === false);
156
+ }
157
+ }
158
+
159
+ const added = addDeclaredCssImports(cssEntry.path, missing.filter(specifier => !unavailable.includes(specifier)));
160
+ if (added.length) {
161
+ summary?.modified?.push({ path: cssEntry.relative, note: `+${added.length} ${added.length === 1 ? 'import' : 'imports'} (${added.join(', ')})` });
162
+ p.log.success(`Added ${added.map(s => pc.cyan(s)).join(' and ')} to ${pc.cyan(cssEntry.relative)}`);
163
+ }
164
+ if (unavailable.length) {
165
+ p.log.warn(`Not added: ${unavailable.join(', ')}. astralkit ${installedSdkVersion() || ''} does not have it, so the import would break your build.`);
166
+ console.log(pc.gray(' The component will not look as designed until astralkit is updated and this line is in your stylesheet:'));
167
+ unavailable.forEach(specifier => console.log(pc.gray(` ${importLine(specifier)}`)));
168
+ unavailable.forEach(specifier => skip(importLine(specifier), `astralkit ${installedSdkVersion() || ''} does not have it`.replace(' ', ' ')));
169
+ }
170
+ }