@astralkit/cli 3.1.0 → 4.1.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,107 +1,57 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const chalk = require('chalk');
4
- const ora = require('ora');
5
- const { getComponent } = require('../lib/api');
6
- const { getProjectConfig, detectFramework } = require('../lib/config');
7
- const { validateSlug, validateFramework, isSafePath } = require('../lib/validators');
8
-
9
- async function diffCommand(componentSlug, options) {
10
- // Validate inputs
11
- if (!validateSlug(componentSlug)) process.exit(1);
12
- if (!validateFramework(options.framework)) process.exit(1);
13
-
14
- const config = getProjectConfig();
15
- const framework = options.framework || config?.framework || detectFramework();
16
- const componentsDir = options.dir || config?.componentsDir || 'src/components/ui';
17
- const targetDir = path.resolve(process.cwd(), componentsDir, componentSlug);
18
-
19
- // Check if component exists locally
20
- if (!fs.existsSync(targetDir)) {
21
- console.log(chalk.yellow(`Component "${componentSlug}" not found locally at ${componentsDir}/${componentSlug}/`));
22
- console.log(chalk.gray('Nothing to diff.'));
23
- return;
24
- }
25
-
26
- const spinner = ora(`Fetching latest ${componentSlug} (${framework})...`).start();
27
-
28
- try {
29
- const data = await getComponent(componentSlug, framework);
30
-
31
- if (!data.files || data.files.length === 0) {
32
- spinner.fail(`No ${framework} code available for "${componentSlug}" on remote.`);
33
- return;
34
- }
35
-
36
- spinner.stop();
37
-
38
- console.log(chalk.blue.bold(`Diff: ${componentSlug} (${framework})`));
39
- console.log();
40
-
41
- let hasChanges = false;
42
-
43
- for (const remoteFile of data.files) {
44
- // Path traversal protection
45
- if (!isSafePath(targetDir, remoteFile.path)) {
46
- console.log(chalk.red(` Skipping suspicious file path: ${remoteFile.path}`));
47
- continue;
48
- }
49
-
50
- const localPath = path.resolve(targetDir, remoteFile.path);
51
-
52
- if (!fs.existsSync(localPath)) {
53
- console.log(chalk.green(`+ ${remoteFile.path}`), chalk.gray('(new file on remote)'));
54
- hasChanges = true;
55
- continue;
56
- }
57
-
58
- const localContent = fs.readFileSync(localPath, 'utf8');
59
- const remoteContent = remoteFile.content;
60
-
61
- if (localContent === remoteContent) {
62
- console.log(chalk.gray(` ${remoteFile.path}`), chalk.green('(up to date)'));
63
- } else {
64
- hasChanges = true;
65
- console.log(chalk.yellow(`~ ${remoteFile.path}`), chalk.yellow('(modified)'));
66
-
67
- // Show simple line count diff
68
- const localLines = localContent.split('\n').length;
69
- const remoteLines = remoteContent.split('\n').length;
70
- const diff = remoteLines - localLines;
71
- if (diff > 0) {
72
- console.log(chalk.gray(` Remote has ${diff} more line(s)`));
73
- } else if (diff < 0) {
74
- console.log(chalk.gray(` Local has ${Math.abs(diff)} more line(s)`));
75
- } else {
76
- console.log(chalk.gray(` Same line count, content differs`));
77
- }
78
- }
79
- }
80
-
81
- // Check for local files not on remote
82
- {
83
- const localFiles = fs.readdirSync(targetDir);
84
- const remoteFilenames = new Set(data.files.map(f => f.path));
85
- for (const localFile of localFiles) {
86
- if (!remoteFilenames.has(localFile)) {
87
- console.log(chalk.red(`- ${localFile}`), chalk.gray('(local only, not on remote)'));
88
- hasChanges = true;
89
- }
90
- }
91
- }
92
-
93
- console.log();
94
- if (hasChanges) {
95
- console.log(chalk.yellow('Changes detected.'));
96
- console.log(chalk.gray(`Run ${chalk.cyan(`astralkit update ${componentSlug}`)} to update.`));
97
- } else {
98
- console.log(chalk.green('All files are up to date.'));
99
- }
100
- } catch (err) {
101
- spinner.fail('Diff failed.');
102
- console.error(chalk.red(err.message));
103
- process.exit(1);
104
- }
105
- }
106
-
107
- module.exports = { diffCommand };
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 } from '../lib/api.js';
6
+ import { getProjectConfig, detectFramework } from '../lib/config.js';
7
+
8
+ export async function diffCommand(componentSlug, options) {
9
+ const ora = (await import('ora')).default;
10
+ const config = getProjectConfig();
11
+ const framework = options.framework || config?.framework || detectFramework();
12
+ const componentsDir = options.dir || config?.componentsDir || 'src/components/ui';
13
+
14
+ const spinner = ora(`Fetching latest ${pc.cyan(componentSlug)}...`).start();
15
+
16
+ try {
17
+ const data = await getComponent(componentSlug, framework);
18
+ spinner.stop();
19
+
20
+ if (!data.files?.length) {
21
+ p.log.warn(`No ${framework} version available for "${componentSlug}".`);
22
+ return;
23
+ }
24
+
25
+ let hasDiff = false;
26
+
27
+ for (const file of data.files) {
28
+ const localPath = path.resolve(process.cwd(), componentsDir, file.path);
29
+ if (!fs.existsSync(localPath)) {
30
+ console.log(pc.yellow(` Not installed: ${file.path}`));
31
+ hasDiff = true;
32
+ continue;
33
+ }
34
+
35
+ const localContent = fs.readFileSync(localPath, 'utf8');
36
+ if (localContent !== file.content) {
37
+ console.log(pc.yellow(` Modified: ${file.path}`));
38
+ hasDiff = true;
39
+ } else {
40
+ console.log(pc.green(` Up to date: ${file.path}`));
41
+ }
42
+ }
43
+
44
+ if (!hasDiff) {
45
+ console.log();
46
+ p.log.success(`${componentSlug} is up to date.`);
47
+ } else {
48
+ console.log();
49
+ p.log.info(`Run ${pc.cyan(`astralkit update ${componentSlug}`)} to update.`);
50
+ }
51
+ } catch (err) {
52
+ spinner.fail('Failed to fetch component.');
53
+ if (err.code === 'AUTH_REQUIRED' || err.code === 'PRO_REQUIRED') p.log.warn(err.message);
54
+ else console.error(pc.red(err.message));
55
+ process.exit(1);
56
+ }
57
+ }
@@ -1,188 +1,148 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const chalk = require('chalk');
4
- const inquirer = require('inquirer');
5
- const ora = require('ora');
6
- const { execSync } = require('child_process');
7
- const {
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import pc from 'picocolors';
4
+ import * as p from '@clack/prompts';
5
+ import {
8
6
  detectFramework,
7
+ detectTailwindVersion,
8
+ detectTypeScript,
9
9
  isAstralkitInstalled,
10
10
  findCssEntryFile,
11
11
  getMissingCssImports,
12
12
  addCssImports,
13
- REQUIRED_CSS_IMPORTS,
14
- } = require('../lib/config');
15
- const { validateFramework } = require('../lib/validators');
16
- const { getAiRulesContent } = require('../lib/ai-rules');
17
- const { saveApiKey, getApiKey } = require('../lib/auth');
18
-
19
- async function initCommand(options) {
20
- console.log(chalk.blue.bold('AstralKit — Project Setup'));
21
- console.log();
13
+ getRequiredCssImports,
14
+ } from '../lib/config.js';
15
+ import { getAiRulesContent } from '../lib/ai-rules.js';
16
+ import { saveApiKey, getApiKey } from '../lib/auth.js';
17
+ import { detectPackageManager, runInstall } from '../lib/pkg-manager.js';
18
+
19
+ const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React' };
20
+
21
+ export async function initCommand(options) {
22
+ p.intro(pc.bgBlue(pc.white(' AstralKit Setup ')));
23
+
24
+ // ─── Step 1: API Key ─────────────────────────────────
25
+ let apiKey = options.apiKey || getApiKey();
22
26
 
23
- // ─── Save API key if provided ────────────────────────
24
27
  if (options.apiKey) {
25
28
  if (!options.apiKey.startsWith('ak_')) {
26
- console.log(chalk.red('Invalid API key format. Keys start with ak_'));
27
- console.log(chalk.gray('Get your key at https://astralkit.com/account'));
29
+ p.cancel(pc.red('Invalid API key format. Keys start with ak_'));
30
+ console.log(pc.gray('Get your key at ') + pc.cyan('https://astralkit.com/account'));
28
31
  process.exit(1);
29
32
  }
30
33
  saveApiKey(options.apiKey);
31
- console.log(chalk.green(' API key saved'));
32
- } else if (!getApiKey()) {
33
- console.log(chalk.yellow('No API key found.'));
34
- console.log(chalk.gray('Get your key at'), chalk.cyan('astralkit.com/account'));
35
- console.log(chalk.gray('Then run:'), chalk.cyan('npx @astralkit/cli init --api-key <your-key>'));
34
+ p.log.success('API key saved');
35
+ } else if (!apiKey) {
36
+ p.log.warn('No API key found.');
36
37
  console.log();
37
- process.exit(1);
38
+ console.log(pc.gray(' Get your free API key at: ') + pc.cyan('https://astralkit.com/account'));
39
+ console.log();
40
+
41
+ const keyInput = await p.text({
42
+ message: 'Paste your API key (or press Enter to skip for now):',
43
+ placeholder: 'ak_...',
44
+ validate(val) {
45
+ if (!val) return;
46
+ if (!val.startsWith('ak_')) return 'Keys start with ak_ — check astralkit.com/account';
47
+ },
48
+ });
49
+
50
+ if (p.isCancel(keyInput)) {
51
+ p.cancel('Setup cancelled.');
52
+ process.exit(0);
53
+ }
54
+
55
+ if (keyInput) {
56
+ saveApiKey(keyInput);
57
+ apiKey = keyInput;
58
+ p.log.success('API key saved');
59
+ } else {
60
+ p.log.warn('Skipping API key — some features will be unavailable.');
61
+ p.log.info('Run ' + pc.cyan('astralkit init --api-key <key>') + ' later to add it.');
62
+ }
63
+ } else {
64
+ p.log.success('API key found');
65
+ }
66
+
67
+ // ─── Step 2: Detect project ────────────────────────────
68
+ const framework = options.framework || detectFramework();
69
+ const tailwindVersion = detectTailwindVersion();
70
+ const isTS = detectTypeScript();
71
+ const pm = detectPackageManager();
72
+
73
+ if (framework !== 'react' && framework !== 'nextjs') {
74
+ p.log.warn('AstralKit CLI is for React and Next.js projects.');
75
+ p.log.info('For HTML, copy components from ' + pc.cyan('https://astralkit.com'));
76
+ p.outro('');
77
+ return;
38
78
  }
39
79
 
40
- // Auto-detect framework
41
- let framework = options.framework;
42
- if (framework && !validateFramework(framework)) process.exit(1);
43
- if (!framework) framework = detectFramework();
44
- console.log(chalk.gray(` Framework: ${framework}`));
45
-
46
- // Detect Tailwind version
47
- const twVersion = detectTailwindVersion();
48
- if (twVersion) console.log(chalk.gray(` Tailwind: v${twVersion}`));
49
-
50
- // Detect TypeScript
51
- const isTS = fs.existsSync(path.join(process.cwd(), 'tsconfig.json'));
52
- if (isTS) console.log(chalk.gray(' TypeScript: Yes'));
53
-
54
- // Component directory — adapt to project structure
55
- const hasSrc = fs.existsSync(path.join(process.cwd(), 'src'));
56
- const componentDir = options.dir || (hasSrc ? 'src/components/ui' : 'components/ui');
57
-
58
- // ─── Step 1: Install astralkit as a real npm dependency ─────
59
- // Downloaded as a tarball from the API, installed via npm/pnpm/yarn/bun.
60
- // This makes it a real dependency in package.json that survives npm ci.
61
- {
62
- if (!isAstralkitInstalled()) {
63
- const spinner = ora('Installing astralkit design tokens...').start();
64
- try {
65
- const { apiRequest, API_BASE } = require('../lib/api');
66
-
67
- // Download the tarball from the API
68
- const response = await apiRequest('/api/cli/sdk/tarball');
69
- const arrayBuffer = await response.arrayBuffer();
70
- const tgzBuffer = Buffer.from(arrayBuffer);
71
-
72
- // Save tarball to a temp location
73
- const tgzPath = path.join(process.cwd(), '.astralkit-sdk.tgz');
74
- fs.writeFileSync(tgzPath, tgzBuffer);
75
-
76
- // Install via the detected package manager — this makes it a REAL dependency
77
- const pm = detectPackageManager();
78
- const installCmd = pm === 'yarn' ? `yarn add ${tgzPath}`
79
- : pm === 'pnpm' ? `pnpm add ${tgzPath}`
80
- : pm === 'bun' ? `bun add ${tgzPath}`
81
- : `npm install ${tgzPath}`;
82
- execSync(installCmd, { stdio: 'pipe', cwd: process.cwd() });
83
-
84
- // Clean up the temp tarball
85
- if (fs.existsSync(tgzPath)) fs.unlinkSync(tgzPath);
86
-
87
- // Verify it installed
88
- if (isAstralkitInstalled()) {
89
- spinner.succeed('Installed astralkit design tokens');
90
- } else {
91
- spinner.fail('Install completed but astralkit not found in node_modules');
92
- }
93
- } catch (err) {
94
- spinner.fail('Failed to install astralkit');
95
- if (err.message?.includes('API key')) {
96
- console.log(chalk.yellow('Invalid API key. Check your key at astralkit.com/account'));
97
- } else {
98
- console.log(chalk.yellow(err.message || 'Check your internet connection and try again.'));
99
- }
100
- // Clean up temp file on error
101
- const tgzPath = path.join(process.cwd(), '.astralkit-sdk.tgz');
102
- if (fs.existsSync(tgzPath)) fs.unlinkSync(tgzPath);
103
- return;
80
+ p.log.step(`Framework: ${pc.cyan(FRAMEWORK_LABELS[framework])}`);
81
+ if (tailwindVersion) p.log.step(`Tailwind: ${pc.cyan('v' + tailwindVersion)}`);
82
+ p.log.step(`TypeScript: ${pc.cyan(isTS ? 'Yes' : 'No')}`);
83
+ p.log.step(`Package manager: ${pc.cyan(pm)}`);
84
+
85
+ // ─── Step 3: Install astralkit (real npm dependency) ────
86
+ //
87
+ // `npm install astralkit` — a proper package on the public registry.
88
+ // Contains: design tokens (CSS), cn() utility, AI rules.
89
+ // Listed in package.json. Survives npm ci. Works for teammates and CI/CD.
90
+
91
+ if (!isAstralkitInstalled()) {
92
+ const ora = (await import('ora')).default;
93
+ const spinner = ora('Installing astralkit...').start();
94
+ try {
95
+ const result = await runInstall(pm, process.cwd(), ['astralkit']);
96
+ if (result.success) {
97
+ spinner.succeed('Installed astralkit');
98
+ } else {
99
+ spinner.fail('Failed to install astralkit.');
100
+ console.log(pc.gray(' ' + (result.hint || result.error)));
101
+ console.log(pc.gray(` Retry manually: ${pm === 'npm' ? 'npm install' : pm + ' add'} astralkit`));
104
102
  }
105
- } else {
106
- console.log(chalk.gray(' astralkit already installed'));
103
+ } catch (err) {
104
+ spinner.fail('Failed to install astralkit.');
105
+ console.log(pc.gray(' ' + err.message));
107
106
  }
107
+ } else {
108
+ p.log.step('astralkit already installed');
108
109
  }
109
110
 
110
- // ─── Step 2: Add CSS imports ────────────────────────────
111
+ // ─── Step 4: CSS imports ─────────────────────────────
111
112
  const cssEntry = findCssEntryFile();
113
+
112
114
  if (cssEntry) {
113
- const missing = getMissingCssImports(cssEntry.path);
115
+ const missing = getMissingCssImports(cssEntry.path, tailwindVersion);
114
116
  if (missing.length > 0) {
115
- console.log(chalk.gray(` Found CSS entry: ${cssEntry.relative}`));
116
117
  addCssImports(cssEntry.path, missing);
117
- console.log(chalk.green(' Added CSS imports'));
118
+ p.log.success(`Updated ${pc.cyan(cssEntry.relative)}`);
118
119
  } else {
119
- console.log(chalk.gray(' CSS imports already present'));
120
+ p.log.step('CSS imports already present');
120
121
  }
121
122
  } else {
122
- // No CSS entry found — create one
123
- const defaultCssPath = (framework === 'nextjs' && hasSrc)
124
- ? path.join(process.cwd(), 'src', 'app', 'globals.css')
125
- : (framework === 'nextjs')
126
- ? path.join(process.cwd(), 'app', 'globals.css')
127
- : (hasSrc)
128
- ? path.join(process.cwd(), 'src', 'index.css')
129
- : path.join(process.cwd(), 'index.css');
123
+ // Create a default CSS file
124
+ const defaultCssPath = path.join(process.cwd(), 'src', 'app', 'globals.css');
130
125
  const defaultCssRelative = path.relative(process.cwd(), defaultCssPath);
131
-
132
- const cssContent = REQUIRED_CSS_IMPORTS.join('\n') + '\n';
133
126
  const cssDir = path.dirname(defaultCssPath);
134
127
  if (!fs.existsSync(cssDir)) fs.mkdirSync(cssDir, { recursive: true });
135
- fs.writeFileSync(defaultCssPath, cssContent, 'utf-8');
136
- console.log(chalk.green(' Created'), chalk.cyan(defaultCssRelative), chalk.green('with AstralKit imports'));
128
+ const imports = getRequiredCssImports(tailwindVersion);
129
+ fs.writeFileSync(defaultCssPath, imports.join('\n') + '\n', 'utf-8');
130
+ p.log.success(`Created ${pc.cyan(defaultCssRelative)}`);
137
131
  }
138
132
 
139
- // ─── Step 3: AI coding rules ─────────────────────────
133
+ // ─── Step 5: AI rules file ───────────────────────────
140
134
  const rulesFile = 'astralkit-ai-rules.md';
141
135
  const rulesPath = path.join(process.cwd(), rulesFile);
142
136
  if (!fs.existsSync(rulesPath)) {
143
137
  fs.writeFileSync(rulesPath, getAiRulesContent());
144
- console.log(chalk.green(' Created'), chalk.cyan(rulesFile));
145
- } else {
146
- console.log(chalk.gray(` ${rulesFile} already exists`));
138
+ p.log.success(`Created ${pc.cyan(rulesFile)}`);
147
139
  }
148
140
 
149
141
  // ─── Done ────────────────────────────────────────────
142
+ p.outro(pc.green('AstralKit is ready!'));
143
+
150
144
  console.log();
151
- console.log(chalk.green('AstralKit initialized.'));
145
+ console.log(pc.gray(' Add a component:'), pc.cyan('astralkit add pricing-table'));
146
+ console.log(pc.gray(' Browse all: '), pc.cyan('astralkit list'));
152
147
  console.log();
153
- console.log(chalk.gray(' Add a component:'), chalk.cyan(`astralkit add sidebar-light`));
154
- console.log(chalk.gray(' Browse components:'), chalk.cyan('astralkit list'));
155
148
  }
156
-
157
- /**
158
- * Detect which package manager the project uses.
159
- */
160
- function detectPackageManager(dir = process.cwd()) {
161
- if (fs.existsSync(path.join(dir, 'bun.lockb')) || fs.existsSync(path.join(dir, 'bun.lock'))) return 'bun';
162
- if (fs.existsSync(path.join(dir, 'pnpm-lock.yaml'))) return 'pnpm';
163
- if (fs.existsSync(path.join(dir, 'yarn.lock'))) return 'yarn';
164
- return 'npm';
165
- }
166
-
167
- /**
168
- * Detect Tailwind CSS version from package.json.
169
- * Returns 3, 4, or null.
170
- */
171
- function detectTailwindVersion(dir = process.cwd()) {
172
- try {
173
- const pkgPath = path.join(dir, 'package.json');
174
- if (!fs.existsSync(pkgPath)) return null;
175
- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
176
- const deps = { ...pkg.dependencies, ...pkg.devDependencies };
177
- const ver = deps['tailwindcss'];
178
- if (!ver) return null;
179
- const major = parseInt(ver.replace(/[^0-9]/, ''), 10);
180
- if (major >= 4) return 4;
181
- if (major === 3) return 3;
182
- return null;
183
- } catch {
184
- return null;
185
- }
186
- }
187
-
188
- module.exports = { initCommand };