@astralkit/cli 3.0.5 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,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,205 +1,177 @@
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 {
8
- detectFramework,
9
- defaultConfig,
10
- writeProjectConfig,
11
- getProjectConfig,
12
- CONFIG_FILENAME,
13
- isAstralkitInstalled,
14
- findCssEntryFile,
15
- getMissingCssImports,
16
- addCssImports,
17
- REQUIRED_CSS_IMPORTS,
18
- } = require('../lib/config');
19
- const { validateFramework } = require('../lib/validators');
20
- const { getAiRulesContent } = require('../lib/ai-rules');
21
- const { saveApiKey, getApiKey } = require('../lib/auth');
22
-
23
- async function initCommand(options) {
24
- console.log(chalk.blue.bold('AstralKit — Project Setup'));
25
- console.log();
26
-
27
- // ─── Save API key if provided ────────────────────────
28
- if (options.apiKey) {
29
- if (!options.apiKey.startsWith('ak_')) {
30
- console.log(chalk.red('Invalid API key format. Keys start with ak_'));
31
- console.log(chalk.gray('Get your key at https://astralkit.com/account'));
32
- process.exit(1);
33
- }
34
- saveApiKey(options.apiKey);
35
- console.log(chalk.green(' API key saved'));
36
- } else if (!getApiKey()) {
37
- console.log(chalk.yellow('No API key found.'));
38
- console.log(chalk.gray('Get your key at'), chalk.cyan('astralkit.com/account'));
39
- console.log(chalk.gray('Then run:'), chalk.cyan('npx @astralkit/cli init --api-key <your-key>'));
40
- console.log();
41
- process.exit(1);
42
- }
43
-
44
- // Validate --framework if provided
45
- if (options.framework && !validateFramework(options.framework)) {
46
- process.exit(1);
47
- }
48
-
49
- // Check if already initialized
50
- const existing = getProjectConfig();
51
- if (existing) {
52
- console.log(chalk.yellow(`Found existing ${CONFIG_FILENAME} at ${existing._path}`));
53
- const { overwrite } = await inquirer.prompt([{
54
- type: 'confirm',
55
- name: 'overwrite',
56
- message: 'Overwrite existing config?',
57
- default: false,
58
- }]);
59
- if (!overwrite) {
60
- console.log(chalk.gray('Aborted.'));
61
- return;
62
- }
63
- }
64
-
65
- // Auto-detect framework silently — no prompt needed during init.
66
- // Framework selection happens during `add` if auto-detection is wrong.
67
- let framework = options.framework;
68
- if (!framework) {
69
- framework = detectFramework();
70
- }
71
- console.log(chalk.gray(` Framework: ${framework}`));
72
-
73
- // Component directory
74
- const componentDir = options.dir || 'src/components/ui';
75
-
76
- // ─── Step 1: Install astralkit design token package ─────
77
- // Fetched from AstralKit API (not npm) to keep tokens private.
78
- // Written to node_modules/astralkit/ so imports resolve normally.
79
- // ALL frameworks need this — HTML uses @import "astralkit/theme", React/Next.js use import { cn }.
80
- {
81
- if (!isAstralkitInstalled()) {
82
- const spinner = ora('Installing astralkit design tokens...').start();
83
- try {
84
- const { apiRequest } = require('../lib/api');
85
- const response = await apiRequest('/api/cli/sdk');
86
- const data = await response.json();
87
-
88
- // Install runtime dependencies FIRST (clsx + tailwind-merge)
89
- // Must happen before writing astralkit files, because npm prunes
90
- // extraneous folders from node_modules during install.
91
- const pm = detectPackageManager();
92
- const depsCmd = pm === 'yarn' ? 'yarn add clsx tailwind-merge'
93
- : pm === 'pnpm' ? 'pnpm add clsx tailwind-merge'
94
- : pm === 'bun' ? 'bun add clsx tailwind-merge'
95
- : 'npm install clsx tailwind-merge';
96
- execSync(depsCmd, { stdio: 'pipe', cwd: process.cwd() });
97
-
98
- // Now write astralkit token files to node_modules/astralkit/
99
- // (after npm install so they don't get pruned)
100
- const sdkDir = path.join(process.cwd(), 'node_modules', 'astralkit');
101
- const libDir = path.join(sdkDir, 'lib');
102
- fs.mkdirSync(libDir, { recursive: true });
103
-
104
- let filesWritten = 0;
105
- for (const [filePath, content] of Object.entries(data.files || {})) {
106
- const fullPath = path.join(sdkDir, filePath);
107
- const dir = path.dirname(fullPath);
108
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
109
- fs.writeFileSync(fullPath, content, 'utf-8');
110
- filesWritten++;
111
- }
112
-
113
- if (filesWritten === 0) {
114
- spinner.fail('No token files received from API');
115
- console.log(chalk.yellow('Try again — the API may be updating.'));
116
- } else {
117
- spinner.succeed(`Installed astralkit design tokens (${filesWritten} files)`);
118
- }
119
- } catch (err) {
120
- spinner.fail('Failed to install astralkit');
121
- if (err.message?.includes('Authentication')) {
122
- console.log(chalk.yellow('Run `astralkit login` first, then try again.'));
123
- } else {
124
- console.log(chalk.yellow('Check your internet connection and try again.'));
125
- }
126
- }
127
- } else {
128
- console.log(chalk.gray(' astralkit already installed'));
129
- }
130
- }
131
-
132
- // ─── Step 2: Add CSS imports ────────────────────────────
133
- const cssEntry = findCssEntryFile();
134
- if (cssEntry) {
135
- const missing = getMissingCssImports(cssEntry.path);
136
- if (missing.length > 0) {
137
- console.log();
138
- console.log(chalk.gray(`Found CSS entry: ${cssEntry.relative}`));
139
- const { addImports } = await inquirer.prompt([{
140
- type: 'confirm',
141
- name: 'addImports',
142
- message: `Add AstralKit imports to ${cssEntry.relative}?`,
143
- default: true,
144
- }]);
145
- if (addImports) {
146
- addCssImports(cssEntry.path, missing);
147
- console.log(chalk.green(' Added CSS imports'));
148
- }
149
- } else {
150
- console.log(chalk.gray(' CSS imports already present'));
151
- }
152
- } else {
153
- // No CSS entry found — create one with AstralKit imports
154
- const defaultCssPath = framework === 'html'
155
- ? path.join(process.cwd(), 'styles.css')
156
- : path.join(process.cwd(), 'src', 'app', 'globals.css');
157
- const defaultCssRelative = path.relative(process.cwd(), defaultCssPath);
158
-
159
- console.log();
160
- const cssContent = REQUIRED_CSS_IMPORTS.join('\n') + '\n';
161
- const cssDir = path.dirname(defaultCssPath);
162
- if (!fs.existsSync(cssDir)) fs.mkdirSync(cssDir, { recursive: true });
163
- fs.writeFileSync(defaultCssPath, cssContent, 'utf-8');
164
- console.log(chalk.green(' Created'), chalk.cyan(defaultCssRelative), chalk.green('with AstralKit imports'));
165
- }
166
-
167
- // ─── Step 3: Write config ──────────────────────────────
168
- const config = defaultConfig(framework);
169
- config.componentsDir = componentDir;
170
- writeProjectConfig(config);
171
-
172
- console.log();
173
- console.log(chalk.green('Created'), chalk.cyan(CONFIG_FILENAME));
174
- console.log(chalk.gray(` Framework: ${framework}`));
175
- console.log(chalk.gray(` Components: ${componentDir}/`));
176
-
177
- // ─── Step 4: AI coding rules ─────────────────────────
178
- const rulesFile = 'astralkit-ai-rules.md';
179
- const rulesPath = path.join(process.cwd(), rulesFile);
180
- if (!fs.existsSync(rulesPath)) {
181
- fs.writeFileSync(rulesPath, getAiRulesContent());
182
- console.log(chalk.green(' Created'), chalk.cyan(rulesFile));
183
- console.log(chalk.gray(' Paste into your AI tool\'s config (.cursorrules, CLAUDE.md, etc.)'));
184
- } else {
185
- console.log(chalk.gray(` ${rulesFile} already exists`));
186
- }
187
-
188
- console.log();
189
- console.log(chalk.green('Next steps:'));
190
- console.log(chalk.gray(' astralkit add sidebar-expanded-light Add a component'));
191
- console.log(chalk.gray(' astralkit list Browse components'));
192
- console.log(chalk.gray(' astralkit login Unlock pro components'));
193
- }
194
-
195
- /**
196
- * Detect which package manager the project uses.
197
- */
198
- function detectPackageManager(dir = process.cwd()) {
199
- if (fs.existsSync(path.join(dir, 'bun.lockb')) || fs.existsSync(path.join(dir, 'bun.lock'))) return 'bun';
200
- if (fs.existsSync(path.join(dir, 'pnpm-lock.yaml'))) return 'pnpm';
201
- if (fs.existsSync(path.join(dir, 'yarn.lock'))) return 'yarn';
202
- return 'npm';
203
- }
204
-
205
- module.exports = { initCommand };
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import pc from 'picocolors';
4
+ import * as p from '@clack/prompts';
5
+ import {
6
+ detectFramework,
7
+ detectTailwindVersion,
8
+ isTypeScriptProject,
9
+ isAstralkitInstalled,
10
+ findCssEntryFile,
11
+ getMissingCssImports,
12
+ addCssImports,
13
+ } from '../lib/config.js';
14
+ import { validateFramework } from '../lib/validators.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
+ import { apiRequest } from '../lib/api.js';
19
+
20
+ const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React', html: 'HTML' };
21
+
22
+ export async function initCommand(options) {
23
+ p.intro(pc.bgBlue(pc.white(' AstralKit Setup ')));
24
+
25
+ // ─── Step 1: API Key ─────────────────────────────────
26
+ let apiKey = options.apiKey || getApiKey();
27
+
28
+ if (options.apiKey) {
29
+ if (!options.apiKey.startsWith('ak_')) {
30
+ p.cancel(pc.red('Invalid API key format. Keys start with ak_'));
31
+ console.log(pc.gray('Get your key at ') + pc.cyan('https://astralkit.com/account'));
32
+ process.exit(1);
33
+ }
34
+ saveApiKey(options.apiKey);
35
+ p.log.success('API key saved');
36
+ } else if (!apiKey) {
37
+ p.log.warn('No API key found.');
38
+ console.log();
39
+ console.log(pc.gray(' Get your free API key at: ') + pc.cyan('https://astralkit.com/account'));
40
+ console.log();
41
+
42
+ const keyInput = await p.text({
43
+ message: 'Paste your API key (or press Enter to skip for now):',
44
+ placeholder: 'ak_...',
45
+ validate(val) {
46
+ if (!val) return;
47
+ if (!val.startsWith('ak_')) return 'Keys start with ak_ — check astralkit.com/account';
48
+ },
49
+ });
50
+
51
+ if (p.isCancel(keyInput)) {
52
+ p.cancel('Setup cancelled.');
53
+ process.exit(0);
54
+ }
55
+
56
+ if (keyInput) {
57
+ saveApiKey(keyInput);
58
+ apiKey = keyInput;
59
+ p.log.success('API key saved');
60
+ } else {
61
+ p.log.warn('Skipping API key — some features will be unavailable.');
62
+ p.log.info('Run ' + pc.cyan('astralkit init --api-key <your-key>') + ' later to add it.');
63
+ }
64
+ } else {
65
+ p.log.success('API key found');
66
+ }
67
+
68
+ // ─── Step 2: Detect Project ────────────────────────────
69
+ if (options.framework && !validateFramework(options.framework)) {
70
+ process.exit(1);
71
+ }
72
+
73
+ let framework = options.framework || detectFramework();
74
+ const twVersion = detectTailwindVersion();
75
+ const isTS = isTypeScriptProject();
76
+ const hasSrc = fs.existsSync(path.join(process.cwd(), 'src'));
77
+ const pm = detectPackageManager();
78
+
79
+ p.log.step(`Framework: ${pc.cyan(FRAMEWORK_LABELS[framework] || framework)}`);
80
+ if (twVersion) p.log.step(`Tailwind: ${pc.cyan('v' + twVersion)}`);
81
+ if (isTS) p.log.step(`TypeScript: ${pc.cyan('Yes')}`);
82
+ p.log.step(`Package manager: ${pc.cyan(pm)}`);
83
+
84
+ // ─── Step 3: Install astralkit as a real npm dependency ────
85
+ if (!isAstralkitInstalled()) {
86
+ if (apiKey) {
87
+ const ora = (await import('ora')).default;
88
+ const spinner = ora('Downloading AstralKit design tokens...').start();
89
+ try {
90
+ const response = await apiRequest('/api/cli/sdk/tarball');
91
+ const contentDisposition = response.headers.get('content-disposition') || '';
92
+ const filenameMatch = contentDisposition.match(/filename="([^"]+)"/);
93
+ const tgzFilename = filenameMatch?.[1] || 'astralkit-0.1.0.tgz';
94
+
95
+ const tgzPath = path.join(process.cwd(), tgzFilename);
96
+ const buffer = Buffer.from(await response.arrayBuffer());
97
+ fs.writeFileSync(tgzPath, buffer);
98
+
99
+ spinner.text = `Installing astralkit via ${pm}...`;
100
+
101
+ const result = await runInstall(pm, process.cwd(), [`./${tgzFilename}`]);
102
+
103
+ if (result.success) {
104
+ spinner.succeed('Installed astralkit design tokens');
105
+ p.log.info(pc.gray(`Commit ${tgzFilename} to git so teammates get it on npm install`));
106
+ } else {
107
+ spinner.fail('Failed to install astralkit.');
108
+ console.log(pc.gray(' ' + (result.hint || result.error)));
109
+ }
110
+ } catch (err) {
111
+ spinner.fail('Could not download design tokens.');
112
+ if (err.code === 'AUTH_REQUIRED') {
113
+ p.log.info('Add your API key: ' + pc.cyan('astralkit init --api-key <key>'));
114
+ } else if (err.code === 'NETWORK_ERROR' || err.code === 'TIMEOUT') {
115
+ p.log.info('Check your connection and run ' + pc.cyan('astralkit init') + ' again.');
116
+ } else {
117
+ p.log.info(pc.gray(err.message));
118
+ }
119
+ }
120
+ } else {
121
+ p.log.warn('Skipping design token install — no API key.');
122
+ p.log.info('Run ' + pc.cyan('astralkit init --api-key <key>') + ' to install them.');
123
+ }
124
+ } else {
125
+ p.log.step('astralkit design tokens already installed');
126
+ }
127
+
128
+ // ─── Step 4: CSS imports ─────────────────────────────
129
+ const cssEntry = findCssEntryFile();
130
+ if (cssEntry) {
131
+ const missing = getMissingCssImports(cssEntry.path);
132
+ if (missing.length > 0) {
133
+ const addImports = await p.confirm({
134
+ message: `Add AstralKit CSS imports to ${pc.cyan(cssEntry.relative)}?`,
135
+ initialValue: true,
136
+ });
137
+ if (!p.isCancel(addImports) && addImports) {
138
+ addCssImports(cssEntry.path, missing);
139
+ p.log.success(`CSS imports added to ${cssEntry.relative}`);
140
+ }
141
+ } else {
142
+ p.log.step('CSS imports already present');
143
+ }
144
+ } else {
145
+ // No CSS entry found — create one at the framework-appropriate location
146
+ const defaultCssPath = (framework === 'nextjs' && hasSrc)
147
+ ? path.join(process.cwd(), 'src', 'app', 'globals.css')
148
+ : (framework === 'nextjs')
149
+ ? path.join(process.cwd(), 'app', 'globals.css')
150
+ : (hasSrc)
151
+ ? path.join(process.cwd(), 'src', 'index.css')
152
+ : path.join(process.cwd(), 'index.css');
153
+ const defaultCssRelative = path.relative(process.cwd(), defaultCssPath);
154
+
155
+ const allImports = getMissingCssImports('/nonexistent'); // get all imports
156
+ const cssDir = path.dirname(defaultCssPath);
157
+ if (!fs.existsSync(cssDir)) fs.mkdirSync(cssDir, { recursive: true });
158
+ addCssImports(defaultCssPath, allImports);
159
+ p.log.success(`Created ${pc.cyan(defaultCssRelative)} with AstralKit imports`);
160
+ }
161
+
162
+ // ─── Step 5: AI rules file ───────────────────────────
163
+ const rulesFile = 'astralkit-ai-rules.md';
164
+ const rulesPath = path.join(process.cwd(), rulesFile);
165
+ if (!fs.existsSync(rulesPath)) {
166
+ fs.writeFileSync(rulesPath, getAiRulesContent());
167
+ p.log.success(`Created ${pc.cyan(rulesFile)}`);
168
+ }
169
+
170
+ // ─── Done ────────────────────────────────────────────
171
+ p.outro(pc.green('AstralKit is ready!'));
172
+
173
+ console.log();
174
+ console.log(pc.gray(' Add a component:'), pc.cyan('astralkit add pricing-table'));
175
+ console.log(pc.gray(' Browse all: '), pc.cyan('astralkit list'));
176
+ console.log();
177
+ }