crap-ts 0.2.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CONTRIBUTING.md CHANGED
@@ -17,6 +17,7 @@ Smaller changes are easier to deal with, larger changes may require more discuss
17
17
  Run these before opening a PR:
18
18
 
19
19
  ```sh
20
+ npm run lint
20
21
  npm run check
21
22
  npm run validate
22
23
  ```
package/README.md CHANGED
@@ -14,10 +14,10 @@ Risky code plus weak tests, now with a name your manager will remember.
14
14
 
15
15
  ## Works Out Of The Box With
16
16
 
17
- - TypeScript source files listed in an Istanbul-style `coverage-final.json`
17
+ - TypeScript source files (`.ts`, `.tsx`, `.mts`, `.cts`)
18
+ - Istanbul-format `coverage-final.json` with statement and function maps:
19
+ Vitest (V8 or Istanbul provider), Jest, nyc/Istanbul
18
20
  - Consumer-provided TypeScript versions `>=5.9 <8`, including TypeScript 7
19
- - Vitest V8 coverage, Jest coverage, or nyc/Istanbul coverage that includes
20
- function maps
21
21
  - npm, Bun, pnpm, or any runner that can produce coverage before `crap-ts` reads
22
22
  it
23
23
 
@@ -35,10 +35,8 @@ TypeScript 7 projects do not get a nested TypeScript 5.x install.
35
35
 
36
36
  ## Usage
37
37
 
38
- Run the built-in TypeScript AST audit against coverage-final data:
39
-
40
38
  ```sh
41
- npx crap-ts score --coverage-command "npm run test:coverage -- --coverage.reporter=json" --coverage-file coverage/unit/coverage-final.json --include src
39
+ npx crap-ts score --coverage-command "npm run test:coverage -- --coverage.reporter=json" --coverage-file coverage/unit/coverage-final.json --include src/ --exclude .test.ts
42
40
  ```
43
41
 
44
42
  Add package scripts:
@@ -58,13 +56,12 @@ Put the long bits in `.crap-ts.json`:
58
56
 
59
57
  ```json
60
58
  {
61
- "coverageCommand": "npm run test:coverage -- --coverage.reporter=json --coverage.reporter=json-summary",
59
+ "coverageCommand": "npm run test:coverage -- --coverage.reporter=json",
62
60
  "coverageFile": "coverage/unit/coverage-final.json",
63
- "include": ["src"],
61
+ "include": ["src/"],
62
+ "exclude": [".test.ts"],
64
63
  "max": 30,
65
- "warn": 25,
66
- "minLines": 10,
67
- "limit": 20
64
+ "warn": 25
68
65
  }
69
66
  ```
70
67
 
@@ -72,33 +69,135 @@ Put the long bits in `.crap-ts.json`:
72
69
  reported on stderr, but only scores above `max` fail the build. Leave it out to
73
70
  skip warnings.
74
71
 
75
- You can also compute CRAP scores from an external metrics file and coverage
76
- summary:
72
+ In CI, keep the machine-readable report even when the gate fails:
77
73
 
78
74
  ```sh
79
- npx crap-ts --metrics fixtures/complexity-metrics.json --coverage-file fixtures/coverage-summary.json
75
+ npx crap-ts score --json > crap-report.json
80
76
  ```
81
77
 
82
- ## Workflow
83
-
84
- The direct CRAP audit:
85
-
86
- - reads function coverage from Istanbul/V8 `coverage-final.json`
87
- - calculates function cyclomatic complexity from the TypeScript AST
88
- - prints the highest-risk functions
89
- - fails strict mode when any score is above the configured threshold
78
+ The report is printed in full before `crap-ts` exits non-zero, and the coverage
79
+ command's own output is sent to stderr so stdout stays valid JSON.
90
80
 
91
- CRAP combines complexity and coverage:
81
+ ## How Scoring Works
92
82
 
93
83
  ```text
94
84
  crap = complexity^2 * (1 - coverage)^3 + complexity
95
85
  ```
96
86
 
97
- For direct audits, `coverage` is function coverage from `coverage-final.json`.
98
- For metrics-file scoring, `coverage` is read from an Istanbul-style
99
- `coverage-summary.json` file.
100
-
101
- When the complexity or CRAP check flags a hotspot:
87
+ Scores are compared unrounded: with `max` 30, a score of exactly 30 passes and
88
+ 30.01 fails.
89
+
90
+ ### Source inventory
91
+
92
+ `crap-ts score` walks the working directory for `.ts`, `.tsx`, `.mts` and
93
+ `.cts` files, skipping `node_modules`, directories whose name starts with `.`,
94
+ symbolic links and `.d.ts` declarations. `include` and `exclude` filter that
95
+ inventory by path substring (relative to the working directory, `/`
96
+ separators). Files named in the coverage JSON that pass the same filters are
97
+ analyzed too, even when their extension is not in the list above.
98
+
99
+ An inventoried file with no coverage entry **fails the gate** if it contains a
100
+ function body or an executable module-level statement. Declaration-only files
101
+ are exempt: type aliases, interfaces, `declare` statements, re-exports
102
+ (`export … from`), binding imports (`import { x } from`), type-only
103
+ `import type X = require()` and namespaces that hold only those. A side-effect
104
+ import (`import "./setup"`) counts as executable. The functions in such a file
105
+ are still listed, with `evidence: "missing"` unless an ignore comment covers
106
+ them.
107
+
108
+ Use `exclude` for tests, fixtures and tooling that your coverage run does not
109
+ instrument.
110
+
111
+ ### Coverage
112
+
113
+ Coverage is per function, from Istanbul statement counters:
114
+
115
+ - A statement belongs to the innermost function whose source range contains
116
+ the statement's start position. Nested functions and callbacks get their own
117
+ rows and never count toward their parent. A statement that starts exactly at
118
+ a function's first token, such as Istanbul's initializer counter for
119
+ `const f = () => …`, belongs to the enclosing scope: it runs when the
120
+ enclosing code does, not when the function is called.
121
+ - `coverage` = executed owned statements / owned statements. Only positive
122
+ counters count as executed.
123
+ - A function with no owned statements (for example `() => {}`) uses its own
124
+ Istanbul function counter instead (`evidence: "function"`): 100% if it ran,
125
+ 0% if not. A counter inside the function is preferred; one placed exactly
126
+ at the function's first token (as per-line V8 converters do) is used when
127
+ there is none inside.
128
+ - A function with no counter at all is reported at 0% with
129
+ `evidence: "missing"` and **fails the gate**: its file has no coverage
130
+ entry, or the function was added after coverage ran.
131
+ - The exception is code under a coverage ignore comment, which coverage tools
132
+ leave without counters on purpose. Such a function is listed with
133
+ `evidence: "ignored"` and level `ignored`, never fails or warns, and sorts
134
+ after every other row. Its `coverage` (0) and `crap` are shown for
135
+ reference only. crap-ts recognises `istanbul`, `v8` and `c8` comments
136
+ (block or line):
137
+ - `ignore next` covers the next statement or declaration, including any
138
+ functions inside it.
139
+ - `ignore next N` covers the next N lines.
140
+ - `ignore if` and `ignore else`, before an `if` statement, cover its `if`
141
+ branch or its `else` branch.
142
+ - `ignore start` … `ignore stop` covers the region between them.
143
+ - `ignore file` covers the whole file, which then needs no coverage entry.
144
+
145
+ Comment-like text inside strings, template literals, regular expressions
146
+ and JSX text is not treated as a comment.
147
+
148
+ An ignore comment only exempts a function that has no counters. If the
149
+ coverage tool still measured it, its counters are used.
150
+ - Module-level statements belong to no function.
151
+
152
+ Pass `--coverage-file` more than once (or a `coverageFile` array) to merge
153
+ runs, such as Node and browser suites. Entries for the same file are merged by
154
+ each counter's original source position, never by counter id or by averaging
155
+ percentages.
156
+
157
+ `crap-ts` refuses coverage whose statements start outside the current source
158
+ (a line that does not exist, or a column past the end of the line): re-run
159
+ coverage after changing the source. This is a cheap staleness guard, not a
160
+ content hash; edits that keep every statement position valid are not detected.
161
+ Malformed coverage (a top-level value that is not an object, missing maps,
162
+ negative or non-integer counters, invalid or reversed positions) is an error,
163
+ not a silent zero.
164
+
165
+ V8-based coverage (for example Vitest's default provider) reports one
166
+ statement per line, so a function's coverage is line-granular there. Use the
167
+ Istanbul provider when you need statement precision.
168
+
169
+ ### Complexity
170
+
171
+ Each function starts at 1 and adds 1 for each:
172
+
173
+ - `if` (an `else if` is another `if`)
174
+ - ternary `?:`
175
+ - `for`, `for…in`, `for…of`, `while`, `do…while`
176
+ - `catch`
177
+ - `case` in a `switch` (`default` does not count)
178
+ - `&&`, `||`, `??`
179
+ - logical assignment `&&=`, `||=`, `??=`
180
+ - default values: parameters (`a = 1`), destructuring in declarations and
181
+ parameters (`const { a = 1 } = x`, `[a = 1]`), and shorthand defaults in
182
+ assignment patterns (`({ a = 1 } = x)`)
183
+
184
+ These add nothing: `else`, `finally`, `default:`, optional chaining (`?.`),
185
+ early `return`/`break`/`continue`, JSX, and anything at the type level (type
186
+ annotations, conditional types). Decisions inside a nested function count only
187
+ toward that nested function.
188
+
189
+ Functions are declarations, function expressions, arrow functions, methods,
190
+ constructors, getters and setters that have a body. Overload signatures and
191
+ abstract methods have no body and no row. Unnamed functions are reported as
192
+ `<anonymous>`; their file, line and column identify them.
193
+
194
+ ### Rows and thresholds
195
+
196
+ `minLines` (default 10) hides functions shorter than that many lines from both
197
+ reports and the gate. A function fails when its score is above `max` or its
198
+ evidence is `missing`. Functions with evidence `ignored` never fail or warn.
199
+
200
+ When the CRAP check flags a hotspot:
102
201
 
103
202
  1. Name the affected function or file in the review.
104
203
  2. Confirm there is direct test coverage for that path.
@@ -111,58 +210,176 @@ branching visible before it becomes a maintenance tax.
111
210
  ## CLI
112
211
 
113
212
  ```sh
114
- crap-ts score [--coverage-file coverage/unit/coverage-final.json] [--coverage-command "npm run test:coverage"]
115
- crap-ts --metrics complexity-metrics.json --coverage-file coverage/coverage-summary.json
213
+ crap-ts score [options]
214
+ crap-ts help
116
215
  ```
117
216
 
118
- Options:
217
+ `score` is required: running `crap-ts` with options but no command is a usage
218
+ error.
119
219
 
120
220
  - `--config <path>`: read config from a JSON file. Defaults to `.crap-ts.json`
121
221
  when present.
122
- - `--coverage-file <path>`: read coverage from a coverage JSON file.
222
+ - `--coverage-file <path>`: Istanbul `coverage-final.json`. Repeat to merge
223
+ several runs. Defaults to `coverage/unit/coverage-final.json`.
123
224
  - `--coverage-command <cmd>`: run a coverage command before scoring.
225
+ - `--include <text>`: only analyze source files whose path contains this text.
226
+ Repeatable.
227
+ - `--exclude <text>`: skip source files whose path contains this text.
228
+ Repeatable.
229
+ - `--json`: print the JSON report instead of the text report.
124
230
  - `--all`: print every analyzed function instead of applying `--limit`.
125
- - `--include <text>`: only analyze coverage files whose path contains this text.
126
- - `--limit <n>`: number of report rows to print. Defaults to `20`.
127
- - `--max <n>`: strict CRAP threshold for direct audit. Defaults to `30`.
231
+ - `--limit <n>`: number of text report rows to print. Defaults to `20`.
232
+ - `--max <n>`: fail when any score is above this. Defaults to `30`.
128
233
  - `--warn <n>`: warn, without failing, when a score is above this. Must not
129
- exceed `--max` (or `--max-crap` with `--metrics`). Off by default.
234
+ exceed `--max`. Off by default.
130
235
  - `--min-lines <n>`: ignore functions shorter than this. Defaults to `10`.
131
- - `--metrics <path>`: read complexity metrics from JSON.
132
- - `--report-only`: print CRAP results without failing on threshold.
133
- - `--skip-coverage`: use an existing coverage file.
134
-
135
- Metrics files use this shape:
136
-
137
- ```json
138
- [
139
- {
140
- "file": "src/example.ts",
141
- "name": "chooseValue",
142
- "complexity": 12
143
- }
144
- ]
145
- ```
146
-
147
- Config files use camelCase keys:
236
+ - `--report-only`: print results without failing on the gate.
237
+ - `--skip-coverage`: do not run the coverage command.
238
+
239
+ Exit codes: `0` passed (or `--report-only`), `1` gate failed, coverage
240
+ command failed, or coverage input is missing, malformed or stale, `2` usage or
241
+ config error (unknown
242
+ command or flag, invalid value, unreadable or invalid config file).
243
+
244
+ When the coverage command fails, `crap-ts` exits `1` before scoring and
245
+ prints no report, not even with `--json`.
246
+
247
+ The text report is for people and may change in any release. Parse `--json`
248
+ instead.
249
+
250
+ ## Configuration
251
+
252
+ `.crap-ts.json` (or the file passed to `--config`) is a JSON object with these
253
+ keys. Unknown keys are an error, so a typo or a removed option never fails
254
+ silently. CLI flags override config. Naturally. The command line gets the last
255
+ word, because you'd be mad at me if it didn't, and I'd also be mad at me.
256
+
257
+ | Key | Type | CLI flag | Default |
258
+ | --- | --- | --- | --- |
259
+ | `coverageCommand` | string | `--coverage-command` | none |
260
+ | `coverageFile` | string or string[] | `--coverage-file` | `coverage/unit/coverage-final.json` |
261
+ | `include` | string or string[] | `--include` | everything |
262
+ | `exclude` | string or string[] | `--exclude` | nothing |
263
+ | `json` | boolean | `--json` | `false` |
264
+ | `all` | boolean | `--all` | `false` |
265
+ | `limit` | number | `--limit` | `20` |
266
+ | `max` | number | `--max` | `30` |
267
+ | `warn` | number | `--warn` | none |
268
+ | `minLines` | number | `--min-lines` | `10` |
269
+ | `reportOnly` | boolean | `--report-only` | `false` |
270
+ | `skipCoverage` | boolean | `--skip-coverage` | `false` |
271
+
272
+ ## JSON Report
273
+
274
+ `crap-ts score --json` prints one JSON document to stdout. Schema version `1`
275
+ is stable for crap-ts 1.x: fields are only added, never renamed, removed or
276
+ changed in meaning. A breaking change bumps `schemaVersion`.
148
277
 
149
278
  ```json
150
279
  {
151
- "coverageCommand": "npm run test:coverage",
152
- "coverageFile": "coverage/unit/coverage-final.json",
153
- "include": ["src"],
154
- "all": false,
155
- "limit": 20,
156
- "max": 30,
157
- "warn": 25,
158
- "minLines": 10,
159
- "reportOnly": false,
160
- "skipCoverage": false
280
+ "schemaVersion": 1,
281
+ "thresholds": { "max": 30, "warn": 25, "minLines": 10 },
282
+ "summary": {
283
+ "files": 28,
284
+ "functions": 126,
285
+ "aboveMax": 0,
286
+ "warning": 2,
287
+ "missingEvidence": 0,
288
+ "ignored": 0,
289
+ "missingFiles": 0,
290
+ "passed": true
291
+ },
292
+ "functions": [
293
+ {
294
+ "file": "src/station/docking.ts",
295
+ "name": "assignDockingPort",
296
+ "line": 12,
297
+ "column": 8,
298
+ "endLine": 41,
299
+ "lines": 30,
300
+ "complexity": 6,
301
+ "coverage": 87.5,
302
+ "statements": 16,
303
+ "coveredStatements": 14,
304
+ "evidence": "statements",
305
+ "crap": 6.0703125,
306
+ "level": "ok"
307
+ }
308
+ ],
309
+ "missingFiles": []
161
310
  }
162
311
  ```
163
312
 
164
- CLI flags override config. Naturally. The command line gets the last word,
165
- because you'd be mad at me if it didn't, and I'd also be mad at me.
313
+ - `thresholds.warn` is `null` when no warn threshold is set.
314
+ - `summary.files`: source files analyzed. `functions`: rows listed.
315
+ `aboveMax`: rows with `crap > max`, not counting `ignored` rows. `warning`: rows with level `warn`.
316
+ `missingEvidence`: rows with evidence `missing`. `ignored`: rows with
317
+ evidence `ignored`. `missingFiles`: length of `missingFiles`.
318
+ - `summary.passed` is the gate verdict, `aboveMax`, `missingEvidence` and
319
+ `missingFiles` all zero, and ignores `--report-only`.
320
+ - `functions` lists every function at or above `minLines`, never truncated by
321
+ `--limit`, sorted by `crap` descending, then `file`, `line`, `column`, with
322
+ `ignored` rows after all others.
323
+ - `file` is relative to the working directory with `/` separators. `line` and
324
+ `column` are one-based and point at the function's first token.
325
+ - `coverage` is a percentage from 0 to 100. `crap` and `coverage` are
326
+ unrounded.
327
+ - `evidence` is `statements`, `function`, `ignored` or `missing` (see
328
+ [Coverage](#coverage)).
329
+ - `level` is `fail` (above `max`, or missing evidence), `warn` (above `warn`),
330
+ `ignored` (evidence `ignored`) or `ok`. For `ignored` rows, `coverage` is 0
331
+ and `crap` is the score at 0% coverage, for reference only.
332
+ - `missingFiles` lists inventoried files with executable code and no coverage
333
+ entry, sorted.
334
+
335
+ ## Programmatic API
336
+
337
+ The package root is the only entry point. These exports, and the types in
338
+ `src/index.d.ts`, are the 1.x API:
339
+
340
+ - `runCrapAudit(options?: CrapAuditOptions): Promise<number>` runs the same
341
+ audit as the CLI and resolves to its exit code (`2` for invalid options,
342
+ including non-finite numbers; `1` for a failed gate, a failed coverage
343
+ command or a missing coverage file). It rejects with an `Error`
344
+ when coverage or source input is malformed or stale. Options mirror the config
345
+ keys: `coverageCommand`, `coveragePaths`, `cwd`, `includes`, `excludes`,
346
+ `json`, `all`, `limit`, `maxScore`, `warnScore`, `minLines`, `reportOnly`,
347
+ `skipCoverage`.
348
+ - `analyzeFileRisk({ filePath, sourceText, coverage?, minLines?, sourceFilePath? }): Promise<FunctionRisk[]>`
349
+ scores the functions in one source text. `coverage` is that file's entry
350
+ from `coverage-final.json`. A function without counters has
351
+ `evidence: "missing"`, or `"ignored"` when an ignore comment covers it.
352
+ `minLines` defaults to 1.
353
+ - `calculateCyclomaticComplexity(node): number` applies the complexity rules
354
+ above to a TypeScript AST node from the consumer's `typescript` package.
355
+ - `calculateCrapScore({ complexity, coverage }): number` is the formula, with
356
+ `coverage` as a percentage from 0 to 100.
357
+
358
+ Everything else under `src/` is internal and may change in any release.
359
+
360
+ ## Upgrading From 0.x
361
+
362
+ 1.0 changes scores and removes an unused mode. Expect different numbers.
363
+
364
+ - Coverage is now owned-statement coverage per function, not the 0/100
365
+ function-called flag. Partially tested functions score lower; a function
366
+ whose callback never runs no longer looks covered.
367
+ - Nested functions no longer add their decisions to the parent. Parameter and
368
+ destructuring defaults and logical assignment now add decisions.
369
+ Constructors, getters and setters now get rows.
370
+ - Source files without coverage entries, and functions without any coverage
371
+ counter, now fail the gate, unless a coverage ignore comment covers them. Add `exclude` entries for tests and tooling
372
+ (for example `"exclude": [".test.ts", "vitest.config"]`) if your `include`
373
+ matches them.
374
+ - `--metrics`, `--max-crap`, the `metrics` and `maxCrap` config keys, and
375
+ running without the `score` command are gone, along with the
376
+ `buildCrapScores` and `getCoverageForFile` exports.
377
+ - The `crap-ts/crap-analysis`, `crap-ts/crap-runner` and `crap-ts/crap-score`
378
+ subpath exports are gone; import from `crap-ts`. `extractCoverageFunctions`
379
+ and `formatRiskLine` are no longer exported, and `analyzeFileRisk` takes an
380
+ Istanbul `coverage` entry instead of `coverageFunctions`.
381
+ - `CrapAuditOptions.coveragePath` is now `coveragePaths` (an array).
382
+ - Unknown `.crap-ts.json` keys are an error.
166
383
 
167
384
  ## Replacing Local CRAP Scripts
168
385
 
@@ -182,9 +399,10 @@ With `.crap-ts.json`:
182
399
 
183
400
  ```json
184
401
  {
185
- "coverageCommand": "bun x vitest run --coverage --coverage.reporter=json --coverage.reporter=json-summary",
402
+ "coverageCommand": "bun x vitest run --coverage --coverage.reporter=json",
186
403
  "coverageFile": "coverage/unit/coverage-final.json",
187
- "include": ["/app/", "/scripts/"]
404
+ "include": ["app/", "scripts/"],
405
+ "exclude": [".test.ts"]
188
406
  }
189
407
  ```
190
408
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "crap-ts",
3
- "version": "0.2.0",
3
+ "version": "1.0.0",
4
4
  "description": "Small CRAP-score audit helper for TypeScript projects.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -14,18 +14,6 @@
14
14
  ".": {
15
15
  "types": "./src/index.d.ts",
16
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
17
  }
30
18
  },
31
19
  "files": [
@@ -35,8 +23,8 @@
35
23
  "LICENSE"
36
24
  ],
37
25
  "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",
26
+ "check": "node --check src/cli.js && node --check src/crap-analysis.js && node --check src/crap-runner.js && node --check src/crap-score.js && node --check src/index.js",
27
+ "score": "node src/cli.js score --coverage-file fixtures/coverage-final.json --coverage-file fixtures/risky-coverage-final.json --include fixtures/ --min-lines 1 --report-only",
40
28
  "test": "node --test tests/*.test.js",
41
29
  "test:consumer-typescript": "node scripts/verify-consumer-typescript.mjs",
42
30
  "validate": "npm run test && npm run score",