crap-ts 0.1.0 → 0.2.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/README.md CHANGED
@@ -15,6 +15,7 @@ Risky code plus weak tests, now with a name your manager will remember.
15
15
  ## Works Out Of The Box With
16
16
 
17
17
  - TypeScript source files listed in an Istanbul-style `coverage-final.json`
18
+ - Consumer-provided TypeScript versions `>=5.9 <8`, including TypeScript 7
18
19
  - Vitest V8 coverage, Jest coverage, or nyc/Istanbul coverage that includes
19
20
  function maps
20
21
  - npm, Bun, pnpm, or any runner that can produce coverage before `crap-ts` reads
@@ -29,6 +30,9 @@ glamorous work, obviously.
29
30
  npm install --save-dev crap-ts
30
31
  ```
31
32
 
33
+ `crap-ts` uses your project's installed TypeScript peer dependency, so
34
+ TypeScript 7 projects do not get a nested TypeScript 5.x install.
35
+
32
36
  ## Usage
33
37
 
34
38
  Run the built-in TypeScript AST audit against coverage-final data:
@@ -58,11 +62,16 @@ Put the long bits in `.crap-ts.json`:
58
62
  "coverageFile": "coverage/unit/coverage-final.json",
59
63
  "include": ["src"],
60
64
  "max": 30,
65
+ "warn": 25,
61
66
  "minLines": 10,
62
67
  "limit": 20
63
68
  }
64
69
  ```
65
70
 
71
+ `warn` gives you an early heads-up: functions above 25 are flagged `WARN` and
72
+ reported on stderr, but only scores above `max` fail the build. Leave it out to
73
+ skip warnings.
74
+
66
75
  You can also compute CRAP scores from an external metrics file and coverage
67
76
  summary:
68
77
 
@@ -116,6 +125,8 @@ Options:
116
125
  - `--include <text>`: only analyze coverage files whose path contains this text.
117
126
  - `--limit <n>`: number of report rows to print. Defaults to `20`.
118
127
  - `--max <n>`: strict CRAP threshold for direct audit. Defaults to `30`.
128
+ - `--warn <n>`: warn, without failing, when a score is above this. Must not
129
+ exceed `--max` (or `--max-crap` with `--metrics`). Off by default.
119
130
  - `--min-lines <n>`: ignore functions shorter than this. Defaults to `10`.
120
131
  - `--metrics <path>`: read complexity metrics from JSON.
121
132
  - `--report-only`: print CRAP results without failing on threshold.
@@ -143,6 +154,7 @@ Config files use camelCase keys:
143
154
  "all": false,
144
155
  "limit": 20,
145
156
  "max": 30,
157
+ "warn": 25,
146
158
  "minLines": 10,
147
159
  "reportOnly": false,
148
160
  "skipCoverage": false
package/package.json CHANGED
@@ -1,51 +1,62 @@
1
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
- }
2
+ "name": "crap-ts",
3
+ "version": "0.2.0",
4
+ "description": "Small CRAP-score audit helper for TypeScript projects.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/cubanx/crap-ts.git"
8
+ },
9
+ "type": "module",
10
+ "bin": {
11
+ "crap-ts": "src/cli.js"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./src/index.d.ts",
16
+ "default": "./src/index.js"
17
+ },
18
+ "./crap-analysis": {
19
+ "types": "./src/crap-analysis.d.ts",
20
+ "default": "./src/crap-analysis.js"
21
+ },
22
+ "./crap-runner": {
23
+ "types": "./src/crap-runner.d.ts",
24
+ "default": "./src/crap-runner.js"
25
+ },
26
+ "./crap-score": {
27
+ "types": "./src/crap-score.d.ts",
28
+ "default": "./src/crap-score.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "src",
33
+ "README.md",
34
+ "CONTRIBUTING.md",
35
+ "LICENSE"
36
+ ],
37
+ "scripts": {
38
+ "check": "node --check src/cli.js && node --check src/crap-analysis.js && node --check src/crap-runner.js && node --check src/crap-score.js",
39
+ "score": "node src/cli.js score --metrics fixtures/complexity-metrics.json --coverage-file fixtures/coverage-summary.json --max-crap 30",
40
+ "test": "node --test tests/*.test.js",
41
+ "test:consumer-typescript": "node scripts/verify-consumer-typescript.mjs",
42
+ "validate": "npm run test && npm run score",
43
+ "lint": "biome ci .",
44
+ "format": "biome check --write ."
45
+ },
46
+ "keywords": [
47
+ "complexity",
48
+ "typescript",
49
+ "quality"
50
+ ],
51
+ "license": "MIT",
52
+ "engines": {
53
+ "node": ">=20"
54
+ },
55
+ "peerDependencies": {
56
+ "typescript": ">=5.9 <8"
57
+ },
58
+ "devDependencies": {
59
+ "@biomejs/biome": "^2.5.3",
60
+ "typescript": "^5.9.3"
61
+ }
51
62
  }
package/src/cli.js CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  import { existsSync, readFileSync, realpathSync } from "node:fs";
4
4
  import { resolve } from "node:path";
5
- import { parseArgs } from "node:util";
6
5
  import { fileURLToPath } from "node:url";
6
+ import { parseArgs } from "node:util";
7
7
 
8
8
  import { runCrapAudit } from "./crap-runner.js";
9
9
  import { buildCrapScores } from "./crap-score.js";
@@ -32,6 +32,7 @@ Options:
32
32
  --min-lines <n> Ignore functions shorter than this. Defaults to 10.
33
33
  --max <n> Fail direct CRAP audit when any row is above this score. Defaults to 30.
34
34
  --max-crap <n> Fail CRAP scoring when any row is above this score.
35
+ --warn <n> Warn, without failing, when any row is above this score.
35
36
  --report-only Print CRAP report without failing on threshold.
36
37
  --skip-coverage Do not run the coverage command.
37
38
  --help Show this help.
@@ -40,215 +41,260 @@ Options:
40
41
  const defaultConfigPath = ".crap-ts.json";
41
42
 
42
43
  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
- }));
44
+ const command = getCommand(argv);
45
+ const args = command === "legacy" ? argv : argv.slice(1);
46
+ const { positionals, values } = parseArgs({
47
+ args,
48
+ allowPositionals: true,
49
+ options: {
50
+ all: { type: "boolean" },
51
+ config: { type: "string" },
52
+ "coverage-file": { type: "string" },
53
+ "coverage-command": { type: "string" },
54
+ help: { type: "boolean", short: "h" },
55
+ include: { type: "string", multiple: true },
56
+ limit: { type: "string" },
57
+ max: { type: "string" },
58
+ "max-crap": { type: "string" },
59
+ metrics: { type: "string" },
60
+ "min-lines": { type: "string" },
61
+ "report-only": { type: "boolean" },
62
+ "skip-coverage": { type: "boolean" },
63
+ warn: { type: "string" },
64
+ },
65
+ });
66
+ const config =
67
+ command === "help" || values.help ? {} : readConfig(values.config, cwd);
68
+
69
+ return applyDefaults(
70
+ mergeConfigWithCli(config, {
71
+ command,
72
+ all: values.all,
73
+ configPath: values.config,
74
+ coverageCommand: values["coverage-command"],
75
+ coveragePath: values["coverage-file"],
76
+ help: values.help,
77
+ includes: values.include,
78
+ limit: parseOptionalNumber(values.limit, "--limit"),
79
+ maxCrap: parseOptionalNumber(values["max-crap"], "--max-crap"),
80
+ maxScore: parseOptionalNumber(values.max, "--max"),
81
+ metricsPath: values.metrics,
82
+ minLines: parseOptionalNumber(values["min-lines"], "--min-lines"),
83
+ paths: positionals,
84
+ reportOnly: values["report-only"],
85
+ skipCoverage: values["skip-coverage"],
86
+ warnScore: parseOptionalNumber(values.warn, "--warn"),
87
+ }),
88
+ );
83
89
  }
84
90
 
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;
91
+ export async function main(argv = process.argv.slice(2)) {
92
+ const options = parseCliArgs(argv);
93
+
94
+ if (options.help || options.command === "help") {
95
+ console.log(helpText);
96
+ return 0;
97
+ }
98
+
99
+ if (
100
+ options.command === "score" ||
101
+ options.metricsPath ||
102
+ options.coveragePath
103
+ ) {
104
+ return runScore(options);
105
+ }
106
+
107
+ if (options.command !== "legacy") {
108
+ console.error(`Unknown command: ${options.command}`);
109
+ return 2;
110
+ }
111
+
112
+ console.error(
113
+ "Usage error: run `crap-ts score --help` for supported commands.",
114
+ );
115
+ return 2;
104
116
  }
105
117
 
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;
118
+ async function runScore(options) {
119
+ if (!options.metricsPath) {
120
+ return runCrapAudit(options);
121
+ }
122
+
123
+ if (!options.coveragePath) {
124
+ console.error("CRAP scoring requires both --metrics and --coverage-file.");
125
+ return 2;
126
+ }
127
+
128
+ if (
129
+ options.maxCrap &&
130
+ options.warnScore !== undefined &&
131
+ options.warnScore > options.maxCrap
132
+ ) {
133
+ console.error(
134
+ `CRAP warn (${options.warnScore}) must not exceed max-crap (${options.maxCrap}).`,
135
+ );
136
+ return 2;
137
+ }
138
+
139
+ const metrics = JSON.parse(readFileSync(options.metricsPath, "utf8"));
140
+ const coverageSummary = JSON.parse(
141
+ readFileSync(options.coveragePath, "utf8"),
142
+ );
143
+ const scores = buildCrapScores({ coverageSummary, metrics });
144
+ const failingScores = options.maxCrap
145
+ ? scores.filter((score) => score.crap > options.maxCrap)
146
+ : [];
147
+ const warningScores =
148
+ options.warnScore === undefined
149
+ ? []
150
+ : scores.filter(
151
+ (score) =>
152
+ score.crap > options.warnScore &&
153
+ !(options.maxCrap && score.crap > options.maxCrap),
154
+ );
155
+
156
+ console.log(JSON.stringify(scores, null, 2));
157
+
158
+ if (warningScores.length > 0) {
159
+ console.error(
160
+ `CRAP warning: ${warningScores.length} row(s) above ${options.warnScore}.`,
161
+ );
162
+ }
163
+
164
+ if (failingScores.length > 0) {
165
+ console.error(
166
+ `CRAP threshold failed: ${failingScores.length} row(s) exceeded ${options.maxCrap}.`,
167
+ );
168
+ return 1;
169
+ }
170
+
171
+ return 0;
133
172
  }
134
173
 
135
174
  function getCommand(argv) {
136
- const firstArg = argv[0];
175
+ const firstArg = argv[0];
137
176
 
138
- if (firstArg === "score" || firstArg === "help") {
139
- return firstArg;
140
- }
177
+ if (firstArg === "score" || firstArg === "help") {
178
+ return firstArg;
179
+ }
141
180
 
142
- return "legacy";
181
+ return "legacy";
143
182
  }
144
183
 
145
184
  function parseOptionalNumber(value, label) {
146
- if (value === undefined) {
147
- return undefined;
148
- }
185
+ if (value === undefined) {
186
+ return undefined;
187
+ }
149
188
 
150
- const parsed = Number(value);
189
+ const parsed = Number(value);
151
190
 
152
- if (!Number.isFinite(parsed)) {
153
- throw new TypeError(`${label} must be a finite number.`);
154
- }
191
+ if (!Number.isFinite(parsed)) {
192
+ throw new TypeError(`${label} must be a finite number.`);
193
+ }
155
194
 
156
- return parsed;
195
+ return parsed;
157
196
  }
158
197
 
159
198
  function readConfig(configPath, cwd) {
160
- const resolvedPath = resolveConfigPath(configPath, cwd);
199
+ const resolvedPath = resolveConfigPath(configPath, cwd);
161
200
 
162
- if (!resolvedPath) {
163
- return {};
164
- }
201
+ if (!resolvedPath) {
202
+ return {};
203
+ }
165
204
 
166
- return JSON.parse(readFileSync(resolvedPath, "utf8"));
205
+ return JSON.parse(readFileSync(resolvedPath, "utf8"));
167
206
  }
168
207
 
169
208
  function resolveConfigPath(configPath, cwd) {
170
- if (configPath) {
171
- return resolve(cwd, configPath);
172
- }
209
+ if (configPath) {
210
+ return resolve(cwd, configPath);
211
+ }
173
212
 
174
- const defaultPath = resolve(cwd, defaultConfigPath);
175
- return existsSync(defaultPath) ? defaultPath : null;
213
+ const defaultPath = resolve(cwd, defaultConfigPath);
214
+ return existsSync(defaultPath) ? defaultPath : null;
176
215
  }
177
216
 
178
217
  function mergeConfigWithCli(config, cliOptions) {
179
- return {
180
- ...normalizeConfig(config),
181
- ...stripUndefined(cliOptions),
182
- };
218
+ return {
219
+ ...normalizeConfig(config),
220
+ ...stripUndefined(cliOptions),
221
+ };
183
222
  }
184
223
 
185
224
  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
- });
225
+ return stripUndefined({
226
+ all: config.all,
227
+ coverageCommand: config.coverageCommand,
228
+ coveragePath: config.coverageFile,
229
+ includes: normalizeConfigList(config.include, "include"),
230
+ limit: parseConfigNumber(config.limit, "limit"),
231
+ maxCrap: parseConfigNumber(config.maxCrap, "maxCrap"),
232
+ maxScore: parseConfigNumber(config.max, "max"),
233
+ metricsPath: config.metrics,
234
+ minLines: parseConfigNumber(config.minLines, "minLines"),
235
+ reportOnly: config.reportOnly,
236
+ skipCoverage: config.skipCoverage,
237
+ warnScore: parseConfigNumber(config.warn, "warn"),
238
+ });
199
239
  }
200
240
 
201
241
  function parseConfigNumber(value, label) {
202
- if (value === undefined) {
203
- return undefined;
204
- }
242
+ if (value === undefined) {
243
+ return undefined;
244
+ }
205
245
 
206
- if (typeof value !== "number" || !Number.isFinite(value)) {
207
- throw new TypeError(`${label} must be a finite number in ${defaultConfigPath}.`);
208
- }
246
+ if (typeof value !== "number" || !Number.isFinite(value)) {
247
+ throw new TypeError(
248
+ `${label} must be a finite number in ${defaultConfigPath}.`,
249
+ );
250
+ }
209
251
 
210
- return value;
252
+ return value;
211
253
  }
212
254
 
213
255
  function normalizeConfigList(value, label) {
214
- if (value === undefined) {
215
- return undefined;
216
- }
256
+ if (value === undefined) {
257
+ return undefined;
258
+ }
217
259
 
218
- if (typeof value === "string") {
219
- return [value];
220
- }
260
+ if (typeof value === "string") {
261
+ return [value];
262
+ }
221
263
 
222
- if (Array.isArray(value) && value.every((item) => typeof item === "string")) {
223
- return value;
224
- }
264
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) {
265
+ return value;
266
+ }
225
267
 
226
- throw new TypeError(`${label} must be a string or string array in ${defaultConfigPath}.`);
268
+ throw new TypeError(
269
+ `${label} must be a string or string array in ${defaultConfigPath}.`,
270
+ );
227
271
  }
228
272
 
229
273
  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
- };
274
+ return {
275
+ ...options,
276
+ all: options.all ?? false,
277
+ help: options.help ?? false,
278
+ includes: options.includes ?? [],
279
+ reportOnly: options.reportOnly ?? false,
280
+ skipCoverage: options.skipCoverage ?? false,
281
+ };
238
282
  }
239
283
 
240
284
  function stripUndefined(values) {
241
- return Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined));
285
+ return Object.fromEntries(
286
+ Object.entries(values).filter(([, value]) => value !== undefined),
287
+ );
242
288
  }
243
289
 
244
290
  if (isDirectExecution()) {
245
- process.exitCode = main();
291
+ process.exitCode = await main();
246
292
  }
247
293
 
248
294
  function isDirectExecution() {
249
- if (!process.argv[1]) {
250
- return false;
251
- }
295
+ if (!process.argv[1]) {
296
+ return false;
297
+ }
252
298
 
253
- return realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
299
+ return realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
254
300
  }
@@ -1,34 +1,33 @@
1
- import ts from "typescript";
2
-
3
1
  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;
2
+ complexity: number;
3
+ coveragePercent: number;
4
+ crapScore: number;
5
+ endLine: number;
6
+ filePath: string;
7
+ lineCount: number;
8
+ name: string;
9
+ startLine: number;
12
10
  }
13
11
 
14
12
  export interface CoverageFunction {
15
- coveragePercent: number;
16
- declarationLine: number;
17
- endLine: number;
18
- startLine: number;
13
+ coveragePercent: number;
14
+ declarationLine: number;
15
+ endLine: number;
16
+ startLine: number;
19
17
  }
20
18
 
21
19
  export function extractCoverageFunctions(
22
- coverageJson: Record<string, unknown>,
20
+ coverageJson: Record<string, unknown>,
23
21
  ): Map<string, CoverageFunction[]>;
24
22
 
25
23
  export function analyzeFileRisk(input: {
26
- coverageFunctions: CoverageFunction[];
27
- filePath: string;
28
- minLines: number;
29
- sourceText: string;
30
- }): FunctionRisk[];
24
+ coverageFunctions: CoverageFunction[];
25
+ filePath: string;
26
+ minLines: number;
27
+ sourceFilePath?: string;
28
+ sourceText: string;
29
+ }): Promise<FunctionRisk[]>;
31
30
 
32
31
  export function formatRiskLine(risk: FunctionRisk): string;
33
32
 
34
- export function calculateCyclomaticComplexity(node: ts.Node): number;
33
+ export function calculateCyclomaticComplexity(node: unknown): number;