crap-ts 0.1.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.
- package/CONTRIBUTING.md +32 -0
- package/LICENSE +21 -0
- package/README.md +190 -0
- package/package.json +51 -0
- package/src/cli.js +254 -0
- package/src/crap-analysis.d.ts +34 -0
- package/src/crap-analysis.js +173 -0
- package/src/crap-runner.d.ts +14 -0
- package/src/crap-runner.js +103 -0
- package/src/crap-score.d.ts +24 -0
- package/src/crap-score.js +65 -0
- package/src/index.d.ts +16 -0
- package/src/index.js +8 -0
- package/src/path-utils.js +3 -0
package/CONTRIBUTING.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Contributing
|
|
2
|
+
|
|
3
|
+
Pull requests are welcome.
|
|
4
|
+
|
|
5
|
+
Good fits:
|
|
6
|
+
|
|
7
|
+
- bug fixes
|
|
8
|
+
- clearer docs
|
|
9
|
+
- small CLI improvements
|
|
10
|
+
- edge-case tests
|
|
11
|
+
- compatibility fixes for common coverage output
|
|
12
|
+
|
|
13
|
+
Smaller changes are easier to deal with, larger changes may require more discussion.
|
|
14
|
+
|
|
15
|
+
## Checks
|
|
16
|
+
|
|
17
|
+
Run these before opening a PR:
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
npm run check
|
|
21
|
+
npm run validate
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Taste
|
|
25
|
+
|
|
26
|
+
- CRAP means cyclomatic complexity plus coverage.
|
|
27
|
+
- Keep coverage input explicit.
|
|
28
|
+
- Prefer obvious flags over clever ones.
|
|
29
|
+
- Add tests for behavior changes.
|
|
30
|
+
- Avoid framework-specific assumptions unless they are configurable.
|
|
31
|
+
|
|
32
|
+
Gotta keep the CRAP low!
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 cubanx
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
# crap-ts
|
|
2
|
+
|
|
3
|
+
Small CRAP-score audit helper for TypeScript projects.
|
|
4
|
+
|
|
5
|
+
`crap-ts` computes CRAP scores from TypeScript cyclomatic complexity plus
|
|
6
|
+
Istanbul/V8 coverage data.
|
|
7
|
+
|
|
8
|
+
CRAP stands for **Change Risk Anti-Patterns**, from Alberto Savoia and Bob
|
|
9
|
+
Evans' work on combining cyclomatic complexity with test coverage. Savoia
|
|
10
|
+
explains the metric in Google's testing blog post, ["This Code is
|
|
11
|
+
CRAP"](https://testing.googleblog.com/2011/02/this-code-is-crap.html), and the
|
|
12
|
+
old [Crap4J FAQ](https://www.crap4j.org/faq.html) uses the same expansion.
|
|
13
|
+
Risky code plus weak tests, now with a name your manager will remember.
|
|
14
|
+
|
|
15
|
+
## Works Out Of The Box With
|
|
16
|
+
|
|
17
|
+
- TypeScript source files listed in an Istanbul-style `coverage-final.json`
|
|
18
|
+
- Vitest V8 coverage, Jest coverage, or nyc/Istanbul coverage that includes
|
|
19
|
+
function maps
|
|
20
|
+
- npm, Bun, pnpm, or any runner that can produce coverage before `crap-ts` reads
|
|
21
|
+
it
|
|
22
|
+
|
|
23
|
+
No Biome required. No framework plugin. Bring coverage JSON, get CRAP. Very
|
|
24
|
+
glamorous work, obviously.
|
|
25
|
+
|
|
26
|
+
## Install
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
npm install --save-dev crap-ts
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Usage
|
|
33
|
+
|
|
34
|
+
Run the built-in TypeScript AST audit against coverage-final data:
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
npx crap-ts score --coverage-command "npm run test:coverage -- --coverage.reporter=json" --coverage-file coverage/unit/coverage-final.json --include src
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Add package scripts:
|
|
41
|
+
|
|
42
|
+
```json
|
|
43
|
+
{
|
|
44
|
+
"scripts": {
|
|
45
|
+
"check:crap": "crap-ts score --report-only",
|
|
46
|
+
"check:crap:strict": "crap-ts score"
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
`check:crap` is useful while calibrating. `check:crap:strict` is the gate.
|
|
52
|
+
|
|
53
|
+
Put the long bits in `.crap-ts.json`:
|
|
54
|
+
|
|
55
|
+
```json
|
|
56
|
+
{
|
|
57
|
+
"coverageCommand": "npm run test:coverage -- --coverage.reporter=json --coverage.reporter=json-summary",
|
|
58
|
+
"coverageFile": "coverage/unit/coverage-final.json",
|
|
59
|
+
"include": ["src"],
|
|
60
|
+
"max": 30,
|
|
61
|
+
"minLines": 10,
|
|
62
|
+
"limit": 20
|
|
63
|
+
}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
You can also compute CRAP scores from an external metrics file and coverage
|
|
67
|
+
summary:
|
|
68
|
+
|
|
69
|
+
```sh
|
|
70
|
+
npx crap-ts --metrics fixtures/complexity-metrics.json --coverage-file fixtures/coverage-summary.json
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Workflow
|
|
74
|
+
|
|
75
|
+
The direct CRAP audit:
|
|
76
|
+
|
|
77
|
+
- reads function coverage from Istanbul/V8 `coverage-final.json`
|
|
78
|
+
- calculates function cyclomatic complexity from the TypeScript AST
|
|
79
|
+
- prints the highest-risk functions
|
|
80
|
+
- fails strict mode when any score is above the configured threshold
|
|
81
|
+
|
|
82
|
+
CRAP combines complexity and coverage:
|
|
83
|
+
|
|
84
|
+
```text
|
|
85
|
+
crap = complexity^2 * (1 - coverage)^3 + complexity
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
For direct audits, `coverage` is function coverage from `coverage-final.json`.
|
|
89
|
+
For metrics-file scoring, `coverage` is read from an Istanbul-style
|
|
90
|
+
`coverage-summary.json` file.
|
|
91
|
+
|
|
92
|
+
When the complexity or CRAP check flags a hotspot:
|
|
93
|
+
|
|
94
|
+
1. Name the affected function or file in the review.
|
|
95
|
+
2. Confirm there is direct test coverage for that path.
|
|
96
|
+
3. Add or tighten tests if behavior is unclear.
|
|
97
|
+
4. Refactor only after the expected behavior is pinned down.
|
|
98
|
+
|
|
99
|
+
The point is not to chase a number for sport. The point is to make hard-to-read
|
|
100
|
+
branching visible before it becomes a maintenance tax.
|
|
101
|
+
|
|
102
|
+
## CLI
|
|
103
|
+
|
|
104
|
+
```sh
|
|
105
|
+
crap-ts score [--coverage-file coverage/unit/coverage-final.json] [--coverage-command "npm run test:coverage"]
|
|
106
|
+
crap-ts --metrics complexity-metrics.json --coverage-file coverage/coverage-summary.json
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Options:
|
|
110
|
+
|
|
111
|
+
- `--config <path>`: read config from a JSON file. Defaults to `.crap-ts.json`
|
|
112
|
+
when present.
|
|
113
|
+
- `--coverage-file <path>`: read coverage from a coverage JSON file.
|
|
114
|
+
- `--coverage-command <cmd>`: run a coverage command before scoring.
|
|
115
|
+
- `--all`: print every analyzed function instead of applying `--limit`.
|
|
116
|
+
- `--include <text>`: only analyze coverage files whose path contains this text.
|
|
117
|
+
- `--limit <n>`: number of report rows to print. Defaults to `20`.
|
|
118
|
+
- `--max <n>`: strict CRAP threshold for direct audit. Defaults to `30`.
|
|
119
|
+
- `--min-lines <n>`: ignore functions shorter than this. Defaults to `10`.
|
|
120
|
+
- `--metrics <path>`: read complexity metrics from JSON.
|
|
121
|
+
- `--report-only`: print CRAP results without failing on threshold.
|
|
122
|
+
- `--skip-coverage`: use an existing coverage file.
|
|
123
|
+
|
|
124
|
+
Metrics files use this shape:
|
|
125
|
+
|
|
126
|
+
```json
|
|
127
|
+
[
|
|
128
|
+
{
|
|
129
|
+
"file": "src/example.ts",
|
|
130
|
+
"name": "chooseValue",
|
|
131
|
+
"complexity": 12
|
|
132
|
+
}
|
|
133
|
+
]
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
Config files use camelCase keys:
|
|
137
|
+
|
|
138
|
+
```json
|
|
139
|
+
{
|
|
140
|
+
"coverageCommand": "npm run test:coverage",
|
|
141
|
+
"coverageFile": "coverage/unit/coverage-final.json",
|
|
142
|
+
"include": ["src"],
|
|
143
|
+
"all": false,
|
|
144
|
+
"limit": 20,
|
|
145
|
+
"max": 30,
|
|
146
|
+
"minLines": 10,
|
|
147
|
+
"reportOnly": false,
|
|
148
|
+
"skipCoverage": false
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
CLI flags override config. Naturally. The command line gets the last word,
|
|
153
|
+
because you'd be mad at me if it didn't, and I'd also be mad at me.
|
|
154
|
+
|
|
155
|
+
## Replacing Local CRAP Scripts
|
|
156
|
+
|
|
157
|
+
For a Bun/Vitest app that already writes coverage to `coverage/unit`, local
|
|
158
|
+
scripts can usually shrink to:
|
|
159
|
+
|
|
160
|
+
```json
|
|
161
|
+
{
|
|
162
|
+
"scripts": {
|
|
163
|
+
"check:crap": "crap-ts score --report-only",
|
|
164
|
+
"check:crap:strict": "crap-ts score"
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
With `.crap-ts.json`:
|
|
170
|
+
|
|
171
|
+
```json
|
|
172
|
+
{
|
|
173
|
+
"coverageCommand": "bun x vitest run --coverage --coverage.reporter=json --coverage.reporter=json-summary",
|
|
174
|
+
"coverageFile": "coverage/unit/coverage-final.json",
|
|
175
|
+
"include": ["/app/", "/scripts/"]
|
|
176
|
+
}
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
After that, repo-local CRAP analyzer scripts and tests can be deleted. Keep the
|
|
180
|
+
project's coverage test config; that remains the source of truth for coverage
|
|
181
|
+
instrumentation.
|
|
182
|
+
|
|
183
|
+
## Contributing
|
|
184
|
+
|
|
185
|
+
Pull requests are welcome. Keep them focused, add tests when behavior changes,
|
|
186
|
+
and see [CONTRIBUTING.md](CONTRIBUTING.md) sullying my code ;)
|
|
187
|
+
|
|
188
|
+
## License
|
|
189
|
+
|
|
190
|
+
MIT
|
package/package.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "crap-ts",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Small CRAP-score audit helper for TypeScript projects.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"crap-ts": "src/cli.js"
|
|
8
|
+
},
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./src/index.d.ts",
|
|
12
|
+
"default": "./src/index.js"
|
|
13
|
+
},
|
|
14
|
+
"./crap-analysis": {
|
|
15
|
+
"types": "./src/crap-analysis.d.ts",
|
|
16
|
+
"default": "./src/crap-analysis.js"
|
|
17
|
+
},
|
|
18
|
+
"./crap-runner": {
|
|
19
|
+
"types": "./src/crap-runner.d.ts",
|
|
20
|
+
"default": "./src/crap-runner.js"
|
|
21
|
+
},
|
|
22
|
+
"./crap-score": {
|
|
23
|
+
"types": "./src/crap-score.d.ts",
|
|
24
|
+
"default": "./src/crap-score.js"
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"files": [
|
|
28
|
+
"src",
|
|
29
|
+
"README.md",
|
|
30
|
+
"CONTRIBUTING.md",
|
|
31
|
+
"LICENSE"
|
|
32
|
+
],
|
|
33
|
+
"scripts": {
|
|
34
|
+
"check": "node --check src/cli.js && node --check src/crap-analysis.js && node --check src/crap-runner.js && node --check src/crap-score.js",
|
|
35
|
+
"score": "node src/cli.js score --metrics fixtures/complexity-metrics.json --coverage-file fixtures/coverage-summary.json --max-crap 30",
|
|
36
|
+
"test": "node --test tests/*.test.js",
|
|
37
|
+
"validate": "npm run test && npm run score"
|
|
38
|
+
},
|
|
39
|
+
"keywords": [
|
|
40
|
+
"complexity",
|
|
41
|
+
"typescript",
|
|
42
|
+
"quality"
|
|
43
|
+
],
|
|
44
|
+
"license": "MIT",
|
|
45
|
+
"dependencies": {
|
|
46
|
+
"typescript": "^5.9.3"
|
|
47
|
+
},
|
|
48
|
+
"engines": {
|
|
49
|
+
"node": ">=20"
|
|
50
|
+
}
|
|
51
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
|
4
|
+
import { resolve } from "node:path";
|
|
5
|
+
import { parseArgs } from "node:util";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
|
|
8
|
+
import { runCrapAudit } from "./crap-runner.js";
|
|
9
|
+
import { buildCrapScores } from "./crap-score.js";
|
|
10
|
+
|
|
11
|
+
const helpText = `crap-ts
|
|
12
|
+
|
|
13
|
+
Run a focused TypeScript quality audit.
|
|
14
|
+
|
|
15
|
+
Usage:
|
|
16
|
+
crap-ts score [--coverage-file coverage/unit/coverage-final.json] [--coverage-command "npm run test:coverage"]
|
|
17
|
+
crap-ts score --metrics complexity-metrics.json --coverage-file coverage/coverage-summary.json [--max-crap 30]
|
|
18
|
+
|
|
19
|
+
Legacy:
|
|
20
|
+
crap-ts --metrics complexity-metrics.json --coverage-file coverage/coverage-summary.json
|
|
21
|
+
|
|
22
|
+
Options:
|
|
23
|
+
--config <path> Config file path. Defaults to .crap-ts.json when present.
|
|
24
|
+
--coverage-file <path>
|
|
25
|
+
Istanbul coverage JSON path.
|
|
26
|
+
--coverage-command <cmd>
|
|
27
|
+
Command to generate coverage before scoring.
|
|
28
|
+
--all Print every analyzed function instead of applying --limit.
|
|
29
|
+
--include <text> Only analyze coverage files whose path contains this text.
|
|
30
|
+
--limit <n> Number of rows to print for direct CRAP audit. Defaults to 20.
|
|
31
|
+
--metrics <path> JSON file with [{ "file", "name", "complexity" }] entries.
|
|
32
|
+
--min-lines <n> Ignore functions shorter than this. Defaults to 10.
|
|
33
|
+
--max <n> Fail direct CRAP audit when any row is above this score. Defaults to 30.
|
|
34
|
+
--max-crap <n> Fail CRAP scoring when any row is above this score.
|
|
35
|
+
--report-only Print CRAP report without failing on threshold.
|
|
36
|
+
--skip-coverage Do not run the coverage command.
|
|
37
|
+
--help Show this help.
|
|
38
|
+
`;
|
|
39
|
+
|
|
40
|
+
const defaultConfigPath = ".crap-ts.json";
|
|
41
|
+
|
|
42
|
+
export function parseCliArgs(argv, { cwd = process.cwd() } = {}) {
|
|
43
|
+
const command = getCommand(argv);
|
|
44
|
+
const args = command === "legacy" ? argv : argv.slice(1);
|
|
45
|
+
const { positionals, values } = parseArgs({
|
|
46
|
+
args,
|
|
47
|
+
allowPositionals: true,
|
|
48
|
+
options: {
|
|
49
|
+
all: { type: "boolean" },
|
|
50
|
+
config: { type: "string" },
|
|
51
|
+
"coverage-file": { type: "string" },
|
|
52
|
+
"coverage-command": { type: "string" },
|
|
53
|
+
help: { type: "boolean", short: "h" },
|
|
54
|
+
include: { type: "string", multiple: true },
|
|
55
|
+
limit: { type: "string" },
|
|
56
|
+
max: { type: "string" },
|
|
57
|
+
"max-crap": { type: "string" },
|
|
58
|
+
metrics: { type: "string" },
|
|
59
|
+
"min-lines": { type: "string" },
|
|
60
|
+
"report-only": { type: "boolean" },
|
|
61
|
+
"skip-coverage": { type: "boolean" },
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
const config = command === "help" || values.help ? {} : readConfig(values.config, cwd);
|
|
65
|
+
|
|
66
|
+
return applyDefaults(mergeConfigWithCli(config, {
|
|
67
|
+
command,
|
|
68
|
+
all: values.all,
|
|
69
|
+
configPath: values.config,
|
|
70
|
+
coverageCommand: values["coverage-command"],
|
|
71
|
+
coveragePath: values["coverage-file"],
|
|
72
|
+
help: values.help,
|
|
73
|
+
includes: values.include,
|
|
74
|
+
limit: parseOptionalNumber(values.limit, "--limit"),
|
|
75
|
+
maxCrap: parseOptionalNumber(values["max-crap"], "--max-crap"),
|
|
76
|
+
maxScore: parseOptionalNumber(values.max, "--max"),
|
|
77
|
+
metricsPath: values.metrics,
|
|
78
|
+
minLines: parseOptionalNumber(values["min-lines"], "--min-lines"),
|
|
79
|
+
paths: positionals,
|
|
80
|
+
reportOnly: values["report-only"],
|
|
81
|
+
skipCoverage: values["skip-coverage"],
|
|
82
|
+
}));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function main(argv = process.argv.slice(2)) {
|
|
86
|
+
const options = parseCliArgs(argv);
|
|
87
|
+
|
|
88
|
+
if (options.help || options.command === "help") {
|
|
89
|
+
console.log(helpText);
|
|
90
|
+
return 0;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (options.command === "score" || options.metricsPath || options.coveragePath) {
|
|
94
|
+
return runScore(options);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (options.command !== "legacy") {
|
|
98
|
+
console.error(`Unknown command: ${options.command}`);
|
|
99
|
+
return 2;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
console.error("Usage error: run `crap-ts score --help` for supported commands.");
|
|
103
|
+
return 2;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function runScore(options) {
|
|
107
|
+
if (!options.metricsPath) {
|
|
108
|
+
return runCrapAudit(options);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (!options.coveragePath) {
|
|
112
|
+
console.error("CRAP scoring requires both --metrics and --coverage-file.");
|
|
113
|
+
return 2;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const metrics = JSON.parse(readFileSync(options.metricsPath, "utf8"));
|
|
117
|
+
const coverageSummary = JSON.parse(readFileSync(options.coveragePath, "utf8"));
|
|
118
|
+
const scores = buildCrapScores({ coverageSummary, metrics });
|
|
119
|
+
const failingScores = options.maxCrap
|
|
120
|
+
? scores.filter((score) => score.crap > options.maxCrap)
|
|
121
|
+
: [];
|
|
122
|
+
|
|
123
|
+
console.log(JSON.stringify(scores, null, 2));
|
|
124
|
+
|
|
125
|
+
if (failingScores.length > 0) {
|
|
126
|
+
console.error(
|
|
127
|
+
`CRAP threshold failed: ${failingScores.length} row(s) exceeded ${options.maxCrap}.`,
|
|
128
|
+
);
|
|
129
|
+
return 1;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return 0;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function getCommand(argv) {
|
|
136
|
+
const firstArg = argv[0];
|
|
137
|
+
|
|
138
|
+
if (firstArg === "score" || firstArg === "help") {
|
|
139
|
+
return firstArg;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return "legacy";
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function parseOptionalNumber(value, label) {
|
|
146
|
+
if (value === undefined) {
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const parsed = Number(value);
|
|
151
|
+
|
|
152
|
+
if (!Number.isFinite(parsed)) {
|
|
153
|
+
throw new TypeError(`${label} must be a finite number.`);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return parsed;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function readConfig(configPath, cwd) {
|
|
160
|
+
const resolvedPath = resolveConfigPath(configPath, cwd);
|
|
161
|
+
|
|
162
|
+
if (!resolvedPath) {
|
|
163
|
+
return {};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
return JSON.parse(readFileSync(resolvedPath, "utf8"));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function resolveConfigPath(configPath, cwd) {
|
|
170
|
+
if (configPath) {
|
|
171
|
+
return resolve(cwd, configPath);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const defaultPath = resolve(cwd, defaultConfigPath);
|
|
175
|
+
return existsSync(defaultPath) ? defaultPath : null;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function mergeConfigWithCli(config, cliOptions) {
|
|
179
|
+
return {
|
|
180
|
+
...normalizeConfig(config),
|
|
181
|
+
...stripUndefined(cliOptions),
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function normalizeConfig(config) {
|
|
186
|
+
return stripUndefined({
|
|
187
|
+
all: config.all,
|
|
188
|
+
coverageCommand: config.coverageCommand,
|
|
189
|
+
coveragePath: config.coverageFile,
|
|
190
|
+
includes: normalizeConfigList(config.include, "include"),
|
|
191
|
+
limit: parseConfigNumber(config.limit, "limit"),
|
|
192
|
+
maxCrap: parseConfigNumber(config.maxCrap, "maxCrap"),
|
|
193
|
+
maxScore: parseConfigNumber(config.max, "max"),
|
|
194
|
+
metricsPath: config.metrics,
|
|
195
|
+
minLines: parseConfigNumber(config.minLines, "minLines"),
|
|
196
|
+
reportOnly: config.reportOnly,
|
|
197
|
+
skipCoverage: config.skipCoverage,
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function parseConfigNumber(value, label) {
|
|
202
|
+
if (value === undefined) {
|
|
203
|
+
return undefined;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
207
|
+
throw new TypeError(`${label} must be a finite number in ${defaultConfigPath}.`);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return value;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function normalizeConfigList(value, label) {
|
|
214
|
+
if (value === undefined) {
|
|
215
|
+
return undefined;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
if (typeof value === "string") {
|
|
219
|
+
return [value];
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
if (Array.isArray(value) && value.every((item) => typeof item === "string")) {
|
|
223
|
+
return value;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
throw new TypeError(`${label} must be a string or string array in ${defaultConfigPath}.`);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function applyDefaults(options) {
|
|
230
|
+
return {
|
|
231
|
+
...options,
|
|
232
|
+
all: options.all ?? false,
|
|
233
|
+
help: options.help ?? false,
|
|
234
|
+
includes: options.includes ?? [],
|
|
235
|
+
reportOnly: options.reportOnly ?? false,
|
|
236
|
+
skipCoverage: options.skipCoverage ?? false,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function stripUndefined(values) {
|
|
241
|
+
return Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined));
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
if (isDirectExecution()) {
|
|
245
|
+
process.exitCode = main();
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function isDirectExecution() {
|
|
249
|
+
if (!process.argv[1]) {
|
|
250
|
+
return false;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
return realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
|
254
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
|
|
3
|
+
export interface FunctionRisk {
|
|
4
|
+
complexity: number;
|
|
5
|
+
coveragePercent: number;
|
|
6
|
+
crapScore: number;
|
|
7
|
+
endLine: number;
|
|
8
|
+
filePath: string;
|
|
9
|
+
lineCount: number;
|
|
10
|
+
name: string;
|
|
11
|
+
startLine: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface CoverageFunction {
|
|
15
|
+
coveragePercent: number;
|
|
16
|
+
declarationLine: number;
|
|
17
|
+
endLine: number;
|
|
18
|
+
startLine: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function extractCoverageFunctions(
|
|
22
|
+
coverageJson: Record<string, unknown>,
|
|
23
|
+
): Map<string, CoverageFunction[]>;
|
|
24
|
+
|
|
25
|
+
export function analyzeFileRisk(input: {
|
|
26
|
+
coverageFunctions: CoverageFunction[];
|
|
27
|
+
filePath: string;
|
|
28
|
+
minLines: number;
|
|
29
|
+
sourceText: string;
|
|
30
|
+
}): FunctionRisk[];
|
|
31
|
+
|
|
32
|
+
export function formatRiskLine(risk: FunctionRisk): string;
|
|
33
|
+
|
|
34
|
+
export function calculateCyclomaticComplexity(node: ts.Node): number;
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
|
|
3
|
+
import { calculateCrapScoreFromPercent } from "./crap-score.js";
|
|
4
|
+
|
|
5
|
+
export function extractCoverageFunctions(coverageJson) {
|
|
6
|
+
const coverageByFile = new Map();
|
|
7
|
+
|
|
8
|
+
for (const [filePath, coverage] of Object.entries(coverageJson)) {
|
|
9
|
+
const functions = Object.entries(coverage.fnMap ?? {}).flatMap(([id, metadata]) => {
|
|
10
|
+
const startLine = metadata.loc?.start?.line;
|
|
11
|
+
const endLine = metadata.loc?.end?.line;
|
|
12
|
+
|
|
13
|
+
if (!startLine || !endLine) {
|
|
14
|
+
return [];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
return [
|
|
18
|
+
{
|
|
19
|
+
coveragePercent: (coverage.f?.[id] ?? 0) > 0 ? 100 : 0,
|
|
20
|
+
declarationLine: metadata.line ?? startLine,
|
|
21
|
+
endLine,
|
|
22
|
+
startLine,
|
|
23
|
+
},
|
|
24
|
+
];
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
coverageByFile.set(filePath, functions);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return coverageByFile;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function analyzeFileRisk({ coverageFunctions, filePath, minLines, sourceText }) {
|
|
34
|
+
const sourceFile = ts.createSourceFile(filePath, sourceText, ts.ScriptTarget.Latest, true);
|
|
35
|
+
const risks = [];
|
|
36
|
+
|
|
37
|
+
function visit(node) {
|
|
38
|
+
if (isFunctionLikeNode(node) && node.body) {
|
|
39
|
+
const startLine =
|
|
40
|
+
sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
|
|
41
|
+
const endLine = sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line + 1;
|
|
42
|
+
const lineCount = endLine - startLine + 1;
|
|
43
|
+
|
|
44
|
+
if (lineCount >= minLines) {
|
|
45
|
+
const complexity = calculateCyclomaticComplexity(node.body);
|
|
46
|
+
const coveragePercent = getFunctionCoveragePercent({
|
|
47
|
+
coverageFunctions,
|
|
48
|
+
endLine,
|
|
49
|
+
startLine,
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
risks.push({
|
|
53
|
+
complexity,
|
|
54
|
+
coveragePercent,
|
|
55
|
+
crapScore: calculateCrapScoreFromPercent(complexity, coveragePercent),
|
|
56
|
+
endLine,
|
|
57
|
+
filePath,
|
|
58
|
+
lineCount,
|
|
59
|
+
name: getFunctionName(node, sourceFile),
|
|
60
|
+
startLine,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
ts.forEachChild(node, visit);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
visit(sourceFile);
|
|
69
|
+
|
|
70
|
+
return risks;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function formatRiskLine(risk) {
|
|
74
|
+
return [
|
|
75
|
+
`${risk.filePath}:${risk.startLine}`,
|
|
76
|
+
risk.name,
|
|
77
|
+
`CRAP ${risk.crapScore.toFixed(1)}`,
|
|
78
|
+
`complexity ${risk.complexity}`,
|
|
79
|
+
`coverage ${risk.coveragePercent.toFixed(0)}%`,
|
|
80
|
+
`${risk.lineCount} lines`,
|
|
81
|
+
].join(" | ");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function calculateCyclomaticComplexity(node) {
|
|
85
|
+
let complexity = 1;
|
|
86
|
+
|
|
87
|
+
function visit(child) {
|
|
88
|
+
if (addsDecisionPath(child)) {
|
|
89
|
+
complexity += 1;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
ts.forEachChild(child, visit);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
visit(node);
|
|
96
|
+
|
|
97
|
+
return complexity;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function addsDecisionPath(node) {
|
|
101
|
+
if (
|
|
102
|
+
ts.isIfStatement(node) ||
|
|
103
|
+
ts.isForStatement(node) ||
|
|
104
|
+
ts.isForInStatement(node) ||
|
|
105
|
+
ts.isForOfStatement(node) ||
|
|
106
|
+
ts.isWhileStatement(node) ||
|
|
107
|
+
ts.isDoStatement(node) ||
|
|
108
|
+
ts.isCaseClause(node) ||
|
|
109
|
+
ts.isCatchClause(node) ||
|
|
110
|
+
ts.isConditionalExpression(node)
|
|
111
|
+
) {
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return (
|
|
116
|
+
ts.isBinaryExpression(node) &&
|
|
117
|
+
(node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ||
|
|
118
|
+
node.operatorToken.kind === ts.SyntaxKind.BarBarToken ||
|
|
119
|
+
node.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken)
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function getFunctionCoveragePercent({ coverageFunctions, endLine, startLine }) {
|
|
124
|
+
const exactMatch = coverageFunctions.find(
|
|
125
|
+
(coverageFunction) =>
|
|
126
|
+
coverageFunction.declarationLine === startLine ||
|
|
127
|
+
(coverageFunction.startLine === startLine && coverageFunction.endLine === endLine),
|
|
128
|
+
);
|
|
129
|
+
|
|
130
|
+
if (exactMatch) {
|
|
131
|
+
return exactMatch.coveragePercent;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const containingMatch = coverageFunctions.find(
|
|
135
|
+
(coverageFunction) =>
|
|
136
|
+
(coverageFunction.declarationLine >= startLine &&
|
|
137
|
+
coverageFunction.declarationLine <= endLine) ||
|
|
138
|
+
(coverageFunction.startLine <= endLine && coverageFunction.endLine >= startLine),
|
|
139
|
+
);
|
|
140
|
+
|
|
141
|
+
return containingMatch?.coveragePercent ?? 0;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function getFunctionName(node, sourceFile) {
|
|
145
|
+
if ((ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)) && node.name) {
|
|
146
|
+
return node.name.getText(sourceFile);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (ts.isMethodDeclaration(node) && node.name) {
|
|
150
|
+
return node.name.getText(sourceFile);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const parent = node.parent;
|
|
154
|
+
|
|
155
|
+
if (ts.isVariableDeclaration(parent) && parent.name) {
|
|
156
|
+
return parent.name.getText(sourceFile);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (ts.isPropertyAssignment(parent) && parent.name) {
|
|
160
|
+
return parent.name.getText(sourceFile);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
return "<anonymous>";
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function isFunctionLikeNode(node) {
|
|
167
|
+
return (
|
|
168
|
+
ts.isFunctionDeclaration(node) ||
|
|
169
|
+
ts.isFunctionExpression(node) ||
|
|
170
|
+
ts.isArrowFunction(node) ||
|
|
171
|
+
ts.isMethodDeclaration(node)
|
|
172
|
+
);
|
|
173
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export interface CrapAuditOptions {
|
|
2
|
+
all?: boolean;
|
|
3
|
+
coverageCommand?: string;
|
|
4
|
+
coveragePath?: string;
|
|
5
|
+
cwd?: string;
|
|
6
|
+
includes?: string[];
|
|
7
|
+
limit?: number;
|
|
8
|
+
maxScore?: number;
|
|
9
|
+
minLines?: number;
|
|
10
|
+
reportOnly?: boolean;
|
|
11
|
+
skipCoverage?: boolean;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function runCrapAudit(options?: CrapAuditOptions): number;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
3
|
+
import { isAbsolute, relative, resolve } from "node:path";
|
|
4
|
+
|
|
5
|
+
import { analyzeFileRisk, extractCoverageFunctions, formatRiskLine } from "./crap-analysis.js";
|
|
6
|
+
import { normalizePath } from "./path-utils.js";
|
|
7
|
+
|
|
8
|
+
export function runCrapAudit({
|
|
9
|
+
all = false,
|
|
10
|
+
coverageCommand,
|
|
11
|
+
coveragePath = "coverage/unit/coverage-final.json",
|
|
12
|
+
cwd = process.cwd(),
|
|
13
|
+
includes = [],
|
|
14
|
+
limit = 20,
|
|
15
|
+
maxScore = 30,
|
|
16
|
+
minLines = 10,
|
|
17
|
+
reportOnly = false,
|
|
18
|
+
skipCoverage = false,
|
|
19
|
+
} = {}) {
|
|
20
|
+
if (!skipCoverage && coverageCommand) {
|
|
21
|
+
const result = spawnSync(coverageCommand, {
|
|
22
|
+
cwd,
|
|
23
|
+
shell: true,
|
|
24
|
+
stdio: "inherit",
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
if (result.status !== 0) {
|
|
28
|
+
return result.status ?? 1;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const resolvedCoveragePath = resolve(cwd, coveragePath);
|
|
33
|
+
|
|
34
|
+
if (!existsSync(resolvedCoveragePath)) {
|
|
35
|
+
console.error(`Missing coverage JSON: ${resolvedCoveragePath}`);
|
|
36
|
+
console.error("Run coverage first, pass --coverage-file, or use a valid --coverage-command.");
|
|
37
|
+
return 1;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const coverageJson = JSON.parse(readFileSync(resolvedCoveragePath, "utf8"));
|
|
41
|
+
const coverageByFile = extractCoverageFunctions(coverageJson);
|
|
42
|
+
const risks = [];
|
|
43
|
+
|
|
44
|
+
for (const [coverageFilePath, coverageFunctions] of coverageByFile.entries()) {
|
|
45
|
+
if (!shouldIncludePath(coverageFilePath, includes)) {
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const sourceFilePath = isAbsolute(coverageFilePath)
|
|
50
|
+
? coverageFilePath
|
|
51
|
+
: resolve(cwd, coverageFilePath);
|
|
52
|
+
|
|
53
|
+
if (!existsSync(sourceFilePath)) {
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const sourceText = readFileSync(sourceFilePath, "utf8");
|
|
58
|
+
const relativeFilePath = relative(cwd, sourceFilePath);
|
|
59
|
+
|
|
60
|
+
risks.push(
|
|
61
|
+
...analyzeFileRisk({
|
|
62
|
+
coverageFunctions,
|
|
63
|
+
filePath: relativeFilePath,
|
|
64
|
+
minLines,
|
|
65
|
+
sourceText,
|
|
66
|
+
}),
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const sortedRisks = risks.sort((left, right) => right.crapScore - left.crapScore);
|
|
71
|
+
const failingRisks = sortedRisks.filter((risk) => risk.crapScore > maxScore);
|
|
72
|
+
|
|
73
|
+
console.log();
|
|
74
|
+
console.log(
|
|
75
|
+
`CRAP report: ${sortedRisks.length} functions checked, ${failingRisks.length} above ${maxScore}.`,
|
|
76
|
+
);
|
|
77
|
+
|
|
78
|
+
const printedRisks = all ? sortedRisks : sortedRisks.slice(0, limit);
|
|
79
|
+
|
|
80
|
+
for (const risk of printedRisks) {
|
|
81
|
+
console.log(formatRiskLine(risk));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (failingRisks.length > 0 && !reportOnly) {
|
|
85
|
+
console.error("");
|
|
86
|
+
console.error(
|
|
87
|
+
"CRAP check failed. Use --report-only while calibrating, or lower complexity / add coverage for the listed functions.",
|
|
88
|
+
);
|
|
89
|
+
return 1;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return 0;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function shouldIncludePath(filePath, includes) {
|
|
96
|
+
if (includes.length === 0) {
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const normalizedPath = normalizePath(filePath);
|
|
101
|
+
|
|
102
|
+
return includes.some((include) => normalizedPath.includes(normalizePath(include)));
|
|
103
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export interface ComplexityMetric {
|
|
2
|
+
file: string;
|
|
3
|
+
name: string;
|
|
4
|
+
complexity: number;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export interface CrapScore {
|
|
8
|
+
file: string;
|
|
9
|
+
name: string;
|
|
10
|
+
complexity: number;
|
|
11
|
+
coverage: number;
|
|
12
|
+
crap: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function calculateCrapScore(input: { complexity: number; coverage: number }): number;
|
|
16
|
+
|
|
17
|
+
export function calculateCrapScoreFromPercent(complexity: number, coveragePercent: number): number;
|
|
18
|
+
|
|
19
|
+
export function buildCrapScores(input: {
|
|
20
|
+
coverageSummary: Record<string, unknown>;
|
|
21
|
+
metrics: ComplexityMetric[];
|
|
22
|
+
}): CrapScore[];
|
|
23
|
+
|
|
24
|
+
export function getCoverageForFile(coverageSummary: Record<string, unknown>, file: string): number;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { normalizePath } from "./path-utils.js";
|
|
2
|
+
|
|
3
|
+
export function calculateCrapScore({ complexity, coverage }) {
|
|
4
|
+
assertFiniteNumber(complexity, "complexity");
|
|
5
|
+
assertFiniteNumber(coverage, "coverage");
|
|
6
|
+
|
|
7
|
+
const uncoveredRatio = 1 - clamp(coverage, 0, 100) / 100;
|
|
8
|
+
return complexity ** 2 * uncoveredRatio ** 3 + complexity;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function calculateCrapScoreFromPercent(complexity, coveragePercent) {
|
|
12
|
+
return calculateCrapScore({ complexity, coverage: coveragePercent });
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function buildCrapScores({ coverageSummary, metrics }) {
|
|
16
|
+
return metrics.map((metric) => {
|
|
17
|
+
const coverage = getCoverageForFile(coverageSummary, metric.file);
|
|
18
|
+
const score = calculateCrapScore({
|
|
19
|
+
complexity: metric.complexity,
|
|
20
|
+
coverage,
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
return {
|
|
24
|
+
file: metric.file,
|
|
25
|
+
name: metric.name,
|
|
26
|
+
complexity: metric.complexity,
|
|
27
|
+
coverage,
|
|
28
|
+
crap: Number(score.toFixed(2)),
|
|
29
|
+
};
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function getCoverageForFile(coverageSummary, file) {
|
|
34
|
+
const entry = findCoverageEntry(coverageSummary, file);
|
|
35
|
+
|
|
36
|
+
if (!entry?.lines || typeof entry.lines.pct !== "number") {
|
|
37
|
+
return 0;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return entry.lines.pct;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function findCoverageEntry(coverageSummary, file) {
|
|
44
|
+
if (coverageSummary[file]) {
|
|
45
|
+
return coverageSummary[file];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const normalizedFile = normalizePath(file);
|
|
49
|
+
const match = Object.entries(coverageSummary).find(([key]) => {
|
|
50
|
+
const normalizedKey = normalizePath(key);
|
|
51
|
+
return normalizedKey === normalizedFile || normalizedKey.endsWith(`/${normalizedFile}`);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
return match?.[1];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function clamp(value, min, max) {
|
|
58
|
+
return Math.min(Math.max(value, min), max);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function assertFiniteNumber(value, label) {
|
|
62
|
+
if (!Number.isFinite(value)) {
|
|
63
|
+
throw new TypeError(`${label} must be a finite number.`);
|
|
64
|
+
}
|
|
65
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export {
|
|
2
|
+
analyzeFileRisk,
|
|
3
|
+
type CoverageFunction,
|
|
4
|
+
calculateCyclomaticComplexity,
|
|
5
|
+
extractCoverageFunctions,
|
|
6
|
+
type FunctionRisk,
|
|
7
|
+
formatRiskLine,
|
|
8
|
+
} from "./crap-analysis.js";
|
|
9
|
+
export { type CrapAuditOptions, runCrapAudit } from "./crap-runner.js";
|
|
10
|
+
export {
|
|
11
|
+
buildCrapScores,
|
|
12
|
+
type ComplexityMetric,
|
|
13
|
+
type CrapScore,
|
|
14
|
+
calculateCrapScore,
|
|
15
|
+
getCoverageForFile,
|
|
16
|
+
} from "./crap-score.js";
|
package/src/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export {
|
|
2
|
+
analyzeFileRisk,
|
|
3
|
+
calculateCyclomaticComplexity,
|
|
4
|
+
extractCoverageFunctions,
|
|
5
|
+
formatRiskLine,
|
|
6
|
+
} from "./crap-analysis.js";
|
|
7
|
+
export { runCrapAudit } from "./crap-runner.js";
|
|
8
|
+
export { buildCrapScores, calculateCrapScore, getCoverageForFile } from "./crap-score.js";
|