@sdxc/kit 2026.10.21 → 2026.10.24

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 (113) hide show
  1. package/README.md +84 -4
  2. package/changelog.jsonl +168 -0
  3. package/config.schema.json +154 -0
  4. package/dist/architecture/complexity.d.ts +73 -0
  5. package/dist/architecture/complexity.js +185 -0
  6. package/dist/architecture/crap.d.ts +62 -0
  7. package/dist/architecture/crap.js +121 -0
  8. package/dist/architecture/graph.d.ts +55 -0
  9. package/dist/architecture/graph.js +194 -0
  10. package/dist/architecture/layers.d.ts +29 -0
  11. package/dist/architecture/layers.js +81 -0
  12. package/dist/architecture/mermaid.d.ts +20 -0
  13. package/dist/architecture/mermaid.js +51 -0
  14. package/dist/cli.js +9 -0
  15. package/dist/commands/create.js +4 -3
  16. package/dist/commands/deploy.js +10 -9
  17. package/dist/commands/destroy.d.ts +1 -1
  18. package/dist/commands/diagram.d.ts +17 -0
  19. package/dist/commands/diagram.js +45 -0
  20. package/dist/commands/fix.d.ts +69 -0
  21. package/dist/commands/fix.js +102 -0
  22. package/dist/commands/make.d.ts +71 -2
  23. package/dist/commands/make.js +46 -0
  24. package/dist/commands/run.d.ts +15 -11
  25. package/dist/commands/run.js +21 -16
  26. package/dist/commands/scaffold.d.ts +1 -1
  27. package/dist/commands/setup.d.ts +26 -0
  28. package/dist/commands/setup.js +33 -0
  29. package/dist/config.d.ts +52 -0
  30. package/dist/config.js +88 -1
  31. package/dist/contract.d.ts +52 -3
  32. package/dist/contract.js +124 -2
  33. package/dist/dependencies.js +7 -1
  34. package/dist/deploy/plan.d.ts +5 -0
  35. package/dist/deploy/plan.js +10 -0
  36. package/dist/destroy.js +13 -6
  37. package/dist/diagram.d.ts +32 -0
  38. package/dist/diagram.js +47 -0
  39. package/dist/doctor/checks.d.ts +2 -1
  40. package/dist/doctor/checks.js +24 -1
  41. package/dist/doctor/complexity.d.ts +13 -0
  42. package/dist/doctor/complexity.js +52 -0
  43. package/dist/doctor/crap.d.ts +14 -0
  44. package/dist/doctor/crap.js +67 -0
  45. package/dist/doctor/dependencies.d.ts +13 -0
  46. package/dist/doctor/dependencies.js +42 -0
  47. package/dist/doctor/duplication.d.ts +19 -0
  48. package/dist/doctor/duplication.js +106 -0
  49. package/dist/doctor/fan-out.d.ts +12 -0
  50. package/dist/doctor/fan-out.js +42 -0
  51. package/dist/doctor/feature-scatter.d.ts +15 -0
  52. package/dist/doctor/feature-scatter.js +84 -0
  53. package/dist/doctor/module-size.d.ts +13 -0
  54. package/dist/doctor/module-size.js +50 -0
  55. package/dist/doctor/mutation.d.ts +20 -0
  56. package/dist/doctor/mutation.js +97 -0
  57. package/dist/doctor/orphans.d.ts +13 -0
  58. package/dist/doctor/orphans.js +50 -0
  59. package/dist/doctor/project.js +8 -5
  60. package/dist/doctor/result-throws.d.ts +17 -0
  61. package/dist/doctor/result-throws.js +72 -0
  62. package/dist/doctor/test-ratio.d.ts +12 -0
  63. package/dist/doctor/test-ratio.js +31 -0
  64. package/dist/fix/commands.d.ts +37 -0
  65. package/dist/fix/commands.js +63 -0
  66. package/dist/fix/emails.d.ts +21 -0
  67. package/dist/fix/emails.js +159 -0
  68. package/dist/fix/env.d.ts +29 -0
  69. package/dist/fix/env.js +58 -0
  70. package/dist/fix/index.d.ts +11 -0
  71. package/dist/fix/index.js +11 -0
  72. package/dist/fix/models.d.ts +20 -0
  73. package/dist/fix/models.js +95 -0
  74. package/dist/lock.js +12 -2
  75. package/dist/make/binding.d.ts +42 -0
  76. package/dist/make/binding.js +237 -0
  77. package/dist/make/imports.js +7 -5
  78. package/dist/make/schema-diff.js +8 -1
  79. package/dist/models.js +7 -7
  80. package/dist/routes/modules.js +8 -5
  81. package/dist/routes/parse.js +8 -7
  82. package/dist/routes/routers.js +9 -5
  83. package/dist/setup/auth.d.ts +12 -0
  84. package/dist/setup/auth.js +209 -0
  85. package/dist/setup/billing.d.ts +11 -0
  86. package/dist/setup/billing.js +116 -0
  87. package/dist/setup/catalog.d.ts +25 -0
  88. package/dist/setup/catalog.js +34 -0
  89. package/dist/setup/credit.d.ts +13 -0
  90. package/dist/setup/credit.js +21 -0
  91. package/dist/setup/flags.d.ts +11 -0
  92. package/dist/setup/flags.js +62 -0
  93. package/dist/setup/index.d.ts +25 -0
  94. package/dist/setup/index.js +53 -0
  95. package/dist/setup/plan.d.ts +38 -0
  96. package/dist/setup/plan.js +62 -0
  97. package/dist/testing.js +3 -3
  98. package/dist/ui/layout.js +1 -1
  99. package/dist/ui/registry.d.ts +2 -2
  100. package/dist/upgrade/project.d.ts +2 -2
  101. package/dist/upgrade/prompt.js +7 -5
  102. package/package.json +11 -8
  103. package/registry/ui/attachment.json +2 -2
  104. package/registry/ui/breadcrumbs.json +6 -3
  105. package/registry/ui/group.json +6 -3
  106. package/registry/ui/link-button.json +3 -3
  107. package/registry/ui/link.json +6 -3
  108. package/registry/ui/nav-link.json +6 -3
  109. package/registry/ui/navigation-menu.json +6 -3
  110. package/registry/ui/pagination.json +3 -3
  111. package/registry/ui/sidebar.json +3 -3
  112. package/templates/app/AGENTS.md +14 -1
  113. package/templates/app/package.json +1 -1
@@ -112,6 +112,123 @@
112
112
  "default": {
113
113
  "accept": []
114
114
  }
115
+ },
116
+ "complexity": {
117
+ "type": "object",
118
+ "properties": {
119
+ "max": {
120
+ "type": "integer",
121
+ "minimum": 1,
122
+ "default": 4,
123
+ "description": "Maximum cyclomatic complexity per function; the complexity check warns above it"
124
+ }
125
+ },
126
+ "additionalProperties": false,
127
+ "default": {
128
+ "max": 4
129
+ }
130
+ },
131
+ "moduleSize": {
132
+ "type": "object",
133
+ "properties": {
134
+ "maxLines": {
135
+ "type": "integer",
136
+ "minimum": 1,
137
+ "default": 200,
138
+ "description": "Maximum code lines per module; the module-size check warns above it"
139
+ }
140
+ },
141
+ "additionalProperties": false,
142
+ "default": {
143
+ "maxLines": 200
144
+ }
145
+ },
146
+ "crap": {
147
+ "type": "object",
148
+ "properties": {
149
+ "max": {
150
+ "type": "integer",
151
+ "minimum": 1,
152
+ "default": 12,
153
+ "description": "Maximum CRAP score per function; the crap check warns above it"
154
+ },
155
+ "coverage": {
156
+ "type": "string",
157
+ "default": "coverage/coverage-final.json",
158
+ "description": "Istanbul coverage-final.json the crap check reads, relative to the project root"
159
+ }
160
+ },
161
+ "additionalProperties": false,
162
+ "default": {
163
+ "max": 12,
164
+ "coverage": "coverage/coverage-final.json"
165
+ }
166
+ },
167
+ "testRatio": {
168
+ "type": "object",
169
+ "properties": {
170
+ "min": {
171
+ "type": "number",
172
+ "minimum": 0,
173
+ "default": 0.3,
174
+ "description": "Minimum tests/code ratio from sdxc stats; the test-ratio check warns below it"
175
+ }
176
+ },
177
+ "additionalProperties": false,
178
+ "default": {
179
+ "min": 0.3
180
+ }
181
+ },
182
+ "fanOut": {
183
+ "type": "object",
184
+ "properties": {
185
+ "max": {
186
+ "type": "integer",
187
+ "minimum": 1,
188
+ "default": 15,
189
+ "description": "Maximum distinct modules one file may import; the fan-out check warns above it"
190
+ }
191
+ },
192
+ "additionalProperties": false,
193
+ "default": {
194
+ "max": 15
195
+ }
196
+ },
197
+ "duplication": {
198
+ "type": "object",
199
+ "properties": {
200
+ "minLines": {
201
+ "type": "integer",
202
+ "minimum": 2,
203
+ "default": 8,
204
+ "description": "Minimum consecutive code lines that count as a duplicated block"
205
+ }
206
+ },
207
+ "additionalProperties": false,
208
+ "default": {
209
+ "minLines": 8
210
+ }
211
+ },
212
+ "mutation": {
213
+ "type": "object",
214
+ "properties": {
215
+ "report": {
216
+ "type": "string",
217
+ "default": "reports/mutation/mutation.json",
218
+ "description": "Mutation report JSON the mutation check reads, relative to the project root"
219
+ },
220
+ "maxSurvived": {
221
+ "type": "integer",
222
+ "minimum": 0,
223
+ "default": 0,
224
+ "description": "Maximum surviving mutants the mutation check allows"
225
+ }
226
+ },
227
+ "additionalProperties": false,
228
+ "default": {
229
+ "report": "reports/mutation/mutation.json",
230
+ "maxSurvived": 0
231
+ }
115
232
  }
116
233
  },
117
234
  "additionalProperties": false,
@@ -119,9 +236,46 @@
119
236
  "checks": ".config/sdxc/checks",
120
237
  "migrations": {
121
238
  "accept": []
239
+ },
240
+ "complexity": {
241
+ "max": 4
242
+ },
243
+ "moduleSize": {
244
+ "maxLines": 200
245
+ },
246
+ "crap": {
247
+ "max": 12,
248
+ "coverage": "coverage/coverage-final.json"
249
+ },
250
+ "testRatio": {
251
+ "min": 0.3
252
+ },
253
+ "fanOut": {
254
+ "max": 15
255
+ },
256
+ "duplication": {
257
+ "minLines": 8
258
+ },
259
+ "mutation": {
260
+ "report": "reports/mutation/mutation.json",
261
+ "maxSurvived": 0
122
262
  }
123
263
  }
124
264
  },
265
+ "run": {
266
+ "type": "object",
267
+ "properties": {
268
+ "entry": {
269
+ "type": "string",
270
+ "default": "bootstrap/cli.ts",
271
+ "description": "Module `sdxc run` starts, relative to the project root; apps keep the default"
272
+ }
273
+ },
274
+ "additionalProperties": false,
275
+ "default": {
276
+ "entry": "bootstrap/cli.ts"
277
+ }
278
+ },
125
279
  "format": {
126
280
  "type": "array",
127
281
  "items": {
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Cyclomatic complexity per function, from an oxc AST walk: each decision point adds one to a
3
+ * base of one, so a straight-line function scores 1 and an `if` raises it to 2. Doctor and CRAP
4
+ * both read this so the same function never gets two answers.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ /** One function (or method) and the cyclomatic complexity of its body. */
10
+ export interface FunctionComplexity {
11
+ /** Human-readable name: `name`, `Class.method`, or `(anonymous)`. */
12
+ name: string;
13
+ /** 1-based line the function starts on. */
14
+ line: number;
15
+ /** McCabe cyclomatic complexity of the function body. */
16
+ complexity: number;
17
+ }
18
+ /** A node the walker recognises as holding a nested AST. */
19
+ interface AstNode {
20
+ type: string;
21
+ start?: number;
22
+ end?: number;
23
+ name?: string;
24
+ key?: AstNode | null;
25
+ id?: AstNode | null;
26
+ value?: AstNode | null;
27
+ body?: AstNode | AstNode[] | null;
28
+ params?: AstNode[];
29
+ operator?: string;
30
+ test?: AstNode | null;
31
+ consequent?: AstNode | null;
32
+ alternate?: AstNode | null;
33
+ expression?: AstNode | null;
34
+ callee?: AstNode | null;
35
+ object?: AstNode | null;
36
+ property?: AstNode | null;
37
+ left?: AstNode | null;
38
+ right?: AstNode | null;
39
+ argument?: AstNode | null;
40
+ arguments?: AstNode[];
41
+ elements?: Array<AstNode | null>;
42
+ properties?: AstNode[];
43
+ declarations?: AstNode[];
44
+ init?: AstNode | null;
45
+ update?: AstNode | null;
46
+ discriminant?: AstNode | null;
47
+ cases?: AstNode[];
48
+ block?: AstNode | null;
49
+ handler?: AstNode | null;
50
+ finalizer?: AstNode | null;
51
+ superClass?: AstNode | null;
52
+ declaration?: AstNode | null;
53
+ specifiers?: AstNode[];
54
+ source?: AstNode | null;
55
+ kind?: string;
56
+ static?: boolean;
57
+ computed?: boolean;
58
+ [key: string]: unknown;
59
+ }
60
+ /**
61
+ * Every function in `source` with its cyclomatic complexity. A file oxc cannot parse yields an
62
+ * empty list so the type checker, not doctor, names the syntax error.
63
+ *
64
+ * @param filename - Path reported for language detection (`.ts` / `.tsx`).
65
+ * @param source - Module text.
66
+ */
67
+ export declare function measureComplexity(filename: string, source: string): FunctionComplexity[];
68
+ /**
69
+ * McCabe complexity of `node`'s own body: nested functions contribute their entry edge only
70
+ * through separate records, not through this count.
71
+ */
72
+ export declare function complexityOf(node: AstNode): number;
73
+ export {};
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Cyclomatic complexity per function, from an oxc AST walk: each decision point adds one to a
3
+ * base of one, so a straight-line function scores 1 and an `if` raises it to 2. Doctor and CRAP
4
+ * both read this so the same function never gets two answers.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import { parseSync } from "oxc-parser";
10
+ /** Node types that open a function whose body is measured on its own. */
11
+ const FUNCTION_TYPES = new Set([
12
+ "FunctionDeclaration",
13
+ "FunctionExpression",
14
+ "ArrowFunctionExpression",
15
+ "TSDeclareFunction",
16
+ ]);
17
+ /**
18
+ * Every function in `source` with its cyclomatic complexity. A file oxc cannot parse yields an
19
+ * empty list so the type checker, not doctor, names the syntax error.
20
+ *
21
+ * @param filename - Path reported for language detection (`.ts` / `.tsx`).
22
+ * @param source - Module text.
23
+ */
24
+ export function measureComplexity(filename, source) {
25
+ let parsed = parseSync(filename, source);
26
+ if (parsed.errors.length > 0 && parsed.program.body.length === 0)
27
+ return [];
28
+ let findings = [];
29
+ visit(parsed.program, source, findings, null);
30
+ return findings;
31
+ }
32
+ /**
33
+ * Walks `node`, recording each function and descending into nested ones without double-counting
34
+ * a method's `FunctionExpression` under its `MethodDefinition`.
35
+ */
36
+ function visit(node, source, findings, className) {
37
+ if (node == null || typeof node !== "object" || typeof node.type !== "string")
38
+ return;
39
+ if (node.type === "ClassDeclaration" || node.type === "ClassExpression") {
40
+ let name = node.id?.name ?? className;
41
+ for (let child of children(node))
42
+ visit(child, source, findings, name ?? null);
43
+ return;
44
+ }
45
+ if (node.type === "MethodDefinition" || node.type === "PropertyDefinition") {
46
+ let method = methodName(node, className);
47
+ if (node.value && FUNCTION_TYPES.has(node.value.type)) {
48
+ recordFunction(node.value, source, findings, method);
49
+ return;
50
+ }
51
+ for (let child of children(node))
52
+ visit(child, source, findings, className);
53
+ return;
54
+ }
55
+ if (node.type === "Property" && node.value && FUNCTION_TYPES.has(node.value.type)) {
56
+ recordFunction(node.value, source, findings, propertyName(node) ?? "(anonymous)");
57
+ return;
58
+ }
59
+ if (FUNCTION_TYPES.has(node.type)) {
60
+ recordFunction(node, source, findings, functionName(node, className));
61
+ return;
62
+ }
63
+ for (let child of children(node))
64
+ visit(child, source, findings, className);
65
+ }
66
+ /** Records one function and walks nested functions inside its body. */
67
+ function recordFunction(node, source, findings, name) {
68
+ if (node.type === "TSDeclareFunction" || node.body == null)
69
+ return;
70
+ findings.push({
71
+ name,
72
+ line: lineOf(source, node.start ?? 0),
73
+ complexity: complexityOf(node),
74
+ });
75
+ for (let child of children(node.body))
76
+ visit(child, source, findings, null);
77
+ for (let param of node.params ?? [])
78
+ visit(param, source, findings, null);
79
+ }
80
+ /**
81
+ * McCabe complexity of `node`'s own body: nested functions contribute their entry edge only
82
+ * through separate records, not through this count.
83
+ */
84
+ export function complexityOf(node) {
85
+ let score = 1;
86
+ walkDecisions(node.body ?? node, (decision) => {
87
+ score += decision;
88
+ });
89
+ return score;
90
+ }
91
+ /** Visits decision points inside `node`, skipping nested function boundaries. */
92
+ function walkDecisions(node, add) {
93
+ if (node == null)
94
+ return;
95
+ if (Array.isArray(node)) {
96
+ for (let child of node)
97
+ walkDecisions(child, add);
98
+ return;
99
+ }
100
+ if (typeof node !== "object" || typeof node.type !== "string")
101
+ return;
102
+ if (FUNCTION_TYPES.has(node.type))
103
+ return;
104
+ switch (node.type) {
105
+ case "IfStatement":
106
+ case "ForStatement":
107
+ case "ForInStatement":
108
+ case "ForOfStatement":
109
+ case "WhileStatement":
110
+ case "DoWhileStatement":
111
+ case "CatchClause":
112
+ case "ConditionalExpression":
113
+ add(1);
114
+ break;
115
+ case "SwitchCase":
116
+ if (node.test != null)
117
+ add(1);
118
+ break;
119
+ case "LogicalExpression":
120
+ if (node.operator === "&&" || node.operator === "||" || node.operator === "??")
121
+ add(1);
122
+ break;
123
+ default:
124
+ break;
125
+ }
126
+ for (let child of children(node))
127
+ walkDecisions(child, add);
128
+ }
129
+ /** Direct child nodes, skipping location metadata. */
130
+ function children(node) {
131
+ let result = [];
132
+ for (let [key, value] of Object.entries(node)) {
133
+ if (key === "type" || key === "start" || key === "end" || key === "range" || key === "loc") {
134
+ continue;
135
+ }
136
+ if (Array.isArray(value)) {
137
+ for (let item of value) {
138
+ if (item && typeof item === "object" && typeof item.type === "string") {
139
+ result.push(item);
140
+ }
141
+ }
142
+ }
143
+ else if (value && typeof value === "object" && typeof value.type === "string") {
144
+ result.push(value);
145
+ }
146
+ }
147
+ return result;
148
+ }
149
+ function functionName(node, className) {
150
+ if (node.id?.name) {
151
+ return className ? `${className}.${node.id.name}` : node.id.name;
152
+ }
153
+ return "(anonymous)";
154
+ }
155
+ function methodName(node, className) {
156
+ let key = propertyName(node) ?? "(anonymous)";
157
+ let prefix = node.static ? "static " : "";
158
+ let kind = node.kind === "get" || node.kind === "set" ? `${node.kind} ` : "";
159
+ let full = `${prefix}${kind}${key}`;
160
+ return className ? `${className}.${full}` : full;
161
+ }
162
+ function propertyName(node) {
163
+ let key = node.key;
164
+ if (!key)
165
+ return null;
166
+ if (key.type === "Identifier")
167
+ return key.name ?? null;
168
+ if (key.type === "PrivateIdentifier")
169
+ return `#${key.name ?? ""}`;
170
+ if (key.type === "Literal") {
171
+ let literal = key;
172
+ if (typeof literal.value === "string")
173
+ return literal.value;
174
+ }
175
+ return null;
176
+ }
177
+ /** 1-based line of `index` in `source`. */
178
+ function lineOf(source, index) {
179
+ let line = 1;
180
+ for (let i = 0; i < index && i < source.length; i++) {
181
+ if (source.charCodeAt(i) === 10)
182
+ line += 1;
183
+ }
184
+ return line;
185
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * CRAP (Change Risk Anti-Patterns) scores: cyclomatic complexity squared times uncovered cubed,
3
+ * plus complexity — the metric Uncle Bob uses with agents so an untested complex function
4
+ * outranks a covered one. Coverage comes from Istanbul's `coverage-final.json` when present.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import type { FunctionComplexity } from "./complexity.js";
10
+ /** One function's CRAP score with the inputs that produced it. */
11
+ export interface CrapScore {
12
+ file: string;
13
+ name: string;
14
+ line: number;
15
+ complexity: number;
16
+ /** Coverage fraction in `[0, 1]`; `null` when no coverage data matched the function. */
17
+ coverage: number | null;
18
+ /** The CRAP value, or `null` when coverage is unknown. */
19
+ crap: number | null;
20
+ }
21
+ /** Istanbul's per-file entry in `coverage-final.json`. */
22
+ interface IstanbulFile {
23
+ path?: string;
24
+ fnMap?: Record<string, {
25
+ name?: string;
26
+ decl?: {
27
+ start?: {
28
+ line?: number;
29
+ };
30
+ };
31
+ }>;
32
+ f?: Record<string, number>;
33
+ s?: Record<string, number>;
34
+ statementMap?: Record<string, {
35
+ start?: {
36
+ line?: number;
37
+ };
38
+ end?: {
39
+ line?: number;
40
+ };
41
+ }>;
42
+ }
43
+ /**
44
+ * CRAP = CC² × (1 − coverage)³ + CC. Coverage is a fraction; a fully covered function of
45
+ * complexity `cc` scores exactly `cc`.
46
+ */
47
+ export declare function crapScore(complexity: number, coverage: number): number;
48
+ /**
49
+ * Scores each function, attaching coverage from `coverageByFile` when a hit map names it.
50
+ * Without a match the score stays `null` so the doctor check can skip or warn on unknowns.
51
+ */
52
+ export declare function scoreFunctions(file: string, functions: readonly FunctionComplexity[], coverageByFile: ReadonlyMap<string, IstanbulFile>): CrapScore[];
53
+ /**
54
+ * Loads Istanbul's `coverage-final.json` at `path` (absolute or relative to `root`) into a map
55
+ * keyed by project-relative paths. A missing or unreadable file yields an empty map.
56
+ */
57
+ export declare function loadCoverage(root: string, path: string): Promise<Map<string, IstanbulFile>>;
58
+ /** Whether `path` exists as a readable coverage file under `root`. */
59
+ export declare function coverageExists(root: string, path: string): Promise<boolean>;
60
+ /** Joins `root` and a relative coverage path for error messages. */
61
+ export declare function coveragePath(root: string, relative: string): string;
62
+ export {};
@@ -0,0 +1,121 @@
1
+ /**
2
+ * CRAP (Change Risk Anti-Patterns) scores: cyclomatic complexity squared times uncovered cubed,
3
+ * plus complexity — the metric Uncle Bob uses with agents so an untested complex function
4
+ * outranks a covered one. Coverage comes from Istanbul's `coverage-final.json` when present.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import { readFile } from "node:fs/promises";
10
+ import { join, resolve } from "node:path";
11
+ import { isFailure, wrap } from "@sdxc/result";
12
+ /**
13
+ * CRAP = CC² × (1 − coverage)³ + CC. Coverage is a fraction; a fully covered function of
14
+ * complexity `cc` scores exactly `cc`.
15
+ */
16
+ export function crapScore(complexity, coverage) {
17
+ let uncovered = 1 - clamp(coverage, 0, 1);
18
+ return complexity * complexity * uncovered * uncovered * uncovered + complexity;
19
+ }
20
+ /**
21
+ * Scores each function, attaching coverage from `coverageByFile` when a hit map names it.
22
+ * Without a match the score stays `null` so the doctor check can skip or warn on unknowns.
23
+ */
24
+ export function scoreFunctions(file, functions, coverageByFile) {
25
+ let entry = coverageByFile.get(normalizePath(file));
26
+ return functions.map((fn) => {
27
+ let coverage = entry ? functionCoverage(entry, fn) : null;
28
+ return {
29
+ file,
30
+ name: fn.name,
31
+ line: fn.line,
32
+ complexity: fn.complexity,
33
+ coverage,
34
+ crap: coverage === null ? null : crapScore(fn.complexity, coverage),
35
+ };
36
+ });
37
+ }
38
+ /**
39
+ * Loads Istanbul's `coverage-final.json` at `path` (absolute or relative to `root`) into a map
40
+ * keyed by project-relative paths. A missing or unreadable file yields an empty map.
41
+ */
42
+ export async function loadCoverage(root, path) {
43
+ let absolute = resolve(root, path);
44
+ let text = await wrap(() => readFile(absolute, "utf8"));
45
+ if (isFailure(text))
46
+ return new Map();
47
+ let parsed = await wrap(() => Promise.resolve(JSON.parse(text.data)));
48
+ if (isFailure(parsed) || typeof parsed.data !== "object" || parsed.data === null) {
49
+ return new Map();
50
+ }
51
+ let map = new Map();
52
+ for (let [key, value] of Object.entries(parsed.data)) {
53
+ let relative = toProjectPath(root, value.path ?? key);
54
+ map.set(normalizePath(relative), value);
55
+ }
56
+ return map;
57
+ }
58
+ /** Whether `path` exists as a readable coverage file under `root`. */
59
+ export async function coverageExists(root, path) {
60
+ let absolute = resolve(root, path);
61
+ let text = await wrap(() => readFile(absolute, "utf8"));
62
+ return !isFailure(text);
63
+ }
64
+ /**
65
+ * Coverage fraction for `fn` from Istanbul's function hit map, falling back to statement
66
+ * coverage on the function's starting line when the name is missing from `fnMap`.
67
+ */
68
+ function functionCoverage(entry, fn) {
69
+ if (entry.fnMap && entry.f) {
70
+ for (let [id, meta] of Object.entries(entry.fnMap)) {
71
+ let name = meta.name ?? "";
72
+ let line = meta.decl?.start?.line;
73
+ let nameMatch = name === fn.name ||
74
+ name.endsWith(`.${fn.name}`) ||
75
+ (fn.name !== "(anonymous)" && name === fn.name.split(".").pop());
76
+ let lineMatch = line === undefined || line === fn.line;
77
+ if (nameMatch && lineMatch) {
78
+ let hits = entry.f[id] ?? 0;
79
+ return hits > 0 ? 1 : 0;
80
+ }
81
+ }
82
+ }
83
+ if (entry.statementMap && entry.s) {
84
+ let total = 0;
85
+ let covered = 0;
86
+ for (let [id, span] of Object.entries(entry.statementMap)) {
87
+ let start = span.start?.line ?? 0;
88
+ let end = span.end?.line ?? start;
89
+ if (fn.line < start || fn.line > end)
90
+ continue;
91
+ total += 1;
92
+ if ((entry.s[id] ?? 0) > 0)
93
+ covered += 1;
94
+ }
95
+ if (total > 0)
96
+ return covered / total;
97
+ }
98
+ return null;
99
+ }
100
+ function toProjectPath(root, filePath) {
101
+ let absolute = resolve(filePath);
102
+ let rootAbsolute = resolve(root);
103
+ if (absolute.startsWith(rootAbsolute)) {
104
+ return absolute
105
+ .slice(rootAbsolute.length)
106
+ .replace(/^[\\/]/, "")
107
+ .split("\\")
108
+ .join("/");
109
+ }
110
+ return filePath.split("\\").join("/");
111
+ }
112
+ function normalizePath(path) {
113
+ return path.split("\\").join("/");
114
+ }
115
+ function clamp(value, min, max) {
116
+ return Math.min(max, Math.max(min, value));
117
+ }
118
+ /** Joins `root` and a relative coverage path for error messages. */
119
+ export function coveragePath(root, relative) {
120
+ return join(root, relative);
121
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The project's import graph over app source: each relative or `~/` edge between modules, so
3
+ * architecture diagrams and the dependency doctor check share one walk of `findModuleReferences`.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ import type { Layer } from "./layers.js";
9
+ /** One directed import from a module to another module inside the project. */
10
+ export interface ImportEdge {
11
+ /** The importing file, relative to the project root. */
12
+ from: string;
13
+ /** The resolved target file when known, else the normalised specifier path. */
14
+ to: string;
15
+ /** The specifier as written in the source. */
16
+ specifier: string;
17
+ }
18
+ /** An edge between two layers, with how many module edges it aggregates. */
19
+ export interface LayerEdge {
20
+ from: Layer;
21
+ to: Layer;
22
+ count: number;
23
+ /** Whether every underlying edge obeys the dependency rule. */
24
+ allowed: boolean;
25
+ }
26
+ /** What {@link projectGraph} reports. */
27
+ export interface ProjectGraph {
28
+ /** Every app-source module that was scanned. */
29
+ modules: string[];
30
+ /** Relative and `~/` imports that resolve inside the project. */
31
+ edges: ImportEdge[];
32
+ /** Module edges rolled up by layer, for the architecture diagram. */
33
+ layers: LayerEdge[];
34
+ /** Strongly connected components with more than one module, or a self-cycle. */
35
+ cycles: string[][];
36
+ /** Module edges that point from an inner layer to an outer one. */
37
+ violations: ImportEdge[];
38
+ }
39
+ /**
40
+ * Builds the import graph of the project at `root` from every app-source module under the
41
+ * layout folders. Specifiers that leave the project (packages, absolute URLs) are ignored.
42
+ */
43
+ export declare function projectGraph(root: string): Promise<ProjectGraph>;
44
+ /** Rolls module edges into layer-to-layer counts. */
45
+ export declare function aggregateLayers(edges: readonly ImportEdge[]): LayerEdge[];
46
+ /**
47
+ * Resolves `specifier` written in `file` to a project-relative path without extension, or
48
+ * `null` when it names a package or a URL.
49
+ */
50
+ export declare function resolveSpecifier(specifier: string, file: string): string | null;
51
+ /**
52
+ * Every cycle in the directed graph, as the modules on the cycle in visit order. A module that
53
+ * imports itself is a one-node cycle.
54
+ */
55
+ export declare function findCycles(modules: readonly string[], edges: readonly ImportEdge[]): string[][];