@vee-stack/delta-cli 2.0.9 → 2.0.10

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.
Files changed (98) hide show
  1. package/dist/adapters/analysis.adapter.d.ts +29 -0
  2. package/dist/analyzer/commands/analyze.d.ts +14 -0
  3. package/dist/analyzer/commands/config.d.ts +12 -0
  4. package/dist/analyzer/commands/report.d.ts +11 -0
  5. package/dist/analyzer/generators/report.generator.d.ts +43 -0
  6. package/dist/analyzer/index.d.ts +8 -0
  7. package/dist/analyzer/scanners/project.scanner.d.ts +29 -0
  8. package/dist/analyzer/validators/contracts.validator.d.ts +27 -0
  9. package/dist/analyzer/validators/maintainability.validator.d.ts +27 -0
  10. package/dist/analyzer/validators/observability.validator.d.ts +27 -0
  11. package/dist/analyzer/validators/performance.validator.d.ts +27 -0
  12. package/dist/analyzer/validators/security.validator.d.ts +27 -0
  13. package/dist/analyzer/validators/soc.validator.d.ts +27 -0
  14. package/dist/auth/device-auth.d.ts +18 -0
  15. package/dist/auth/secure-auth.d.ts +35 -0
  16. package/dist/bundle.mjs +422 -0
  17. package/dist/commands/analyze.d.ts +12 -0
  18. package/dist/commands/auth-new.d.ts +6 -0
  19. package/dist/commands/auth.d.ts +17 -0
  20. package/dist/commands/config.d.ts +8 -0
  21. package/dist/commands/deploy.d.ts +5 -0
  22. package/dist/commands/init.d.ts +7 -0
  23. package/dist/commands/logout.d.ts +2 -0
  24. package/dist/commands/plugins.d.ts +7 -0
  25. package/dist/commands/status.d.ts +5 -0
  26. package/dist/commands/sync.d.ts +5 -0
  27. package/dist/commands/whoami.d.ts +4 -0
  28. package/dist/components/Dashboard.d.ts +8 -0
  29. package/dist/components/DeltaApp.d.ts +13 -0
  30. package/dist/components/UnifiedManager.d.ts +10 -0
  31. package/dist/core/audit.d.ts +60 -0
  32. package/dist/core/completion.d.ts +79 -0
  33. package/dist/core/contracts.d.ts +127 -0
  34. package/dist/core/engine.d.ts +26 -0
  35. package/dist/core/exit-codes.d.ts +19 -0
  36. package/dist/core/hooks.d.ts +50 -0
  37. package/dist/core/{index.js → index.d.ts} +1 -1
  38. package/dist/core/policy.d.ts +24 -0
  39. package/dist/core/profiles.d.ts +45 -0
  40. package/dist/core/wizard.d.ts +28 -0
  41. package/dist/interactive/index.d.ts +5 -0
  42. package/dist/plugins/GitStatusPlugin.d.ts +25 -0
  43. package/dist/providers/ai-provider.d.ts +21 -0
  44. package/dist/providers/local-provider.d.ts +21 -0
  45. package/dist/providers/remote-provider.d.ts +15 -0
  46. package/dist/telemetry/wrapper.d.ts +18 -0
  47. package/dist/types/api.d.ts +46 -0
  48. package/dist/ui.d.ts +52 -0
  49. package/dist/welcome.d.ts +8 -0
  50. package/package.json +8 -10
  51. package/dist/adapters/analysis.adapter.js +0 -42
  52. package/dist/analyzer/commands/analyze.js +0 -220
  53. package/dist/analyzer/commands/config.js +0 -83
  54. package/dist/analyzer/commands/report.js +0 -38
  55. package/dist/analyzer/generators/report.generator.js +0 -123
  56. package/dist/analyzer/index.js +0 -44
  57. package/dist/analyzer/scanners/project.scanner.js +0 -92
  58. package/dist/analyzer/validators/contracts.validator.js +0 -42
  59. package/dist/analyzer/validators/maintainability.validator.js +0 -40
  60. package/dist/analyzer/validators/observability.validator.js +0 -39
  61. package/dist/analyzer/validators/performance.validator.js +0 -42
  62. package/dist/analyzer/validators/security.validator.js +0 -66
  63. package/dist/analyzer/validators/soc.validator.js +0 -75
  64. package/dist/auth/device-auth.js +0 -261
  65. package/dist/auth/secure-auth.js +0 -401
  66. package/dist/commands/analyze.js +0 -393
  67. package/dist/commands/auth-new.js +0 -37
  68. package/dist/commands/auth.js +0 -131
  69. package/dist/commands/config.js +0 -51
  70. package/dist/commands/deploy.js +0 -6
  71. package/dist/commands/init.js +0 -47
  72. package/dist/commands/logout.js +0 -31
  73. package/dist/commands/plugins.js +0 -21
  74. package/dist/commands/status.js +0 -82
  75. package/dist/commands/sync.js +0 -6
  76. package/dist/commands/whoami.js +0 -72
  77. package/dist/components/Dashboard.js +0 -167
  78. package/dist/components/DeltaApp.js +0 -57
  79. package/dist/components/UnifiedManager.js +0 -372
  80. package/dist/core/audit.js +0 -184
  81. package/dist/core/completion.js +0 -305
  82. package/dist/core/contracts.js +0 -6
  83. package/dist/core/engine.js +0 -130
  84. package/dist/core/exit-codes.js +0 -79
  85. package/dist/core/hooks.js +0 -181
  86. package/dist/core/policy.js +0 -115
  87. package/dist/core/profiles.js +0 -161
  88. package/dist/core/wizard.js +0 -203
  89. package/dist/index.js +0 -403
  90. package/dist/interactive/index.js +0 -11
  91. package/dist/plugins/GitStatusPlugin.js +0 -93
  92. package/dist/providers/ai-provider.js +0 -74
  93. package/dist/providers/local-provider.js +0 -304
  94. package/dist/providers/remote-provider.js +0 -100
  95. package/dist/telemetry/wrapper.js +0 -114
  96. package/dist/types/api.js +0 -3
  97. package/dist/ui.js +0 -226
  98. package/dist/welcome.js +0 -91
@@ -1,393 +0,0 @@
1
- /**
2
- * Analyze Command - Run local analysis with optional upload to cloud
3
- */
4
- import * as fs from 'fs/promises';
5
- import * as path from 'path';
6
- import * as crypto from 'crypto';
7
- import { loadConfig } from './auth.js';
8
- import { SecureTokenStore } from '../auth/secure-auth.js';
9
- import chalk from 'chalk';
10
- import { icons, startSpinner, stopSpinner, printSuccess, printInfo, printWarning, createTable, printDivider, } from '../ui.js';
11
- function extractApiErrorPayload(payload) {
12
- if (!payload || typeof payload !== 'object')
13
- return {};
14
- const maybeError = payload.error;
15
- if (!maybeError || typeof maybeError !== 'object')
16
- return {};
17
- const e = maybeError;
18
- return {
19
- message: typeof e.message === 'string' ? e.message : undefined,
20
- details: e.details,
21
- };
22
- }
23
- export async function analyzeCommand(projectPath, options) {
24
- const targetPath = path.resolve(projectPath);
25
- // Check authentication FIRST for all operations
26
- printInfo('🔐 Checking authentication...');
27
- await loadConfig();
28
- const pat = await SecureTokenStore.getAccessToken();
29
- if (!pat) {
30
- console.error();
31
- console.error(chalk.red('❌ Error: You must be logged in to use Delta CLI.'));
32
- console.error();
33
- console.error(chalk.yellow('Please authenticate first:'));
34
- console.error(chalk.cyan(' delta login'));
35
- console.error();
36
- console.error(chalk.dim('Or use a valid PAT:'));
37
- console.error(chalk.cyan(' delta login --token <your-pat>'));
38
- console.error();
39
- process.exit(1);
40
- }
41
- printSuccess('✓ Authenticated');
42
- console.log();
43
- // Additional check for upload permission
44
- if (options.upload) {
45
- printInfo('📤 Upload mode enabled');
46
- console.log();
47
- }
48
- printInfo('🔍 Starting Delta Analysis Engine...');
49
- printDivider();
50
- console.log(`${icons.folder} Project: ${chalk.cyan(targetPath)}`);
51
- console.log();
52
- // Phase 1: File Discovery
53
- startSpinner('Scanning project files...');
54
- const files = await discoverFiles(targetPath, {
55
- include: options.include ? [options.include] : ['**/*.{ts,tsx,js,jsx}'],
56
- exclude: options.exclude
57
- ? [options.exclude].concat(['node_modules', 'dist', '.git'])
58
- : ['node_modules', 'dist', '.git'],
59
- maxSize: parseInt(options.maxSize, 10),
60
- });
61
- stopSpinner(true, `Found ${files.length} files to analyze`);
62
- console.log();
63
- if (files.length === 0) {
64
- printWarning('No files found matching the criteria');
65
- printInfo('Try adjusting --include or --exclude patterns');
66
- process.exit(0);
67
- }
68
- // Phase 2: Analysis with Progress
69
- console.log(`${icons.loading} Analyzing ${files.length} files...`);
70
- console.log();
71
- const startTime = Date.now();
72
- const summary = {
73
- totalFiles: files.length,
74
- successfulParses: 0,
75
- failedParses: 0,
76
- totalLines: 0,
77
- totalFunctions: 0,
78
- totalClasses: 0,
79
- totalDuration: 0,
80
- errors: [],
81
- };
82
- const findings = [];
83
- // Process files with progress indication
84
- for (let i = 0; i < files.length; i++) {
85
- const file = files[i];
86
- const progress = Math.round(((i + 1) / files.length) * 100);
87
- const bar = renderProgressBar(progress);
88
- // Clear line and print progress
89
- process.stdout.write(`\r${bar} ${chalk.cyan(`${i + 1}/${files.length}`)} ${chalk.dim(file.split(/[/\\]/).pop() || '')}`);
90
- try {
91
- const content = await fs.readFile(file, 'utf-8');
92
- const lines = content.split('\n');
93
- summary.totalLines += lines.length;
94
- summary.successfulParses++;
95
- // Simple heuristics for demo
96
- if (content.includes('function '))
97
- summary.totalFunctions++;
98
- if (content.includes('class '))
99
- summary.totalClasses++;
100
- // Find potential issues
101
- if (content.includes('eval(')) {
102
- findings.push({
103
- file: path.relative(targetPath, file),
104
- type: 'security',
105
- severity: 'high',
106
- message: 'Use of eval() detected',
107
- });
108
- }
109
- if (content.includes('console.log')) {
110
- findings.push({
111
- file: path.relative(targetPath, file),
112
- type: 'maintainability',
113
- severity: 'low',
114
- message: 'Console.log statement found',
115
- });
116
- }
117
- }
118
- catch (error) {
119
- summary.failedParses++;
120
- summary.errors.push({
121
- file: path.relative(targetPath, file),
122
- error: error instanceof Error ? error.message : String(error),
123
- });
124
- }
125
- }
126
- // Clear progress line
127
- process.stdout.write('\r' + ' '.repeat(80) + '\r');
128
- console.log(`${icons.check} Analysis complete: ${chalk.green(`${summary.successfulParses} successful`)}, ${summary.failedParses > 0 ? chalk.red(`${summary.failedParses} failed`) : ''}`);
129
- console.log();
130
- summary.totalDuration = Date.now() - startTime;
131
- // Build report
132
- const report = {
133
- schema_version: '1.0',
134
- engine_version: '0.5.0',
135
- created_at: new Date().toISOString(),
136
- project: {
137
- name: options.projectName || path.basename(targetPath),
138
- root_fingerprint: '',
139
- path: targetPath,
140
- },
141
- tools_used: [{ id: 'delta-core', version: '0.5.0', adapter_version: '0.5.0' }],
142
- summary: {
143
- total: findings.length,
144
- high: findings.filter(f => f.severity === 'high').length,
145
- medium: findings.filter(f => f.severity === 'medium').length,
146
- low: findings.filter(f => f.severity === 'low').length,
147
- },
148
- findings,
149
- metadata: summary,
150
- };
151
- // Phase 3: Results Display
152
- printDivider();
153
- printSuccess('Analysis Complete');
154
- console.log();
155
- // Summary table
156
- const summaryTable = createTable(['Metric', 'Value']);
157
- summaryTable.push([icons.folder + ' Files Analyzed', summary.totalFiles.toString()], [icons.chart + ' Total Lines', summary.totalLines.toLocaleString()], [icons.gear + ' Functions Found', summary.totalFunctions.toString()], [icons.package + ' Classes Found', summary.totalClasses.toString()], [icons.loading + ' Duration', formatDuration(summary.totalDuration)]);
158
- console.log(summaryTable.toString());
159
- console.log();
160
- // Findings summary
161
- if (findings.length > 0) {
162
- printWarning(`Found ${findings.length} issues:`);
163
- const issuesTable = createTable(['Severity', 'Count']);
164
- const highCount = findings.filter(f => f.severity === 'high').length;
165
- const mediumCount = findings.filter(f => f.severity === 'medium').length;
166
- const lowCount = findings.filter(f => f.severity === 'low').length;
167
- if (highCount > 0)
168
- issuesTable.push([chalk.red('🔴 High'), highCount.toString()]);
169
- if (mediumCount > 0)
170
- issuesTable.push([chalk.yellow('🟡 Medium'), mediumCount.toString()]);
171
- if (lowCount > 0)
172
- issuesTable.push([chalk.blue('🔵 Low'), lowCount.toString()]);
173
- console.log(issuesTable.toString());
174
- }
175
- else {
176
- printSuccess('✨ No issues found! Great job!');
177
- }
178
- console.log();
179
- // Save report to file ONLY if not uploading
180
- if (!options.upload) {
181
- const outputDir = path.resolve(options.output);
182
- await fs.mkdir(outputDir, { recursive: true });
183
- const reportFile = path.join(outputDir, `report-${Date.now()}.json`);
184
- await fs.writeFile(reportFile, JSON.stringify(report, null, 2));
185
- printInfo(`${icons.chart} Report saved: ${chalk.cyan(reportFile)}`);
186
- console.log();
187
- }
188
- else {
189
- printInfo(`${icons.chart} Report will be available on Delta Cloud Dashboard`);
190
- console.log();
191
- }
192
- // Upload to cloud if requested
193
- if (options.upload) {
194
- console.log(`${icons.rocket} Uploading to Delta Cloud...`);
195
- await uploadReport(report);
196
- }
197
- process.exit(0);
198
- }
199
- async function uploadReport(report) {
200
- const config = await loadConfig();
201
- // Get PAT from secure keychain storage, NOT from config file
202
- const pat = await SecureTokenStore.getAccessToken();
203
- if (!pat) {
204
- console.error('❌ Error: Not authenticated. Run: delta login --token <pat>');
205
- process.exit(1);
206
- }
207
- const apiUrl = process.env.DELTA_API_URL || config.apiUrl || 'http://localhost:3000';
208
- const reportJson = JSON.stringify(report);
209
- const reportHash = crypto.createHash('sha256').update(reportJson).digest('hex');
210
- try {
211
- // Step 1: Init upload session
212
- const initResponse = await fetch(`${apiUrl}/api/upload/init`, {
213
- method: 'POST',
214
- headers: {
215
- Authorization: `Bearer ${pat}`,
216
- 'Content-Type': 'application/json',
217
- 'Idempotency-Key': crypto.randomUUID(),
218
- },
219
- body: JSON.stringify({
220
- schemaVersion: '1.0',
221
- engineVersion: '0.5.0',
222
- reportHash: reportHash,
223
- reportSizeBytes: Buffer.byteLength(reportJson),
224
- toolsUsed: [{ id: 'delta-core', version: '0.5.0', adapterVersion: '0.5.0' }],
225
- }),
226
- });
227
- if (!initResponse.ok) {
228
- let payload = undefined;
229
- try {
230
- payload = await initResponse.json();
231
- }
232
- catch {
233
- payload = await initResponse.text().catch(() => undefined);
234
- }
235
- const apiError = extractApiErrorPayload(payload);
236
- const details = apiError.details ? `\nDetails: ${JSON.stringify(apiError.details)}` : '';
237
- const message = apiError.message || `Init failed: ${initResponse.status}`;
238
- throw new Error(message + details);
239
- }
240
- const initData = (await initResponse.json());
241
- if (!initData.success) {
242
- throw new Error(initData.error?.message || 'Upload init failed');
243
- }
244
- const uploadId = initData.data.uploadId;
245
- const secret = initData.data.signing.secret;
246
- console.log(` Upload session: ${uploadId}`);
247
- // Step 2: Sign and upload report
248
- const signature = crypto.createHmac('sha256', secret).update(reportJson).digest('hex');
249
- const uploadResponse = await fetch(`${apiUrl}/api/upload/${uploadId}`, {
250
- method: 'PUT',
251
- headers: {
252
- Authorization: `Bearer ${pat}`,
253
- 'Content-Type': 'application/json',
254
- },
255
- body: JSON.stringify({
256
- report: Object.assign({}, report, {
257
- integrity: {
258
- report_hash: reportHash,
259
- signature: signature,
260
- algorithm: 'HMAC-SHA256',
261
- },
262
- }),
263
- }),
264
- });
265
- if (!uploadResponse.ok) {
266
- let payload = undefined;
267
- try {
268
- payload = await uploadResponse.json();
269
- }
270
- catch {
271
- payload = await uploadResponse.text().catch(() => undefined);
272
- }
273
- const apiError = extractApiErrorPayload(payload);
274
- const details = apiError.details ? `\nDetails: ${JSON.stringify(apiError.details)}` : '';
275
- const message = apiError.message || `Upload failed: ${uploadResponse.status}`;
276
- throw new Error(message + details);
277
- }
278
- console.log(' Report uploaded');
279
- // Step 3: Finalize
280
- const finalizeResponse = await fetch(`${apiUrl}/api/upload/${uploadId}/finalize`, {
281
- method: 'POST',
282
- headers: {
283
- Authorization: `Bearer ${pat}`,
284
- 'Content-Type': 'application/json',
285
- 'Idempotency-Key': crypto.randomUUID(),
286
- },
287
- body: '{}',
288
- });
289
- if (!finalizeResponse.ok) {
290
- let payload = undefined;
291
- try {
292
- payload = await finalizeResponse.json();
293
- }
294
- catch {
295
- payload = await finalizeResponse.text().catch(() => undefined);
296
- }
297
- const apiError = extractApiErrorPayload(payload);
298
- const details = apiError.details ? `\nDetails: ${JSON.stringify(apiError.details)}` : '';
299
- const message = apiError.message || `Finalize failed: ${finalizeResponse.status}`;
300
- throw new Error(message + details);
301
- }
302
- const finalizeData = (await finalizeResponse.json());
303
- if (!finalizeData.success) {
304
- throw new Error(finalizeData.error?.message || 'Upload finalize failed');
305
- }
306
- console.log(`✅ Report finalized: ${finalizeData.data.reportId}`);
307
- console.log(` Quota updated`);
308
- }
309
- catch (error) {
310
- console.error('❌ Upload failed:', error instanceof Error ? error.message : String(error));
311
- process.exit(1);
312
- }
313
- }
314
- async function discoverFiles(rootPath, options) {
315
- const files = [];
316
- async function walk(dir) {
317
- const entries = await fs.readdir(dir, { withFileTypes: true });
318
- for (const entry of entries) {
319
- const fullPath = path.join(dir, entry.name);
320
- if (entry.isDirectory()) {
321
- // Skip excluded directories
322
- if (options.exclude.some(e => entry.name.includes(e)))
323
- continue;
324
- await walk(fullPath);
325
- }
326
- else if (entry.isFile()) {
327
- // Check include patterns - support glob patterns like **/*.{ts,tsx}
328
- const shouldInclude = options.include.some(pattern => {
329
- // Handle brace expansion: **/*.{ts,tsx} → match **/*.ts or **/*.tsx
330
- if (pattern.includes('{') && pattern.includes('}')) {
331
- const braceMatch = pattern.match(/\{([^}]+)\}/);
332
- if (braceMatch) {
333
- const extensions = braceMatch[1].split(',');
334
- const basePattern = pattern.replace(/\{[^}]+\}/, '');
335
- return extensions.some(ext => {
336
- const fullPattern = basePattern + ext;
337
- return matchGlob(fullPath, fullPattern);
338
- });
339
- }
340
- }
341
- return matchGlob(fullPath, pattern);
342
- });
343
- if (shouldInclude) {
344
- // Check file size
345
- try {
346
- const stats = await fs.stat(fullPath);
347
- if (stats.size <= options.maxSize) {
348
- files.push(fullPath);
349
- }
350
- }
351
- catch {
352
- // Skip files we can't stat
353
- }
354
- }
355
- }
356
- }
357
- }
358
- await walk(rootPath);
359
- return files;
360
- }
361
- function matchGlob(filePath, pattern) {
362
- // Convert glob pattern to regex
363
- // **/*.ts → matches any .ts file in any directory
364
- // *.ts → matches .ts files in current directory
365
- const fileName = filePath.split(/[/\\]/).pop() || '';
366
- if (pattern.includes('**')) {
367
- // Match any directory depth
368
- const ext = pattern.replace('**/*', '');
369
- return fileName.endsWith(ext);
370
- }
371
- else if (pattern.includes('*')) {
372
- // Simple wildcard
373
- const ext = pattern.replace('*', '');
374
- return fileName.endsWith(ext);
375
- }
376
- // Exact match
377
- return filePath.includes(pattern);
378
- }
379
- function renderProgressBar(percentage) {
380
- const width = 20;
381
- const filled = Math.round((percentage / 100) * width);
382
- const empty = width - filled;
383
- const filledBar = chalk.cyan('█'.repeat(filled));
384
- const emptyBar = chalk.gray('░'.repeat(empty));
385
- return `${filledBar}${emptyBar} ${chalk.bold(`${percentage}%`)}`;
386
- }
387
- // Helper to format duration
388
- function formatDuration(ms) {
389
- if (ms < 1000)
390
- return `${ms}ms`;
391
- return `${(ms / 1000).toFixed(2)}s`;
392
- }
393
- //# sourceMappingURL=analyze.js.map
@@ -1,37 +0,0 @@
1
- import chalk from 'chalk';
2
- import { startOAuthFlow, authenticateWithPAT, SecureTokenStore } from '../auth/secure-auth.js';
3
- import { printSuccess, printInfo } from '../ui.js';
4
- import prompts from 'prompts';
5
- export async function loginCommand(options) {
6
- // Check if already authenticated
7
- if (await SecureTokenStore.hasTokens()) {
8
- const overwrite = await prompts({
9
- type: 'confirm',
10
- name: 'value',
11
- message: chalk.yellow('Already authenticated. Overwrite existing credentials?'),
12
- initial: false,
13
- });
14
- if (!overwrite.value) {
15
- printInfo('Login cancelled');
16
- return;
17
- }
18
- }
19
- if (options.token) {
20
- // PAT authentication
21
- await authenticateWithPAT(options.token);
22
- }
23
- else {
24
- // OAuth2 flow
25
- const method = options.method || 'oauth';
26
- const success = await startOAuthFlow(method);
27
- if (success) {
28
- printSuccess('You are now logged in!');
29
- printInfo('Run "delta whoami" to see your account info');
30
- }
31
- }
32
- }
33
- export async function logoutCommand() {
34
- const { logout } = await import('../auth/secure-auth.js');
35
- await logout();
36
- }
37
- //# sourceMappingURL=auth-new.js.map
@@ -1,131 +0,0 @@
1
- /**
2
- * Enhanced Auth Commands - Professional CLI with interactive prompts
3
- */
4
- import * as fs from 'fs/promises';
5
- import * as path from 'path';
6
- import * as os from 'os';
7
- import { icons, startSpinner, stopSpinner, printHeader, printSection, printSuccess, printError, printInfo, printKeyValue, printCommandHint, createTable, printWelcome, } from '../ui.js';
8
- import { SecureTokenStore } from '../auth/secure-auth.js';
9
- import { startDeviceFlow } from '../auth/device-auth.js';
10
- const CONFIG_DIR = path.join(os.homedir(), '.delta');
11
- const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
12
- async function loadConfig() {
13
- try {
14
- const data = await fs.readFile(CONFIG_FILE, 'utf-8');
15
- return JSON.parse(data);
16
- }
17
- catch {
18
- return {};
19
- }
20
- }
21
- async function saveConfig(config) {
22
- await fs.mkdir(CONFIG_DIR, { recursive: true });
23
- await fs.writeFile(CONFIG_FILE, JSON.stringify(config, null, 2));
24
- }
25
- export const authCommands = {
26
- async login(options) {
27
- printWelcome();
28
- printHeader('Authentication');
29
- const token = options.token ?? process.env.DELTA_PAT;
30
- // Load existing config to get custom apiUrl if set
31
- const existingConfig = await loadConfig();
32
- const apiUrl = process.env.DELTA_API_URL || existingConfig.apiUrl || 'http://localhost:3000';
33
- // If no token provided, use Device Authorization Flow
34
- if (!token) {
35
- printInfo('No token provided. Starting Device Authorization Flow...');
36
- printInfo('This will open your browser for secure authentication.');
37
- console.log();
38
- const success = await startDeviceFlow(apiUrl);
39
- if (!success) {
40
- printError('Device authorization failed');
41
- console.log();
42
- printInfo('You can also authenticate using a Personal Access Token:');
43
- printCommandHint('delta login --token <your-token>', '');
44
- process.exit(1);
45
- }
46
- // Device flow already saved the token and showed success
47
- process.exit(0);
48
- }
49
- // PAT Token flow (when token is provided)
50
- // Validate token format
51
- if (!token.startsWith('delta_pat_')) {
52
- printError('Invalid PAT token format', 'Token should start with "delta_pat_"');
53
- console.log();
54
- printInfo('You can get your PAT from:');
55
- printCommandHint('http://localhost:3000/dashboard/cli-tokens', '');
56
- process.exit(1);
57
- }
58
- printSection('Connecting to Platform');
59
- printKeyValue('API Endpoint', apiUrl);
60
- console.log();
61
- startSpinner('Verifying credentials...');
62
- try {
63
- const controller = new AbortController();
64
- const timeout = setTimeout(() => controller.abort(), 10000);
65
- const response = await fetch(`${apiUrl}/api/me/entitlements`, {
66
- headers: {
67
- Authorization: `Bearer ${token}`,
68
- 'Content-Type': 'application/json',
69
- },
70
- signal: controller.signal,
71
- });
72
- clearTimeout(timeout);
73
- if (!response.ok) {
74
- const errorText = await response.text().catch(() => response.statusText);
75
- throw new Error(`HTTP ${response.status}: ${errorText}`);
76
- }
77
- const data = (await response.json());
78
- if (!data.success) {
79
- throw new Error(data.error?.message || 'Authentication failed');
80
- }
81
- // Save config - store PAT securely in keychain, NOT in config file
82
- await SecureTokenStore.saveAccessToken(token);
83
- // Save only non-sensitive config
84
- await saveConfig({
85
- apiUrl,
86
- lastUsedAt: new Date().toISOString(),
87
- });
88
- stopSpinner(true, 'Authentication successful!');
89
- console.log();
90
- const user = data.data.user;
91
- const quota = data.data.quota;
92
- printHeader('Account Overview');
93
- // User info table
94
- const userTable = createTable(['Property', 'Value']);
95
- userTable.push([icons.user + ' Email', user.email], [icons.package + ' Plan', user.plan], [icons.chart + ' Quota Used', `${quota.used}/${quota.limit} reports`], [icons.lock + ' Config', CONFIG_FILE]);
96
- console.log(userTable.toString());
97
- console.log();
98
- printSuccess(`Welcome back, ${user.email.split('@')[0]}! 🎉`);
99
- console.log();
100
- printCommandHint('delta whoami', 'to see full account details');
101
- printCommandHint('delta analyze', 'to start analyzing code');
102
- process.exit(0);
103
- }
104
- catch (error) {
105
- stopSpinner(false, 'Authentication failed');
106
- console.log();
107
- if (error instanceof Error && error.name === 'AbortError') {
108
- printError('Request timeout (10s)', 'Check if the server is running and accessible');
109
- }
110
- else {
111
- const message = error instanceof Error ? error.message : String(error);
112
- if (message.includes('401')) {
113
- printError('Invalid or expired token', 'Generate a new token from the web app');
114
- }
115
- else if (message.includes('ENOTFOUND') || message.includes('ECONNREFUSED')) {
116
- printError('Cannot connect to server', 'Check your internet connection and API URL');
117
- }
118
- else {
119
- printError(message);
120
- }
121
- }
122
- console.log();
123
- printInfo('Need help? Visit: http://localhost:3000/docs/cli/authentication');
124
- process.exit(1);
125
- }
126
- },
127
- };
128
- // Export individual commands for direct import
129
- export const loginCommand = authCommands.login;
130
- export { loadConfig, saveConfig, CONFIG_FILE };
131
- //# sourceMappingURL=auth.js.map
@@ -1,51 +0,0 @@
1
- /**
2
- * Config Command - Manage CLI configuration
3
- */
4
- import { loadConfig, saveConfig, CONFIG_FILE } from './auth.js';
5
- import { SecureTokenStore } from '../auth/secure-auth.js';
6
- export async function configCommand(options) {
7
- const config = await loadConfig();
8
- if (options.get) {
9
- const value = config[options.get];
10
- if (value !== undefined) {
11
- console.log(`${options.get}: ${value}`);
12
- }
13
- else {
14
- console.log(`${options.get}: (not set)`);
15
- }
16
- process.exit(0);
17
- }
18
- if (options.set) {
19
- const [key, value] = options.set.split('=');
20
- if (!key || value === undefined) {
21
- console.error('❌ Error: Invalid format. Use: key=value');
22
- process.exit(1);
23
- }
24
- const newConfig = {
25
- ...config,
26
- apiUrl: config.apiUrl || 'http://localhost:3000',
27
- [key]: value,
28
- };
29
- await saveConfig(newConfig);
30
- console.log(`✅ Set ${key} = ${value}`);
31
- process.exit(0);
32
- }
33
- if (options.list || (!options.get && !options.set)) {
34
- console.log('🔧 Delta CLI Configuration');
35
- console.log(` Config file: ${CONFIG_FILE}`);
36
- console.log();
37
- const hasPat = await SecureTokenStore.hasTokens();
38
- if (hasPat) {
39
- console.log(' PAT: ✅ Set (securely stored in keychain)');
40
- }
41
- else {
42
- console.log(' PAT: ❌ Not set');
43
- }
44
- console.log(` API URL: ${config.apiUrl || 'http://localhost:3000 (default)'}`);
45
- if (config.lastUsedAt) {
46
- console.log(` Last used: ${new Date(config.lastUsedAt).toLocaleString()}`);
47
- }
48
- process.exit(0);
49
- }
50
- }
51
- //# sourceMappingURL=config.js.map
@@ -1,6 +0,0 @@
1
- import { printSuccess, printInfo } from '../ui.js';
2
- export async function deployCommand(_options) {
3
- printInfo('Deploying documentation site...');
4
- printSuccess('Deploy completed successfully');
5
- }
6
- //# sourceMappingURL=deploy.js.map
@@ -1,47 +0,0 @@
1
- /**
2
- * Init Command - Initialize a new Delta project
3
- */
4
- import * as fs from 'fs/promises';
5
- import * as path from 'path';
6
- export async function initCommand(projectPath, options) {
7
- const targetPath = path.resolve(projectPath);
8
- const configPath = path.join(targetPath, 'delta.config.json');
9
- try {
10
- // Check if directory exists
11
- await fs.access(targetPath);
12
- }
13
- catch {
14
- console.log(`📁 Creating directory: ${targetPath}`);
15
- await fs.mkdir(targetPath, { recursive: true });
16
- }
17
- // Check if config already exists
18
- try {
19
- await fs.access(configPath);
20
- if (!options.force) {
21
- console.log('⚠️ Delta config already exists');
22
- console.log(' Use --force to overwrite');
23
- return;
24
- }
25
- }
26
- catch {
27
- // Config doesn't exist, continue
28
- }
29
- // Create default config
30
- const config = {
31
- name: path.basename(targetPath),
32
- version: '1.0.0',
33
- template: options.template || 'default',
34
- createdAt: new Date().toISOString(),
35
- settings: {
36
- include: ['src/**/*'],
37
- exclude: ['node_modules', 'dist', '.git'],
38
- maxFileSize: 10485760,
39
- },
40
- };
41
- await fs.writeFile(configPath, JSON.stringify(config, null, 2));
42
- console.log('✅ Project initialized');
43
- console.log(` Path: ${targetPath}`);
44
- console.log(` Config: ${configPath}`);
45
- console.log(` Template: ${config.template}`);
46
- }
47
- //# sourceMappingURL=init.js.map