crap-ts 1.0.0 → 2.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/README.md CHANGED
@@ -36,7 +36,7 @@ TypeScript 7 projects do not get a nested TypeScript 5.x install.
36
36
  ## Usage
37
37
 
38
38
  ```sh
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
39
+ npx crap-ts score --coverage-command "npm run test:coverage -- --coverage.reporter=json" --coverage-file coverage/unit/coverage-final.json --include 'src/**'
40
40
  ```
41
41
 
42
42
  Add package scripts:
@@ -58,8 +58,7 @@ Put the long bits in `.crap-ts.json`:
58
58
  {
59
59
  "coverageCommand": "npm run test:coverage -- --coverage.reporter=json",
60
60
  "coverageFile": "coverage/unit/coverage-final.json",
61
- "include": ["src/"],
62
- "exclude": [".test.ts"],
61
+ "include": ["src/**"],
63
62
  "max": 30,
64
63
  "warn": 25
65
64
  }
@@ -91,10 +90,24 @@ Scores are compared unrounded: with `max` 30, a score of exactly 30 passes and
91
90
 
92
91
  `crap-ts score` walks the working directory for `.ts`, `.tsx`, `.mts` and
93
92
  `.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.
93
+ symbolic links and `.d.ts` declarations. `include` and `exclude` match paths
94
+ relative to the working directory. A pattern ending in `/**` matches files
95
+ below a directory at that root. For example, `src/**` matches `src/a.ts`
96
+ and `src/lib/b.ts`. Plain patterns match substrings. For example, `src/`
97
+ also matches `tests/fixtures/src/c.ts`. An asterisk outside the trailing
98
+ `/**` is a usage error. Both forms accept `/` and `\` as
99
+ separators. The same filters, including the test-file default below, apply
100
+ to files named in the coverage JSON. Coverage entries for `.js`, `.jsx`,
101
+ `.mjs` and `.cjs` files are scored too. Coverage entries for other files, such
102
+ as CSS or JSON modules that Vitest reports for side-effect imports, are not
103
+ scored.
104
+
105
+ If the filters select no source files, `crap-ts` exits `1` before scoring,
106
+ also with `--report-only`. If only the test-file default removed the matching
107
+ files, the message names `--include-tests`.
108
+
109
+ If the selected files hold no function with at least `--min-lines` lines,
110
+ the gate fails: a gate that checks nothing never passes. With `--report-only`, `crap-ts` prints a warning and exits `0`.
98
111
 
99
112
  An inventoried file with no coverage entry **fails the gate** if it contains a
100
113
  function body or an executable module-level statement. Declaration-only files
@@ -105,8 +118,15 @@ import (`import "./setup"`) counts as executable. The functions in such a file
105
118
  are still listed, with `evidence: "missing"` unless an ignore comment covers
106
119
  them.
107
120
 
108
- Use `exclude` for tests, fixtures and tooling that your coverage run does not
109
- instrument.
121
+ Test files are skipped by default: file names that end in `.test.<ext>`,
122
+ `.spec.<ext>`, `.test-d.<ext>` or `.spec-d.<ext>`, and any file below a
123
+ `__tests__/` directory. These are the files Vitest and Jest treat as tests by
124
+ default, so their coverage runs do not instrument them. `include` and
125
+ `exclude` apply on top of this default. Pass `--include-tests` (or set
126
+ `includeTests: true`) to analyze test files too.
127
+
128
+ Use `exclude` for other files that your coverage run does not instrument,
129
+ such as fixtures, test helpers and tooling.
110
130
 
111
131
  ### Coverage
112
132
 
@@ -130,9 +150,9 @@ Coverage is per function, from Istanbul statement counters:
130
150
  entry, or the function was added after coverage ran.
131
151
  - The exception is code under a coverage ignore comment, which coverage tools
132
152
  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
153
+ `evidence: "ignored"` and sorts after every other row. By default, its
154
+ level is `ignored` and it does not affect the gate. Its `coverage` (0) and
155
+ `crap` are shown for reference only. crap-ts recognises `istanbul`, `v8` and `c8` comments
136
156
  (block or line):
137
157
  - `ignore next` covers the next statement or declaration, including any
138
158
  functions inside it.
@@ -140,13 +160,19 @@ Coverage is per function, from Istanbul statement counters:
140
160
  - `ignore if` and `ignore else`, before an `if` statement, cover its `if`
141
161
  branch or its `else` branch.
142
162
  - `ignore start` … `ignore stop` covers the region between them.
143
- - `ignore file` covers the whole file, which then needs no coverage entry.
163
+ - `ignore file` covers the whole file. By default, the file needs no
164
+ coverage entry.
144
165
 
145
166
  Comment-like text inside strings, template literals, regular expressions
146
167
  and JSX text is not treated as a comment.
147
168
 
148
169
  An ignore comment only exempts a function that has no counters. If the
149
170
  coverage tool still measured it, its counters are used.
171
+
172
+ Set `failOnIgnored: true` or pass `--fail-on-ignored` to fail on audited
173
+ functions with `evidence: "ignored"`. The text report names these functions
174
+ even when they fall outside `--limit`. An executable file with an
175
+ `ignore file` comment also needs a coverage entry when this setting is on.
150
176
  - Module-level statements belong to no function.
151
177
 
152
178
  Pass `--coverage-file` more than once (or a `coverageFile` array) to merge
@@ -154,6 +180,11 @@ runs, such as Node and browser suites. Entries for the same file are merged by
154
180
  each counter's original source position, never by counter id or by averaging
155
181
  percentages.
156
182
 
183
+ Each listed coverage file must contain at least one source entry. The CLI
184
+ rejects `{}` before applying path filters, exits with code 1, and names the
185
+ empty file. This check also runs with `--report-only`. To accept empty files
186
+ as in 1.0, set `allowEmptyCoverage: true` or pass `--allow-empty-coverage`.
187
+
157
188
  `crap-ts` refuses coverage whose statements start outside the current source
158
189
  (a line that does not exist, or a column past the end of the line): re-run
159
190
  coverage after changing the source. This is a cheap staleness guard, not a
@@ -195,7 +226,8 @@ abstract methods have no body and no row. Unnamed functions are reported as
195
226
 
196
227
  `minLines` (default 10) hides functions shorter than that many lines from both
197
228
  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.
229
+ evidence is `missing`. With `failOnIgnored` enabled, it also fails when its
230
+ evidence is `ignored`.
199
231
 
200
232
  When the CRAP check flags a hotspot:
201
233
 
@@ -222,10 +254,14 @@ error.
222
254
  - `--coverage-file <path>`: Istanbul `coverage-final.json`. Repeat to merge
223
255
  several runs. Defaults to `coverage/unit/coverage-final.json`.
224
256
  - `--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.
257
+ - `--include <pattern>`: only analyze matching paths. Repeatable. Quote
258
+ patterns like `'src/**'` to pass them directly to crap-ts.
259
+ - `--exclude <pattern>`: skip matching paths. Repeatable.
260
+ - `--fail-on-ignored`: fail on ignored functions and require coverage entries
261
+ for executable files with an `ignore file` comment.
262
+ - `--allow-empty-coverage`: accept listed coverage files containing `{}`.
263
+ - `--include-tests`: also analyze test files, which are skipped by default.
264
+ See [Source inventory](#source-inventory).
229
265
  - `--json`: print the JSON report instead of the text report.
230
266
  - `--all`: print every analyzed function instead of applying `--limit`.
231
267
  - `--limit <n>`: number of text report rows to print. Defaults to `20`.
@@ -236,10 +272,10 @@ error.
236
272
  - `--report-only`: print results without failing on the gate.
237
273
  - `--skip-coverage`: do not run the coverage command.
238
274
 
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).
275
+ Exit codes: `0` passed (or `--report-only`), `1` gate failed, no source
276
+ files matched the filters, coverage command failed, or coverage input is
277
+ missing, malformed, stale or rejected for being empty, `2` usage or config error (unknown command or flag, invalid
278
+ value, unreadable or invalid config file).
243
279
 
244
280
  When the coverage command fails, `crap-ts` exits `1` before scoring and
245
281
  prints no report, not even with `--json`.
@@ -260,6 +296,9 @@ word, because you'd be mad at me if it didn't, and I'd also be mad at me.
260
296
  | `coverageFile` | string or string[] | `--coverage-file` | `coverage/unit/coverage-final.json` |
261
297
  | `include` | string or string[] | `--include` | everything |
262
298
  | `exclude` | string or string[] | `--exclude` | nothing |
299
+ | `failOnIgnored` | boolean | `--fail-on-ignored` | `false` |
300
+ | `allowEmptyCoverage` | boolean | `--allow-empty-coverage` | `false` |
301
+ | `includeTests` | boolean | `--include-tests` | `false` |
263
302
  | `json` | boolean | `--json` | `false` |
264
303
  | `all` | boolean | `--all` | `false` |
265
304
  | `limit` | number | `--limit` | `20` |
@@ -272,7 +311,7 @@ word, because you'd be mad at me if it didn't, and I'd also be mad at me.
272
311
  ## JSON Report
273
312
 
274
313
  `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
314
+ is stable for crap-ts 1.x and 2.x: fields are only added, never renamed, removed or
276
315
  changed in meaning. A breaking change bumps `schemaVersion`.
277
316
 
278
317
  ```json
@@ -312,11 +351,13 @@ changed in meaning. A breaking change bumps `schemaVersion`.
312
351
 
313
352
  - `thresholds.warn` is `null` when no warn threshold is set.
314
353
  - `summary.files`: source files analyzed. `functions`: rows listed.
315
- `aboveMax`: rows with `crap > max`, not counting `ignored` rows. `warning`: rows with level `warn`.
354
+ `aboveMax`: rows with `crap > max`, excluding rows with evidence `ignored`.
355
+ `warning`: rows with level `warn`.
316
356
  `missingEvidence`: rows with evidence `missing`. `ignored`: rows with
317
357
  evidence `ignored`. `missingFiles`: length of `missingFiles`.
318
- - `summary.passed` is the gate verdict, `aboveMax`, `missingEvidence` and
319
- `missingFiles` all zero, and ignores `--report-only`.
358
+ - `summary.passed` is true when `aboveMax`, `missingEvidence` and
359
+ `missingFiles` are all zero. With `failOnIgnored` enabled, `ignored` must
360
+ also be zero. The verdict is independent of `--report-only`.
320
361
  - `functions` lists every function at or above `minLines`, never truncated by
321
362
  `--limit`, sorted by `crap` descending, then `file`, `line`, `column`, with
322
363
  `ignored` rows after all others.
@@ -326,25 +367,28 @@ changed in meaning. A breaking change bumps `schemaVersion`.
326
367
  unrounded.
327
368
  - `evidence` is `statements`, `function`, `ignored` or `missing` (see
328
369
  [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.
370
+ - `level` is `fail` (above `max`, missing evidence, or ignored evidence with
371
+ `failOnIgnored` enabled), `warn` (above `warn`), `ignored` or `ok`. With
372
+ ignored evidence, `coverage` is 0 and `crap` is the score at 0% coverage,
373
+ for reference only.
332
374
  - `missingFiles` lists inventoried files with executable code and no coverage
333
375
  entry, sorted.
334
376
 
335
377
  ## Programmatic API
336
378
 
337
379
  The package root is the only entry point. These exports, and the types in
338
- `src/index.d.ts`, are the 1.x API:
380
+ `src/index.d.ts`, are the 2.x API:
339
381
 
340
382
  - `runCrapAudit(options?: CrapAuditOptions): Promise<number>` runs the same
341
383
  audit as the CLI and resolves to its exit code (`2` for invalid options,
342
384
  including non-finite numbers; `1` for a failed gate, a failed coverage
343
385
  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`.
386
+ when coverage or source input is malformed or stale, or when a required
387
+ coverage file is empty and `allowEmptyCoverage` is false. Options include
388
+ `coverageCommand`, `coveragePaths`, `cwd`, `includes`, `excludes`,
389
+ `failOnIgnored`, `allowEmptyCoverage`, `includeTests`,
390
+ `json`, `all`, `limit`, `maxScore`, `warnScore`, `minLines`, `reportOnly`
391
+ and `skipCoverage`.
348
392
  - `analyzeFileRisk({ filePath, sourceText, coverage?, minLines?, sourceFilePath? }): Promise<FunctionRisk[]>`
349
393
  scores the functions in one source text. `coverage` is that file's entry
350
394
  from `coverage-final.json`. A function without counters has
@@ -357,6 +401,45 @@ The package root is the only entry point. These exports, and the types in
357
401
 
358
402
  Everything else under `src/` is internal and may change in any release.
359
403
 
404
+ ## Upgrading From 2.0
405
+
406
+ Scores and the JSON schema do not change. The gate can fail where 2.0 passed
407
+ or crashed:
408
+
409
+ - Test files (`*.test.*`, `*.spec.*`, `*.test-d.*`, `*.spec-d.*` and files
410
+ below `__tests__/`) are skipped by default. You can remove `exclude` entries
411
+ such as `.test.ts`. To keep scoring test files, pass `--include-tests` or
412
+ set `includeTests: true`.
413
+ - If `include` and `exclude` select no source files, `crap-ts` exits `1`,
414
+ also with `--report-only`.
415
+ - If no function is checked, the gate fails. With `--report-only`, `crap-ts`
416
+ warns and exits `0`.
417
+ - Coverage entries for files that are not TypeScript or JavaScript sources,
418
+ such as CSS and JSON modules from side-effect imports, are no longer
419
+ scored. With
420
+ TypeScript 7, these entries crashed 2.0.
421
+ - A positional argument such as `crap-ts score src` is still a usage error.
422
+ The message now suggests the matching `--include` pattern.
423
+
424
+ ## Upgrading From 1.x
425
+
426
+ 2.0 has two breaking changes. Scores and the JSON schema do not change.
427
+
428
+ - A listed coverage file that contains `{}` now fails with exit code 1, also
429
+ with `--report-only`. Fix the coverage run so that it writes entries. To
430
+ accept empty files as in 1.0, pass `--allow-empty-coverage` or set
431
+ `allowEmptyCoverage: true`.
432
+ - An `include` or `exclude` pattern with `*` anywhere other than a trailing
433
+ `/**` now exits with code 2. Replace `src/*` or `src/**/*.ts` with `src/**`,
434
+ or use a plain substring pattern such as `src/`.
435
+
436
+ New options:
437
+
438
+ - `--fail-on-ignored` (`failOnIgnored`) fails the gate on functions that
439
+ coverage ignore comments exempt.
440
+ - A pattern ending in `/**` matches only below that directory at the working
441
+ directory root. Plain patterns still match substrings.
442
+
360
443
  ## Upgrading From 0.x
361
444
 
362
445
  1.0 changes scores and removes an unused mode. Expect different numbers.
@@ -401,8 +484,7 @@ With `.crap-ts.json`:
401
484
  {
402
485
  "coverageCommand": "bun x vitest run --coverage --coverage.reporter=json",
403
486
  "coverageFile": "coverage/unit/coverage-final.json",
404
- "include": ["app/", "scripts/"],
405
- "exclude": [".test.ts"]
487
+ "include": ["app/**", "scripts/**"]
406
488
  }
407
489
  ```
408
490
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "crap-ts",
3
- "version": "1.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "Small CRAP-score audit helper for TypeScript projects.",
5
5
  "repository": {
6
6
  "type": "git",
package/src/cli.js CHANGED
@@ -21,8 +21,14 @@ Options:
21
21
  --coverage-command <cmd>
22
22
  Command to generate coverage before scoring.
23
23
  --all Print every analyzed function instead of applying --limit.
24
- --include <text> Only analyze source files whose path contains this text.
25
- --exclude <text> Skip source files whose path contains this text.
24
+ --include <pattern> Only analyze matching source paths. Use dir/** to anchor.
25
+ --exclude <pattern> Skip matching source paths. Use dir/** to anchor.
26
+ --fail-on-ignored
27
+ Fail when an audited function has coverage evidence marked ignored.
28
+ --allow-empty-coverage
29
+ Accept listed coverage JSON files with no entries.
30
+ --include-tests Also analyze test files (*.test.*, *.spec.*, __tests__/),
31
+ which are skipped by default.
26
32
  --json Print the full JSON report (schema version 1) instead of text.
27
33
  --limit <n> Number of rows to print in the text report. Defaults to 20.
28
34
  --min-lines <n> Ignore functions shorter than this. Defaults to 10.
@@ -41,12 +47,15 @@ export function parseCliArgs(argv, { cwd = process.cwd() } = {}) {
41
47
  args,
42
48
  options: {
43
49
  all: { type: "boolean" },
50
+ "allow-empty-coverage": { type: "boolean" },
44
51
  config: { type: "string" },
45
52
  "coverage-file": { type: "string", multiple: true },
46
53
  "coverage-command": { type: "string" },
47
54
  exclude: { type: "string", multiple: true },
55
+ "fail-on-ignored": { type: "boolean" },
48
56
  help: { type: "boolean", short: "h" },
49
57
  include: { type: "string", multiple: true },
58
+ "include-tests": { type: "boolean" },
50
59
  json: { type: "boolean" },
51
60
  limit: { type: "string" },
52
61
  max: { type: "string" },
@@ -62,12 +71,15 @@ export function parseCliArgs(argv, { cwd = process.cwd() } = {}) {
62
71
  mergeConfigWithCli(config, {
63
72
  command,
64
73
  all: values.all,
74
+ allowEmptyCoverage: values["allow-empty-coverage"],
65
75
  configPath: values.config,
66
76
  coverageCommand: values["coverage-command"],
67
77
  coveragePaths: values["coverage-file"],
68
78
  excludes: values.exclude,
79
+ failOnIgnored: values["fail-on-ignored"],
69
80
  help: values.help,
70
81
  includes: values.include,
82
+ includeTests: values["include-tests"],
71
83
  json: values.json,
72
84
  limit: parseOptionalNumber(values.limit, "--limit"),
73
85
  maxScore: parseOptionalNumber(values.max, "--max"),
@@ -99,7 +111,12 @@ export async function main(argv = process.argv.slice(2)) {
99
111
  try {
100
112
  options = parseCliArgs(argv);
101
113
  } catch (error) {
102
- console.error(`Usage error: ${error.message}`);
114
+ const positional = /^Unexpected argument '(.*)'/.exec(error.message)?.[1];
115
+ const hint =
116
+ error.code === "ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL" && positional
117
+ ? ` Pass source directories as --include patterns, for example --include '${positional.replace(/\/+$/, "")}/**'.`
118
+ : "";
119
+ console.error(`Usage error: ${error.message}${hint}`);
103
120
  return 2;
104
121
  }
105
122
 
@@ -158,10 +175,13 @@ function mergeConfigWithCli(config, cliOptions) {
158
175
 
159
176
  const configKeys = new Set([
160
177
  "all",
178
+ "allowEmptyCoverage",
161
179
  "coverageCommand",
162
180
  "coverageFile",
163
181
  "exclude",
182
+ "failOnIgnored",
164
183
  "include",
184
+ "includeTests",
165
185
  "json",
166
186
  "limit",
167
187
  "max",
@@ -186,6 +206,11 @@ function normalizeConfig(config) {
186
206
 
187
207
  return stripUndefined({
188
208
  all: parseConfigType(config.all, "all", "boolean"),
209
+ allowEmptyCoverage: parseConfigType(
210
+ config.allowEmptyCoverage,
211
+ "allowEmptyCoverage",
212
+ "boolean",
213
+ ),
189
214
  coverageCommand: parseConfigType(
190
215
  config.coverageCommand,
191
216
  "coverageCommand",
@@ -193,7 +218,17 @@ function normalizeConfig(config) {
193
218
  ),
194
219
  coveragePaths: normalizeConfigList(config.coverageFile, "coverageFile"),
195
220
  excludes: normalizeConfigList(config.exclude, "exclude"),
221
+ failOnIgnored: parseConfigType(
222
+ config.failOnIgnored,
223
+ "failOnIgnored",
224
+ "boolean",
225
+ ),
196
226
  includes: normalizeConfigList(config.include, "include"),
227
+ includeTests: parseConfigType(
228
+ config.includeTests,
229
+ "includeTests",
230
+ "boolean",
231
+ ),
197
232
  json: parseConfigType(config.json, "json", "boolean"),
198
233
  limit: parseConfigNumber(config.limit, "limit"),
199
234
  maxScore: parseConfigNumber(config.max, "max"),
@@ -255,6 +290,7 @@ function applyDefaults(options) {
255
290
  help: options.help ?? false,
256
291
  excludes: options.excludes ?? [],
257
292
  includes: options.includes ?? [],
293
+ includeTests: options.includeTests ?? false,
258
294
  json: options.json ?? false,
259
295
  reportOnly: options.reportOnly ?? false,
260
296
  skipCoverage: options.skipCoverage ?? false,
@@ -33,6 +33,7 @@ export async function analyzeFileRisk({
33
33
 
34
34
  export async function analyzeSource({
35
35
  coverage,
36
+ failOnIgnored = false,
36
37
  filePath,
37
38
  sourceFilePath,
38
39
  sourceText,
@@ -53,7 +54,7 @@ export async function analyzeSource({
53
54
 
54
55
  return {
55
56
  executable:
56
- !ignore.file &&
57
+ (!ignore.file || failOnIgnored) &&
57
58
  (functions.length > 0 || hasExecutableModuleStatements(adapter)),
58
59
  functions: functions.map(({ ignored, risk }) => {
59
60
  // No counters is only acceptable where an ignore comment removed them.
@@ -1,13 +1,19 @@
1
1
  export interface CrapAuditOptions {
2
2
  all?: boolean;
3
+ /** Accept listed coverage JSON files with no source entries. Defaults to false. */
4
+ allowEmptyCoverage?: boolean;
3
5
  coverageCommand?: string;
4
6
  /** Istanbul `coverage-final.json` files, merged by source position. Defaults to `["coverage/unit/coverage-final.json"]`. */
5
7
  coveragePaths?: string[];
6
8
  cwd?: string;
7
- /** Skip source files whose path contains any of these substrings. */
9
+ /** Skip files matching these path substrings or root-anchored `dir/**` patterns. */
8
10
  excludes?: string[];
9
- /** Only analyze source files whose path contains one of these substrings. */
11
+ /** Fail on functions with ignored evidence and require coverage entries for executable files with an ignore-file comment. Defaults to false. */
12
+ failOnIgnored?: boolean;
13
+ /** Analyze files matching these path substrings or root-anchored `dir/**` patterns. */
10
14
  includes?: string[];
15
+ /** Also analyze test files (`*.test.*`, `*.spec.*`, `*.test-d.*`, `__tests__/`). Defaults to false. */
16
+ includeTests?: boolean;
11
17
  /** Print the JSON report (schema version 1) to stdout instead of the text report. */
12
18
  json?: boolean;
13
19
  limit?: number;
@@ -21,6 +27,6 @@ export interface CrapAuditOptions {
21
27
 
22
28
  /**
23
29
  * Resolves to the process exit code: 0 pass, 1 gate failure, failed coverage command or missing coverage file, 2 usage error (including non-finite numeric options).
24
- * Rejects when coverage or source input is malformed or stale.
30
+ * Rejects when coverage or source input is malformed or stale, or when a coverage file is empty and `allowEmptyCoverage` is false.
25
31
  */
26
32
  export function runCrapAudit(options?: CrapAuditOptions): Promise<number>;
@@ -8,15 +8,25 @@ import { normalizePath } from "./path-utils.js";
8
8
  const reportSchemaVersion = 1;
9
9
 
10
10
  const sourceFilePattern = /\.[cm]?tsx?$/;
11
+ // The inventory walk finds TypeScript only, but JavaScript sources named in
12
+ // coverage are scored too, as in 2.0.
13
+ const javaScriptFilePattern = /\.[cm]?jsx?$/;
11
14
  const declarationFilePattern = /\.d\.[cm]?ts$/;
15
+ // The test files Vitest and Jest find by default: `*.test.*`, `*.spec.*`
16
+ // (and Vitest's `*.test-d.*` type tests), and anything under `__tests__/`.
17
+ const testFilePattern =
18
+ /(?:^|\/)__tests__\/|\.(?:test|spec)(?:-d)?\.[cm]?[jt]sx?$/;
12
19
 
13
20
  export async function runCrapAudit({
14
21
  all = false,
22
+ allowEmptyCoverage = false,
15
23
  coverageCommand,
16
24
  coveragePaths = ["coverage/unit/coverage-final.json"],
17
25
  cwd = process.cwd(),
18
26
  excludes = [],
27
+ failOnIgnored = false,
19
28
  includes = [],
29
+ includeTests = false,
20
30
  json = false,
21
31
  limit = 20,
22
32
  maxScore = 30,
@@ -44,6 +54,18 @@ export async function runCrapAudit({
44
54
  return 2;
45
55
  }
46
56
 
57
+ const unsupportedPattern = [...includes, ...excludes].find((pattern) =>
58
+ normalizePath(pattern)
59
+ .replace(/\/\*\*$/, "")
60
+ .includes("*"),
61
+ );
62
+ if (unsupportedPattern !== undefined) {
63
+ console.error(
64
+ `Unsupported path pattern ${JSON.stringify(unsupportedPattern)}. Use a substring or a directory pattern such as src/**.`,
65
+ );
66
+ return 2;
67
+ }
68
+
47
69
  if (!skipCoverage && coverageCommand) {
48
70
  const result = spawnSync(coverageCommand, {
49
71
  cwd,
@@ -78,22 +100,49 @@ export async function runCrapAudit({
78
100
  // Coverage tools report real paths; compare everything in the file
79
101
  // system's canonical form (`.native` also canonicalises letter case).
80
102
  const root = realpathSync.native(cwd);
81
- const coverageByFile = readCoverageFiles(resolvedCoveragePaths, root);
82
- const isSelected = (path) => {
103
+ const coverageByFile = readCoverageFiles(
104
+ resolvedCoveragePaths,
105
+ root,
106
+ allowEmptyCoverage,
107
+ );
108
+ const matchesFilters = (path) => {
83
109
  const relativePath = relative(root, path);
84
110
  return (
85
111
  matchesAny(relativePath, includes, true) &&
86
112
  !matchesAny(relativePath, excludes, false)
87
113
  );
88
114
  };
89
- const sourcePaths = new Set(listSourceFiles(root).filter(isSelected));
115
+ const isTestFile = (path) =>
116
+ testFilePattern.test(normalizePath(relative(root, path)));
117
+ const candidatePaths = new Set(listSourceFiles(root).filter(matchesFilters));
90
118
 
119
+ // Coverage tools also list non-source modules (CSS, JSON) and even
120
+ // directories; only TypeScript and JavaScript sources can be scored.
91
121
  for (const path of coverageByFile.keys()) {
92
- if (existsSync(path) && isSelected(path)) {
93
- sourcePaths.add(path);
122
+ if (
123
+ isCoverageSourceFile(path) &&
124
+ existsSync(path) &&
125
+ matchesFilters(path)
126
+ ) {
127
+ candidatePaths.add(path);
94
128
  }
95
129
  }
96
130
 
131
+ const sourcePaths = new Set(
132
+ [...candidatePaths].filter((path) => includeTests || !isTestFile(path)),
133
+ );
134
+
135
+ if (sourcePaths.size === 0) {
136
+ const testHint =
137
+ candidatePaths.size > 0
138
+ ? ` The ${candidatePaths.size} matching file(s) were skipped as test files; pass --include-tests to analyze them.`
139
+ : "";
140
+ console.error(
141
+ `No source files matched under ${root}. Check --include and --exclude; patterns are relative to the working directory, for example --include 'src/**'.${testHint}`,
142
+ );
143
+ return 1;
144
+ }
145
+
97
146
  const functions = [];
98
147
  const missingFiles = [];
99
148
 
@@ -102,6 +151,7 @@ export async function runCrapAudit({
102
151
  const coverage = coverageByFile.get(sourceFilePath);
103
152
  const analysis = await analyzeSource({
104
153
  coverage,
154
+ failOnIgnored,
105
155
  filePath,
106
156
  sourceFilePath,
107
157
  sourceText: readFileSync(sourceFilePath, "utf8"),
@@ -117,6 +167,7 @@ export async function runCrapAudit({
117
167
  }
118
168
 
119
169
  const report = buildReport({
170
+ failOnIgnored,
120
171
  files: sourcePaths.size,
121
172
  functions,
122
173
  maxScore,
@@ -140,6 +191,13 @@ export async function runCrapAudit({
140
191
  );
141
192
  }
142
193
 
194
+ if (summary.functions === 0) {
195
+ console.error("");
196
+ console.error(
197
+ `No functions checked in ${summary.files} source file(s). Check --include, --exclude and --min-lines (${minLines}).`,
198
+ );
199
+ }
200
+
143
201
  if (missingFiles.length > 0) {
144
202
  console.error("");
145
203
  console.error(
@@ -163,6 +221,7 @@ export async function runCrapAudit({
163
221
  }
164
222
 
165
223
  function buildReport({
224
+ failOnIgnored,
166
225
  files,
167
226
  functions,
168
227
  maxScore,
@@ -173,7 +232,7 @@ function buildReport({
173
232
  const rows = functions
174
233
  .sort(
175
234
  (left, right) =>
176
- // Ignored rows never gate, so keep them below every gated row.
235
+ // Keep ignored scores below rows that use coverage to score the gate.
177
236
  Number(left.evidence === "ignored") -
178
237
  Number(right.evidence === "ignored") ||
179
238
  right.crapScore - left.crapScore ||
@@ -194,13 +253,13 @@ function buildReport({
194
253
  coveredStatements: risk.coveredStatements,
195
254
  evidence: risk.evidence,
196
255
  crap: risk.crapScore,
197
- level: getRiskLevel(risk, { maxScore, warnScore }),
256
+ level: getRiskLevel(risk, { failOnIgnored, maxScore, warnScore }),
198
257
  }));
199
258
  const count = (predicate) => rows.filter(predicate).length;
200
259
  const summary = {
201
260
  files,
202
261
  functions: rows.length,
203
- aboveMax: count((row) => row.level !== "ignored" && row.crap > maxScore),
262
+ aboveMax: count((row) => row.evidence !== "ignored" && row.crap > maxScore),
204
263
  warning: count((row) => row.level === "warn"),
205
264
  missingEvidence: count((row) => row.evidence === "missing"),
206
265
  ignored: count((row) => row.evidence === "ignored"),
@@ -212,10 +271,13 @@ function buildReport({
212
271
  thresholds: { max: maxScore, warn: warnScore ?? null, minLines },
213
272
  summary: {
214
273
  ...summary,
274
+ // A gate that checks nothing must not pass.
215
275
  passed:
276
+ summary.functions > 0 &&
216
277
  summary.aboveMax === 0 &&
217
278
  summary.missingEvidence === 0 &&
218
- summary.missingFiles === 0,
279
+ summary.missingFiles === 0 &&
280
+ (!failOnIgnored || summary.ignored === 0),
219
281
  },
220
282
  functions: rows,
221
283
  missingFiles,
@@ -240,9 +302,15 @@ function printTextReport({ all, limit, maxScore, report, warnScore }) {
240
302
  `CRAP report: ${summary.functions} functions checked, ${summary.aboveMax} above ${maxScore}${warningSummary}${missingSummary}${ignoredSummary}.`,
241
303
  );
242
304
 
243
- for (const row of all ? functions : functions.slice(0, limit)) {
305
+ const visibleRows = all ? functions : functions.slice(0, limit);
306
+ for (const row of visibleRows) {
244
307
  console.log(formatReportRow(row));
245
308
  }
309
+ for (const row of functions.slice(visibleRows.length)) {
310
+ if (row.evidence === "ignored" && row.level === "fail") {
311
+ console.log(formatReportRow(row));
312
+ }
313
+ }
246
314
  }
247
315
 
248
316
  const rowTags = { fail: "FAIL", ignored: "SKIP", ok: " ok", warn: "WARN" };
@@ -260,9 +328,9 @@ function formatReportRow(row) {
260
328
  ].join(" | ");
261
329
  }
262
330
 
263
- function getRiskLevel(risk, { maxScore, warnScore }) {
331
+ function getRiskLevel(risk, { failOnIgnored, maxScore, warnScore }) {
264
332
  if (risk.evidence === "ignored") {
265
- return "ignored";
333
+ return failOnIgnored ? "fail" : "ignored";
266
334
  }
267
335
 
268
336
  if (risk.crapScore > maxScore || risk.evidence === "missing") {
@@ -276,14 +344,19 @@ function getRiskLevel(risk, { maxScore, warnScore }) {
276
344
  return "ok";
277
345
  }
278
346
 
279
- function readCoverageFiles(coveragePaths, root) {
347
+ function readCoverageFiles(coveragePaths, root, allowEmptyCoverage) {
280
348
  const coverageByFile = new Map();
281
349
 
282
350
  for (const coveragePath of coveragePaths) {
283
351
  const coverageJson = parseCoverageJson(coveragePath);
284
352
  assertObject(coverageJson, coveragePath);
353
+ const entries = Object.entries(coverageJson);
285
354
 
286
- for (const [key, entry] of Object.entries(coverageJson)) {
355
+ if (!allowEmptyCoverage && entries.length === 0) {
356
+ throw new Error(`Empty coverage JSON: ${coveragePath}`);
357
+ }
358
+
359
+ for (const [key, entry] of entries) {
287
360
  const label = `${coveragePath} (${key})`;
288
361
  validateFileCoverage(entry, label);
289
362
 
@@ -430,14 +503,18 @@ function listSourceFiles(directory) {
430
503
  : listSourceFiles(path);
431
504
  }
432
505
 
433
- return entry.isFile() &&
434
- sourceFilePattern.test(entry.name) &&
435
- !declarationFilePattern.test(entry.name)
436
- ? [path]
437
- : [];
506
+ return entry.isFile() && isSourceFile(entry.name) ? [path] : [];
438
507
  });
439
508
  }
440
509
 
510
+ function isSourceFile(path) {
511
+ return sourceFilePattern.test(path) && !declarationFilePattern.test(path);
512
+ }
513
+
514
+ function isCoverageSourceFile(path) {
515
+ return isSourceFile(path) || javaScriptFilePattern.test(path);
516
+ }
517
+
441
518
  function matchesAny(path, patterns, emptyResult) {
442
519
  if (patterns.length === 0) {
443
520
  return emptyResult;
@@ -445,7 +522,18 @@ function matchesAny(path, patterns, emptyResult) {
445
522
 
446
523
  const normalizedPath = normalizePath(path);
447
524
 
448
- return patterns.some((pattern) =>
449
- normalizedPath.includes(normalizePath(pattern)),
450
- );
525
+ return patterns.some((pattern) => {
526
+ const normalizedPattern = normalizePath(pattern);
527
+
528
+ if (normalizedPattern.endsWith("/**")) {
529
+ return (
530
+ !isAbsolute(path) &&
531
+ normalizedPath !== ".." &&
532
+ !normalizedPath.startsWith("../") &&
533
+ normalizedPath.startsWith(normalizedPattern.slice(0, -2))
534
+ );
535
+ }
536
+
537
+ return normalizedPath.includes(normalizedPattern);
538
+ });
451
539
  }