@vee-stack/delta-cli 2.0.4 → 2.0.6

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