-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode-health.ts
More file actions
1556 lines (1338 loc) · 50.1 KB
/
Copy pathcode-health.ts
File metadata and controls
1556 lines (1338 loc) · 50.1 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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bun
/**
* Unified Code Health Report
* Combines: oxlint, knip (dead code), jscpd (duplicates), madge (orphans/circular),
* tsc (types), complexity analysis, architecture boundaries, structure analysis
*
* Usage:
* bun scripts/code-health.ts # Full report
* bun scripts/code-health.ts --quick # Skip slow checks (jscpd, madge, architecture)
* bun scripts/code-health.ts --fix # Auto-fix what's possible
*/
import { writeFile, mkdir, readFile, readdir, stat } from "fs/promises";
import { join } from "path";
// ============================================================================
// Configuration
// ============================================================================
const LOG_DIR = join(process.cwd(), "logs");
const REPORT_FILE = join(LOG_DIR, "code-health-report.md");
const JSON_FILE = join(LOG_DIR, "code-health-report.json");
const args = process.argv.slice(2);
const isQuick = args.includes("--quick");
const isFix = args.includes("--fix");
interface CheckResult {
name: string;
status: "pass" | "warn" | "fail" | "skip";
duration: number;
issues: Issue[];
summary: string;
rawOutput?: string;
}
interface Issue {
type: "error" | "warning" | "info";
file?: string;
line?: number;
message: string;
rule?: string;
fix?: string; // Suggested fix for the issue
}
// Complexity thresholds - these are guidelines, not hard rules
const THRESHOLDS = {
FILE_LINES_WARNING: 300,
FILE_LINES_ERROR: 500,
COMPONENT_HOOKS_WARNING: 6, // Many hooks suggests component is doing too much
COMPONENT_HOOKS_ERROR: 10,
COMPONENT_USEEFFECT_WARNING: 4, // Many effects suggests side-effect sprawl
COMPONENT_USEMEMO_WARNING: 6, // Many memos suggests over-optimization or complexity
FOLDER_DEPTH_WARNING: 5,
FOLDER_DEPTH_ERROR: 7,
FILES_PER_FOLDER_WARNING: 15,
FILES_PER_FOLDER_ERROR: 25,
};
interface HealthReport {
timestamp: string;
duration: number;
checks: CheckResult[];
totals: {
errors: number;
warnings: number;
info: number;
};
grade: "A" | "B" | "C" | "D" | "F";
}
// ============================================================================
// Utility Functions
// ============================================================================
async function runCommand(cmd: string[], cwd?: string): Promise<{ stdout: string; stderr: string; exitCode: number }> {
try {
const proc = Bun.spawn(cmd, {
stdout: "pipe",
stderr: "pipe",
cwd: cwd ?? process.cwd(),
});
const [stdout, stderr] = await Promise.all([
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
]);
const exitCode = await proc.exited;
return { stdout, stderr, exitCode };
} catch (error: any) {
return { stdout: "", stderr: error.message, exitCode: 1 };
}
}
function formatDuration(ms: number): string {
if (ms < 1000) return `${ms}ms`;
return `${(ms / 1000).toFixed(1)}s`;
}
function getStatusEmoji(status: CheckResult["status"]): string {
switch (status) {
case "pass": return "✅";
case "warn": return "⚠️";
case "fail": return "❌";
case "skip": return "⏭️";
}
}
// ============================================================================
// Check Implementations
// ============================================================================
async function checkEslint(): Promise<CheckResult> {
const start = Date.now();
const issues: Issue[] = [];
console.log(" Running ESLint (import/complexity rules)...");
const { stdout, stderr } = await runCommand(["bunx", "eslint", ".", "--ext", ".ts,.tsx", "--format", "json", "--max-warnings", "0"]);
try {
const parsed = JSON.parse(stdout);
const eslintResults = Array.isArray(parsed) ? parsed : parsed.results || [];
for (const result of eslintResults) {
if (result.messages && Array.isArray(result.messages)) {
for (const message of result.messages) {
const line = message.line || 0;
issues.push({
type: message.severity === 2 ? "error" : "warning",
file: result.filePath,
line,
message: message.message,
rule: message.ruleId,
});
}
}
}
} catch {
// Fallback to text parsing
const lines = stdout.split("\n").filter(Boolean);
for (const line of lines) {
if (line.includes("error") || line.includes("warning")) {
const parts = line.split(":");
const file = parts[0]?.trim();
const lineNum = parseInt(parts[1]?.trim() || "0");
const msg = parts.slice(2).join(":").trim();
issues.push({
type: line.includes("error") ? "error" : "warning",
file,
line: lineNum,
message: msg
});
}
}
}
const errors = issues.filter(i => i.type === "error").length;
const warnings = issues.filter(i => i.type === "warning").length;
return {
name: "Import & Complexity (ESLint)",
status: errors > 0 ? "fail" : warnings > 0 ? "warn" : "pass",
duration: Date.now() - start,
issues,
summary: `${errors} errors, ${warnings} warnings`,
rawOutput: stdout + stderr,
};
}
async function checkOxlint(): Promise<CheckResult> {
const start = Date.now();
const issues: Issue[] = [];
console.log(" Running oxlint...");
const fixArgs = isFix ? ["--fix"] : [];
const { stdout, stderr } = await runCommand(["bunx", "oxlint", "--format", "json", ...fixArgs]);
try {
const parsed = JSON.parse(stdout);
// Handle oxlint JSON format with diagnostics array
const diagnostics = parsed.diagnostics || (Array.isArray(parsed) ? parsed : []);
for (const item of diagnostics) {
// Extract line number from labels if available
let line = item.line;
if (!line && item.labels && item.labels[0]?.span?.line) {
line = item.labels[0].span.line;
}
issues.push({
type: item.severity === "error" ? "error" : "warning",
file: item.filename || item.file,
line,
message: item.message,
rule: item.code || item.ruleId || item.rule,
});
}
} catch {
// Non-JSON output, parse text
const lines = stdout.split("\n").filter(Boolean);
for (const line of lines) {
if (line.includes("error") || line.includes("warning")) {
issues.push({ type: "warning", message: line });
}
}
}
const errors = issues.filter(i => i.type === "error").length;
const warnings = issues.filter(i => i.type === "warning").length;
return {
name: "Linting (oxlint)",
status: errors > 0 ? "fail" : warnings > 0 ? "warn" : "pass",
duration: Date.now() - start,
issues,
summary: `${errors} errors, ${warnings} warnings`,
rawOutput: stdout + stderr,
};
}
async function checkKnip(): Promise<CheckResult> {
const start = Date.now();
const issues: Issue[] = [];
console.log(" Running knip (dead code detection)...");
const { stdout, stderr } = await runCommand(["bunx", "knip", "--reporter", "json"]);
try {
const parsed = JSON.parse(stdout);
// Process unused files
if (parsed.files && Array.isArray(parsed.files)) {
for (const file of parsed.files) {
issues.push({
type: "warning",
file,
message: "Unused file - not imported anywhere",
rule: "knip/unused-file",
});
}
}
// Process issues array (knip v5 format)
if (parsed.issues && Array.isArray(parsed.issues)) {
for (const issue of parsed.issues) {
const file = issue.file;
// Unused dependencies
if (issue.dependencies && Array.isArray(issue.dependencies)) {
for (const dep of issue.dependencies) {
issues.push({
type: "warning",
file,
line: dep.line,
message: `Unused dependency: ${dep.name}`,
rule: "knip/unused-dependency",
});
}
}
// Unused devDependencies
if (issue.devDependencies && Array.isArray(issue.devDependencies)) {
for (const dep of issue.devDependencies) {
issues.push({
type: "info",
file,
line: dep.line,
message: `Unused devDependency: ${dep.name}`,
rule: "knip/unused-devdep",
});
}
}
// Unused exports
if (issue.exports && Array.isArray(issue.exports)) {
for (const exp of issue.exports) {
issues.push({
type: "info",
file,
line: exp.line,
message: `Unused export: ${exp.name}`,
rule: "knip/unused-export",
});
}
}
// Unused types
if (issue.types && Array.isArray(issue.types)) {
for (const typ of issue.types) {
issues.push({
type: "info",
file,
line: typ.line,
message: `Unused type: ${typ.name}`,
rule: "knip/unused-type",
});
}
}
// Unresolved imports
if (issue.unresolved && Array.isArray(issue.unresolved)) {
for (const unres of issue.unresolved) {
issues.push({
type: "error",
file,
line: unres.line,
message: `Unresolved import: ${unres.name}`,
rule: "knip/unresolved",
});
}
}
// Duplicate exports
if (issue.duplicates && Array.isArray(issue.duplicates)) {
for (const dup of issue.duplicates) {
if (Array.isArray(dup) && dup.length > 1) {
const names = dup.map((d: any) => d.name).join(", ");
issues.push({
type: "info",
file,
message: `Duplicate exports: ${names}`,
rule: "knip/duplicate-export",
});
}
}
}
}
}
// Fallback: old knip format
if (parsed.exports && Array.isArray(parsed.exports)) {
for (const exp of parsed.exports) {
issues.push({
type: "info",
file: exp.file || exp.filename,
message: `Unused export: ${exp.name || exp.symbol}`,
rule: "knip/unused-export",
});
}
}
if (parsed.dependencies && Array.isArray(parsed.dependencies)) {
for (const dep of parsed.dependencies) {
issues.push({
type: "warning",
message: `Unused dependency: ${dep}`,
rule: "knip/unused-dependency",
});
}
}
if (parsed.unlisted && Array.isArray(parsed.unlisted)) {
for (const dep of parsed.unlisted) {
issues.push({
type: "error",
message: `Unlisted dependency used: ${dep}`,
rule: "knip/unlisted-dependency",
});
}
}
} catch {
// Parse text output as fallback
const lines = stdout.split("\n").filter(Boolean);
for (const line of lines) {
if (line.includes("Unused") || line.includes("unused")) {
issues.push({ type: "warning", message: line.trim() });
}
}
}
const errors = issues.filter(i => i.type === "error").length;
const warnings = issues.filter(i => i.type === "warning").length;
const infos = issues.filter(i => i.type === "info").length;
return {
name: "Dead Code (knip)",
status: errors > 0 ? "fail" : warnings > 0 ? "warn" : "pass",
duration: Date.now() - start,
issues,
summary: `${errors} errors, ${warnings} unused deps, ${infos} unused exports`,
rawOutput: stdout + stderr,
};
}
async function checkJscpd(): Promise<CheckResult> {
if (isQuick) {
return {
name: "Duplicate Code (jscpd)",
status: "skip",
duration: 0,
issues: [],
summary: "Skipped (--quick mode)",
};
}
const start = Date.now();
const issues: Issue[] = [];
console.log(" Running jscpd (duplicate detection)...");
const { stdout, stderr } = await runCommand([
"bunx", "jscpd",
"./packages", "./apps",
"--min-lines", "10",
"--reporters", "json,console",
"--ignore", "**/node_modules/**,**/*.test.*,**/_generated/**,**/routeTree.gen.ts",
]);
const output = stdout + stderr;
// Parse text output - jscpd outputs "Clone found" blocks to console
// Format: Clone found (tsx):
// - file1.tsx [line:col - line:col] (X lines, Y tokens)
// file2.tsx [line:col - line:col]
// Strip ANSI codes for cleaner parsing
// eslint-disable-next-line no-control-regex
const cleanOutput = output.replace(/\u001b\[[0-9;]*m/g, "");
// Match clone blocks - each "Clone found" section
const cloneRegex = /Clone found \((\w+)\):\s*\n\s*-\s*(.+?)\s*\[(\d+):\d+\s*-\s*(\d+):\d+\]\s*\((\d+)\s*lines[^)]*\)\s*\n\s*(.+?)\s*\[(\d+):\d+\s*-\s*(\d+):\d+\]/g;
let match;
while ((match = cloneRegex.exec(cleanOutput)) !== null) {
const [, _lang, file1, startLine1, endLine1, lineCount, file2, startLine2, endLine2] = match;
// Clean up file paths
const cleanFile1 = file1.replace(/\\/g, "/").trim();
const cleanFile2 = file2.replace(/\\/g, "/").trim();
issues.push({
type: "warning",
file: cleanFile1,
line: parseInt(startLine1),
message: `Duplicate code (${lineCount} lines, L${startLine1}-${endLine1}) also in: ${cleanFile2} (L${startLine2}-${endLine2})`,
rule: "jscpd/duplicate",
});
}
// If regex didn't match, try simpler counting
if (issues.length === 0 && cleanOutput.includes("Clone found")) {
const cloneMatches = cleanOutput.match(/Clone found/g);
const count = cloneMatches?.length || 0;
// Parse simpler format line by line
const lines = cleanOutput.split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line.includes("Clone found")) {
// Get the next two lines for file info
const file1Line = lines[i + 1] || "";
const file2Line = lines[i + 2] || "";
const file1Match = file1Line.match(/-\s*(.+?)\s*\[(\d+):\d+\s*-\s*(\d+):\d+\]\s*\((\d+)\s*lines/);
const file2Match = file2Line.match(/^\s+(.+?)\s*\[(\d+):\d+\s*-\s*(\d+):\d+\]/);
if (file1Match && file2Match) {
const [, f1, start1, end1, lineCount] = file1Match;
const [, f2, start2, end2] = file2Match;
issues.push({
type: "warning",
file: f1.replace(/\\/g, "/").trim(),
line: parseInt(start1),
message: `Duplicate (${lineCount} lines, L${start1}-${end1}) → ${f2.replace(/\\/g, "/").trim()} (L${start2}-${end2})`,
rule: "jscpd/duplicate",
});
}
}
}
// Fallback if still no matches
if (issues.length === 0 && count > 0) {
issues.push({
type: "warning",
message: `Found ${count} code duplications (see logs/code-health-report.json for rawOutput)`,
rule: "jscpd/duplicate",
});
}
}
// Try to read the JSON report for additional stats
try {
const jsonReport = await Bun.file(join(process.cwd(), "report", "jscpd-report.json")).json();
if (jsonReport.statistics?.total) {
const stats = jsonReport.statistics.total;
if (stats.percentage > 0) {
issues.push({
type: "info",
message: `Overall duplication: ${stats.percentage.toFixed(1)}% of codebase (${stats.clones || issues.length} clones, ${stats.duplicatedLines || "?"} duplicated lines)`,
rule: "jscpd/stats",
});
}
}
} catch {
// JSON report not available, that's fine
}
const warnings = issues.filter(i => i.type === "warning").length;
return {
name: "Duplicate Code (jscpd)",
status: warnings > 10 ? "warn" : "pass",
duration: Date.now() - start,
issues,
summary: `${warnings} duplicate blocks found`,
rawOutput: output,
};
}
async function checkMadge(): Promise<CheckResult> {
if (isQuick) {
return {
name: "Dependency Graph (madge)",
status: "skip",
duration: 0,
issues: [],
summary: "Skipped (--quick mode)",
};
}
const start = Date.now();
const issues: Issue[] = [];
console.log(" Running madge (orphans & circular deps)...");
// Check for orphan files
const orphanResult = await runCommand([
"bunx", "madge", "--orphans", "--extensions", "ts,tsx",
"./packages/backend/convex",
]);
const orphans = orphanResult.stdout
.split("\n")
.map(line => line.trim())
.filter(line => {
if (!line) return false;
if (line.includes("No orphans")) return false;
if (line.startsWith("Using")) return false;
if (line.startsWith("Processed")) return false;
if (line.includes("files (")) return false;
// Must look like a file path
return line.endsWith(".ts") || line.endsWith(".tsx");
});
for (const orphan of orphans) {
// Skip config files that are expected to be orphans
const isExpectedOrphan =
orphan.includes("config.ts") ||
orphan.includes(".config.ts") ||
orphan.includes("_generated");
issues.push({
type: isExpectedOrphan ? "info" : "warning",
file: `packages/backend/convex/${orphan}`,
message: isExpectedOrphan
? "Config file (expected to be standalone)"
: "Orphan file - nothing imports this",
rule: "madge/orphan",
});
}
// Check for circular dependencies
const circularResult = await runCommand([
"bunx", "madge", "--circular", "--extensions", "ts,tsx",
"./packages/backend/convex",
]);
// Parse circular deps - look for chains like "a.ts → b.ts → c.ts"
const circularLines = circularResult.stdout
.split("\n")
.filter(line => line.includes("→") && !line.startsWith("Processed"));
for (const cycle of circularLines) {
const cleanCycle = cycle.trim();
if (cleanCycle) {
issues.push({
type: "error",
message: `Circular: ${cleanCycle}`,
rule: "madge/circular",
});
}
}
const errors = issues.filter(i => i.type === "error").length;
const warnings = issues.filter(i => i.type === "warning").length;
return {
name: "Dependency Graph (madge)",
status: errors > 0 ? "fail" : warnings > 0 ? "warn" : "pass",
duration: Date.now() - start,
issues,
summary: `${errors} circular deps, ${warnings} orphan files`,
rawOutput: orphanResult.stdout + "\n---\n" + circularResult.stdout,
};
}
async function checkTypeScript(): Promise<CheckResult> {
const start = Date.now();
const issues: Issue[] = [];
console.log(" Running TypeScript type check...");
const { stdout, stderr } = await runCommand([
"bunx", "turbo", "check-types", "--output-logs=errors-only"
]);
const output = stdout + stderr;
// Parse TypeScript errors from turbo output
const errorLines = output.split("\n").filter(line =>
line.includes("error TS") || line.includes(": error")
);
for (const line of errorLines) {
const match = line.match(/(.+?)\((\d+),\d+\):\s*error\s*(TS\d+):\s*(.+)/);
if (match) {
issues.push({
type: "error",
file: match[1],
line: parseInt(match[2]),
message: match[4],
rule: match[3],
});
} else if (line.includes("error")) {
issues.push({
type: "error",
message: line.trim(),
});
}
}
const errors = issues.length;
return {
name: "TypeScript Types",
status: errors > 0 ? "fail" : "pass",
duration: Date.now() - start,
issues,
summary: `${errors} type errors`,
rawOutput: output,
};
}
// ============================================================================
// Complexity Analysis - File size, hook patterns, component complexity
// ============================================================================
interface FileAnalysis {
path: string;
lines: number;
hooks: {
useState: number;
useEffect: number;
useMemo: number;
useCallback: number;
useRef: number;
useQuery: number;
useMutation: number;
custom: number;
};
patterns: {
inlineErrorBoundary: boolean;
multipleComponents: boolean;
deepJsxNesting: boolean;
longFunctions: string[];
mixedConcerns: boolean;
};
}
async function analyzeFile(filePath: string): Promise<FileAnalysis | null> {
try {
const content = await readFile(filePath, "utf-8");
const lines = content.split("\n");
// Count hooks
const hooks = {
useState: (content.match(/useState\s*[<(]/g) || []).length,
useEffect: (content.match(/useEffect\s*\(/g) || []).length,
useMemo: (content.match(/useMemo\s*\(/g) || []).length,
useCallback: (content.match(/useCallback\s*\(/g) || []).length,
useRef: (content.match(/useRef\s*[<(]/g) || []).length,
useQuery: (content.match(/useQuery\s*\(/g) || []).length,
useMutation: (content.match(/useMutation\s*\(/g) || []).length,
custom: (content.match(/\buse[A-Z][a-zA-Z]*\s*\(/g) || []).length -
(content.match(/useState|useEffect|useMemo|useCallback|useRef|useQuery|useMutation/g) || []).length,
};
// Detect problematic patterns
const patterns = {
// Inline error boundary class in a functional component file
inlineErrorBoundary: /class\s+\w*Error\w*\s+extends\s+React\.Component/.test(content),
// Multiple exported components in one file
multipleComponents: (content.match(/export\s+(const|function)\s+[A-Z][a-zA-Z]*\s*[=:]/g) || []).length > 2,
// Deep JSX nesting (rough heuristic: many nested divs/fragments)
deepJsxNesting: (content.match(/<(?:div|Fragment|>)[^>]*>\s*<(?:div|Fragment|>)/g) || []).length > 10,
// Long functions (functions over ~50 lines)
longFunctions: detectLongFunctions(content),
// Mixed concerns: business logic + UI in same file
mixedConcerns: detectMixedConcerns(content),
};
return {
path: filePath,
lines: lines.length,
hooks,
patterns,
};
} catch {
return null;
}
}
function detectLongFunctions(content: string): string[] {
const longFunctions: string[] = [];
// Simple heuristic: find function declarations and check distance to next one
const lines = content.split("\n");
let currentFunction = "";
let functionStartLine = 0;
let braceDepth = 0;
let inFunction = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Detect function start
const funcMatch = line.match(/(?:function\s+(\w+)|const\s+(\w+)\s*=\s*(?:async\s*)?\(|const\s+(\w+)\s*=\s*React\.memo)/);
if (funcMatch && !inFunction) {
currentFunction = funcMatch[1] || funcMatch[2] || funcMatch[3] || "anonymous";
functionStartLine = i;
inFunction = true;
braceDepth = 0;
}
// Track braces
braceDepth += (line.match(/{/g) || []).length;
braceDepth -= (line.match(/}/g) || []).length;
// Function end
if (inFunction && braceDepth <= 0 && i > functionStartLine) {
const functionLength = i - functionStartLine;
if (functionLength > 80) {
longFunctions.push(`${currentFunction} (${functionLength} lines)`);
}
inFunction = false;
}
}
return longFunctions;
}
function detectMixedConcerns(content: string): boolean {
// Check if file has both heavy business logic AND JSX
const hasJsx = /<\w+[^>]*>/.test(content);
const hasHeavyLogic =
(content.match(/\.map\s*\(/g) || []).length > 3 &&
(content.match(/\.filter\s*\(/g) || []).length > 2 ||
(content.match(/if\s*\(/g) || []).length > 10;
return hasJsx && hasHeavyLogic;
}
async function findFiles(dir: string, pattern: RegExp, ignore: RegExp[]): Promise<string[]> {
const files: string[] = [];
async function walk(currentDir: string) {
try {
const entries = await readdir(currentDir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = join(currentDir, entry.name);
// Check ignore patterns
if (ignore.some(re => re.test(fullPath))) continue;
if (entry.isDirectory()) {
await walk(fullPath);
} else if (entry.isFile() && pattern.test(entry.name)) {
files.push(fullPath);
}
}
} catch {
// Directory not accessible
}
}
await walk(dir);
return files;
}
async function checkComplexity(): Promise<CheckResult> {
const start = Date.now();
const issues: Issue[] = [];
console.log(" Running complexity analysis...");
const ignorePatterns = [
/node_modules/,
/_generated/,
/\.test\./,
/\.spec\./,
/routeTree\.gen/,
];
// Find all TSX/TS files in apps/web/src
const files = await findFiles(
join(process.cwd(), "apps/web/src"),
/\.(tsx?|ts)$/,
ignorePatterns
);
let largeFiles = 0;
let complexComponents = 0;
for (const file of files) {
const analysis = await analyzeFile(file);
if (!analysis) continue;
const relativePath = file.replace(process.cwd() + "/", "").replace(process.cwd() + "\\", "");
// Check file size
if (analysis.lines > THRESHOLDS.FILE_LINES_ERROR) {
largeFiles++;
issues.push({
type: "error",
file: relativePath,
message: `File has ${analysis.lines} lines (max ${THRESHOLDS.FILE_LINES_ERROR})`,
rule: "complexity/file-size",
fix: "Split into smaller, focused modules. Extract hooks, utilities, and sub-components.",
});
} else if (analysis.lines > THRESHOLDS.FILE_LINES_WARNING) {
issues.push({
type: "warning",
file: relativePath,
message: `File has ${analysis.lines} lines (consider splitting at ${THRESHOLDS.FILE_LINES_WARNING}+)`,
rule: "complexity/file-size",
fix: "Consider extracting reusable logic into hooks or utilities.",
});
}
// Check hook complexity (only for .tsx files - components)
if (file.endsWith(".tsx")) {
const totalHooks = analysis.hooks.useState + analysis.hooks.useEffect +
analysis.hooks.useMemo + analysis.hooks.useCallback +
analysis.hooks.useRef + analysis.hooks.custom;
if (totalHooks >= THRESHOLDS.COMPONENT_HOOKS_ERROR) {
complexComponents++;
issues.push({
type: "error",
file: relativePath,
message: `Component uses ${totalHooks} hooks (useState: ${analysis.hooks.useState}, useEffect: ${analysis.hooks.useEffect}, useMemo: ${analysis.hooks.useMemo}, useCallback: ${analysis.hooks.useCallback}, custom: ${analysis.hooks.custom})`,
rule: "complexity/too-many-hooks",
fix: "Extract related hooks into a custom hook (e.g., useComponentNameState). Split component into smaller pieces.",
});
} else if (totalHooks >= THRESHOLDS.COMPONENT_HOOKS_WARNING) {
issues.push({
type: "warning",
file: relativePath,
message: `Component uses ${totalHooks} hooks - getting complex`,
rule: "complexity/too-many-hooks",
fix: "Consider extracting related state and effects into a custom hook.",
});
}
// Check for too many useEffects (side-effect sprawl)
if (analysis.hooks.useEffect >= THRESHOLDS.COMPONENT_USEEFFECT_WARNING) {
issues.push({
type: "warning",
file: relativePath,
message: `Component has ${analysis.hooks.useEffect} useEffect calls - side-effect sprawl`,
rule: "complexity/effect-sprawl",
fix: "Consolidate related effects or extract to custom hooks. Consider if effects can be replaced with event handlers.",
});
}
// Check for over-memoization
if (analysis.hooks.useMemo + analysis.hooks.useCallback >= THRESHOLDS.COMPONENT_USEMEMO_WARNING) {
issues.push({
type: "info",
file: relativePath,
message: `Component has ${analysis.hooks.useMemo} useMemo and ${analysis.hooks.useCallback} useCallback - possible over-optimization`,
rule: "complexity/over-memoization",
fix: "Review if all memos are necessary. React 19 compiler handles most memoization automatically.",
});
}
}
// Check for problematic patterns
if (analysis.patterns.inlineErrorBoundary) {
issues.push({
type: "warning",
file: relativePath,
message: "Inline error boundary class in component file",
rule: "pattern/inline-error-boundary",
fix: "Move error boundary to shared/components/ErrorBoundary.tsx and import it.",
});
}
if (analysis.patterns.multipleComponents) {
issues.push({
type: "info",
file: relativePath,
message: "Multiple exported components in one file",
rule: "pattern/multiple-components",
fix: "Consider splitting each component into its own file for better organization.",
});
}
if (analysis.patterns.longFunctions.length > 0) {
for (const func of analysis.patterns.longFunctions.slice(0, 3)) {
issues.push({
type: "warning",
file: relativePath,
message: `Long function: ${func}`,
rule: "complexity/long-function",
fix: "Break down into smaller functions. Extract logic into utilities or hooks.",
});
}
}
if (analysis.patterns.mixedConcerns) {
issues.push({
type: "info",
file: relativePath,
message: "File appears to mix business logic with UI rendering",
rule: "pattern/mixed-concerns",
fix: "Extract business logic to hooks/utilities. Keep components focused on rendering.",
});
}
}
const errors = issues.filter(i => i.type === "error").length;
const warnings = issues.filter(i => i.type === "warning").length;
return {
name: "Complexity Analysis",
status: errors > 0 ? "fail" : warnings > 5 ? "warn" : "pass",
duration: Date.now() - start,
issues,
summary: `${largeFiles} oversized files, ${complexComponents} complex components, ${warnings} warnings`,
};
}
// ============================================================================
// Architecture Boundaries - Using dependency-cruiser
// ============================================================================
async function checkArchitecture(): Promise<CheckResult> {
if (isQuick) {
return {
name: "Architecture Boundaries",
status: "skip",
duration: 0,
issues: [],
summary: "Skipped (--quick mode)",
};
}
const start = Date.now();
const issues: Issue[] = [];
console.log(" Running architecture boundary check...");
// Check if dependency-cruiser config exists
const configPath = join(process.cwd(), ".dependency-cruiser.cjs");
try {
await stat(configPath);
} catch {
return {
name: "Architecture Boundaries",
status: "skip",
duration: Date.now() - start,
issues: [{
type: "info",
message: "No .dependency-cruiser.cjs config found - skipping architecture check",
fix: "Create .dependency-cruiser.cjs to define module boundaries",
}],
summary: "Config not found",
};
}
const { stdout, stderr } = await runCommand([
"bunx", "dependency-cruiser",
"--config", ".dependency-cruiser.cjs",
"--output-type", "json",
"./apps/web/src"
]);
try {