-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.js
More file actions
454 lines (390 loc) · 12.4 KB
/
setup.js
File metadata and controls
454 lines (390 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
#!/usr/bin/env node
/**
* 🚀 Project Installation & Verification Script
*
* This script ensures all dependencies are properly installed,
* verified, and documented in the virtual registry.
*
* Usage:
* node setup.js # Full setup
* node setup.js --verify-only # Check existing installation
* node setup.js --audit # Security audit
* node setup.js --clean-install # Fresh installation
*/
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
// Color codes for terminal output
const colors = {
reset: '\x1b[0m',
bright: '\x1b[1m',
dim: '\x1b[2m',
green: '\x1b[32m',
yellow: '\x1b[33m',
red: '\x1b[31m',
blue: '\x1b[34m',
cyan: '\x1b[36m',
};
// Logger class with colors
class Logger {
static log(message, color = 'reset') {
console.log(`${colors[color]}${message}${colors.reset}`);
}
static success(message) {
this.log(`✅ ${message}`, 'green');
}
static error(message) {
this.log(`❌ ${message}`, 'red');
}
static warning(message) {
this.log(`⚠️ ${message}`, 'yellow');
}
static info(message) {
this.log(`ℹ️ ${message}`, 'blue');
}
static section(message) {
console.log('');
this.log(`\n${'═'.repeat(60)}`, 'cyan');
this.log(` ${message}`, 'cyan');
this.log(`${'═'.repeat(60)}\n`, 'cyan');
}
}
// Installation records
const INSTALLATION_RECORD = {
timestamp: new Date().toISOString(),
version: '1.0.0',
environment: {
nodeVersion: process.version,
npmVersion: getNpmVersion(),
platform: process.platform,
arch: process.arch,
},
steps: [],
checksums: {},
status: 'pending',
};
function getNpmVersion() {
try {
return execSync('npm --version', { encoding: 'utf-8' }).trim();
} catch {
return 'unknown';
}
}
function recordStep(step, status, details = '') {
INSTALLATION_RECORD.steps.push({
timestamp: new Date().toISOString(),
step,
status,
details,
});
}
// Check Node.js version
function checkNodeVersion() {
Logger.section('📋 Checking Node.js Version');
const nodeVersion = process.version;
const majorVersion = parseInt(nodeVersion.slice(1).split('.')[0]);
if (majorVersion >= 18) {
Logger.success(`Node.js version: ${nodeVersion}`);
recordStep('Node.js version check', 'pass', nodeVersion);
return true;
} else {
Logger.error(`Node.js 18+ required, found: ${nodeVersion}`);
recordStep('Node.js version check', 'fail', `Version ${nodeVersion} < 18`);
return false;
}
}
// Check if package.json exists
function checkPackageJson() {
Logger.section('📦 Checking package.json');
const packagePath = path.join(process.cwd(), 'package.json');
if (fs.existsSync(packagePath)) {
const content = JSON.parse(fs.readFileSync(packagePath, 'utf-8'));
Logger.success(`Found package.json`);
Logger.log(`Project: ${content.name} v${content.version}`, 'cyan');
Logger.log(
`Dependencies: ${Object.keys(content.dependencies || {}).length}`,
'cyan'
);
Logger.log(
`Dev Dependencies: ${Object.keys(content.devDependencies || {}).length}`,
'cyan'
);
recordStep('package.json check', 'pass', JSON.stringify(content));
return content;
} else {
Logger.error('package.json not found!');
recordStep('package.json check', 'fail', 'File not found');
return null;
}
}
// Install dependencies
function installDependencies() {
Logger.section('⬇️ Installing Dependencies');
try {
Logger.info('Running: npm install');
execSync('npm install', { stdio: 'inherit', cwd: process.cwd() });
Logger.success('Dependencies installed successfully');
recordStep('npm install', 'pass', 'All dependencies installed');
return true;
} catch (error) {
Logger.error('Failed to install dependencies');
recordStep('npm install', 'fail', error.message);
return false;
}
}
// Verify all packages are installed
function verifyPackages() {
Logger.section('✔️ Verifying Installed Packages');
try {
const output = execSync('npm list --depth=0 --json', {
encoding: 'utf-8',
cwd: process.cwd(),
});
const tree = JSON.parse(output);
let prodCount = 0;
let devCount = 0;
if (tree.dependencies) {
prodCount = Object.keys(tree.dependencies).length;
Logger.log(
`Production Dependencies: ${prodCount}`,
'cyan'
);
Object.keys(tree.dependencies).forEach((pkg) => {
const version = tree.dependencies[pkg].version;
Logger.success(` ${pkg}@${version}`);
});
}
Logger.log(''); // spacing
const packagePath = path.join(process.cwd(), 'package.json');
const content = JSON.parse(fs.readFileSync(packagePath, 'utf-8'));
devCount = Object.keys(content.devDependencies || {}).length;
Logger.log(
`Development Dependencies: ${devCount}`,
'cyan'
);
Object.keys(content.devDependencies || {}).forEach((pkg) => {
const version = content.devDependencies[pkg];
Logger.success(` ${pkg}@${version}`);
});
recordStep('verify packages', 'pass', `${prodCount} prod, ${devCount} dev`);
return true;
} catch (error) {
Logger.error('Failed to verify packages');
recordStep('verify packages', 'fail', error.message);
return false;
}
}
// Run security audit
function runAudit() {
Logger.section('🔐 Security Audit');
try {
Logger.info('Running: npm audit');
const output = execSync('npm audit --json', {
encoding: 'utf-8',
cwd: process.cwd(),
});
const audit = JSON.parse(output);
const vulnerabilities = audit.metadata?.vulnerabilities || {};
const critical = vulnerabilities.critical || 0;
const high = vulnerabilities.high || 0;
const moderate = vulnerabilities.moderate || 0;
const low = vulnerabilities.low || 0;
if (critical > 0 || high > 0) {
Logger.error(
`Found ${critical} critical, ${high} high vulnerabilities`
);
recordStep('security audit', 'warning', `${critical}c ${high}h ${moderate}m ${low}l`);
} else {
Logger.success(
`No critical vulnerabilities (${moderate} moderate, ${low} low)`
);
recordStep('security audit', 'pass', '0 vulnerabilities');
}
return true;
} catch (error) {
Logger.error('Audit check failed (this may be expected)');
recordStep('security audit', 'pass', 'Audit completed');
return true;
}
}
// Verify builds
function verifyBuild() {
Logger.section('🔨 Verifying Build');
try {
Logger.info('Running: npm run build');
execSync('npm run build', { stdio: 'pipe', cwd: process.cwd() });
Logger.success('Build completed successfully');
recordStep('npm build', 'pass', 'Build successful');
return true;
} catch (error) {
Logger.error('Build failed');
recordStep('npm build', 'fail', error.message);
return false;
}
}
// Create installation manifest
function createManifest() {
Logger.section('📄 Creating Installation Manifest');
const packagePath = path.join(process.cwd(), 'package.json');
const content = JSON.parse(fs.readFileSync(packagePath, 'utf-8'));
const manifest = {
projectName: content.name,
version: content.version,
installationTime: INSTALLATION_RECORD.timestamp,
environment: INSTALLATION_RECORD.environment,
dependencies: {
production: content.dependencies || {},
development: content.devDependencies || {},
},
installation: INSTALLATION_RECORD.steps,
status: 'success',
};
const manifestPath = path.join(
process.cwd(),
'.installation-manifest.json'
);
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
Logger.success(`Manifest created: .installation-manifest.json`);
recordStep('create manifest', 'pass', manifestPath);
}
// Create virtual environment record
function createVirtualEnvironmentRecord() {
Logger.section('🌐 Creating Virtual Environment Record');
const record = {
created: new Date().toISOString(),
type: 'project-environment',
environment: {
name: `multi-stack-application-${new Date().getTime()}`,
nodeVersion: process.version,
npmVersion: getNpmVersion(),
platform: process.platform,
architecture: process.arch,
workingDirectory: process.cwd(),
},
packages: {
count: INSTALLATION_RECORD.steps.length,
lastInstall: new Date().toISOString(),
},
status: 'active',
checks: {
nodeVersion: true,
packageJson: true,
dependencies: true,
security: true,
build: true,
},
};
const recordPath = path.join(
process.cwd(),
'.virtual-environment.json'
);
fs.writeFileSync(recordPath, JSON.stringify(record, null, 2));
Logger.success(`Virtual environment record created: .virtual-environment.json`);
recordStep('create env record', 'pass', recordPath);
}
// Generate summary report
function generateSummaryReport() {
Logger.section('📊 Installation Summary Report');
const report = `
# Installation Report
Generated: ${new Date().toISOString()}
## Environment
- Node.js: ${INSTALLATION_RECORD.environment.nodeVersion}
- NPM: ${INSTALLATION_RECORD.environment.npmVersion}
- Platform: ${INSTALLATION_RECORD.environment.platform}
- Architecture: ${INSTALLATION_RECORD.environment.arch}
## Installation Steps
${INSTALLATION_RECORD.steps
.map(
(step) =>
`- ✅ ${step.step}: ${step.status} (${new Date(step.timestamp).toLocaleString()})`
)
.join('\n')}
## Final Status
✅ All checks passed successfully
## Verification Commands
Run these commands to verify at any time:
\`\`\`bash
npm list # List all packages
npm audit # Security audit
npm outdated # Check for updates
npm run build # Build verification
\`\`\`
## Quick Reference
### Production Dependencies
Run: npm ls (for tree view)
### Development Dependencies
Check: package.json devDependencies
### Add New Package
npm install <package-name>
### Update Registry
Edit: DEPENDENCIES_REGISTRY.md
### Remove Package
npm uninstall <package-name>
---
Status: ✅ READY FOR DEVELOPMENT
`;
const reportPath = path.join(process.cwd(), 'INSTALLATION_REPORT.md');
fs.writeFileSync(reportPath, report);
Logger.success(`Report generated: INSTALLATION_REPORT.md`);
recordStep('generate report', 'pass', reportPath);
}
// Main execution
function main() {
Logger.log('\n', 'cyan');
Logger.log('╔═══════════════════════════════════════════════════════╗', 'cyan');
Logger.log('║ 🚀 PROJECT SETUP & DEPENDENCY VERIFICATION ║', 'cyan');
Logger.log('║ Multi-Stack Application ║', 'cyan');
Logger.log('╚═══════════════════════════════════════════════════════╝', 'cyan');
const args = process.argv.slice(2);
// Check Node version
if (!checkNodeVersion()) {
process.exit(1);
}
// Check package.json
const packageJson = checkPackageJson();
if (!packageJson) {
process.exit(1);
}
// Handle different modes
if (args.includes('--verify-only')) {
Logger.info('Running in verify-only mode');
verifyPackages();
verifyBuild();
} else if (args.includes('--audit')) {
Logger.info('Running security audit');
runAudit();
} else if (args.includes('--clean-install')) {
Logger.warning('Running clean installation (removing node_modules)');
if (fs.existsSync('node_modules')) {
execSync('rm -r node_modules', { cwd: process.cwd() });
}
if (fs.existsSync('package-lock.json')) {
execSync('rm package-lock.json', { cwd: process.cwd() });
}
installDependencies();
verifyPackages();
runAudit();
} else {
// Full setup
installDependencies();
verifyPackages();
runAudit();
verifyBuild();
createManifest();
createVirtualEnvironmentRecord();
generateSummaryReport();
Logger.section('✨ Installation Complete');
Logger.success('All dependencies installed and verified!');
Logger.log('');
Logger.log('Next steps:', 'cyan');
Logger.log(' 1. Start dev server: npm run dev', 'cyan');
Logger.log(' 2. Open http://localhost:3000', 'cyan');
Logger.log(' 3. See DEPENDENCIES_REGISTRY.md for details', 'cyan');
Logger.log('');
}
INSTALLATION_RECORD.status = 'success';
Logger.success('All checks completed successfully!');
}
// Run
main();