@monodog/backend 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/.eslintrc.cjs +15 -0
  2. package/dist/cli.js +98 -0
  3. package/dist/gitService.js +240 -0
  4. package/dist/index.js +1185 -0
  5. package/dist/utils/helpers.js +198 -0
  6. package/package.json +41 -0
  7. package/prisma/migrations/20251017041048_init/migration.sql +19 -0
  8. package/prisma/migrations/20251017083007_add_package/migration.sql +21 -0
  9. package/prisma/migrations/20251021083705_alter_package/migration.sql +37 -0
  10. package/prisma/migrations/20251022085155_test/migration.sql +2 -0
  11. package/prisma/migrations/20251022160841_/migration.sql +35 -0
  12. package/prisma/migrations/20251023130158_rename_column_name/migration.sql +34 -0
  13. package/prisma/migrations/20251023174837_/migration.sql +34 -0
  14. package/prisma/migrations/20251023175830_uodate_schema/migration.sql +32 -0
  15. package/prisma/migrations/20251024103700_add_dependency_info/migration.sql +13 -0
  16. package/prisma/migrations/20251025192150_add_dependency_info/migration.sql +19 -0
  17. package/prisma/migrations/20251025192342_add_dependency_info/migration.sql +40 -0
  18. package/prisma/migrations/20251025204613_add_dependency_info/migration.sql +8 -0
  19. package/prisma/migrations/20251026071336_add_dependency_info/migration.sql +25 -0
  20. package/prisma/migrations/20251027062626_add_commit/migration.sql +10 -0
  21. package/prisma/migrations/20251027062748_add_commit/migration.sql +23 -0
  22. package/prisma/migrations/20251027092741_add_commit/migration.sql +17 -0
  23. package/prisma/migrations/20251027112736_add_health_status/migration.sql +16 -0
  24. package/prisma/migrations/20251027140546_init_packages/migration.sql +16 -0
  25. package/prisma/migrations/20251029073436_added_package_heath_key/migration.sql +34 -0
  26. package/prisma/migrations/20251029073830_added_package_health_key/migration.sql +49 -0
  27. package/prisma/migrations/migration_lock.toml +3 -0
  28. package/prisma/schema.prisma +130 -0
  29. package/src/cli.ts +68 -0
  30. package/src/gitService.ts +274 -0
  31. package/src/index.ts +1366 -0
  32. package/src/utils/helpers.js +199 -0
  33. package/src/utils/helpers.js.map +1 -0
  34. package/src/utils/helpers.ts +223 -0
  35. package/tsconfig.json +15 -0
  36. package/tsconfig.o.json +29 -0
package/dist/index.js ADDED
@@ -0,0 +1,1185 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.startServer = startServer;
7
+ const express_1 = __importDefault(require("express"));
8
+ const cors_1 = __importDefault(require("cors"));
9
+ const path_1 = __importDefault(require("path"));
10
+ const fs_1 = __importDefault(require("fs"));
11
+ // import { glob } from 'glob';
12
+ const body_parser_1 = require("body-parser");
13
+ const monorepo_scanner_1 = require("@monodog/monorepo-scanner");
14
+ const ci_status_1 = require("@monodog/ci-status");
15
+ const helpers_1 = require("@monodog/utils/helpers");
16
+ const helpers_2 = require("./utils/helpers");
17
+ const client_1 = require("@prisma/client");
18
+ // Import the validateConfig function from your utils
19
+ // import { validateConfig } from '../../apps/dashboard/src/components/modules/config-inspector/utils/config.utils';
20
+ const gitService_1 = require("./gitService");
21
+ const prisma = new client_1.PrismaClient();
22
+ const DEFAULT_PORT = 4000;
23
+ // The main function exported and called by the CLI
24
+ function startServer(rootPath) {
25
+ const app = (0, express_1.default)();
26
+ const port = process.env.PORT ? parseInt(process.env.PORT) : DEFAULT_PORT;
27
+ // --- Middleware ---
28
+ // 1. Logging Middleware
29
+ app.use((_req, _res, next) => {
30
+ console.log(`[SERVER] ${_req.method} ${_req.url} (Root: ${rootPath})`);
31
+ next();
32
+ });
33
+ app.use((0, cors_1.default)());
34
+ app.use((0, body_parser_1.json)());
35
+ // // 2. CORS (Critical for the frontend app to talk to this local server)
36
+ // // In a production setup, this would be highly restricted, but for local monorepo tools,
37
+ // // we often allow all origins or restrict to a known local hostname/port.
38
+ // app.use((_req: Request, res: Response, next: NextFunction) => {
39
+ // res.setHeader('Access-Control-Allow-Origin', '*'); // Adjust this in production
40
+ // res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
41
+ // res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
42
+ // next();
43
+ // });
44
+ // // 3. JSON body parser
45
+ // app.use(express.json());
46
+ // Health check
47
+ app.get('/api/health', (_, res) => {
48
+ res.json({
49
+ status: 'ok',
50
+ timestamp: Date.now(),
51
+ version: '1.0.0',
52
+ services: {
53
+ scanner: 'active',
54
+ ci: 'active',
55
+ database: 'active',
56
+ },
57
+ });
58
+ });
59
+ // Get all packages from database (DONE)
60
+ app.get('/api/packages', async (_req, res) => {
61
+ try {
62
+ // Try to get packages from database first
63
+ let dbPackages = await prisma.package.findMany();
64
+ if (!dbPackages.length) {
65
+ try {
66
+ const rootDir = path_1.default.resolve(rootPath);
67
+ const packages = (0, helpers_1.scanMonorepo)(rootDir);
68
+ console.log('packages --> scan', packages.length);
69
+ for (const pkg of packages) {
70
+ await (0, helpers_2.storePackage)(pkg);
71
+ }
72
+ }
73
+ catch (error) {
74
+ throw new Error('Error ' + error);
75
+ }
76
+ dbPackages = await prisma.package.findMany();
77
+ }
78
+ const transformedPackages = dbPackages.map(pkg => {
79
+ // We create a new object 'transformedPkg' based on the database record 'pkg'
80
+ const transformedPkg = { ...pkg };
81
+ // 1. Maintainers (Your Logic)
82
+ transformedPkg.maintainers = pkg.maintainers
83
+ ? JSON.parse(pkg.maintainers)
84
+ : [];
85
+ // 2. Tags
86
+ // transformedPkg.tags = pkg.tags
87
+ // ? JSON.parse(pkg.tags)
88
+ // : [];
89
+ // 3. Scripts/repository (should default to an object, not an array)
90
+ transformedPkg.scripts = pkg.scripts ? JSON.parse(pkg.scripts) : {};
91
+ transformedPkg.repository = pkg.repository
92
+ ? JSON.parse(pkg.repository)
93
+ : {};
94
+ // 4. Dependencies List
95
+ transformedPkg.dependencies = pkg.dependencies
96
+ ? JSON.parse(pkg.dependencies)
97
+ : [];
98
+ transformedPkg.devDependencies = pkg.devDependencies
99
+ ? JSON.parse(pkg.devDependencies)
100
+ : [];
101
+ transformedPkg.peerDependencies = pkg.peerDependencies
102
+ ? JSON.parse(pkg.peerDependencies)
103
+ : [];
104
+ return transformedPkg; // Return the fully transformed object
105
+ });
106
+ res.json(transformedPackages);
107
+ }
108
+ catch (error) {
109
+ res.status(500).json({ error: 'Failed to fetch packages, ' + error });
110
+ }
111
+ });
112
+ app.get('/api/packages/refresh', async (_req, res) => {
113
+ try {
114
+ const rootDir = path_1.default.resolve(rootPath);
115
+ const packages = (0, helpers_1.scanMonorepo)(rootDir);
116
+ console.log('packages -->', packages.length);
117
+ for (const pkg of packages) {
118
+ (0, helpers_2.storePackage)(pkg);
119
+ }
120
+ res.json(packages);
121
+ }
122
+ catch (error) {
123
+ res.status(500).json({ error: 'Failed to refresh packages' });
124
+ }
125
+ });
126
+ // Get package details
127
+ app.get('/api/packages/:name', async (_req, res) => {
128
+ try {
129
+ const { name } = _req.params;
130
+ const pkg = await prisma.package.findUnique({
131
+ where: {
132
+ name: name,
133
+ },
134
+ include: {
135
+ dependenciesInfo: true,
136
+ commits: true,
137
+ packageHealth: true,
138
+ },
139
+ });
140
+ if (!pkg) {
141
+ return res.status(404).json({ error: 'Package not found' });
142
+ }
143
+ const transformedPkg = { ...pkg };
144
+ // --- APPLY PARSING TO EACH FIELD ---
145
+ // 1. Maintainers (Your Logic)
146
+ // transformedPkg.maintainers = pkg.maintainers
147
+ // ? JSON.parse(pkg.maintainers)
148
+ // : [];
149
+ // 2. Tags
150
+ // transformedPkg.tags = pkg.tags
151
+ // ? JSON.parse(pkg.tags)
152
+ // : [];
153
+ // 3. Scripts/repository (should default to an object, not an array)
154
+ transformedPkg.scripts = pkg.scripts ? JSON.parse(pkg.scripts) : {};
155
+ transformedPkg.repository = pkg.repository
156
+ ? JSON.parse(pkg.repository)
157
+ : {};
158
+ // 4. Dependencies List
159
+ transformedPkg.dependencies = pkg.dependencies
160
+ ? JSON.parse(pkg.dependencies)
161
+ : [];
162
+ transformedPkg.devDependencies = pkg.devDependencies
163
+ ? JSON.parse(pkg.devDependencies)
164
+ : [];
165
+ transformedPkg.peerDependencies = pkg.peerDependencies
166
+ ? JSON.parse(pkg.peerDependencies)
167
+ : [];
168
+ // Get additional package information
169
+ const reports = await (0, monorepo_scanner_1.generateReports)();
170
+ const packageReport = reports.find(r => r.package.name === name);
171
+ const result = {
172
+ ...transformedPkg,
173
+ report: packageReport,
174
+ ciStatus: await ci_status_1.ciStatusManager.getPackageStatus(name),
175
+ };
176
+ res.json(result);
177
+ }
178
+ catch (error) {
179
+ res.status(500).json({ error: 'Failed to fetch package details' });
180
+ }
181
+ });
182
+ // Get commit details
183
+ app.get('/api/commits/:packagePath', async (_req, res) => {
184
+ try {
185
+ const { packagePath } = _req.params;
186
+ // Decode the package path
187
+ const decodedPath = decodeURIComponent(packagePath);
188
+ console.log('🔍 Fetching commits for path:', decodedPath);
189
+ console.log('📁 Current working directory:', process.cwd());
190
+ const gitService = new gitService_1.GitService();
191
+ // Check if this is an absolute path and convert to relative if needed
192
+ let relativePath = decodedPath;
193
+ const projectRoot = process.cwd();
194
+ // If it's an absolute path, make it relative to project root
195
+ if (path_1.default.isAbsolute(decodedPath)) {
196
+ relativePath = path_1.default.relative(projectRoot, decodedPath);
197
+ console.log('🔄 Converted absolute path to relative:', relativePath);
198
+ }
199
+ // Check if the path exists
200
+ try {
201
+ await fs_1.default.promises.access(relativePath);
202
+ console.log('✅ Path exists:', relativePath);
203
+ }
204
+ catch (fsError) {
205
+ console.log('❌ Path does not exist:', relativePath);
206
+ // Try the original path as well
207
+ try {
208
+ await fs_1.default.promises.access(decodedPath);
209
+ console.log('✅ Original path exists:', decodedPath);
210
+ relativePath = decodedPath; // Use original path if it exists
211
+ }
212
+ catch (secondError) {
213
+ return res.status(404).json({
214
+ error: `Package path not found: ${relativePath} (also tried: ${decodedPath})`,
215
+ });
216
+ }
217
+ }
218
+ const commits = await gitService.getAllCommits(relativePath);
219
+ console.log(`✅ Successfully fetched ${commits.length} commits for ${relativePath}`);
220
+ res.json(commits);
221
+ }
222
+ catch (error) {
223
+ console.error('💥 Error fetching commit details:', error);
224
+ res.status(500).json({
225
+ error: 'Failed to fetch commit details',
226
+ message: error.message,
227
+ stack: process.env.NODE_ENV === 'development' ? error.stack : undefined,
228
+ });
229
+ }
230
+ });
231
+ // Get dependency graph
232
+ app.get('/api/graph', async (_req, res) => {
233
+ try {
234
+ const packages = (0, helpers_1.scanMonorepo)(process.cwd());
235
+ const graph = (0, helpers_1.generateDependencyGraph)(packages);
236
+ const circularDeps = (0, helpers_1.findCircularDependencies)(packages);
237
+ res.json({
238
+ ...graph,
239
+ circularDependencies: circularDeps,
240
+ metadata: {
241
+ totalNodes: graph.nodes.length,
242
+ totalEdges: graph.edges.length,
243
+ circularDependencies: circularDeps.length,
244
+ },
245
+ });
246
+ }
247
+ catch (error) {
248
+ res.status(500).json({ error: 'Failed to generate dependency graph' });
249
+ }
250
+ });
251
+ // Get monorepo statistics
252
+ app.get('/api/stats', async (_req, res) => {
253
+ try {
254
+ const packages = (0, helpers_1.scanMonorepo)(process.cwd());
255
+ const stats = (0, helpers_1.generateMonorepoStats)(packages);
256
+ res.json({
257
+ ...stats,
258
+ timestamp: Date.now(),
259
+ scanDuration: 0, // Would be calculated from actual scan
260
+ });
261
+ }
262
+ catch (error) {
263
+ res.status(500).json({ error: 'Failed to fetch statistics' });
264
+ }
265
+ });
266
+ // Get CI status for all packages
267
+ app.get('/api/ci/status', async (_req, res) => {
268
+ try {
269
+ const packages = (0, helpers_1.scanMonorepo)(process.cwd());
270
+ const ciStatus = await (0, ci_status_1.getMonorepoCIStatus)(packages);
271
+ res.json(ciStatus);
272
+ }
273
+ catch (error) {
274
+ res.status(500).json({ error: 'Failed to fetch CI status' });
275
+ }
276
+ });
277
+ // Get CI status for specific package
278
+ app.get('/api/ci/packages/:name', async (_req, res) => {
279
+ try {
280
+ const { name } = _req.params;
281
+ const status = await ci_status_1.ciStatusManager.getPackageStatus(name);
282
+ if (!status) {
283
+ return res.status(404).json({ error: 'Package CI status not found' });
284
+ }
285
+ res.json(status);
286
+ }
287
+ catch (error) {
288
+ res.status(500).json({ error: 'Failed to fetch package CI status' });
289
+ }
290
+ });
291
+ // Trigger CI build for package
292
+ app.post('/api/ci/trigger', async (_req, res) => {
293
+ try {
294
+ const { packageName, providerName, branch } = _req.body;
295
+ if (!packageName) {
296
+ return res.status(400).json({ error: 'Package name is required' });
297
+ }
298
+ const result = await ci_status_1.ciStatusManager.triggerBuild(packageName, providerName || 'github', branch || 'main');
299
+ if (result.success) {
300
+ res.json({
301
+ success: true,
302
+ buildId: result.buildId,
303
+ message: `Build triggered for ${packageName}`,
304
+ });
305
+ }
306
+ else {
307
+ res.status(400).json({
308
+ success: false,
309
+ error: result.error,
310
+ });
311
+ }
312
+ }
313
+ catch (error) {
314
+ res.status(500).json({ error: 'Failed to trigger build' });
315
+ }
316
+ });
317
+ // Get build logs
318
+ app.get('/api/ci/builds/:buildId/logs', async (_req, res) => {
319
+ try {
320
+ const { buildId } = _req.params;
321
+ const { provider } = _req.query;
322
+ if (!provider) {
323
+ return res.status(400).json({ error: 'Provider is required' });
324
+ }
325
+ const logs = await ci_status_1.ciStatusManager.getBuildLogs(buildId, provider);
326
+ res.json({ buildId, logs });
327
+ }
328
+ catch (error) {
329
+ res.status(500).json({ error: 'Failed to fetch build logs' });
330
+ }
331
+ });
332
+ // Get build artifacts
333
+ app.get('/api/ci/builds/:buildId/artifacts', async (_req, res) => {
334
+ try {
335
+ const { buildId } = _req.params;
336
+ const { provider } = _req.query;
337
+ if (!provider) {
338
+ return res.status(400).json({ error: 'Provider is required' });
339
+ }
340
+ const artifacts = await ci_status_1.ciStatusManager.getBuildArtifacts(buildId, provider);
341
+ res.json({ buildId, artifacts });
342
+ }
343
+ catch (error) {
344
+ res.status(500).json({ error: 'Failed to fetch build artifacts' });
345
+ }
346
+ });
347
+ // Perform full monorepo scan
348
+ app.post('/api/scan', async (_req, res) => {
349
+ try {
350
+ const { force } = _req.body;
351
+ if (force) {
352
+ monorepo_scanner_1.scanner.clearCache();
353
+ }
354
+ const result = await (0, monorepo_scanner_1.quickScan)();
355
+ res.json({
356
+ success: true,
357
+ message: 'Scan completed successfully',
358
+ result,
359
+ });
360
+ }
361
+ catch (error) {
362
+ res.status(500).json({
363
+ success: false,
364
+ error: 'Failed to perform scan',
365
+ });
366
+ }
367
+ });
368
+ // Get scan results
369
+ app.get('/api/scan/results', async (_req, res) => {
370
+ try {
371
+ const result = await (0, monorepo_scanner_1.quickScan)();
372
+ res.json(result);
373
+ }
374
+ catch (error) {
375
+ res.status(500).json({ error: 'Failed to fetch scan results' });
376
+ }
377
+ });
378
+ // Export scan results
379
+ app.get('/api/scan/export/:format', async (_req, res) => {
380
+ try {
381
+ const { format } = _req.params;
382
+ const { filename } = _req.query;
383
+ if (!['json', 'csv', 'html'].includes(format)) {
384
+ return res.status(400).json({ error: 'Invalid export format' });
385
+ }
386
+ const result = await (0, monorepo_scanner_1.quickScan)();
387
+ const exportData = monorepo_scanner_1.scanner.exportResults(result, format);
388
+ if (format === 'json') {
389
+ res.json(result);
390
+ }
391
+ else {
392
+ const contentType = format === 'csv' ? 'text/csv' : 'text/html';
393
+ const contentDisposition = filename
394
+ ? `attachment; filename="${filename}"`
395
+ : `attachment; filename="monorepo-scan.${format}"`;
396
+ res.setHeader('Content-Type', contentType);
397
+ res.setHeader('Content-Disposition', contentDisposition);
398
+ res.send(exportData);
399
+ }
400
+ }
401
+ catch (error) {
402
+ res.status(500).json({ error: 'Failed to export scan results' });
403
+ }
404
+ });
405
+ // ---------- HEALTH --------------------
406
+ // Get package health metrics
407
+ app.get('/api/health/packages/:name', async (_req, res) => {
408
+ try {
409
+ console.log('_req.params -->', _req.params);
410
+ const { name } = _req.params;
411
+ const packages = (0, helpers_1.scanMonorepo)(process.cwd());
412
+ const packageInfo = packages.find(p => p.name === name);
413
+ if (!packageInfo) {
414
+ return res.status(404).json({ error: 'Package not found' });
415
+ }
416
+ // Get health metrics (mock data for now)
417
+ const health = {
418
+ buildStatus: 'success',
419
+ testCoverage: Math.floor(Math.random() * 100),
420
+ lintStatus: 'pass',
421
+ securityAudit: 'pass',
422
+ overallScore: Math.floor(Math.random() * 40) + 60,
423
+ lastUpdated: new Date(),
424
+ };
425
+ res.json({
426
+ packageName: name,
427
+ health,
428
+ size: {
429
+ size: Math.floor(Math.random() * 1024 * 1024), // Random size
430
+ files: Math.floor(Math.random() * 1000),
431
+ },
432
+ });
433
+ }
434
+ catch (error) {
435
+ res.status(500).json({ error: 'Failed to fetch health metrics' });
436
+ }
437
+ });
438
+ // Get all package health metrics
439
+ // app.get('/api/health/packages', async (_req, res) => {
440
+ // try {
441
+ // // Try to get health data from database
442
+ // const healthData = await prisma.healthStatus.findMany();
443
+ // console.log('healthData -->', healthData);
444
+ // // Transform the data to match the expected frontend format
445
+ // const transformedHealthData = healthData.map(health => {
446
+ // const transformedHealth = { ...health };
447
+ // // Parse any JSON fields that were stored as strings
448
+ // if (health.metrics) {
449
+ // transformedHealth.metrics = JSON.parse(health.metrics);
450
+ // } else {
451
+ // transformedHealth.metrics = [];
452
+ // }
453
+ // if (health.packageHealth) {
454
+ // transformedHealth.packageHealth = JSON.parse(health.packageHealth);
455
+ // } else {
456
+ // transformedHealth.packageHealth = [];
457
+ // }
458
+ // // Ensure we have all required fields with defaults
459
+ // return {
460
+ // id: transformedHealth.id,
461
+ // overallScore: transformedHealth.overallScore || 0,
462
+ // metrics: transformedHealth.metrics || [],
463
+ // packageHealth: transformedHealth.packageHealth || [],
464
+ // createdAt: transformedHealth.createdAt,
465
+ // updatedAt: transformedHealth.updatedAt,
466
+ // };
467
+ // });
468
+ // // Return the latest health data (you might want to sort by createdAt desc)
469
+ // const latestHealthData = transformedHealthData.sort(
470
+ // (a, b) => new Date(b.createdAt) - new Date(a.createdAt)
471
+ // )[0] || {
472
+ // overallScore: 0,
473
+ // metrics: [],
474
+ // packageHealth: [],
475
+ // };
476
+ // res.json(latestHealthData);
477
+ // } catch (error) {
478
+ // console.error('Error fetching health data:', error);
479
+ // res.status(500).json({ error: 'Failed to fetch health data' });
480
+ // }
481
+ // });
482
+ app.get('/api/health/packages', async (_req, res) => {
483
+ try {
484
+ // Fetch all package health data from database
485
+ const packageHealthData = await prisma.packageHealth.findMany();
486
+ console.log('packageHealthData -->', packageHealthData.length);
487
+ // Transform the data to match the expected frontend format
488
+ const packages = packageHealthData.map(pkg => {
489
+ const health = {
490
+ buildStatus: pkg.packageBuildStatus,
491
+ testCoverage: pkg.packageTestCoverage,
492
+ lintStatus: pkg.packageLintStatus,
493
+ securityAudit: pkg.packageSecurity,
494
+ overallScore: pkg.packageOverallScore,
495
+ };
496
+ return {
497
+ packageName: pkg.packageName,
498
+ health: health,
499
+ isHealthy: pkg.packageOverallScore >= 80,
500
+ };
501
+ });
502
+ // Calculate summary statistics
503
+ const total = packages.length;
504
+ const healthy = packages.filter(pkg => pkg.isHealthy).length;
505
+ const unhealthy = packages.filter(pkg => !pkg.isHealthy).length;
506
+ const averageScore = packages.length > 0
507
+ ? packages.reduce((sum, pkg) => sum + pkg.health.overallScore, 0) /
508
+ packages.length
509
+ : 0;
510
+ const response = {
511
+ packages: packages,
512
+ summary: {
513
+ total: total,
514
+ healthy: healthy,
515
+ unhealthy: unhealthy,
516
+ averageScore: averageScore,
517
+ },
518
+ };
519
+ console.log('Transformed health data -->', response.summary);
520
+ res.json(response);
521
+ }
522
+ catch (error) {
523
+ console.error('Error fetching health data from database:', error);
524
+ res
525
+ .status(500)
526
+ .json({ error: 'Failed to fetch health data from database' });
527
+ }
528
+ });
529
+ app.get('/api/health/refresh', async (_req, res) => {
530
+ try {
531
+ const rootDir = path_1.default.resolve(rootPath);
532
+ const packages = (0, helpers_1.scanMonorepo)(rootDir);
533
+ console.log('packages -->', packages.length);
534
+ const healthMetrics = await Promise.all(packages.map(async (pkg) => {
535
+ try {
536
+ // Await each health check function since they return promises
537
+ const buildStatus = await (0, monorepo_scanner_1.funCheckBuildStatus)(pkg);
538
+ const testCoverage = await (0, monorepo_scanner_1.funCheckTestCoverage)(pkg);
539
+ const lintStatus = await (0, monorepo_scanner_1.funCheckLintStatus)(pkg);
540
+ const securityAudit = await (0, monorepo_scanner_1.funCheckSecurityAudit)(pkg);
541
+ // Calculate overall health score
542
+ const overallScore = (0, helpers_1.calculatePackageHealth)(buildStatus, testCoverage, lintStatus, securityAudit);
543
+ const health = {
544
+ buildStatus: buildStatus,
545
+ testCoverage: testCoverage,
546
+ lintStatus: lintStatus,
547
+ securityAudit: securityAudit,
548
+ overallScore: overallScore.overallScore,
549
+ };
550
+ const packageStatus = health.overallScore >= 80 ? 'healthy' : (health.overallScore >= 60 && health.overallScore < 80 ? 'warning' : 'error');
551
+ console.log(pkg.name, '-->', health, packageStatus);
552
+ // FIX: Use upsert to handle existing packages and proper Prisma syntax
553
+ await prisma.packageHealth.upsert({
554
+ where: {
555
+ packageName: pkg.name,
556
+ },
557
+ update: {
558
+ packageOverallScore: overallScore.overallScore,
559
+ packageBuildStatus: buildStatus,
560
+ packageTestCoverage: testCoverage,
561
+ packageLintStatus: lintStatus,
562
+ packageSecurity: securityAudit,
563
+ packageDependencies: '',
564
+ updatedAt: new Date(),
565
+ package: {
566
+ update: {
567
+ where: { name: pkg.name },
568
+ data: { status: packageStatus },
569
+ },
570
+ },
571
+ },
572
+ create: {
573
+ packageName: pkg.name,
574
+ packageOverallScore: overallScore.overallScore,
575
+ packageBuildStatus: buildStatus,
576
+ packageTestCoverage: testCoverage,
577
+ packageLintStatus: lintStatus,
578
+ packageSecurity: securityAudit,
579
+ packageDependencies: '',
580
+ },
581
+ });
582
+ return {
583
+ packageName: pkg.name,
584
+ health,
585
+ isHealthy: health.overallScore >= 80,
586
+ };
587
+ }
588
+ catch (error) {
589
+ return {
590
+ packageName: pkg.name,
591
+ health: null,
592
+ isHealthy: false,
593
+ error: 'Failed to fetch health metrics',
594
+ };
595
+ }
596
+ }));
597
+ res.json({
598
+ packages: healthMetrics,
599
+ summary: {
600
+ total: packages.length,
601
+ healthy: healthMetrics.filter(h => h.isHealthy).length,
602
+ unhealthy: healthMetrics.filter(h => !h.isHealthy).length,
603
+ averageScore: healthMetrics
604
+ .filter(h => h.health)
605
+ .reduce((sum, h) => sum + h.health.overallScore, 0) /
606
+ healthMetrics.filter(h => h.health).length,
607
+ },
608
+ });
609
+ }
610
+ catch (error) {
611
+ res.status(500).json({ error: 'Failed to fetch health metrics' });
612
+ }
613
+ });
614
+ // function calculateHealthStatus(
615
+ // healthy: number,
616
+ // total: number
617
+ // ): 'healthy' | 'warning' | 'error' {
618
+ // if (total === 0) return 'healthy';
619
+ // const ratio = healthy / total;
620
+ // if (ratio >= 0.8) return 'healthy';
621
+ // if (ratio >= 0.6) return 'warning';
622
+ // return 'error';
623
+ // }
624
+ // Search packages
625
+ app.get('/api/search', async (_req, res) => {
626
+ try {
627
+ const { q: query, type, status } = _req.query;
628
+ const packages = (0, helpers_1.scanMonorepo)(process.cwd());
629
+ let filtered = packages;
630
+ // Filter by search query
631
+ if (query) {
632
+ const searchTerm = query.toLowerCase();
633
+ filtered = filtered.filter(pkg => pkg.name.toLowerCase().includes(searchTerm) ||
634
+ pkg.description?.toLowerCase().includes(searchTerm));
635
+ }
636
+ // Filter by type
637
+ if (type && type !== 'all') {
638
+ filtered = filtered.filter(pkg => pkg.type === type);
639
+ }
640
+ // Filter by status (would need health data)
641
+ if (status && status !== 'all') {
642
+ // This would filter by actual health status
643
+ // For now, just return all packages
644
+ }
645
+ res.json({
646
+ query,
647
+ results: filtered,
648
+ total: filtered.length,
649
+ filters: { type, status },
650
+ });
651
+ }
652
+ catch (error) {
653
+ res.status(500).json({ error: 'Failed to search packages' });
654
+ }
655
+ });
656
+ // Get recent activity
657
+ app.get('/api/activity', async (_req, res) => {
658
+ try {
659
+ const { limit = 20 } = _req.query;
660
+ const packages = (0, helpers_1.scanMonorepo)(process.cwd());
661
+ // Mock recent activity data
662
+ const activities = packages
663
+ .slice(0, Math.min(Number(limit), packages.length))
664
+ .map((pkg, index) => ({
665
+ id: `activity-${Date.now()}-${index}`,
666
+ type: [
667
+ 'package_updated',
668
+ 'build_success',
669
+ 'test_passed',
670
+ 'dependency_updated',
671
+ ][Math.floor(Math.random() * 4)],
672
+ packageName: pkg.name,
673
+ message: `Activity for ${pkg.name}`,
674
+ timestamp: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000), // Random time in last week
675
+ metadata: {
676
+ version: pkg.version,
677
+ type: pkg.type,
678
+ },
679
+ }));
680
+ // Sort by timestamp (newest first)
681
+ activities.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
682
+ res.json({
683
+ activities: activities.slice(0, Number(limit)),
684
+ total: activities.length,
685
+ });
686
+ }
687
+ catch (error) {
688
+ res.status(500).json({ error: 'Failed to fetch recent activity' });
689
+ }
690
+ });
691
+ // Get system information
692
+ app.get('/api/system', (_, res) => {
693
+ res.json({
694
+ nodeVersion: process.version,
695
+ platform: process.platform,
696
+ arch: process.arch,
697
+ memory: process.memoryUsage(),
698
+ uptime: process.uptime(),
699
+ pid: process.pid,
700
+ cwd: process.cwd(),
701
+ env: {
702
+ NODE_ENV: process.env.NODE_ENV,
703
+ PORT: process.env.PORT,
704
+ },
705
+ });
706
+ });
707
+ // ------------------------- CONFIGURATION TAB ------------------------- //
708
+ // Get all configuration files from the file system
709
+ app.get('/api/config/files', async (_req, res) => {
710
+ try {
711
+ // Find the monorepo root instead of using process.cwd()
712
+ const rootDir = findMonorepoRoot();
713
+ console.log('Monorepo root directory:', rootDir);
714
+ console.log('Backend directory:', __dirname);
715
+ const configFiles = await scanConfigFiles(rootDir);
716
+ // Transform to match frontend ConfigFile interface
717
+ const transformedFiles = configFiles.map(file => ({
718
+ id: file.id,
719
+ name: file.name,
720
+ path: file.path,
721
+ type: file.type,
722
+ content: file.content,
723
+ size: file.size,
724
+ lastModified: file.lastModified,
725
+ hasSecrets: file.hasSecrets,
726
+ isEditable: true,
727
+ // validation: validateConfig(file.content, file.name),
728
+ }));
729
+ res.json({
730
+ success: true,
731
+ files: transformedFiles,
732
+ total: transformedFiles.length,
733
+ timestamp: Date.now(),
734
+ });
735
+ }
736
+ catch (error) {
737
+ console.error('Error fetching configuration files:', error);
738
+ res.status(500).json({
739
+ success: false,
740
+ error: 'Failed to fetch configuration files',
741
+ });
742
+ }
743
+ });
744
+ /**
745
+ * Find the monorepo root by looking for package.json with workspaces or pnpm-workspace.yaml
746
+ */
747
+ function findMonorepoRoot() {
748
+ let currentDir = __dirname;
749
+ while (currentDir !== path_1.default.parse(currentDir).root) {
750
+ const packageJsonPath = path_1.default.join(currentDir, 'package.json');
751
+ const pnpmWorkspacePath = path_1.default.join(currentDir, 'pnpm-workspace.yaml');
752
+ // Check if this directory has package.json with workspaces or pnpm-workspace.yaml
753
+ if (fs_1.default.existsSync(packageJsonPath)) {
754
+ try {
755
+ const packageJson = JSON.parse(fs_1.default.readFileSync(packageJsonPath, 'utf8'));
756
+ // If it has workspaces or is the root monorepo package
757
+ if (packageJson.workspaces || fs_1.default.existsSync(pnpmWorkspacePath)) {
758
+ console.log('✅ Found monorepo root:', currentDir);
759
+ return currentDir;
760
+ }
761
+ }
762
+ catch (error) {
763
+ // Continue searching if package.json is invalid
764
+ }
765
+ }
766
+ // Check if we're at the git root
767
+ const gitPath = path_1.default.join(currentDir, '.git');
768
+ if (fs_1.default.existsSync(gitPath)) {
769
+ console.log('✅ Found git root (likely monorepo root):', currentDir);
770
+ return currentDir;
771
+ }
772
+ // Go up one directory
773
+ const parentDir = path_1.default.dirname(currentDir);
774
+ if (parentDir === currentDir)
775
+ break; // Prevent infinite loop
776
+ currentDir = parentDir;
777
+ }
778
+ // Fallback to process.cwd() if we can't find the root
779
+ console.log('⚠️ Could not find monorepo root, using process.cwd():', process.cwd());
780
+ return process.cwd();
781
+ }
782
+ // Helper function to scan for configuration files
783
+ async function scanConfigFiles(rootDir) {
784
+ const configPatterns = [
785
+ // Root level config files
786
+ 'package.json',
787
+ 'pnpm-workspace.yaml',
788
+ 'pnpm-lock.yaml',
789
+ 'turbo.json',
790
+ 'tsconfig.json',
791
+ '.eslintrc.*',
792
+ '.prettierrc',
793
+ '.prettierignore',
794
+ '.editorconfig',
795
+ '.nvmrc',
796
+ '.gitignore',
797
+ 'commitlint.config.js',
798
+ '.releaserc.json',
799
+ 'env.example',
800
+ // App-specific config files
801
+ 'vite.config.*',
802
+ 'tailwind.config.*',
803
+ 'postcss.config.*',
804
+ 'components.json',
805
+ // Package-specific config files
806
+ 'jest.config.*',
807
+ '.env*',
808
+ 'dockerfile*',
809
+ ];
810
+ const configFiles = [];
811
+ const scannedPaths = new Set();
812
+ function scanDirectory(dir, depth = 0) {
813
+ if (scannedPaths.has(dir) || depth > 8)
814
+ return; // Limit depth for safety
815
+ scannedPaths.add(dir);
816
+ try {
817
+ const items = fs_1.default.readdirSync(dir, { withFileTypes: true });
818
+ for (const item of items) {
819
+ const fullPath = path_1.default.join(dir, item.name);
820
+ if (item.isDirectory()) {
821
+ // Skip node_modules and other non-source directories
822
+ if (!shouldSkipDirectory(item.name, depth)) {
823
+ scanDirectory(fullPath, depth + 1);
824
+ }
825
+ }
826
+ else {
827
+ // Check if file matches config patterns
828
+ if (isConfigFile(item.name)) {
829
+ try {
830
+ const stats = fs_1.default.statSync(fullPath);
831
+ const content = fs_1.default.readFileSync(fullPath, 'utf8');
832
+ const relativePath = fullPath.replace(rootDir, '').replace(/\\/g, '/') ||
833
+ `/${item.name}`;
834
+ configFiles.push({
835
+ id: relativePath,
836
+ name: item.name,
837
+ path: relativePath,
838
+ type: getFileType(item.name),
839
+ content: content,
840
+ size: stats.size,
841
+ lastModified: stats.mtime.toISOString(),
842
+ hasSecrets: containsSecrets(content, item.name),
843
+ });
844
+ }
845
+ catch (error) {
846
+ console.warn(`Could not read file: ${fullPath}`);
847
+ }
848
+ }
849
+ }
850
+ }
851
+ }
852
+ catch (error) {
853
+ console.warn(`Could not scan directory: ${dir}`);
854
+ }
855
+ }
856
+ function shouldSkipDirectory(dirName, depth) {
857
+ const skipDirs = [
858
+ 'node_modules',
859
+ 'dist',
860
+ 'build',
861
+ '.git',
862
+ '.next',
863
+ '.vscode',
864
+ '.turbo',
865
+ '.husky',
866
+ '.github',
867
+ '.vite',
868
+ 'migrations',
869
+ 'coverage',
870
+ '.cache',
871
+ 'tmp',
872
+ 'temp',
873
+ ];
874
+ // At root level, be more permissive
875
+ if (depth === 0) {
876
+ return skipDirs.includes(dirName);
877
+ }
878
+ // Deeper levels, skip more directories
879
+ return skipDirs.includes(dirName) || dirName.startsWith('.');
880
+ }
881
+ function isConfigFile(filename) {
882
+ return configPatterns.some(pattern => {
883
+ if (pattern.includes('*')) {
884
+ const regex = new RegExp('^' + pattern.replace(/\*/g, '.*') + '$');
885
+ return regex.test(filename.toLowerCase());
886
+ }
887
+ return filename.toLowerCase() === pattern.toLowerCase();
888
+ });
889
+ }
890
+ console.log(`🔍 Scanning for config files in: ${rootDir}`);
891
+ // Start scanning from root
892
+ scanDirectory(rootDir);
893
+ // Sort files by path for consistent ordering
894
+ configFiles.sort((a, b) => a.path.localeCompare(b.path));
895
+ console.log(`📁 Found ${configFiles.length} configuration files`);
896
+ // Log some sample files for debugging
897
+ if (configFiles.length > 0) {
898
+ console.log('Sample config files found:');
899
+ configFiles.slice(0, 5).forEach(file => {
900
+ console.log(` - ${file.path} (${file.type})`);
901
+ });
902
+ if (configFiles.length > 5) {
903
+ console.log(` ... and ${configFiles.length - 5} more`);
904
+ }
905
+ }
906
+ return configFiles;
907
+ }
908
+ function getFileType(filename) {
909
+ const extension = filename.split('.').pop()?.toLowerCase();
910
+ switch (extension) {
911
+ case 'json':
912
+ return 'json';
913
+ case 'yaml':
914
+ case 'yml':
915
+ return 'yaml';
916
+ case 'js':
917
+ return 'javascript';
918
+ case 'ts':
919
+ return 'typescript';
920
+ case 'env':
921
+ return 'env';
922
+ case 'md':
923
+ return 'markdown';
924
+ case 'cjs':
925
+ return 'javascript';
926
+ case 'config':
927
+ return 'text';
928
+ case 'example':
929
+ return filename.includes('.env') ? 'env' : 'text';
930
+ default:
931
+ return 'text';
932
+ }
933
+ }
934
+ function containsSecrets(content, filename) {
935
+ // Only check .env files and files that might contain secrets
936
+ if (!filename.includes('.env') && !filename.includes('config')) {
937
+ return false;
938
+ }
939
+ const secretPatterns = [
940
+ /password\s*=\s*[^\s]/i,
941
+ /secret\s*=\s*[^\s]/i,
942
+ /key\s*=\s*[^\s]/i,
943
+ /token\s*=\s*[^\s]/i,
944
+ /auth\s*=\s*[^\s]/i,
945
+ /credential\s*=\s*[^\s]/i,
946
+ /api_key\s*=\s*[^\s]/i,
947
+ /private_key\s*=\s*[^\s]/i,
948
+ /DATABASE_URL/i,
949
+ /JWT_SECRET/i,
950
+ /GITHUB_TOKEN/i,
951
+ ];
952
+ return secretPatterns.some(pattern => pattern.test(content));
953
+ }
954
+ // Save configuration file
955
+ // app.put('/api/config/files/:id', async (_req, res) => {
956
+ // try {
957
+ // const { id } = _req.params;
958
+ // const { content } = _req.body;
959
+ // if (!content) {
960
+ // return res.status(400).json({
961
+ // success: false,
962
+ // error: 'Content is required',
963
+ // });
964
+ // }
965
+ // const rootDir = process.cwd();
966
+ // const filePath = path.join(rootDir, id.startsWith('/') ? id.slice(1) : id);
967
+ // // Security check: ensure the file is within the project directory
968
+ // if (!filePath.startsWith(rootDir)) {
969
+ // return res.status(403).json({
970
+ // success: false,
971
+ // error: 'Access denied',
972
+ // });
973
+ // }
974
+ // // Check if file exists and is writable
975
+ // try {
976
+ // await fs.promises.access(filePath, fs.constants.W_OK);
977
+ // } catch (error) {
978
+ // return res.status(403).json({
979
+ // success: false,
980
+ // error: 'File is not writable or does not exist',
981
+ // });
982
+ // }
983
+ // // // Backup the original file (optional but recommended)
984
+ // // const backupPath = `${filePath}.backup-${Date.now()}`;
985
+ // // try {
986
+ // // await fs.promises.copyFile(filePath, backupPath);
987
+ // // } catch (error) {
988
+ // // console.warn('Could not create backup file:', error);
989
+ // // }
990
+ // // Write the new content
991
+ // await fs.promises.writeFile(filePath, content, 'utf8');
992
+ // // Get file stats for updated information
993
+ // const stats = await fs.promises.stat(filePath);
994
+ // const filename = path.basename(filePath);
995
+ // const updatedFile = {
996
+ // id: id,
997
+ // name: filename,
998
+ // path: id,
999
+ // type: getFileType(filename),
1000
+ // content: content,
1001
+ // size: stats.size,
1002
+ // lastModified: stats.mtime.toISOString(),
1003
+ // hasSecrets: containsSecrets(content, filename),
1004
+ // isEditable: true,
1005
+ // validation: validateConfig(content, filename),
1006
+ // };
1007
+ // res.json({
1008
+ // success: true,
1009
+ // file: updatedFile,
1010
+ // message: 'File saved successfully',
1011
+ // // backupCreated: fs.existsSync(backupPath),
1012
+ // });
1013
+ // } catch (error) {
1014
+ // console.error('Error saving configuration file:', error);
1015
+ // res.status(500).json({
1016
+ // success: false,
1017
+ // error: 'Failed to save configuration file',
1018
+ // });
1019
+ // }
1020
+ // });
1021
+ app.put('/api/config/files/:id', async (_req, res) => {
1022
+ try {
1023
+ const { id } = _req.params;
1024
+ const { content } = _req.body;
1025
+ if (!content) {
1026
+ return res.status(400).json({
1027
+ success: false,
1028
+ error: 'Content is required',
1029
+ });
1030
+ }
1031
+ // Use the monorepo root
1032
+ const rootDir = findMonorepoRoot();
1033
+ const filePath = path_1.default.join(rootDir, id.startsWith('/') ? id.slice(1) : id);
1034
+ console.log('💾 Saving file:', filePath);
1035
+ console.log('📁 Root directory:', rootDir);
1036
+ // Security check: ensure the file is within the project directory
1037
+ if (!filePath.startsWith(rootDir)) {
1038
+ return res.status(403).json({
1039
+ success: false,
1040
+ error: 'Access denied',
1041
+ });
1042
+ }
1043
+ // Check if file exists and is writable
1044
+ try {
1045
+ await fs_1.default.promises.access(filePath, fs_1.default.constants.W_OK);
1046
+ }
1047
+ catch (error) {
1048
+ return res.status(403).json({
1049
+ success: false,
1050
+ error: 'File is not writable or does not exist',
1051
+ });
1052
+ }
1053
+ // Write the new content
1054
+ await fs_1.default.promises.writeFile(filePath, content, 'utf8');
1055
+ // Get file stats for updated information
1056
+ const stats = await fs_1.default.promises.stat(filePath);
1057
+ const filename = path_1.default.basename(filePath);
1058
+ const updatedFile = {
1059
+ id: id,
1060
+ name: filename,
1061
+ path: id,
1062
+ type: getFileType(filename),
1063
+ content: content,
1064
+ size: stats.size,
1065
+ lastModified: stats.mtime.toISOString(),
1066
+ hasSecrets: containsSecrets(content, filename),
1067
+ isEditable: true,
1068
+ // validation: validateConfig(content, filename),
1069
+ };
1070
+ res.json({
1071
+ success: true,
1072
+ file: updatedFile,
1073
+ message: 'File saved successfully',
1074
+ });
1075
+ }
1076
+ catch (error) {
1077
+ console.error('Error saving configuration file:', error);
1078
+ res.status(500).json({
1079
+ success: false,
1080
+ error: 'Failed to save configuration file',
1081
+ });
1082
+ }
1083
+ });
1084
+ // Error handling middleware
1085
+ app.use((error, _req, res, _next) => {
1086
+ console.error('Error:', error);
1087
+ res.status(500).json({
1088
+ error: 'Internal server error',
1089
+ message: error.message,
1090
+ timestamp: Date.now(),
1091
+ });
1092
+ });
1093
+ // 404 handler
1094
+ app.use('*', (_, res) => {
1095
+ res.status(404).json({
1096
+ error: 'Endpoint not found',
1097
+ timestamp: Date.now(),
1098
+ });
1099
+ });
1100
+ const PORT = process.env.PORT || 4000;
1101
+ app.listen(PORT, () => {
1102
+ console.log(`🚀 Backend server running on http://localhost:${PORT}`);
1103
+ console.log(`📊 API endpoints available:`);
1104
+ console.log(` - GET /api/health`);
1105
+ console.log(` - GET /api/packages/refresh`);
1106
+ console.log(` - GET /api/packages`);
1107
+ console.log(` - GET /api/packages/:name`);
1108
+ console.log(` - GET /api/commits/:packagePath`);
1109
+ console.log(` - GET /api/graph`);
1110
+ console.log(` - GET /api/stats`);
1111
+ console.log(` - GET /api/ci/status`);
1112
+ console.log(` - POST /api/ci/trigger`);
1113
+ console.log(` - POST /api/scan`);
1114
+ console.log(` - GET /api/health/packages`);
1115
+ console.log(` - GET /api/search`);
1116
+ console.log(` - GET /api/activity`);
1117
+ console.log(` - GET /api/system`);
1118
+ }).on('error', (err) => {
1119
+ // Handle common errors like EADDRINUSE (port already in use)
1120
+ if (err.message.includes('EADDRINUSE')) {
1121
+ console.error(`Error: Port ${port} is already in use. Please specify a different port via the PORT environment variable.`);
1122
+ process.exit(1);
1123
+ }
1124
+ else {
1125
+ console.error('Server failed to start:', err);
1126
+ process.exit(1);
1127
+ }
1128
+ });
1129
+ // export default app;
1130
+ // const overallScore =
1131
+ // healthMetrics.reduce((sum, h) => sum + h.health!.overallScore, 0) /
1132
+ // healthMetrics.length;
1133
+ // const metrics: HealthMetric[] = [
1134
+ // {
1135
+ // name: 'Package Health',
1136
+ // value: healthMetrics.filter(h => h.isHealthy).length || 0,
1137
+ // status: calculateHealthStatus(
1138
+ // healthMetrics.filter(h => h.isHealthy).length,
1139
+ // packages.length
1140
+ // ),
1141
+ // description: `${healthMetrics.filter(h => h.isHealthy).length || 0} healthy packages out of ${packages.length || 0}`,
1142
+ // },
1143
+ // {
1144
+ // name: 'Overall Score',
1145
+ // value: Math.round(overallScore),
1146
+ // status:
1147
+ // Math.round(overallScore) >= 80
1148
+ // ? 'healthy'
1149
+ // : Math.round(overallScore) >= 60
1150
+ // ? 'warning'
1151
+ // : 'error',
1152
+ // description: `Average health score: ${Math.round(overallScore)}/100`,
1153
+ // },
1154
+ // {
1155
+ // name: 'Unhealthy Packages',
1156
+ // value: healthMetrics.filter(h => !h.isHealthy).length || 0,
1157
+ // status:
1158
+ // (healthMetrics.filter(h => !h.isHealthy).length || 0) === 0
1159
+ // ? 'healthy'
1160
+ // : (healthMetrics.filter(h => !h.isHealthy).length || 0) <= 2
1161
+ // ? 'warning'
1162
+ // : 'error',
1163
+ // description: `${healthMetrics.filter(h => !h.isHealthy).length || 0} packages need attention`,
1164
+ // },
1165
+ // ];
1166
+ // const packageHealth = packages.map((pkg: any) => ({
1167
+ // package: pkg.packageName,
1168
+ // score: pkg.health?.overallScore || 0,
1169
+ // issues: pkg.error
1170
+ // ? [pkg.error]
1171
+ // : (pkg.health?.overallScore || 0) < 80
1172
+ // ? ['Needs improvement']
1173
+ // : [],
1174
+ // }));
1175
+ // res.status(200).json({
1176
+ // overallScore,
1177
+ // metrics,
1178
+ // packageHealth,
1179
+ // });
1180
+ }
1181
+ // This is a test file to ensure the TypeScript compiler can find an input.
1182
+ // export const runBackend = (name: string): string => {
1183
+ // return `Backend running successfully for ${name}.`;
1184
+ // };
1185
+ // console.log(runBackend("MonoDog"));