vibecodingmachine-cli 2025.12.6-1702 → 2025.12.24-2348

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/utils/auth.js CHANGED
@@ -2,7 +2,6 @@ const chalk = require('chalk');
2
2
  const http = require('http');
3
3
  const crypto = require('crypto');
4
4
  const fs = require('fs');
5
- const path = require('path');
6
5
  const net = require('net');
7
6
  const sharedAuth = require('vibecodingmachine-core/src/auth/shared-auth-storage');
8
7
 
@@ -33,7 +32,11 @@ class CLIAuth {
33
32
  async isAuthenticated() {
34
33
  // First check if current token is valid
35
34
  const isValid = await sharedAuth.isAuthenticated();
36
- if (isValid) return true;
35
+ if (isValid) {
36
+ // Update user activity in database
37
+ await this._updateUserActivity();
38
+ return true;
39
+ }
37
40
 
38
41
  // If not valid, try to refresh
39
42
  try {
@@ -47,6 +50,9 @@ class CLIAuth {
47
50
 
48
51
  // Save new tokens
49
52
  await sharedAuth.saveToken(newTokens);
53
+
54
+ // Update user activity in database
55
+ await this._updateUserActivity();
50
56
  return true;
51
57
  }
52
58
  } catch (error) {
@@ -398,6 +404,9 @@ class CLIAuth {
398
404
  // Save token
399
405
  await sharedAuth.saveToken(tokens);
400
406
 
407
+ // Register/update user in enhanced database
408
+ await this._registerUserInDatabase(idToken);
409
+
401
410
  // Show success page
402
411
  res.writeHead(200, {
403
412
  'Content-Type': 'text/html',
@@ -656,6 +665,9 @@ class CLIAuth {
656
665
  // Save token using shared storage (only if validation passed)
657
666
  await sharedAuth.saveToken(tokens);
658
667
 
668
+ // Register/update user in enhanced database
669
+ await this._registerUserInDatabase(idToken);
670
+
659
671
  console.log(chalk.green('\n✓ Authentication successful!'));
660
672
  return idToken;
661
673
  } catch (error) {
@@ -691,6 +703,141 @@ class CLIAuth {
691
703
  async activateLicense(licenseKey) {
692
704
  return await sharedAuth.activateLicense(licenseKey);
693
705
  }
706
+
707
+ /**
708
+ * Register or update user in enhanced database system
709
+ */
710
+ async _registerUserInDatabase(idToken) {
711
+ try {
712
+ // Decode JWT to get user info (without verification since we already validated)
713
+ const payload = JSON.parse(Buffer.from(idToken.split('.')[1], 'base64').toString());
714
+
715
+ const UserDatabase = require('vibecodingmachine-core/src/database/user-schema');
716
+ const userDb = new UserDatabase();
717
+
718
+ const userInfo = {
719
+ email: payload.email,
720
+ name: payload.name || payload.email.split('@')[0],
721
+ cognitoId: payload.sub
722
+ };
723
+
724
+ // Register/update user
725
+ const user = await userDb.registerUser(userInfo);
726
+
727
+ // Register computer
728
+ await userDb.registerComputer(user.userId, {
729
+ interface: 'cli'
730
+ });
731
+
732
+ // Track login activity
733
+ await userDb.trackActivity(user.userId, {
734
+ interface: 'cli',
735
+ action: 'login',
736
+ duration: 0,
737
+ metadata: {
738
+ authMethod: 'cognito',
739
+ timestamp: Date.now()
740
+ }
741
+ });
742
+
743
+ } catch (error) {
744
+ // Don't fail authentication if database registration fails
745
+ console.error('Warning: Failed to register user in database:', error.message);
746
+ }
747
+ }
748
+
749
+ /**
750
+ * Update user activity in database
751
+ */
752
+ async _updateUserActivity() {
753
+ try {
754
+ const token = await sharedAuth.getToken();
755
+ if (!token || !token.id_token) return;
756
+
757
+ // Decode JWT to get user info
758
+ const payload = JSON.parse(Buffer.from(token.id_token.split('.')[1], 'base64').toString());
759
+
760
+ const UserDatabase = require('vibecodingmachine-core/src/database/user-schema');
761
+ const userDb = new UserDatabase();
762
+
763
+ const userId = userDb.generateUserId(payload.email);
764
+
765
+ // Update last activity
766
+ await userDb.updateUserActivity(userId, {
767
+ lastActivity: Date.now()
768
+ });
769
+
770
+ } catch (error) {
771
+ // Silently fail - don't disrupt user experience
772
+ console.error('Warning: Failed to update user activity:', error.message);
773
+ }
774
+ }
775
+
776
+ /**
777
+ * Track CLI usage activity
778
+ */
779
+ async trackCLIActivity(action, metadata = {}) {
780
+ try {
781
+ const token = await sharedAuth.getToken();
782
+ if (!token) return;
783
+
784
+ // Handle both string tokens and object tokens with id_token property
785
+ const idToken = typeof token === 'string' ? token : token.id_token;
786
+ if (!idToken) return;
787
+
788
+ const payload = JSON.parse(Buffer.from(idToken.split('.')[1], 'base64').toString());
789
+
790
+ const UserDatabase = require('vibecodingmachine-core/src/database/user-schema');
791
+ const userDb = new UserDatabase();
792
+
793
+ const userId = userDb.generateUserId(payload.email);
794
+
795
+ await userDb.trackActivity(userId, {
796
+ interface: 'cli',
797
+ action,
798
+ duration: metadata.duration || 0,
799
+ metadata: {
800
+ ...metadata,
801
+ timestamp: Date.now()
802
+ }
803
+ });
804
+
805
+ } catch (error) {
806
+ // Silently fail - don't disrupt user experience
807
+ console.error('Warning: Failed to track CLI activity:', error.message);
808
+ }
809
+ }
810
+
811
+ /**
812
+ * Get current user information
813
+ */
814
+ async getCurrentUser() {
815
+ try {
816
+ const token = await sharedAuth.getToken();
817
+ if (!token) return null;
818
+
819
+ // Handle both string token and object with id_token
820
+ const idToken = typeof token === 'string' ? token : token.id_token;
821
+ if (!idToken) return null;
822
+
823
+ const payload = JSON.parse(Buffer.from(idToken.split('.')[1], 'base64').toString());
824
+
825
+ const UserDatabase = require('vibecodingmachine-core/src/database/user-schema');
826
+ const userDb = new UserDatabase();
827
+
828
+ const userId = userDb.generateUserId(payload.email);
829
+
830
+ return {
831
+ userId,
832
+ email: payload.email,
833
+ name: payload.name || payload.email.split('@')[0],
834
+ cognitoId: payload.sub
835
+ };
836
+ } catch (error) {
837
+ console.error('Error getting current user:', error.message);
838
+ return null;
839
+ }
840
+ }
694
841
  }
695
842
 
696
843
  module.exports = new CLIAuth();
@@ -1,6 +1,5 @@
1
1
  const chalk = require('chalk');
2
2
  const ansiEscapes = require('ansi-escapes');
3
- const stripAnsi = require('strip-ansi');
4
3
 
5
4
  /**
6
5
  * ANSI-based UI for Auto Mode
@@ -79,7 +79,7 @@ class AutoModeSimpleUI {
79
79
  { name: 'DONE', color: chalk.green }
80
80
  ];
81
81
 
82
- const workflowLine = stages.map((stage, index) => {
82
+ const workflowLine = stages.map((stage, _index) => {
83
83
  const icon = this.getStepIcon(stage.name, this.step);
84
84
  const isCurrent = stage.name === this.step;
85
85
  const stageColor = isCurrent ? currentStepColor.bold : stage.color;
@@ -0,0 +1,166 @@
1
+ /**
2
+ * CLI Compliance Check Utility
3
+ *
4
+ * Checks and prompts for compliance on CLI startup
5
+ */
6
+
7
+ let CompliancePrompt
8
+ try {
9
+ CompliancePrompt = require('vibecodingmachine-core/src/compliance/compliance-prompt')
10
+ } catch (e) {
11
+ // If core package isn't installed (local dev), gracefully skip compliance by returning true
12
+ CompliancePrompt = null
13
+ }
14
+ const auth = require('./auth')
15
+
16
+ async function checkCompliance() {
17
+ try {
18
+ // First check if user is authenticated
19
+ const isAuth = await auth.isAuthenticated()
20
+ if (!isAuth) {
21
+ // User not authenticated, skip compliance check (will be checked after login)
22
+ return true
23
+ }
24
+
25
+ // Get current user
26
+ const user = await auth.getCurrentUser()
27
+
28
+ if (!user || !user.userId) {
29
+ // If we can't get user info but they're authenticated, something is wrong
30
+ // But don't block them - they can still use the app
31
+ console.warn('Warning: Unable to verify compliance status')
32
+ return true
33
+ }
34
+
35
+ // If CompliancePrompt is not available (dev environment), skip compliance checks
36
+ if (!CompliancePrompt) {
37
+ if (process.env.DEBUG) console.log('Compliance checks skipped: vibecodingmachine-core not available')
38
+ return true
39
+ }
40
+
41
+ // Check and prompt for compliance
42
+ const compliancePrompt = new CompliancePrompt()
43
+ const status = await compliancePrompt.complianceManager.checkComplianceStatus(user.userId)
44
+
45
+ if (!status.needsAcknowledgment) {
46
+ return true
47
+ }
48
+
49
+ // Handle CLI prompting locally
50
+ const isCompliant = await promptCLI(user.userId, status, compliancePrompt)
51
+ return isCompliant
52
+ } catch (error) {
53
+ // Log error but don't block user
54
+ console.error('Error checking compliance:', error.message)
55
+ if (process.env.DEBUG) {
56
+ console.error(error.stack)
57
+ }
58
+ // Return true to not block the user if there's a system error
59
+ return true
60
+ }
61
+ }
62
+
63
+ /**
64
+ * CLI prompt for compliance
65
+ */
66
+ async function promptCLI(userId, status, compliancePrompt) {
67
+ const chalk = require('chalk')
68
+ const inquirer = require('inquirer')
69
+
70
+ console.log(chalk.cyan('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'))
71
+ console.log(chalk.cyan.bold(' 📋 Terms & Privacy Acknowledgment Required'))
72
+ console.log(chalk.cyan('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n'))
73
+
74
+ console.log(chalk.white('Before continuing, please review and accept:\n'))
75
+
76
+ const questions = []
77
+
78
+ if (status.requiredActions.includes('terms')) {
79
+ const terms = await compliancePrompt.complianceManager.getTermsOfService()
80
+
81
+ console.log(chalk.yellow('📄 Terms of Service'))
82
+ console.log(chalk.gray('─'.repeat(70)))
83
+ console.log(formatForCLI(terms.content))
84
+ console.log(chalk.gray('─'.repeat(70)))
85
+ console.log(chalk.gray(`Version ${terms.version} | Effective: ${terms.effectiveDate}\n`))
86
+
87
+ questions.push({
88
+ type: 'confirm',
89
+ name: 'acceptTerms',
90
+ message: 'Do you accept the Terms of Service?',
91
+ default: false
92
+ })
93
+ }
94
+
95
+ if (status.requiredActions.includes('privacy')) {
96
+ const privacy = await compliancePrompt.complianceManager.getPrivacyPolicy()
97
+
98
+ console.log(chalk.yellow('🔒 Privacy Policy'))
99
+ console.log(chalk.gray('─'.repeat(70)))
100
+ console.log(formatForCLI(privacy.content))
101
+ console.log(chalk.gray('─'.repeat(70)))
102
+ console.log(chalk.gray(`Version ${privacy.version} | Effective: ${privacy.effectiveDate}\n`))
103
+
104
+ questions.push({
105
+ type: 'confirm',
106
+ name: 'acceptPrivacy',
107
+ message: 'Do you accept the Privacy Policy?',
108
+ default: false
109
+ })
110
+ }
111
+
112
+ const answers = await inquirer.prompt(questions)
113
+
114
+ // Check if user accepted all required items
115
+ const allAccepted =
116
+ (!status.requiredActions.includes('terms') || answers.acceptTerms) &&
117
+ (!status.requiredActions.includes('privacy') || answers.acceptPrivacy)
118
+
119
+ if (!allAccepted) {
120
+ console.log(chalk.red('\n❌ You must accept the Terms and Privacy Policy to use VibeCodingMachine.\n'))
121
+ return false
122
+ }
123
+
124
+ // Record acceptance
125
+ await compliancePrompt.complianceManager.recordAcknowledgment(userId, {
126
+ terms: answers.acceptTerms || undefined,
127
+ privacy: answers.acceptPrivacy || undefined
128
+ })
129
+
130
+ console.log(chalk.green('\n✅ Thank you! Your acceptance has been recorded.\n'))
131
+ return true
132
+ }
133
+
134
+ /**
135
+ * Format markdown content for CLI display
136
+ */
137
+ function formatForCLI(content) {
138
+ // Simple markdown formatting for terminal
139
+ return content
140
+ .split('\n')
141
+ .map(line => {
142
+ // Headers
143
+ if (line.startsWith('# ')) {
144
+ return ' ' + line.substring(2).toUpperCase()
145
+ }
146
+ if (line.startsWith('## ')) {
147
+ return ' ' + line.substring(3)
148
+ }
149
+ // Bold
150
+ line = line.replace(/\*\*(.*?)\*\*/g, '$1')
151
+ // Lists
152
+ if (line.startsWith('- ')) {
153
+ return ' • ' + line.substring(2)
154
+ }
155
+ if (/^\d+\./.test(line)) {
156
+ return ' ' + line
157
+ }
158
+ // Regular text
159
+ return line ? ' ' + line : ''
160
+ })
161
+ .join('\n')
162
+ }
163
+
164
+ module.exports = {
165
+ checkCompliance
166
+ }
@@ -52,13 +52,39 @@ async function setAutoConfig(autoConfig) {
52
52
  await writeConfig(cfg);
53
53
  }
54
54
 
55
+ const DEFAULT_STAGES = Object.freeze([
56
+ 'PREPARE',
57
+ 'REPRODUCE',
58
+ 'CREATE UNIT TEST',
59
+ 'ACT',
60
+ 'CLEAN UP',
61
+ 'VERIFY',
62
+ 'RUN UNIT TESTS',
63
+ 'DONE'
64
+ ]);
65
+
66
+ async function getStages() {
67
+ const config = await getAutoConfig();
68
+ // Return a copy to prevent mutation of the internal array
69
+ return [...(config.stages || DEFAULT_STAGES)];
70
+ }
71
+
72
+ async function setStages(stages) {
73
+ const cfg = await readConfig();
74
+ cfg.auto = { ...(cfg.auto || {}), stages };
75
+ await writeConfig(cfg);
76
+ }
77
+
55
78
  module.exports = {
56
79
  getRepoPath,
57
80
  setRepoPath,
58
81
  getAutoConfig,
59
82
  setAutoConfig,
60
83
  readConfig,
61
- writeConfig
84
+ writeConfig,
85
+ getStages,
86
+ setStages,
87
+ DEFAULT_STAGES
62
88
  };
63
89
 
64
90
 
@@ -0,0 +1,167 @@
1
+ const { spawn, execSync } = require('child_process');
2
+ const fs = require('fs-extra');
3
+ const path = require('path');
4
+
5
+ function progressBar(percent, width) {
6
+ const fill = Math.round((percent / 100) * width);
7
+ return '█'.repeat(fill) + '-'.repeat(Math.max(0, width - fill));
8
+ }
9
+
10
+ function formatEta(sec) {
11
+ if (!isFinite(sec) || sec === null) return '--:--';
12
+ const s = Math.max(0, Math.round(sec));
13
+ const m = Math.floor(s / 60);
14
+ const ss = s % 60;
15
+ return `${m}:${ss.toString().padStart(2, '0')}`;
16
+ }
17
+
18
+ async function tryRsync(src, dest, spinner, timeoutMs = 5 * 60 * 1000) {
19
+ try {
20
+ execSync('which rsync', { stdio: 'ignore' });
21
+ } catch (e) {
22
+ return false;
23
+ }
24
+ // choose progress option based on rsync version
25
+ let rsyncArgs = ['-a'];
26
+ try {
27
+ const verOut = execSync('rsync --version', { encoding: 'utf8', timeout: 2000 });
28
+ const m = verOut.match(/version\s+(\d+)\.(\d+)/i);
29
+ if (m) {
30
+ const major = Number(m[1]);
31
+ const minor = Number(m[2] || 0);
32
+ if (major > 3 || (major === 3 && minor >= 1)) {
33
+ rsyncArgs.push('--info=progress2');
34
+ } else {
35
+ rsyncArgs.push('--progress');
36
+ }
37
+ } else {
38
+ rsyncArgs.push('--progress');
39
+ }
40
+ } catch (e) {
41
+ rsyncArgs.push('--progress');
42
+ }
43
+
44
+ return await new Promise((resolve) => {
45
+ const rsync = spawn('rsync', rsyncArgs.concat([src + '/', dest]), { stdio: 'inherit' });
46
+ let finished = false;
47
+ const to = setTimeout(() => {
48
+ if (!finished) {
49
+ try { rsync.kill('SIGINT'); } catch (e) { /* ignore */ }
50
+ resolve(false);
51
+ }
52
+ }, timeoutMs);
53
+ rsync.on('close', (code) => { finished = true; clearTimeout(to); resolve(code === 0); });
54
+ rsync.on('error', () => { finished = true; clearTimeout(to); resolve(false); });
55
+ });
56
+ }
57
+
58
+ async function tryDitto(src, dest, spinner, timeoutMs = 5 * 60 * 1000) {
59
+ try {
60
+ await fs.ensureDir(path.dirname(dest));
61
+ return await new Promise((resolve) => {
62
+ const ditto = spawn('ditto', ['-v', src, dest], { stdio: 'inherit' });
63
+ let finished = false;
64
+ const to = setTimeout(() => {
65
+ if (!finished) {
66
+ try { ditto.kill('SIGINT'); } catch (e) { /* ignore */ }
67
+ resolve(false);
68
+ }
69
+ }, timeoutMs);
70
+ ditto.on('close', (code) => { finished = true; clearTimeout(to); resolve(code === 0); });
71
+ ditto.on('error', () => { finished = true; clearTimeout(to); resolve(false); });
72
+ });
73
+ } catch (e) {
74
+ return false;
75
+ }
76
+ }
77
+
78
+ async function nodeStreamCopy(src, dest, _spinner) {
79
+ // Determine total size (attempt du -sk fallback to recursive stat)
80
+ let total = 0;
81
+ try {
82
+ const out = execSync(`du -sk "${src}" | cut -f1`, { encoding: 'utf8' }).trim();
83
+ total = Number(out) * 1024;
84
+ } catch (e) {
85
+ // fallback: sum file sizes via traversal
86
+ await (async function walk(p) {
87
+ const entries = await fs.readdir(p);
88
+ for (const e of entries) {
89
+ const full = path.join(p, e);
90
+ const stat = await fs.stat(full);
91
+ if (stat.isDirectory()) await walk(full);
92
+ else total += stat.size;
93
+ }
94
+ })(src);
95
+ }
96
+
97
+ let copied = 0;
98
+ const start = Date.now();
99
+ const width = 30;
100
+
101
+ async function copyEntry(srcPath, dstPath) {
102
+ const stat = await fs.stat(srcPath);
103
+ if (stat.isDirectory()) {
104
+ await fs.ensureDir(dstPath);
105
+ const entries = await fs.readdir(srcPath);
106
+ for (const e of entries) {
107
+ await copyEntry(path.join(srcPath, e), path.join(dstPath, e));
108
+ }
109
+ } else {
110
+ await fs.ensureDir(path.dirname(dstPath));
111
+ await new Promise((resolve, reject) => {
112
+ const rs = fs.createReadStream(srcPath);
113
+ const ws = fs.createWriteStream(dstPath);
114
+ rs.on('data', (chunk) => {
115
+ copied += chunk.length;
116
+ if (total) {
117
+ const percent = Math.round((copied / total) * 100);
118
+ const mbCopied = (copied / (1024 * 1024)).toFixed(1);
119
+ const mbTotal = (total / (1024 * 1024)).toFixed(1);
120
+ const elapsed = Math.max(0.001, (Date.now() - start) / 1000);
121
+ const speed = copied / elapsed;
122
+ const eta = formatEta((total - copied) / (speed || 1));
123
+ const bar = progressBar(percent, width);
124
+ process.stdout.write(`\r\x1b[2K[${bar}] ${percent}% ${mbCopied}MB / ${mbTotal}MB ETA: ${eta}`);
125
+ } else {
126
+ process.stdout.write(`\r\x1b[2KCopying ${ (copied/(1024*1024)).toFixed(1) } MB`);
127
+ }
128
+ });
129
+ rs.on('error', reject);
130
+ ws.on('error', reject);
131
+ ws.on('close', resolve);
132
+ rs.pipe(ws);
133
+ });
134
+ }
135
+ }
136
+
137
+ await copyEntry(src, dest);
138
+ process.stdout.write('\n');
139
+ return true;
140
+ }
141
+
142
+ async function copyAppWithProgress(src, dest, opts = {}) {
143
+ const spinner = (opts && opts.spinner) || { start: () => {}, stop: () => {}, fail: () => {}, succeed: () => {} };
144
+
145
+ // Try rsync first
146
+ spinner.stop && spinner.stop();
147
+ console.log(`Copying ${path.basename(src)} -> ${dest} (attempting rsync...)`);
148
+ const okRsync = await tryRsync(src, dest, spinner);
149
+ if (okRsync) return true;
150
+
151
+ // Try ditto (macOS)
152
+ console.log('rsync failed or not available — trying ditto...');
153
+ const okDitto = await tryDitto(src, dest, spinner);
154
+ if (okDitto) return true;
155
+
156
+ // Fallback to Node streaming copy with progress
157
+ console.log('Falling back to node-stream copy with progress...');
158
+ try {
159
+ await nodeStreamCopy(src, dest, spinner);
160
+ return true;
161
+ } catch (e) {
162
+ console.error('node-stream copy failed:', e.message || e);
163
+ return false;
164
+ }
165
+ }
166
+
167
+ module.exports = { copyAppWithProgress };
@@ -0,0 +1,84 @@
1
+ const fs = require('fs');
2
+ const ora = require('ora');
3
+
4
+ async function downloadWithProgress(url, dest, opts = {}) {
5
+ const fetch = require('node-fetch');
6
+ const spinner = opts.spinner || ora();
7
+ const label = opts.label || 'Downloading...';
8
+
9
+ spinner.start(label);
10
+
11
+ const res = await fetch(url);
12
+ if (!res.ok) {
13
+ spinner.fail(`Download failed: ${res.status} ${res.statusText}`);
14
+ throw new Error(`Failed to download ${url}: ${res.status}`);
15
+ }
16
+ // Stop the ora spinner so we can write an in-place progress line without conflicts
17
+ try { spinner.stop(); } catch (e) { /* ignore */ }
18
+ // Print initial progress line so user sees immediate feedback
19
+ try { process.stdout.write('\r\x1b[2KDownloading: 0.0 MB'); } catch (e) { /* ignore */ }
20
+
21
+ const total = Number(res.headers.get('content-length')) || 0;
22
+ const fileStream = fs.createWriteStream(dest);
23
+
24
+ return await new Promise((resolve, reject) => {
25
+ let downloaded = 0;
26
+ const start = Date.now();
27
+ let lastPercent = -1;
28
+
29
+ res.body.on('data', (chunk) => {
30
+ downloaded += chunk.length;
31
+ if (total) {
32
+ const percent = Math.round((downloaded / total) * 100);
33
+ if (percent !== lastPercent) {
34
+ lastPercent = percent;
35
+ const mbDownloaded = (downloaded / (1024 * 1024)).toFixed(1);
36
+ const mbTotal = (total / (1024 * 1024)).toFixed(1);
37
+ const elapsed = Math.max(0.001, (Date.now() - start) / 1000);
38
+ const speed = downloaded / elapsed; // bytes/sec
39
+ const etaSec = (total - downloaded) / (speed || 1);
40
+ const eta = formatEta(etaSec);
41
+ const bar = progressBar(percent, 30);
42
+ process.stdout.write(`\r\x1b[2K[${bar}] ${percent}% ${mbDownloaded}MB / ${mbTotal}MB ETA: ${eta}`);
43
+ }
44
+ } else {
45
+ const mbDownloaded = (downloaded / (1024 * 1024)).toFixed(1);
46
+ process.stdout.write(`\r\x1b[2K${label} ${mbDownloaded} MB`);
47
+ }
48
+ });
49
+
50
+ res.body.on('error', (err) => {
51
+ spinner.fail('Download error');
52
+ reject(err);
53
+ });
54
+
55
+ fileStream.on('error', (err) => {
56
+ spinner.fail('File write error');
57
+ reject(err);
58
+ });
59
+
60
+ fileStream.on('finish', () => {
61
+ process.stdout.write('\n');
62
+ spinner.succeed('Download complete');
63
+ resolve();
64
+ });
65
+
66
+ // Pipe the response body to file
67
+ res.body.pipe(fileStream);
68
+ });
69
+ }
70
+
71
+ function progressBar(percent, width) {
72
+ const fill = Math.round((percent / 100) * width);
73
+ return '█'.repeat(fill) + '-'.repeat(Math.max(0, width - fill));
74
+ }
75
+
76
+ function formatEta(sec) {
77
+ if (!isFinite(sec) || sec === null) return '--:--';
78
+ const s = Math.max(0, Math.round(sec));
79
+ const m = Math.floor(s / 60);
80
+ const ss = s % 60;
81
+ return `${m}:${ss.toString().padStart(2, '0')}`;
82
+ }
83
+
84
+ module.exports = { downloadWithProgress };