mandrel 2.86.0 → 2.87.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.
@@ -21,6 +21,30 @@ const require = createRequire(import.meta.url);
21
21
  /** jscpd 5 is a Rust rewrite with no Node API; only major 4 exposes one. */
22
22
  const SUPPORTED_JSCPD_MAJOR = '^4';
23
23
 
24
+ /** `err.code` of the missing-install refusal, so a CLI prints it stackless. */
25
+ export const JSCPD_MISSING = 'JSCPD_MISSING';
26
+
27
+ /**
28
+ * jscpd is an optional peer dependency: only a consumer that enables the
29
+ * duplication gate installs it. A missing install names the fix rather than
30
+ * surfacing `MODULE_NOT_FOUND`; any other load failure propagates as-is.
31
+ *
32
+ * @param {NodeJS.Require} requireFn
33
+ * @returns {object}
34
+ */
35
+ function loadJscpd(requireFn) {
36
+ try {
37
+ return requireFn('jscpd');
38
+ } catch (err) {
39
+ if (err?.code !== 'MODULE_NOT_FOUND') throw err;
40
+ const missing = new Error(
41
+ `[Duplication] jscpd is not installed. The duplication gate scans with jscpd ${SUPPORTED_JSCPD_MAJOR}, an optional peer dependency of mandrel — install it in this project: npm i -D jscpd@${SUPPORTED_JSCPD_MAJOR}`,
42
+ );
43
+ missing.code = JSCPD_MISSING;
44
+ throw missing;
45
+ }
46
+ }
47
+
24
48
  /**
25
49
  * Lazy CJS load: jscpd's ESM entry has a broken transitive `colors/safe`
26
50
  * specifier under strict ESM resolution, and importers that never scan should
@@ -32,7 +56,7 @@ const SUPPORTED_JSCPD_MAJOR = '^4';
32
56
  * @returns {(opts: object) => Promise<Array<object>>}
33
57
  */
34
58
  export function resolveDetectClones(requireFn = require) {
35
- const jscpd = requireFn('jscpd');
59
+ const jscpd = loadJscpd(requireFn);
36
60
  if (typeof jscpd?.detectClones !== 'function') {
37
61
  const version = resolveDependencyVersion('jscpd', requireFn) ?? 'unknown';
38
62
  throw new Error(
@@ -11,11 +11,13 @@ import nodeFs from 'node:fs';
11
11
  import { createRequire } from 'node:module';
12
12
  import path from 'node:path';
13
13
  import { execFileCaptureAsync } from '../child-exec.js';
14
+ import { COVERAGE_GATE_DEFAULTS } from '../config/quality.js';
14
15
  import { getQuality, resolveConfig } from '../config-resolver.js';
15
16
  import {
16
17
  buildScopePredicate,
17
18
  scoreCoverageFinal,
18
19
  } from '../coverage-baseline.js';
20
+ import { missingCoverageArtifactMessage } from '../coverage-capture.js';
19
21
  import { loadCoverage } from '../coverage-utils.js';
20
22
  import {
21
23
  resolveEscomplexVersion,
@@ -27,7 +29,9 @@ import {
27
29
  isIgnoredByGlobs as isIgnoredByGlobsMi,
28
30
  scanDirectory as scanDirectoryMi,
29
31
  } from '../maintainability-utils.js';
32
+ import { buildBundleSizeScorer } from './bundle-size-scorer.js';
30
33
  import { resolveDetectClones, scanDuplication } from './duplication-scanner.js';
34
+ import { getKindModule } from './kernel.js';
31
35
  import { filterExcludedRows } from './kinds/maintainability.js';
32
36
  import { canonicalizeBaselinePath } from './path-canon.js';
33
37
  import {
@@ -42,6 +46,7 @@ const SUPPORTED_KINDS = Object.freeze([
42
46
  'crap',
43
47
  'coverage',
44
48
  'duplication',
49
+ 'bundle-size',
45
50
  ]);
46
51
 
47
52
  /**
@@ -56,6 +61,8 @@ const KIND_FILE_PREDICATES = Object.freeze({
56
61
  // Over-inclusive is inert for JS-only jscpd; under-inclusive would pin a
57
62
  // changed file's prior row.
58
63
  duplication: (p) => /\.(?:m?[jt]sx?)$/i.test(p),
64
+ // Bundle names are not paths: no changed file scopes a bundle row.
65
+ 'bundle-size': () => false,
59
66
  });
60
67
 
61
68
  /**
@@ -71,6 +78,22 @@ function resolveQualityBlock({ quality, config } = {}) {
71
78
  return {};
72
79
  }
73
80
 
81
+ /**
82
+ * No coverage artifact: a full-scope refresh over zero rows would read as
83
+ * "nothing to score", so it throws naming the capture contract; a scoped one
84
+ * yields no rows and `refreshBaseline` refuses the missing in-scope files.
85
+ *
86
+ * @param {string} absPath
87
+ * @param {{ fullScope?: boolean } | undefined} opts
88
+ * @returns {object[]}
89
+ */
90
+ function noArtifactRows(absPath, opts) {
91
+ if (opts?.fullScope) {
92
+ throw new Error(missingCoverageArtifactMessage(absPath));
93
+ }
94
+ return [];
95
+ }
96
+
74
97
  /**
75
98
  * @param {{ cwd: string, config?: object, quality?: object }} opts
76
99
  * @returns {(files: string[], opts: object) => Promise<object[]>}
@@ -92,7 +115,7 @@ function buildDefaultCrapScorer({ cwd, config, quality } = {}) {
92
115
  ? coverageRelPath
93
116
  : path.resolve(effectiveCwd, coverageRelPath);
94
117
  const coverage = loadCoverage(coverageAbs);
95
- if (!coverage && requireCoverage) return [];
118
+ if (!coverage && requireCoverage) return noArtifactRows(coverageAbs, opts);
96
119
  const scopeFiles = opts?.fullScope ? null : (files ?? null);
97
120
  const { rows } = await scanAndScore({
98
121
  targetDirs,
@@ -111,24 +134,24 @@ function buildDefaultCrapScorer({ cwd, config, quality } = {}) {
111
134
  }
112
135
 
113
136
  /**
114
- * Coverage rows from coverage-final.json, scoped by the optional `.c8rc.cjs`.
137
+ * Coverage rows from the configured `coverage.coveragePath` artifact, scoped by
138
+ * the optional `.c8rc.cjs`. A missing artifact throws on a full-scope refresh:
139
+ * an empty row set would otherwise read as "nothing measured".
115
140
  *
116
- * @param {{ cwd: string }} opts
141
+ * @param {{ cwd: string, config?: object, quality?: object }} opts
117
142
  * @returns {(files: string[], opts: object) => object[]}
118
143
  */
119
- function buildDefaultCoverageScorer({ cwd } = {}) {
144
+ function buildDefaultCoverageScorer({ cwd, config, quality } = {}) {
145
+ const coverageRelPath =
146
+ resolveQualityBlock({ quality, config })?.coverage?.coveragePath ??
147
+ COVERAGE_GATE_DEFAULTS.coveragePath;
120
148
  return (files, opts) => {
121
149
  const effectiveCwd = opts?.cwd ?? cwd ?? process.cwd();
122
- const coverageFinalPath = path.resolve(
123
- effectiveCwd,
124
- 'coverage/coverage-final.json',
125
- );
126
- let raw;
127
- try {
128
- raw = JSON.parse(nodeFs.readFileSync(coverageFinalPath, 'utf-8'));
129
- } catch {
130
- return [];
150
+ const coverageFinalPath = path.resolve(effectiveCwd, coverageRelPath);
151
+ if (!nodeFs.existsSync(coverageFinalPath)) {
152
+ return noArtifactRows(coverageFinalPath, opts);
131
153
  }
154
+ const raw = JSON.parse(nodeFs.readFileSync(coverageFinalPath, 'utf-8'));
132
155
  let c8Scope;
133
156
  try {
134
157
  const c8rcPath = path.resolve(effectiveCwd, '.c8rc.cjs');
@@ -217,6 +240,7 @@ const KIND_SCORER_BUILDERS = Object.freeze({
217
240
  crap: buildDefaultCrapScorer,
218
241
  coverage: buildDefaultCoverageScorer,
219
242
  duplication: buildDefaultDuplicationScorer,
243
+ 'bundle-size': buildBundleSizeScorer,
220
244
  });
221
245
 
222
246
  /**
@@ -249,7 +273,7 @@ export function resolveDefaultScorer(kind, { cwd } = {}) {
249
273
  * scoped file produced no row.
250
274
  *
251
275
  * @param {{
252
- * kind: 'maintainability' | 'crap' | 'coverage' | 'duplication',
276
+ * kind: 'maintainability' | 'crap' | 'coverage' | 'duplication' | 'bundle-size',
253
277
  * baseRef?: string,
254
278
  * headRef?: string,
255
279
  * scopeFiles?: string[] | null,
@@ -321,11 +345,7 @@ export async function refreshBaseline(opts = {}) {
321
345
  );
322
346
  }
323
347
 
324
- // Rows leave the service canonical whatever scorer produced them.
325
- const canonicalRows = scoredRows.map((row) => ({
326
- ...row,
327
- path: canonicalizeBaselinePath(row.path ?? row.file),
328
- }));
348
+ const canonicalRows = canonicalizeRows(kind, scoredRows);
329
349
 
330
350
  assertRequiredScopeRows({
331
351
  kind,
@@ -370,6 +390,22 @@ export async function refreshBaseline(opts = {}) {
370
390
  };
371
391
  }
372
392
 
393
+ /**
394
+ * Rows leave the service canonical whatever scorer produced them. Only
395
+ * path-keyed kinds carry a path; bundle-size rows are keyed on a name.
396
+ *
397
+ * @param {string} kind
398
+ * @param {object[]} rows
399
+ * @returns {object[]}
400
+ */
401
+ function canonicalizeRows(kind, rows) {
402
+ if (getKindModule(kind).keyField !== 'path') return rows;
403
+ return rows.map((row) => ({
404
+ ...row,
405
+ path: canonicalizeBaselinePath(row.path ?? row.file),
406
+ }));
407
+ }
408
+
373
409
  function assertRequiredScopeRows({
374
410
  kind,
375
411
  scope,
@@ -24,7 +24,7 @@ export const COVERAGE_GATE = {
24
24
  ...SAFE_STRING,
25
25
  minLength: 1,
26
26
  description:
27
- 'Repo-relative path to the Istanbul `coverage-final.json` the capture step writes and the gate reads.',
27
+ 'Repo-relative path to the Istanbul `coverage-final.json` the capture step writes and the gate reads. The capture contract: `npm run test:coverage` MUST write Istanbul per-file JSON (the `json` reporter) here — the coverage and CRAP refreshes both read it. A `json-summary` (`coverage-summary.json`) alone cannot feed them, so a green capture that leaves no file here fails and a full-scope refresh refuses to run.',
28
28
  default: COVERAGE_GATE_DEFAULTS.coveragePath,
29
29
  },
30
30
  captureScope: {
@@ -60,7 +60,7 @@ const FLOORS_SCHEMA = {
60
60
  const COMPONENTS_SCHEMA = {
61
61
  type: 'object',
62
62
  description:
63
- 'Per-gate component map — component name to the glob list whose files roll up under it. Defaults to `{ "*": ["**"] }` at the resolver layer.',
63
+ 'Per-gate component map — component name to the glob list whose rows roll up under it (matched against the row key: the file path, or the bundle name for bundle-size). `check-baselines` reports one rollup per component that matches a row and holds it to `floors.<component>`, falling back to `floors["*"]`. Defaults to `{ "*": ["**"] }` at the resolver layer.',
64
64
  additionalProperties: {
65
65
  type: 'array',
66
66
  items: { type: 'string', minLength: 1 },
@@ -89,6 +89,7 @@ const CRAP_GATE_KEYS = new Set([
89
89
  'baselinePath',
90
90
  'tolerance',
91
91
  'floors',
92
+ 'components',
92
93
  'targetDirs',
93
94
  'newMethodCeiling',
94
95
  'requireCoverage',
@@ -102,6 +103,7 @@ const COVERAGE_GATE_KEYS = new Set([
102
103
  'baselinePath',
103
104
  'tolerance',
104
105
  'floors',
106
+ 'components',
105
107
  'coveragePath',
106
108
  'captureScope',
107
109
  'timeoutMs',
@@ -112,6 +114,7 @@ const MI_GATE_KEYS = new Set([
112
114
  'baselinePath',
113
115
  'tolerance',
114
116
  'floors',
117
+ 'components',
115
118
  'targetDirs',
116
119
  'ignoreGlobs',
117
120
  ]);
@@ -400,14 +403,15 @@ export function resolveQuality(userQuality) {
400
403
 
401
404
  /**
402
405
  * The writer folds sub-epsilon row deltas back to the prior bytes so env
403
- * variance never rewrites a baseline. bundle-size is bytes.
406
+ * variance never rewrites a baseline. Each value is in its kind's row unit:
407
+ * bundle-size rows are KB, so 1 means "ignore sub-KB jitter".
404
408
  */
405
409
  const BASELINE_EPSILON = Object.freeze({
406
410
  maintainability: 0.5,
407
411
  crap: 0.5,
408
412
  coverage: 0.1,
409
413
  mutation: 0.5,
410
- 'bundle-size': 1024,
414
+ 'bundle-size': 1,
411
415
  duplication: 0.5,
412
416
  });
413
417
 
@@ -7,10 +7,13 @@ import fs from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import picomatch from 'picomatch';
9
9
  import { write, writeFile } from './baselines/writer.js';
10
- import { captureStampPath } from './coverage-capture.js';
10
+ import {
11
+ captureStampPath,
12
+ missingCoverageArtifactMessage,
13
+ } from './coverage-capture.js';
11
14
 
12
15
  const COVERAGE_FINAL_PATH = 'coverage/coverage-final.json';
13
- export const COVERAGE_BASELINE_PATH = 'baselines/coverage.json';
16
+ const COVERAGE_BASELINE_PATH = 'baselines/coverage.json';
14
17
  // Percentage points; baselines store two decimals.
15
18
  export const COVERAGE_TOLERANCE = 0.01;
16
19
  // One instrumentation event of slack per axis: V8 coverage flaps by a single
@@ -84,7 +87,7 @@ export function scoreCoverageFinal({ raw, cwd, scope }) {
84
87
  return out;
85
88
  }
86
89
 
87
- /** Throws, naming the capture command, when the artifact is missing. */
90
+ /** Throws, naming the capture contract, when the artifact is missing. */
88
91
  export function readCoverageFinal(cwd, opts = {}, fsImpl) {
89
92
  const resolvedFs = fsImpl ?? fs;
90
93
  const coveragePath =
@@ -95,9 +98,7 @@ export function readCoverageFinal(cwd, opts = {}, fsImpl) {
95
98
  ? coveragePath
96
99
  : path.resolve(cwd, coveragePath);
97
100
  if (!resolvedFs.existsSync(abs)) {
98
- throw new Error(
99
- `coverage-final.json not found at ${abs}. Run \`npm run test:coverage\` first.`,
100
- );
101
+ throw new Error(missingCoverageArtifactMessage(abs));
101
102
  }
102
103
  return JSON.parse(resolvedFs.readFileSync(abs, 'utf8'));
103
104
  }
@@ -478,6 +478,50 @@ export function creditedCapture(runCaptureFn, { requireCredited, logger }) {
478
478
  };
479
479
  }
480
480
 
481
+ /**
482
+ * The capture contract every coverage consumer leans on: `test:coverage`
483
+ * writes Istanbul per-file JSON at `coveragePath`. A summary-only reporter
484
+ * cannot feed the coverage or CRAP baselines (CRAP joins per-function maps).
485
+ *
486
+ * @param {string} abs Absolute artifact path that was looked for.
487
+ * @returns {string}
488
+ */
489
+ export function missingCoverageArtifactMessage(abs) {
490
+ return (
491
+ `coverage artifact not found at ${abs}. \`npm run test:coverage\` must ` +
492
+ 'write Istanbul per-file JSON (the `json` reporter → coverage-final.json) ' +
493
+ 'at delivery.quality.gates.coverage.coveragePath; a `json-summary` ' +
494
+ '(coverage-summary.json) alone cannot feed the coverage or CRAP baselines.'
495
+ );
496
+ }
497
+
498
+ /**
499
+ * Wrap a capture runner so a green run that left no artifact at
500
+ * `coveragePath` exits 1: a broken capture contract, not a capture. Every
501
+ * capture path already returns before stamping on a non-zero code.
502
+ *
503
+ * @param {(opts: object) => Promise<number>} run
504
+ * @param {{ cwd: string, coveragePath: string,
505
+ * existsSync?: (p: string) => boolean,
506
+ * logger: { error: Function } }} opts
507
+ * @returns {(opts: object) => Promise<number>}
508
+ */
509
+ export function requireCaptureArtifact(
510
+ run,
511
+ { cwd, coveragePath, existsSync = fs.existsSync, logger },
512
+ ) {
513
+ return async (captureOpts) => {
514
+ const code = await run(captureOpts);
515
+ if (code !== 0) return code;
516
+ const abs = path.resolve(cwd, coveragePath);
517
+ if (existsSync(abs)) return 0;
518
+ logger.error(
519
+ `[coverage-capture] ✖ test:coverage passed but ${missingCoverageArtifactMessage(abs)}`,
520
+ );
521
+ return 1;
522
+ };
523
+ }
524
+
481
525
  /**
482
526
  * Stamp the pre-spawn digest (the tree the run measured), and write nothing
483
527
  * when the post-run digest differs — the artifact then describes a tree no