bivium 0.4.0 → 0.5.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/dist/cli.js ADDED
@@ -0,0 +1,1854 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ version,
4
+ BiviumError,
5
+ didYouMean,
6
+ globToRegExp,
7
+ inRoot,
8
+ sorted,
9
+ QUERY,
10
+ UNDECLARED_READS,
11
+ RELATIVE,
12
+ aliasPath,
13
+ createResolver,
14
+ SCANNED,
15
+ formatOf,
16
+ extract,
17
+ stringsOf,
18
+ finish,
19
+ gotoPage,
20
+ walksByTypes,
21
+ importersOf,
22
+ affectedBy,
23
+ formatSelection,
24
+ orphanOf,
25
+ plural,
26
+ computePlan,
27
+ prepare
28
+ } from "./shared.js";
29
+
30
+ // src/main.ts
31
+ import { spawnSync } from "node:child_process";
32
+ import { appendFileSync, realpathSync } from "node:fs";
33
+ import {
34
+ basename,
35
+ dirname,
36
+ isAbsolute as isAbsolute2,
37
+ join as join3,
38
+ posix as posix3,
39
+ relative,
40
+ resolve
41
+ } from "node:path";
42
+
43
+ // src/check.ts
44
+ import { statSync } from "node:fs";
45
+ import { join as join2, posix as posix2 } from "node:path";
46
+
47
+ // src/fanin.ts
48
+ function fanIn(graph, suite) {
49
+ const ids = new Map;
50
+ const nodes = [...graph.keys()];
51
+ for (const [i, node] of nodes.entries())
52
+ ids.set(node, i);
53
+ const matches = new Map;
54
+ const matching = (re) => {
55
+ let found = matches.get(re.source);
56
+ if (!found) {
57
+ found = [];
58
+ for (const [i, node] of nodes.entries())
59
+ if (re.test(node))
60
+ found.push(i);
61
+ matches.set(re.source, found);
62
+ }
63
+ return found;
64
+ };
65
+ const forward = [];
66
+ const direct = [];
67
+ for (const node of nodes) {
68
+ const deps = graph.get(node);
69
+ const out = [];
70
+ const read = [];
71
+ if (deps) {
72
+ for (const file of deps.files) {
73
+ if (!suite.types && deps.types?.has(file))
74
+ continue;
75
+ const id = ids.get(file);
76
+ if (id !== undefined)
77
+ out.push(id);
78
+ }
79
+ for (const re of deps.patterns)
80
+ out.push(...matching(re));
81
+ for (const re of [...deps.reads, ...deps.lists ?? []]) {
82
+ read.push(...matching(re));
83
+ }
84
+ }
85
+ forward.push(out);
86
+ direct.push(read);
87
+ }
88
+ const counts = new Uint32Array(nodes.length);
89
+ const stamp = new Int32Array(nodes.length).fill(-1);
90
+ const stack = [];
91
+ for (const [t, test] of nodes.entries()) {
92
+ if (!suite.isTest(test))
93
+ continue;
94
+ const reached = [];
95
+ const visit = (id) => {
96
+ if (stamp[id] === t)
97
+ return;
98
+ stamp[id] = t;
99
+ reached.push(id);
100
+ };
101
+ visit(t);
102
+ stack.push(t);
103
+ while (stack.length > 0) {
104
+ const at = stack.pop() ?? 0;
105
+ for (const next of forward[at]) {
106
+ if (stamp[next] === t)
107
+ continue;
108
+ visit(next);
109
+ stack.push(next);
110
+ }
111
+ }
112
+ for (const id of [...reached])
113
+ for (const read of direct[id])
114
+ visit(read);
115
+ for (const id of reached)
116
+ counts[id]++;
117
+ }
118
+ const result = new Map;
119
+ for (const [i, node] of nodes.entries())
120
+ result.set(node, counts[i]);
121
+ return result;
122
+ }
123
+ function graphReport(graph, suites) {
124
+ const counts = suites.map((suite) => [suite.name, fanIn(graph, suite)]);
125
+ const unknown = [...graph].filter(([, deps]) => deps.unknown.length > 0).map(([node]) => node);
126
+ const everyChange = walksByTypes(graph, unknown, {
127
+ includeUnknown: false,
128
+ readers: false
129
+ });
130
+ return {
131
+ suites: Object.fromEntries(suites.map((suite) => [
132
+ suite.name,
133
+ {
134
+ total: [...graph.keys()].filter(suite.isTest).length,
135
+ everyChange: sorted(everyChange(suite.types)).filter(suite.isTest)
136
+ }
137
+ ])),
138
+ nodes: [...graph].map(([node, deps]) => ({
139
+ node,
140
+ imports: sorted(deps.files),
141
+ importers: sorted(importersOf(graph, node)),
142
+ fanIn: Object.fromEntries(counts.map(([name, count]) => [name, count.get(node) ?? 0])),
143
+ unknown: deps.unknown.length > 0
144
+ }))
145
+ };
146
+ }
147
+ function buckets(total) {
148
+ const list = [
149
+ [0, 0],
150
+ [1, 1]
151
+ ];
152
+ for (let low = 2, high = 10;low < total; low = high + 1, high *= 10) {
153
+ list.push([low, Math.min(high, total - 1)]);
154
+ }
155
+ if (total > 1)
156
+ list.push([total, total]);
157
+ return list;
158
+ }
159
+ function formatGraph(report, top) {
160
+ const lines = [];
161
+ const files = report.nodes.filter(({ node }) => !node.startsWith("pkg:") && !node.includes("#"));
162
+ for (const [name, { total: tests, everyChange }] of Object.entries(report.suites)) {
163
+ const any = everyChange.length;
164
+ lines.push(`${name}: ${plural(tests, "test")}${any > 0 ? `; ${any} run on any change (\`bivium check\` says why)` : ""}`);
165
+ const ranked = files.map(({ node, fanIn: reach }) => [node, reach[name] ?? 0]).filter(([, count]) => count > 0).sort(([a, x], [b, y]) => y - x || (a < b ? -1 : 1));
166
+ const width = Math.max(String(tests).length, 5);
167
+ if (ranked.length > 0) {
168
+ lines.push(` ${"tests".padStart(width)} file`);
169
+ for (const [id, count] of ranked.slice(0, top)) {
170
+ lines.push(` ${String(count).padStart(width)} ${id}`);
171
+ }
172
+ if (ranked.length > top) {
173
+ lines.push(` … ${ranked.length - top} more (--top <n> shows more)`);
174
+ }
175
+ }
176
+ lines.push(` files by how many ${name} tests a change to one selects:`);
177
+ const rows = buckets(tests).map(([low, high]) => {
178
+ const label = low === high ? String(low) : `${low}–${high}`;
179
+ const count = files.filter(({ fanIn: reach }) => {
180
+ const n = reach[name] ?? 0;
181
+ return n >= low && n <= high;
182
+ }).length;
183
+ return [label, count];
184
+ });
185
+ const labelWidth = Math.max(...rows.map(([label]) => label.length));
186
+ for (const [label, count] of rows) {
187
+ lines.push(` ${label.padStart(labelWidth)} ${count}`);
188
+ }
189
+ }
190
+ return lines.join(`
191
+ `);
192
+ }
193
+
194
+ // src/locate.ts
195
+ import { readFile } from "node:fs/promises";
196
+ import { isAbsolute, join } from "node:path";
197
+ var DISK_READ = /\bfrom\s*["'](?:node:)?(?:fs|fs\/promises|child_process)["']|\brequire\s*\(\s*["'](?:node:)?(?:fs|fs\/promises|child_process)["']|\bBun\.(?:file|Glob|spawn)/;
198
+ var NON_LITERAL_IMPORT = /\b(?:import|require|vi\.(?:mock|doMock|unmock|importActual|importMock))\s*(?:<[^>]*>)?\(\s*(?!["'][^"'`$]*["']\s*[,)])/;
199
+ var GLOB_CALL = /\bimport\.meta\.glob/;
200
+ var QUOTED_CAUSE = /"([^"]+)"/;
201
+ var LOADS = /\b(?:import|export|from|require|mock|doMock|unmock|importActual|importMock)\b|\b(?:src|href)\s*=/;
202
+ var GOTO_CALL = /\bgoto\s*\(/;
203
+ function lineAt(source, index) {
204
+ let line = 1;
205
+ for (let i = source.indexOf(`
206
+ `);i !== -1 && i < index; i = source.indexOf(`
207
+ `, i + 1)) {
208
+ line++;
209
+ }
210
+ return line;
211
+ }
212
+ function lineOf(source, needle) {
213
+ const index = typeof needle === "string" ? source.indexOf(needle) : source.search(needle);
214
+ return index === -1 ? undefined : lineAt(source, index);
215
+ }
216
+ function commentRanges(source) {
217
+ const ranges = [];
218
+ for (let i = 0;i < source.length; i++) {
219
+ const c = source[i];
220
+ if (c === '"' || c === "'") {
221
+ while (++i < source.length && source[i] !== c && source[i] !== `
222
+ `) {
223
+ if (source[i] === "\\")
224
+ i++;
225
+ }
226
+ } else if (c === "`") {
227
+ while (++i < source.length && source[i] !== "`") {
228
+ if (source[i] === "\\")
229
+ i++;
230
+ }
231
+ } else if (source.startsWith("//", i)) {
232
+ const end = source.indexOf(`
233
+ `, i);
234
+ ranges.push([i, end === -1 ? source.length : end]);
235
+ i = end === -1 ? source.length : end;
236
+ } else if (source.startsWith("/*", i) || source.startsWith("<!--", i)) {
237
+ const close = c === "/" ? "*/" : "-->";
238
+ const end = source.indexOf(close, i + 2);
239
+ const stop = end === -1 ? source.length : end + close.length;
240
+ ranges.push([i, stop]);
241
+ i = stop - 1;
242
+ }
243
+ }
244
+ return ranges;
245
+ }
246
+ function lineTextAt(source, index) {
247
+ const start = source.lastIndexOf(`
248
+ `, index - 1) + 1;
249
+ const end = source.indexOf(`
250
+ `, index);
251
+ return source.slice(start, end === -1 ? source.length : end);
252
+ }
253
+ function bestLine(source, needles, near) {
254
+ let comments;
255
+ const inComment = (index) => {
256
+ comments ??= commentRanges(source);
257
+ return comments.some(([start, end]) => index >= start && index < end);
258
+ };
259
+ let code;
260
+ let any;
261
+ for (const needle of needles) {
262
+ for (let index = source.indexOf(needle);index !== -1; index = source.indexOf(needle, index + 1)) {
263
+ any ??= index;
264
+ if (inComment(index))
265
+ continue;
266
+ if (near === undefined || near.test(lineTextAt(source, index))) {
267
+ return lineAt(source, index);
268
+ }
269
+ code ??= index;
270
+ }
271
+ }
272
+ const found = code ?? any;
273
+ return found === undefined ? undefined : lineAt(source, found);
274
+ }
275
+ function specifierLine(source, specifier) {
276
+ const quoted = ['"', "'", "`"].map((quote) => `${quote}${specifier}${quote}`);
277
+ return bestLine(source, quoted, LOADS) ?? bestLine(source, [specifier]);
278
+ }
279
+ function gotoLine(source, argument, page) {
280
+ return (argument === undefined ? undefined : bestLine(source, [argument], GOTO_CALL)) ?? bestLine(source, [page.slice(page.lastIndexOf("/") + 1)], GOTO_CALL);
281
+ }
282
+ function callLine(source, call) {
283
+ return bestLine(source, [call]);
284
+ }
285
+ function causeLine(source, cause) {
286
+ if (cause.startsWith("unresolved ")) {
287
+ const specifier = QUOTED_CAUSE.exec(cause)?.[1];
288
+ return specifier === undefined ? undefined : specifierLine(source, specifier);
289
+ }
290
+ if (cause === "non-literal dynamic import")
291
+ return lineOf(source, NON_LITERAL_IMPORT);
292
+ if (cause === "non-literal glob import")
293
+ return lineOf(source, GLOB_CALL);
294
+ if (cause === UNDECLARED_READS) {
295
+ return lineOf(source, DISK_READ);
296
+ }
297
+ if (cause.startsWith("non-literal goto(")) {
298
+ return lineOf(source, cause.slice("non-literal ".length, -1));
299
+ }
300
+ const url = QUOTED_CAUSE.exec(cause)?.[1];
301
+ return url === undefined ? undefined : lineOf(source, url);
302
+ }
303
+ function textLine(source, text) {
304
+ return lineOf(source, text);
305
+ }
306
+ function annotationLine(source, tag, glob) {
307
+ const index = source.split(`
308
+ `).findIndex((line) => line.includes(tag) && line.includes(glob));
309
+ return index === -1 ? undefined : index + 1;
310
+ }
311
+ function lineText(source, line) {
312
+ let start = 0;
313
+ for (let n = 1;n < line; n++) {
314
+ const next = source.indexOf(`
315
+ `, start);
316
+ if (next === -1)
317
+ return "";
318
+ start = next + 1;
319
+ }
320
+ const end = source.indexOf(`
321
+ `, start);
322
+ return source.slice(start, end === -1 ? source.length : end).trim();
323
+ }
324
+ async function sourceOf(root, file) {
325
+ try {
326
+ return await readFile(isAbsolute(file) ? file : join(root, file), "utf-8");
327
+ } catch {
328
+ return;
329
+ }
330
+ }
331
+ function fileOf(node) {
332
+ const hash = node.indexOf("#");
333
+ return hash === -1 ? node : node.slice(0, hash);
334
+ }
335
+ async function causesOf(root, computed, node) {
336
+ const file = fileOf(node);
337
+ const source = await sourceOf(root, file);
338
+ return (computed.graph.get(node)?.unknown ?? []).map((cause) => {
339
+ if (source === undefined)
340
+ return { cause };
341
+ const line = causeLine(source, cause);
342
+ return line === undefined ? { cause } : { cause, at: `${file}:${line}`, text: lineText(source, line) };
343
+ });
344
+ }
345
+
346
+ // src/spelled.ts
347
+ import { posix } from "node:path";
348
+ var PATH_LIKE = /^[\w@.+~()[\]-]+(?:\/[\w@.+~()[\]-]+)*$/;
349
+ var LETTER = /[a-z]/i;
350
+ var LEADING_SLASHES = /^\/+/;
351
+ var TRAILING_SLASHES = /\/+$/;
352
+ var DOT_RELATIVE = /^\.\.?\//;
353
+ function candidates(file, text) {
354
+ let path = text.replace(TRAILING_SLASHES, "");
355
+ const rooted = path.startsWith("/");
356
+ if (rooted)
357
+ path = path.replace(LEADING_SLASHES, "");
358
+ if (!PATH_LIKE.test(path) || !LETTER.test(path))
359
+ return [];
360
+ const dir = posix.dirname(file);
361
+ let found;
362
+ if (rooted)
363
+ found = path.includes("/") ? [posix.normalize(path)] : [];
364
+ else if (DOT_RELATIVE.test(path))
365
+ found = [posix.join(dir, path)];
366
+ else if (path.includes("/")) {
367
+ found = [posix.normalize(path), posix.join(dir, path)];
368
+ } else
369
+ found = [posix.join(dir, path)];
370
+ return found.filter((p) => p !== "." && !p.startsWith("../"));
371
+ }
372
+ function fixFor(file, path, dir) {
373
+ if (dir) {
374
+ return `if it reads them, add \`reads: { "${file}": "${path}/**" }\` (or \`// @reads ${path}/**\`), \`@depends-on\` if it runs them, \`@lists\` if it only names them`;
375
+ }
376
+ if (SCANNED.test(path)) {
377
+ return `if it runs it, add \`edges: { "${file}": "${path}" }\` (or \`// @depends-on ${path}\`), \`@reads\` if it reads it as text, \`@lists\` if it only names it`;
378
+ }
379
+ return `if it reads it, add \`reads: { "${file}": "${path}" }\` (or \`// @reads ${path}\`), \`@lists\` if it only names it`;
380
+ }
381
+ function spellers(config, { graph }) {
382
+ const found = new Map;
383
+ for (const suite of config.suites) {
384
+ const reached = fanIn(graph, suite);
385
+ for (const [node, deps] of graph) {
386
+ if (deps.unknown.length > 0 || !SCANNED.test(node))
387
+ continue;
388
+ if (node.startsWith("pkg:") || node.includes("#"))
389
+ continue;
390
+ if (suite.isTest(node) || (reached.get(node) ?? 0) > 0 && suite.roots.some((root) => inRoot(node, root))) {
391
+ const suites = found.get(node);
392
+ suites ? suites.push(suite) : found.set(node, [suite]);
393
+ }
394
+ }
395
+ }
396
+ return new Map(sorted(found.keys()).map((node) => [node, found.get(node) ?? []]));
397
+ }
398
+ function runsAnyway(config, { graph }, suites, targets) {
399
+ if (targets.some((file) => config.isSelf(file) || suites.some((suite) => suite.isWiring(file)))) {
400
+ return "wiring";
401
+ }
402
+ const orphan = targets.some((file) => !config.isIgnored(file) && suites.some((suite) => orphanOf(graph, config, suite, file)));
403
+ return orphan ? "orphan" : undefined;
404
+ }
405
+ function withNames(graph, targets) {
406
+ return targets.flatMap((file) => [
407
+ file,
408
+ ...[...graph.get(file)?.barrel?.keys() ?? []].map((name) => `${file}#${name}`)
409
+ ]);
410
+ }
411
+ async function spelledPaths(root, config, computed) {
412
+ const { graph } = computed;
413
+ const files = new Set;
414
+ const dirs = new Map;
415
+ for (const node of graph.keys()) {
416
+ if (node.startsWith("pkg:") || node.includes("#"))
417
+ continue;
418
+ files.add(node);
419
+ for (let dir = posix.dirname(node);dir !== "."; ) {
420
+ const list = dirs.get(dir);
421
+ list ? list.push(node) : dirs.set(dir, [node]);
422
+ dir = posix.dirname(dir);
423
+ }
424
+ }
425
+ const found = { undeclared: [], orphaned: [] };
426
+ const spelling = spellers(config, computed);
427
+ const nodes = [...spelling.keys()];
428
+ const sources = await Promise.all(nodes.map((node) => sourceOf(root, node)));
429
+ for (const [i, node] of nodes.entries()) {
430
+ const source = sources[i];
431
+ const suites = spelling.get(node) ?? [];
432
+ const through = [
433
+ ...affectedBy(graph, [node], { includeUnknown: false })
434
+ ].filter((path) => suites.some((suite) => suite.isTest(path)));
435
+ if (source === undefined)
436
+ continue;
437
+ const seen = new Set;
438
+ for (const text of stringsOf(formatOf(node), source) ?? []) {
439
+ for (const path of candidates(node, text)) {
440
+ if (seen.has(path) || path === node)
441
+ continue;
442
+ seen.add(path);
443
+ const dir = !files.has(path);
444
+ if (dir && node.startsWith(`${path}/`))
445
+ continue;
446
+ const targets = dir ? dirs.get(path) : [path];
447
+ if (!targets)
448
+ continue;
449
+ const selected = affectedBy(graph, withNames(graph, targets));
450
+ if (through.every((test) => selected.has(test)))
451
+ continue;
452
+ const anyway = runsAnyway(config, computed, suites, targets);
453
+ if (anyway === "wiring")
454
+ continue;
455
+ const line = specifierLine(source, text);
456
+ const entry = {
457
+ file: node,
458
+ path,
459
+ dir,
460
+ fix: fixFor(node, path, dir)
461
+ };
462
+ if (line !== undefined)
463
+ entry.at = `${node}:${line}`;
464
+ found[anyway === "orphan" ? "orphaned" : "undeclared"].push(entry);
465
+ }
466
+ }
467
+ }
468
+ return found;
469
+ }
470
+
471
+ // src/check.ts
472
+ var EXAMPLES = 3;
473
+ var TAGS = {
474
+ "depends-on": "@depends-on",
475
+ reads: "@reads",
476
+ lists: "@lists",
477
+ glob: "import.meta.glob",
478
+ edges: "edges",
479
+ setup: "setup"
480
+ };
481
+ var QUOTED = /"([^"]+)"/;
482
+ function fixFor2(cause) {
483
+ if (cause.startsWith("unresolved ")) {
484
+ const specifier = QUOTED.exec(cause)?.[1] ?? "";
485
+ if (specifier.startsWith("./%sveltekit.assets%/")) {
486
+ return "no file in the SvelteKit project's `static/` (a custom `kit.files.assets` isn't read): fix the path, or add an `edges` entry for it";
487
+ }
488
+ if (RELATIVE.test(specifier)) {
489
+ return "no file at that path: fix the import, or add an `edges` entry if a build generates it";
490
+ }
491
+ if (specifier.startsWith("#")) {
492
+ return "map it in the `imports` of the file's package.json, or with `alias`";
493
+ }
494
+ return "declare the package in a package.json, list it in `external` if a dependency installs it, or map it with `alias` or tsconfig `paths`";
495
+ }
496
+ if (cause.startsWith("only declarations for ")) {
497
+ return "only a declaration file is there, so what runs isn't in the graph: if a build writes it, name it in `edges` with its inputs, or import it with `import type` if only its types are used";
498
+ }
499
+ if (cause === "non-literal dynamic import") {
500
+ return "spell the path as a string literal, load the files with `import.meta.glob` and literal patterns, or list the file in `hermetic` if it only imports paths its caller passes";
501
+ }
502
+ if (cause === "non-literal glob import") {
503
+ return "pass `import.meta.glob` literal patterns";
504
+ }
505
+ if (cause === UNDECLARED_READS) {
506
+ return "name what it reads: `// @depends-on <glob>`, or `// @reads <glob>` for files read as text, or an `edges` or `reads` entry for the file in the config; list the file in `hermetic` if it reads no file of the repository";
507
+ }
508
+ if (cause.startsWith("non-literal goto(")) {
509
+ return "pass `goto()` a literal URL, or a template whose path before `?` or `#` is literal; or name the pages it can open with `// @depends-on <glob>`";
510
+ }
511
+ if (cause.startsWith("missing fixture ")) {
512
+ return "no page at that URL: fix the URL, or the suite's `urls`";
513
+ }
514
+ if (cause.startsWith("goto(")) {
515
+ return "map the URL to a file with the suite's `urls`";
516
+ }
517
+ return "see the cause";
518
+ }
519
+ function isFile(path) {
520
+ return statSync(path, { throwIfNoEntry: false })?.isFile() ?? false;
521
+ }
522
+ function stemOf(path) {
523
+ const slash = path.lastIndexOf("/");
524
+ const dot = path.indexOf(".", slash + 2);
525
+ return dot === -1 ? path : path.slice(0, dot);
526
+ }
527
+ function nearMisses(root, config, { graph, listed }) {
528
+ let stems;
529
+ const listedSet = new Set(listed);
530
+ const siblings = (path) => {
531
+ if (!stems) {
532
+ stems = new Map;
533
+ for (const file of listed) {
534
+ const stem = stemOf(file);
535
+ const list = stems.get(stem);
536
+ list ? list.push(file) : stems.set(stem, [file]);
537
+ }
538
+ }
539
+ return stems.get(stemOf(path)) ?? [];
540
+ };
541
+ const candidates = (base) => [
542
+ base,
543
+ ...config.extensions.map((ext) => base + ext),
544
+ ...config.extensions.map((ext) => `${base}/index${ext}`)
545
+ ];
546
+ return (node, cause) => {
547
+ if (!cause.startsWith("unresolved "))
548
+ return;
549
+ const specifier = (QUOTED.exec(cause)?.[1] ?? "").replace(QUERY, "");
550
+ const base = RELATIVE.test(specifier) ? posix2.join(posix2.dirname(fileOf(node)), specifier) : config.alias.map((alias) => aliasPath(alias, specifier)).find((path) => path !== undefined);
551
+ if (base === undefined || base.startsWith("../"))
552
+ return;
553
+ const tried = candidates(base);
554
+ const outside = tried.find((path) => listedSet.has(path) && !graph.has(path));
555
+ if (outside !== undefined) {
556
+ return `${outside} exists, but outside \`roots\`: add it to \`roots\``;
557
+ }
558
+ const unlisted = tried.find((path) => isFile(join2(root, path)));
559
+ if (unlisted !== undefined && !listedSet.has(unlisted)) {
560
+ return `${unlisted} exists, but git doesn't list it (ignored?): if a build writes it, name it in \`edges\` with its inputs`;
561
+ }
562
+ const sibling = siblings(base).find((file) => graph.has(file));
563
+ if (sibling !== undefined) {
564
+ return `${sibling} exists: import it by that name, or add its extension to \`extensions\``;
565
+ }
566
+ return;
567
+ };
568
+ }
569
+ function declaredGlobs(node, extraction) {
570
+ const relative = finish(node, extraction).globs;
571
+ return [
572
+ ...extraction.dependsOn.map((glob) => ({
573
+ kind: "depends-on",
574
+ glob,
575
+ pattern: globToRegExp(glob)
576
+ })),
577
+ ...extraction.reads.map((glob) => ({
578
+ kind: "reads",
579
+ glob,
580
+ pattern: globToRegExp(glob)
581
+ })),
582
+ ...extraction.lists.map((glob) => ({
583
+ kind: "lists",
584
+ glob,
585
+ pattern: globToRegExp(glob)
586
+ })),
587
+ ...extraction.globs.map((glob, i) => ({
588
+ kind: "glob",
589
+ glob,
590
+ pattern: globToRegExp(relative[i])
591
+ }))
592
+ ];
593
+ }
594
+ function problemOf(matches, ignored) {
595
+ if (matches === 0)
596
+ return "matches nothing";
597
+ if (ignored === 0)
598
+ return;
599
+ return ignored === matches ? "matches only ignored files" : "partly ignored";
600
+ }
601
+ function deadOf(node, kind, glob, patterns, listed, skipped) {
602
+ const matches = listed.filter((file) => patterns.some((re) => re.test(file)));
603
+ const ignored = sorted(matches.filter(skipped));
604
+ const problem = problemOf(matches.length, ignored.length);
605
+ if (problem === undefined)
606
+ return;
607
+ return {
608
+ node,
609
+ kind,
610
+ glob,
611
+ problem,
612
+ matches: matches.length,
613
+ ignored: ignored.length,
614
+ examples: ignored.slice(0, EXAMPLES),
615
+ fix: problem === "matches nothing" ? "fix the path" : "point it at files the selector reads, or allowlist it in `deadGlobs` with a reason"
616
+ };
617
+ }
618
+ function configDeadGlobs(config, { graph, listed }, skipped) {
619
+ const file = config.file ?? "the config";
620
+ const found = [];
621
+ const entries = [
622
+ ...config.generated.map((map) => ["edges", map]),
623
+ ...config.reads.map((map) => ["reads", map])
624
+ ];
625
+ for (const [kind, map] of entries) {
626
+ const patterns = map.values.map(() => new Map);
627
+ let matched = false;
628
+ for (const node of graph.keys()) {
629
+ const targets = map.targets(node);
630
+ if (!targets)
631
+ continue;
632
+ matched = true;
633
+ for (const [i, re] of targets.entries())
634
+ patterns[i]?.set(re.source, re);
635
+ }
636
+ if (!matched) {
637
+ found.push({
638
+ node: file,
639
+ kind,
640
+ glob: map.key,
641
+ problem: "matches nothing",
642
+ matches: 0,
643
+ ignored: 0,
644
+ examples: [],
645
+ fix: "fix the path: no file the graph reads matches it"
646
+ });
647
+ continue;
648
+ }
649
+ for (const [i, glob] of map.values.entries()) {
650
+ const expanded = [...patterns[i]?.values() ?? []];
651
+ const dead = deadOf(file, kind, glob, expanded, listed, skipped);
652
+ if (dead)
653
+ found.push(dead);
654
+ }
655
+ }
656
+ for (const suite of config.suites) {
657
+ for (const glob of suite.setup) {
658
+ const pattern = globToRegExp(glob);
659
+ const dead = deadOf(file, "setup", glob, [pattern], listed, skipped);
660
+ if (dead)
661
+ found.push(dead);
662
+ }
663
+ }
664
+ return found;
665
+ }
666
+ async function findDeadGlobs(root, config, computed) {
667
+ const { graph, extractions, listed } = computed;
668
+ const skipped = (file) => config.isIgnored(file) && !graph.has(file);
669
+ const found = [];
670
+ for (const node of graph.keys()) {
671
+ const extraction = extractions.get(node);
672
+ if (!extraction)
673
+ continue;
674
+ for (const { kind, glob, pattern } of declaredGlobs(node, extraction)) {
675
+ const dead = deadOf(node, kind, glob, [pattern], listed, skipped);
676
+ if (dead)
677
+ found.push(dead);
678
+ }
679
+ }
680
+ const configured = configDeadGlobs(config, computed, skipped);
681
+ const nodes = [
682
+ ...new Set([
683
+ ...found.map(({ node }) => node),
684
+ ...configured.map(({ node }) => node)
685
+ ])
686
+ ];
687
+ const texts = await Promise.all(nodes.map((node) => sourceOf(root, node)));
688
+ const sources = new Map(nodes.map((node, i) => [node, texts[i]]));
689
+ const locate = (dead, line) => {
690
+ const source = sources.get(dead.node);
691
+ const at = source === undefined ? undefined : line(source);
692
+ return at === undefined ? dead : { ...dead, at: `${dead.node}:${at}` };
693
+ };
694
+ return [
695
+ ...found.map((dead) => locate(dead, (source) => dead.kind === "glob" ? specifierLine(source, dead.glob) : annotationLine(source, TAGS[dead.kind], dead.glob))),
696
+ ...configured.map((dead) => locate(dead, (source) => specifierLine(source, dead.glob)))
697
+ ];
698
+ }
699
+ var CONFIG_FILE = /(?:^|[./_-])(?:config|setup|teardown|harness)(?:[./_-]|$)|^tsconfig[^/]*\.json$|^\.[^/]*rc(?:\.[^/]+)?$/;
700
+ function unreachedFix(file, tests, spelled) {
701
+ const named = spelled.find(({ path }) => file === path || file.startsWith(`${path}/`));
702
+ if (named !== undefined) {
703
+ return `${named.at ?? named.file} names ${named.path}: ${named.fix}`;
704
+ }
705
+ const name = posix2.basename(file);
706
+ const owner = tests.find((test) => name.startsWith(`${posix2.basename(test)}.`));
707
+ if (owner !== undefined) {
708
+ return `if ${owner} reads it, add \`reads: { "${owner}": "${file}" }\` (or \`// @reads ${file}\` in the test)`;
709
+ }
710
+ if (CONFIG_FILE.test(name)) {
711
+ return "if the runner loads it, name it in the suite's `wiring` (or `setup`, if it runs before every test), which makes the full run deliberate";
712
+ }
713
+ return "if a test reads or runs it, say so with `reads` or `@depends-on` in that test or what loads it; if none can observe it, list it in the suite's `nonInputs`, or delete it if it's dead";
714
+ }
715
+ function unreachedFiles(config, { graph }, spelled) {
716
+ const found = [];
717
+ const files = [...graph.keys()].filter((node) => !node.startsWith("pkg:") && !node.includes("#"));
718
+ for (const suite of config.suites) {
719
+ const reached = fanIn(graph, suite);
720
+ const tests = files.filter(suite.isTest);
721
+ for (const file of files) {
722
+ if ((reached.get(file) ?? 0) > 0)
723
+ continue;
724
+ if (config.isIgnored(file) || config.isSelf(file))
725
+ continue;
726
+ if (suite.isWiring(file))
727
+ continue;
728
+ if (!orphanOf(graph, config, suite, file))
729
+ continue;
730
+ found.push({
731
+ suite: suite.name,
732
+ file,
733
+ fix: unreachedFix(file, tests, spelled)
734
+ });
735
+ }
736
+ }
737
+ return found;
738
+ }
739
+ async function check(root, config, computed) {
740
+ const nodes = [...computed.graph].filter(([, deps]) => deps.unknown.length > 0).map(([node]) => node);
741
+ const testsOf = (node) => {
742
+ const reach = walksByTypes(computed.graph, [node], {
743
+ includeUnknown: false,
744
+ readers: false
745
+ });
746
+ const found = new Set;
747
+ for (const suite of config.suites) {
748
+ for (const test of reach(suite.types)) {
749
+ if (suite.isTest(test))
750
+ found.add(test);
751
+ }
752
+ }
753
+ return sorted(found);
754
+ };
755
+ const nearMiss = nearMisses(root, config, computed);
756
+ const known = new Map((config.knownUnknowns ?? []).map((entry) => [entry.file, entry.reason]));
757
+ const unknown = await Promise.all(nodes.map(async (node) => {
758
+ const causes = (await causesOf(root, computed, node)).map(({ cause, at }) => {
759
+ const fix = nearMiss(node, cause) ?? fixFor2(cause);
760
+ return at === undefined ? { cause, fix } : { cause, at, fix };
761
+ });
762
+ const reason = known.get(node);
763
+ const entry = { node, causes, tests: testsOf(node) };
764
+ if (reason !== undefined)
765
+ entry.known = reason;
766
+ return entry;
767
+ }));
768
+ const fallbacks = [...computed.fallbacks].map(([file, reason]) => ({
769
+ file,
770
+ reason
771
+ }));
772
+ const dead = await findDeadGlobs(root, config, computed);
773
+ const spelled = await spelledPaths(root, config, computed);
774
+ const unreached = unreachedFiles(config, computed, [
775
+ ...spelled.undeclared,
776
+ ...spelled.orphaned
777
+ ]);
778
+ const allows = (entry, found) => entry.file === found.node && entry.glob === found.glob;
779
+ return {
780
+ unknown,
781
+ fallbacks,
782
+ unparsedTsconfigs: computed.unparsedTsconfigs,
783
+ deadGlobs: dead.filter((found) => !config.deadGlobs.some((entry) => allows(entry, found))),
784
+ unlistedUnknowns: config.knownUnknowns ? unknown.filter((entry) => entry.tests.length > 0 && entry.known === undefined).map((entry) => entry.node) : [],
785
+ staleKnownUnknowns: (config.knownUnknowns ?? []).filter((entry) => !nodes.includes(entry.file)).map((entry) => ({
786
+ ...entry,
787
+ fix: "remove the entry: its dependencies are known now"
788
+ })),
789
+ unreached,
790
+ undeclaredPaths: spelled.undeclared,
791
+ staleDeadGlobs: config.deadGlobs.filter((entry) => !dead.some((found) => allows(entry, found))).map((entry) => ({
792
+ ...entry,
793
+ fix: "remove the entry: its glob is no longer dead"
794
+ }))
795
+ };
796
+ }
797
+ function summary({ problem, matches, ignored, examples }) {
798
+ if (problem === "matches nothing")
799
+ return problem;
800
+ const shown = [...examples, ...ignored > examples.length ? ["…"] : []];
801
+ const count = problem === "partly ignored" ? `${ignored} of ${matches}` : `${ignored}`;
802
+ return `${problem} (${count}: ${shown.join(", ")})`;
803
+ }
804
+ function widening(report) {
805
+ return report.unknown.filter((node) => node.tests.length > 0);
806
+ }
807
+ function failed(report, max) {
808
+ return max !== undefined && widening(report).length > max || report.unlistedUnknowns.length > 0 || report.staleKnownUnknowns.length > 0 || report.deadGlobs.length > 0 || report.staleDeadGlobs.length > 0 || report.undeclaredPaths.length > 0;
809
+ }
810
+ function pushUnknown(lines, { node, causes, tests, known }, shown) {
811
+ lines.push(known === undefined ? node : `${node} (known: ${known})`);
812
+ for (const { cause, at, fix } of causes) {
813
+ const first = shown.get(fix);
814
+ if (first === undefined)
815
+ shown.set(fix, node);
816
+ lines.push(` ✗ ${cause}${at ? ` ${at}` : ""}`, ` fix: ${first === undefined ? fix : `as for ${first}`}`);
817
+ }
818
+ if (tests.length > 0) {
819
+ const more = tests.length > 3 ? `, and ${tests.length - 3} more` : "";
820
+ lines.push(` runs on any change: ${tests.slice(0, 3).join(", ")}${more}`);
821
+ }
822
+ }
823
+ function categoryOf(cause) {
824
+ if (cause.startsWith("unresolved ")) {
825
+ const specifier = QUOTED.exec(cause)?.[1] ?? "";
826
+ if (RELATIVE.test(specifier))
827
+ return "unresolved relative import";
828
+ if (specifier.startsWith("#"))
829
+ return "unresolved # import";
830
+ return "unresolved bare import (a package, alias or path)";
831
+ }
832
+ if (cause.startsWith("only declarations for ")) {
833
+ return "a .js import with only its declarations there";
834
+ }
835
+ if (cause.startsWith("non-literal goto("))
836
+ return "non-literal goto()";
837
+ if (cause.startsWith("goto("))
838
+ return "goto() URL no `urls` pattern maps";
839
+ if (cause.startsWith("missing fixture "))
840
+ return "goto() of a missing page";
841
+ return cause;
842
+ }
843
+ var POSITION = /(?: in <>)? at \d+.*$/;
844
+ var BLANK_LINES = /\n{3,}/g;
845
+ function byCount(counts) {
846
+ return Object.fromEntries([...counts].sort(([a, x], [b, y]) => y - x || (a < b ? -1 : 1)));
847
+ }
848
+ function counted(counts) {
849
+ return Object.entries(counts).map(([what, count]) => `${count} ${what}`);
850
+ }
851
+ function summarize(report) {
852
+ const widen = widening(report);
853
+ const causes = new Map;
854
+ for (const node of widen) {
855
+ for (const category of new Set(node.causes.map(({ cause }) => categoryOf(cause)))) {
856
+ causes.set(category, (causes.get(category) ?? 0) + 1);
857
+ }
858
+ }
859
+ const reasons = new Map;
860
+ for (const { reason } of report.fallbacks) {
861
+ const what = reason.replace(POSITION, "");
862
+ reasons.set(what, (reasons.get(what) ?? 0) + 1);
863
+ }
864
+ return {
865
+ unknown: widen.length,
866
+ testsOnAnyChange: new Set(widen.flatMap((node) => node.tests)).size,
867
+ unknownByCause: byCount(causes),
868
+ unknownNoTestReaches: report.unknown.length - widen.length,
869
+ fallbacks: report.fallbacks.length,
870
+ fallbackReasons: byCount(reasons),
871
+ unparsedTsconfigs: report.unparsedTsconfigs.length,
872
+ deadGlobs: report.deadGlobs.length,
873
+ staleDeadGlobs: report.staleDeadGlobs.length,
874
+ unlistedUnknowns: report.unlistedUnknowns.length,
875
+ staleKnownUnknowns: report.staleKnownUnknowns.length,
876
+ undeclaredPaths: report.undeclaredPaths.length,
877
+ unreached: report.unreached.length
878
+ };
879
+ }
880
+ function summaryLines(report) {
881
+ const counts = summarize(report);
882
+ const lines = [];
883
+ if (counts.unknown > 0) {
884
+ const { unknown, testsOnAnyChange: tests } = counts;
885
+ lines.push(`${plural(unknown, "node")} with unknown dependencies ${unknown === 1 ? "reaches" : "reach"} ${plural(tests, "test")}, which ${tests === 1 ? "runs" : "run"} on any change:`);
886
+ lines.push(...counted(counts.unknownByCause).map((line) => ` ${line}`));
887
+ }
888
+ if (counts.unknownNoTestReaches > 0) {
889
+ lines.push(`${plural(counts.unknownNoTestReaches, "more node")} with unknown dependencies no test reaches`);
890
+ }
891
+ if (counts.fallbacks > 0) {
892
+ lines.push(`${plural(counts.fallbacks, "file")} read by the regex extractor: ${counted(counts.fallbackReasons).join(", ")}`);
893
+ }
894
+ const problems = [
895
+ [
896
+ counts.unparsedTsconfigs,
897
+ "tsconfig file that doesn't parse",
898
+ "tsconfig files that don't parse"
899
+ ],
900
+ [counts.deadGlobs, "dead glob", "dead globs"],
901
+ [
902
+ counts.staleDeadGlobs,
903
+ "stale `deadGlobs` entry",
904
+ "stale `deadGlobs` entries"
905
+ ],
906
+ [
907
+ counts.unlistedUnknowns,
908
+ "unknown not in `knownUnknowns`",
909
+ "unknowns not in `knownUnknowns`"
910
+ ],
911
+ [
912
+ counts.staleKnownUnknowns,
913
+ "stale `knownUnknowns` entry",
914
+ "stale `knownUnknowns` entries"
915
+ ],
916
+ [
917
+ counts.undeclaredPaths,
918
+ "path spelled in code that nothing declares",
919
+ "paths spelled in code that nothing declares"
920
+ ],
921
+ [
922
+ counts.unreached,
923
+ "file under a suite's root that no test reaches",
924
+ "files under a suite's root that no test reaches"
925
+ ]
926
+ ];
927
+ for (const [count, one, many] of problems) {
928
+ if (count > 0)
929
+ lines.push(plural(count, one, many));
930
+ }
931
+ return lines.length === 0 ? [] : ["Summary:", ...lines.map((line) => ` ${line}`), ""];
932
+ }
933
+ var UNREACHED_SHOWN = 10;
934
+ function pushUnreached(lines, unreached) {
935
+ if (unreached.length === 0)
936
+ return;
937
+ lines.push("", "Files under a suite's root that no test reaches: a change to one runs the whole suite:");
938
+ for (const suite of new Set(unreached.map((entry) => entry.suite))) {
939
+ const entries = unreached.filter((entry) => entry.suite === suite);
940
+ lines.push(` ${suite} (${entries.length})`);
941
+ for (const { file, fix } of entries.slice(0, UNREACHED_SHOWN)) {
942
+ lines.push(` ${file}`, ` fix: ${fix}`);
943
+ }
944
+ const rest = entries.slice(UNREACHED_SHOWN);
945
+ if (rest.length === 0)
946
+ continue;
947
+ const dirs = new Map;
948
+ for (const { file } of rest) {
949
+ const dir = posix2.dirname(file);
950
+ dirs.set(dir, (dirs.get(dir) ?? 0) + 1);
951
+ }
952
+ const counts = [...dirs].sort(([a, x], [b, y]) => y - x || (a < b ? -1 : 1)).map(([dir, count]) => `${dir}/ (${count})`);
953
+ lines.push(` … ${rest.length} more in ${counts.slice(0, 5).join(", ")}${counts.length > 5 ? ", …" : ""} (--json lists each)`);
954
+ }
955
+ }
956
+ function pushUndeclared(lines, spelled) {
957
+ if (spelled.length === 0)
958
+ return;
959
+ lines.push("", "Paths spelled in code that nothing declares: a change there doesn't select the tests that reach the file:");
960
+ let file;
961
+ for (const { file: node, path, dir, at, fix } of spelled) {
962
+ if (node !== file)
963
+ lines.push(` ${node}`);
964
+ file = node;
965
+ lines.push(` ✗ ${dir ? `${path}/` : path}${at ? ` ${at}` : ""}`, ` fix: ${fix}`);
966
+ }
967
+ }
968
+ function formatReport(report, max) {
969
+ const lines = summaryLines(report);
970
+ const widen = widening(report);
971
+ const shown = new Map;
972
+ for (const unknown of widen)
973
+ pushUnknown(lines, unknown, shown);
974
+ const idle = report.unknown.filter((node) => node.tests.length === 0);
975
+ if (idle.length > 0) {
976
+ lines.push("", "Unknown, but no test depends on them, so they widen nothing:");
977
+ for (const unknown of idle)
978
+ pushUnknown(lines, unknown, shown);
979
+ }
980
+ if (report.fallbacks.length > 0) {
981
+ lines.push("", "Read by the regex extractor, which the lexer couldn't read:");
982
+ for (const { file, reason } of report.fallbacks) {
983
+ lines.push(` ${file}: ${reason}`);
984
+ }
985
+ }
986
+ pushUndeclared(lines, report.undeclaredPaths);
987
+ pushUnreached(lines, report.unreached);
988
+ if (report.unparsedTsconfigs.length > 0) {
989
+ lines.push("", "tsconfig files that don't parse, whose `paths` are ignored:");
990
+ for (const { file, reason } of report.unparsedTsconfigs) {
991
+ lines.push(` ${file}: ${reason}`);
992
+ }
993
+ }
994
+ if (report.deadGlobs.length > 0) {
995
+ lines.push("", "Dead globs: a change to what they match, or to some of it, selects nothing:");
996
+ let node;
997
+ for (const dead of report.deadGlobs) {
998
+ if (dead.node !== node)
999
+ lines.push(` ${dead.node}`);
1000
+ node = dead.node;
1001
+ lines.push(` ✗ ${dead.kind} ${dead.glob}: ${summary(dead)}${dead.at ? ` ${dead.at}` : ""}`, ` fix: ${dead.fix}`);
1002
+ }
1003
+ }
1004
+ if (report.staleDeadGlobs.length > 0) {
1005
+ lines.push("", "`deadGlobs` entries that match no dead glob:");
1006
+ for (const { file, glob, fix } of report.staleDeadGlobs) {
1007
+ lines.push(` ${file}: ${glob}`, ` fix: ${fix}`);
1008
+ }
1009
+ }
1010
+ if (report.staleKnownUnknowns.length > 0) {
1011
+ lines.push("", "`knownUnknowns` entries whose dependencies are known:");
1012
+ for (const { file, fix } of report.staleKnownUnknowns) {
1013
+ lines.push(` ${file}`, ` fix: ${fix}`);
1014
+ }
1015
+ }
1016
+ const count = widen.length;
1017
+ const limit = max === undefined ? "" : ` (at most ${max})`;
1018
+ lines.push("", `${count} ${count === 1 ? "node" : "nodes"} with unknown dependencies ${count === 1 ? "reaches" : "reach"} a test${limit}: each such test runs on any change.`);
1019
+ const unlisted = report.unlistedUnknowns.length;
1020
+ if (unlisted > 0) {
1021
+ lines.push(`${unlisted} of them not in \`knownUnknowns\`: fix ${unlisted === 1 ? "it" : "them"}, or list ${unlisted === 1 ? "it" : "them"} with a reason.`);
1022
+ }
1023
+ if (idle.length > 0) {
1024
+ lines.push(`${idle.length} more no test reaches.`);
1025
+ }
1026
+ const staleKnown = report.staleKnownUnknowns.length;
1027
+ if (staleKnown > 0) {
1028
+ lines.push(`${plural(staleKnown, "stale `knownUnknowns` entry", "stale `knownUnknowns` entries")}.`);
1029
+ }
1030
+ const undeclared = report.undeclaredPaths.length;
1031
+ if (undeclared > 0) {
1032
+ lines.push(`${plural(undeclared, "path", "paths")} spelled in code that nothing declares.`);
1033
+ }
1034
+ const dead = report.deadGlobs.length;
1035
+ const stale = report.staleDeadGlobs.length;
1036
+ if (dead > 0) {
1037
+ lines.push(`${plural(dead, "dead glob")} not in \`deadGlobs\`.`);
1038
+ }
1039
+ if (stale > 0) {
1040
+ lines.push(`${plural(stale, "stale `deadGlobs` entry", "stale `deadGlobs` entries")}.`);
1041
+ }
1042
+ return lines.join(`
1043
+ `).replace(BLANK_LINES, `
1044
+
1045
+ `).trimStart();
1046
+ }
1047
+
1048
+ // src/why.ts
1049
+ var CONFIG_EDGES = "edges in the config";
1050
+ var CONFIG_SETUP = "setup in the config";
1051
+ var CONFIGURED = {
1052
+ edges: CONFIG_EDGES,
1053
+ setup: CONFIG_SETUP
1054
+ };
1055
+ var CONFIG_READS = "reads in the config";
1056
+ async function edgeAt(context, node, via) {
1057
+ const spelled = CONFIGURED[via.kind];
1058
+ if (spelled !== undefined)
1059
+ return { at: spelled };
1060
+ if (via.kind === "unknown")
1061
+ return {};
1062
+ const file = fileOf(node);
1063
+ const source = SCANNED.test(file) ? await sourceOf(context.root, file) : undefined;
1064
+ const configured = (maps) => maps.some((map) => map.targets(node)?.some((re) => re.test(via.from)));
1065
+ if (via.kind === "reads" && configured(context.config.reads)) {
1066
+ const declared = source !== undefined && extract(formatOf(file), source).reads.some((glob) => globToRegExp(glob).test(via.from));
1067
+ if (!declared)
1068
+ return { at: CONFIG_READS };
1069
+ }
1070
+ if (source === undefined)
1071
+ return {};
1072
+ const line = edgeLine(context, node, via, source);
1073
+ return line === undefined ? {} : { at: `${file}:${line}`, text: lineText(source, line) };
1074
+ }
1075
+ function edgeLine({ config, resolve }, node, via, source) {
1076
+ const file = fileOf(node);
1077
+ const extraction = extract(formatOf(file), source);
1078
+ const matches = (glob) => globToRegExp(glob).test(via.from);
1079
+ if (via.kind === "reads" || via.kind === "depends-on" || via.kind === "lists") {
1080
+ const tag = `@${via.kind}`;
1081
+ const globs = {
1082
+ reads: extraction.reads,
1083
+ "depends-on": extraction.dependsOn,
1084
+ lists: extraction.lists
1085
+ }[via.kind];
1086
+ const glob = globs.find(matches);
1087
+ return (glob === undefined ? undefined : annotationLine(source, tag, glob)) ?? textLine(source, tag);
1088
+ }
1089
+ if (via.kind === "glob") {
1090
+ const relative = finish(file, extraction).globs;
1091
+ const glob = extraction.globs.find((_, i) => matches(relative[i]));
1092
+ return (glob === undefined ? undefined : specifierLine(source, glob)) ?? callLine(source, "import.meta.glob");
1093
+ }
1094
+ const target = fileOf(via.from);
1095
+ if (via.kind === "goto") {
1096
+ const argument = extraction.gotos.find((candidate) => gotoPage(config, file, candidate)?.includes(target));
1097
+ return gotoLine(source, argument, target);
1098
+ }
1099
+ const loads = (specifier) => {
1100
+ const resolved = resolve(file, specifier);
1101
+ return resolved !== undefined && "files" in resolved && resolved.files.includes(target);
1102
+ };
1103
+ if (via.kind === "export") {
1104
+ const barrel = extraction.barrel;
1105
+ if (!barrel)
1106
+ return;
1107
+ const own = barrel.names.get(node.slice(node.indexOf("#") + 1));
1108
+ const specifier = [
1109
+ ...own === undefined ? [] : [own],
1110
+ ...barrel.names.values(),
1111
+ ...barrel.stars
1112
+ ].find(loads);
1113
+ return specifier === undefined ? undefined : specifierLine(source, specifier);
1114
+ }
1115
+ const imported = extraction.imports.find(({ specifier }) => loads(specifier));
1116
+ return imported === undefined ? undefined : specifierLine(source, imported.specifier);
1117
+ }
1118
+ function rootCause(computed, rootNode, from) {
1119
+ if (from !== undefined)
1120
+ return "given";
1121
+ if (computed.changed.includes(rootNode))
1122
+ return "changed";
1123
+ const bumped = computed.plan.packageCauses.get(rootNode);
1124
+ if (bumped !== undefined)
1125
+ return bumped;
1126
+ const setting = computed.plan.settingCauses.get(rootNode);
1127
+ if (setting !== undefined)
1128
+ return setting;
1129
+ if (computed.barrelNames.includes(rootNode))
1130
+ return "barrel name moved";
1131
+ for (const { narrower, result } of computed.narrowed) {
1132
+ if ("seeds" in result && result.seeds.includes(rootNode)) {
1133
+ return `seeded by the ${narrower.name} narrower`;
1134
+ }
1135
+ }
1136
+ return "changed";
1137
+ }
1138
+ function walks(computed, { name, types }, from) {
1139
+ const { plan, graph } = computed;
1140
+ if (from !== undefined)
1141
+ return [{ seeds: [from], opaque: undefined, types }];
1142
+ const { quiet, layout } = plan;
1143
+ const narrowings = plan.narrowings.get(name);
1144
+ if (!narrowings) {
1145
+ return [{ seeds: plan.seeds, quiet, layout, opaque: undefined, types }];
1146
+ }
1147
+ const matched = new Set(narrowings.flatMap((narrowing) => narrowing.matched));
1148
+ return [
1149
+ {
1150
+ seeds: plan.seeds.filter((seed) => !matched.has(seed)),
1151
+ quiet,
1152
+ layout,
1153
+ opaque: undefined,
1154
+ types
1155
+ },
1156
+ ...narrowings.map((narrowing) => ({
1157
+ seeds: [...narrowing.matched, ...narrowing.seeds].filter((seed) => graph.has(seed) || computed.changed.includes(seed)),
1158
+ opaque: narrowing.narrower.opaque,
1159
+ layout,
1160
+ types
1161
+ }))
1162
+ ];
1163
+ }
1164
+ function shortestChain(computed, candidates, test) {
1165
+ for (const { seeds, ...options } of candidates) {
1166
+ const parents = new Map;
1167
+ const reached = affectedBy(computed.graph, seeds, { ...options, parents });
1168
+ if (!reached.has(test))
1169
+ continue;
1170
+ const edges = [];
1171
+ let node = test;
1172
+ for (let via = parents.get(node);via; via = parents.get(node)) {
1173
+ edges.push([node, via]);
1174
+ node = via.from;
1175
+ if (via.kind === "unknown")
1176
+ break;
1177
+ }
1178
+ return { edges, root: node };
1179
+ }
1180
+ return;
1181
+ }
1182
+ function reachers(computed, candidates, test, except) {
1183
+ const found = new Set;
1184
+ const unseen = (seed) => seed !== except && !found.has(seed);
1185
+ for (const { seeds, quiet = [], ...options } of candidates) {
1186
+ for (const seed of seeds.filter(unseen)) {
1187
+ if (affectedBy(computed.graph, [seed], options).has(test)) {
1188
+ found.add(seed);
1189
+ }
1190
+ }
1191
+ for (const seed of quiet.filter(unseen)) {
1192
+ const reached = affectedBy(computed.graph, [], {
1193
+ ...options,
1194
+ quiet: [seed]
1195
+ });
1196
+ if (reached.has(test))
1197
+ found.add(seed);
1198
+ }
1199
+ }
1200
+ return sorted(found);
1201
+ }
1202
+ async function chainOf(context, { edges, root }, from) {
1203
+ const last = edges.at(-1);
1204
+ const [links, causes] = await Promise.all([
1205
+ Promise.all(edges.map(async ([node, via]) => ({
1206
+ node,
1207
+ kind: via.kind,
1208
+ ...await edgeAt(context, node, via)
1209
+ }))),
1210
+ last?.[1].kind === "unknown" ? causesOf(context.root, context.computed, last[0]) : []
1211
+ ]);
1212
+ return {
1213
+ links,
1214
+ root,
1215
+ cause: rootCause(context.computed, root, from),
1216
+ unknown: causes.map((cause) => ({ ...cause, fix: fixFor2(cause.cause) }))
1217
+ };
1218
+ }
1219
+ function unselected(config, computed, suite, from) {
1220
+ const changed = computed.changed.length;
1221
+ if (from === undefined)
1222
+ return { kind: "unselected", suite, changed };
1223
+ const reachedBy = walksByTypes(computed.graph, [from], {
1224
+ includeUnknown: false
1225
+ });
1226
+ const reaches = {};
1227
+ let example;
1228
+ for (const { name, isTest, types } of config.suites) {
1229
+ const tests = sorted(reachedBy(types)).filter((node) => isTest(node));
1230
+ if (tests.length === 0)
1231
+ continue;
1232
+ reaches[name] = tests.length;
1233
+ if (name === suite || example === undefined)
1234
+ example = tests[0];
1235
+ }
1236
+ return {
1237
+ kind: "unselected",
1238
+ suite,
1239
+ from,
1240
+ changed,
1241
+ reaches,
1242
+ ...example !== undefined && { example }
1243
+ };
1244
+ }
1245
+ async function explain(root, config, computed, test, from, { all = false } = {}) {
1246
+ const suite = config.suites.find((candidate) => candidate.isTest(test));
1247
+ if (!suite)
1248
+ throw new Error(`bivium why: ${test} is no suite's test`);
1249
+ if (!computed.graph.has(test))
1250
+ throw new Error(`bivium why: no file ${test}`);
1251
+ if (from === undefined && computed.plan.full.includes(suite.name)) {
1252
+ return { kind: "full", suite: suite.name, reasons: computed.plan.reasons };
1253
+ }
1254
+ const candidates = walks(computed, suite, from);
1255
+ const found = shortestChain(computed, candidates, test);
1256
+ if (!found)
1257
+ return unselected(config, computed, suite.name, from);
1258
+ const context = {
1259
+ root,
1260
+ config,
1261
+ computed,
1262
+ resolve: createResolver({
1263
+ files: new Set(computed.graph.keys()),
1264
+ config,
1265
+ packages: computed.packages,
1266
+ tsconfigs: computed.tsconfigs
1267
+ })
1268
+ };
1269
+ const everything = found.edges.at(-1)?.[1].kind === "unknown";
1270
+ const more = from !== undefined || everything ? [] : reachers(computed, candidates, test, found.root);
1271
+ const [chain, others] = await Promise.all([
1272
+ chainOf(context, found, from),
1273
+ Promise.all((all ? more : []).map((seed) => {
1274
+ const alone = candidates.map((walk) => ({
1275
+ ...walk,
1276
+ seeds: walk.seeds.filter((candidate) => candidate === seed),
1277
+ quiet: walk.quiet?.filter((candidate) => candidate === seed)
1278
+ }));
1279
+ const other = shortestChain(computed, alone, test);
1280
+ return other && chainOf(context, other, undefined);
1281
+ }))
1282
+ ]);
1283
+ return {
1284
+ kind: "chain",
1285
+ suite: suite.name,
1286
+ test,
1287
+ ...chain,
1288
+ more,
1289
+ others: others.filter((other) => other !== undefined)
1290
+ };
1291
+ }
1292
+ var FORMATS = ["tree", "chain", "source"];
1293
+ function isFormat(value) {
1294
+ return FORMATS.some((format) => format === value);
1295
+ }
1296
+ var VERBS = {
1297
+ import: "imported by",
1298
+ type: "type-imported by",
1299
+ setup: "a setup file of",
1300
+ goto: "opened by",
1301
+ html: "loaded by page",
1302
+ name: "imported by",
1303
+ glob: "globbed by",
1304
+ "depends-on": "depended on by",
1305
+ edges: "an input of",
1306
+ reads: "read as text by",
1307
+ lists: "listed by",
1308
+ unknown: "depends on every change"
1309
+ };
1310
+ var LIST = 3;
1311
+ function nameOf(node) {
1312
+ return node.slice(node.indexOf("#") + 1);
1313
+ }
1314
+ function aligned(rows) {
1315
+ const width = Math.max(0, ...rows.filter(([, at]) => at !== undefined).map(([text]) => text.length));
1316
+ return rows.map(([text, at]) => at === undefined ? text : `${text.padEnd(width)} ${at}`);
1317
+ }
1318
+ function tree(test, chain) {
1319
+ const rows = [[test, undefined]];
1320
+ const width = Math.max(0, ...chain.links.filter((link) => link.kind !== "unknown").map((link) => link.kind.length));
1321
+ let indent = "";
1322
+ for (const [i, link] of chain.links.entries()) {
1323
+ const next = chain.links[i + 1]?.node ?? chain.root;
1324
+ if (link.kind === "unknown") {
1325
+ rows.push([`${indent}└─ depends on every change:`, undefined]);
1326
+ for (const { cause, at } of chain.unknown) {
1327
+ rows.push([`${indent} ✗ ${cause}`, at]);
1328
+ }
1329
+ indent += " ";
1330
+ rows.push([`${indent}└─ ${next}`, undefined]);
1331
+ indent += " ";
1332
+ break;
1333
+ }
1334
+ rows.push([`${indent}└─ ${link.kind.padEnd(width)} ${next}`, link.at]);
1335
+ indent += " ";
1336
+ }
1337
+ rows.push([`${indent}● ${chain.cause}`, undefined]);
1338
+ return aligned(rows);
1339
+ }
1340
+ function verbOf(link) {
1341
+ return link.kind === "export" ? `exported as ${nameOf(link.node)}` : VERBS[link.kind];
1342
+ }
1343
+ function whereOf(link) {
1344
+ const configured = CONFIGURED[link.kind];
1345
+ if (configured !== undefined)
1346
+ return `${link.node} (${configured})`;
1347
+ return link.at ?? link.node;
1348
+ }
1349
+ function steps(links) {
1350
+ const rows = [...links].reverse().map((link) => [verbOf(link), whereOf(link)]);
1351
+ const width = Math.max(0, ...rows.map(([verb]) => verb.length));
1352
+ return rows.map(([verb, where], i) => `${verb.padEnd(width)} ${where}${i === rows.length - 1 ? " ← selected" : ""}`);
1353
+ }
1354
+ function header({ root, cause }) {
1355
+ if (cause === "changed")
1356
+ return `${root} changed`;
1357
+ if (cause === "given")
1358
+ return `if ${root} changes`;
1359
+ return `${root}: ${cause}`;
1360
+ }
1361
+ function chained(test, chain) {
1362
+ const unknownAt = chain.links.findIndex((link) => link.kind === "unknown");
1363
+ if (unknownAt === -1) {
1364
+ return [header(chain), ...steps(chain.links).map((step) => ` ${step}`)];
1365
+ }
1366
+ const node = chain.links[unknownAt].node;
1367
+ const where = chain.unknown.map(({ at }) => at ?? node);
1368
+ const width = Math.max(0, ...where.map((at) => at.length));
1369
+ const lines = [`${test} runs on every change`];
1370
+ for (const [i, { cause, fix }] of chain.unknown.entries()) {
1371
+ lines.push(` because ${where[i].padEnd(width)} ${cause}`, ` fix: ${fix}`);
1372
+ }
1373
+ if (unknownAt > 0) {
1374
+ lines.push(` reached via ${node}`, ...steps(chain.links.slice(0, unknownAt)).map((step) => ` ${step}`));
1375
+ }
1376
+ return lines;
1377
+ }
1378
+ var LINE_NUMBER = /:(\d+)$/;
1379
+ function lineNumber(at) {
1380
+ return at === undefined ? undefined : LINE_NUMBER.exec(at)?.[1];
1381
+ }
1382
+ function sourced(test, chain) {
1383
+ const unknownAt = chain.links.findIndex((link) => link.kind === "unknown");
1384
+ const hops = unknownAt === -1 ? chain.links : chain.links.slice(0, unknownAt);
1385
+ const numbers = [...chain.links, ...chain.unknown].map(({ at }) => lineNumber(at));
1386
+ const width = Math.max(0, ...numbers.map((n) => n?.length ?? 0));
1387
+ const gutter = " ".repeat(width);
1388
+ const cited = (at, text) => {
1389
+ const n = lineNumber(at);
1390
+ return n === undefined || text === undefined ? [] : [`${n.padStart(width)} | ${text}`];
1391
+ };
1392
+ const count = plural(hops.length, "hop", "hops");
1393
+ const lines = unknownAt === -1 ? [
1394
+ `selected: ${test} ← ${chain.root} (${count}${chain.cause === "changed" ? "" : `, ${chain.cause}`})`
1395
+ ] : [
1396
+ `selected: ${test} ← every change (${unknownAt === 0 ? "its dependencies can't be read" : `${count} to ${chain.links[unknownAt].node}, whose dependencies can't be read`})`
1397
+ ];
1398
+ lines.push("");
1399
+ for (const link of hops) {
1400
+ const configured = CONFIGURED[link.kind];
1401
+ const where = configured === undefined ? link.at ?? link.node : link.node;
1402
+ const kind = configured ?? link.kind;
1403
+ lines.push(`${gutter}--> ${where} ${kind}`, ...cited(link.at, link.text));
1404
+ }
1405
+ if (unknownAt === -1) {
1406
+ lines.push(`${gutter}● ${chain.root}: ${chain.cause}`);
1407
+ return lines;
1408
+ }
1409
+ const node = chain.links[unknownAt].node;
1410
+ for (const { cause, at, text, fix } of chain.unknown) {
1411
+ lines.push(`${gutter}✗ ${at ?? node} ${cause}`, ...cited(at, text), `${gutter} = fix: ${fix}`);
1412
+ }
1413
+ return lines;
1414
+ }
1415
+ var RENDER = {
1416
+ tree,
1417
+ chain: chained,
1418
+ source: sourced
1419
+ };
1420
+ function moreLine(more, all) {
1421
+ const shown = more.slice(0, LIST).join(", ");
1422
+ const rest = more.length > LIST ? ", …" : "";
1423
+ const changes = plural(more.length, "more change reaches", "more changes reach");
1424
+ const hint = all ? "" : " (--all shows each chain)";
1425
+ return `+ ${changes} this test: ${shown}${rest}${hint}`;
1426
+ }
1427
+ function unselectedMessage(explanation) {
1428
+ const { from, changed, reaches, example } = explanation;
1429
+ if (from === undefined) {
1430
+ return changed === 0 ? "Not selected: nothing changed." : `Not selected: ${changed === 1 ? "the changed file doesn't reach" : `none of the ${changed} changed files reaches`} it.`;
1431
+ }
1432
+ const counts = Object.entries(reaches ?? {}).map(([suite, count]) => `${count} ${suite}`);
1433
+ const total = Object.values(reaches ?? {}).reduce((a, b) => a + b, 0);
1434
+ return [
1435
+ `Not selected by a change to ${from}: no chain reaches it.`,
1436
+ total === 0 ? "Its chains reach no test." : `Its chains reach ${plural(total, "test", "tests")} (${counts.join(", ")}), such as ${example}.`
1437
+ ].join(`
1438
+ `);
1439
+ }
1440
+ function formatExplanation(explanation, format = "tree") {
1441
+ if (explanation.kind === "full") {
1442
+ return [
1443
+ `The ${explanation.suite} suite runs in full:`,
1444
+ ...explanation.reasons.map((reason) => ` ${reason}`)
1445
+ ].join(`
1446
+ `);
1447
+ }
1448
+ if (explanation.kind === "unselected")
1449
+ return unselectedMessage(explanation);
1450
+ const { test, more, others } = explanation;
1451
+ const render = RENDER[format];
1452
+ const lines = render(test, explanation);
1453
+ if (more.length > 0)
1454
+ lines.push(moreLine(more, others.length > 0));
1455
+ for (const other of others)
1456
+ lines.push("", ...render(test, other));
1457
+ return lines.join(`
1458
+ `);
1459
+ }
1460
+
1461
+ // src/main.ts
1462
+ var USAGE = `Usage:
1463
+ bivium plan [base] [--json] [--github] print the tests a change can affect
1464
+ bivium run [base] [--suite <name>] run a suite's selected tests
1465
+ bivium why <test> [file] [--base <ref>] the chain from a change (or file) to a test
1466
+ [--format <f>] [--all] [--json]
1467
+ bivium check [--max-unknown <n>] [--json]
1468
+ what the graph can't read, and dead globs
1469
+ bivium graph [--suite <name>] [--top <n>] [--json]
1470
+ each file's test fan-in, and the graph
1471
+ bivium --version print the version
1472
+ bivium --help print this
1473
+
1474
+ base defaults to the config's base, else the upstream default branch.
1475
+ Options go before or after the command, as --flag value or --flag=value.
1476
+ Paths may be repo-relative, relative to the current directory, or
1477
+ absolute.
1478
+
1479
+ Options:
1480
+ --config <file> config file (default: bivium.config.{ts,mts,mjs,js,json})
1481
+ --cwd <dir> repository (default: the current directory)
1482
+ --no-cache read every file; don't read or write the extraction cache
1483
+ --suite <name> for run: the suite (default: the first one); for graph:
1484
+ only this suite (default: every one)
1485
+ --json for plan, why, check and graph: print JSON
1486
+ --github for plan: also write each suite's selection to
1487
+ $GITHUB_OUTPUT as <output>=all|none|<files>
1488
+ --base <ref> for why and check: the base ref
1489
+ --format <f> for why: tree (default), chain (from the change to the
1490
+ test), source (each hop's line of source) or json
1491
+ --all for why: every change's chain to the test, not only the
1492
+ shortest
1493
+ --max-unknown <n> for check: fail when more unknown nodes than this reach
1494
+ a test
1495
+ --top <n> for graph: how many files to list per suite (default: 10)
1496
+
1497
+ Exit status: 0 done; 1 check found problems; 2 a usage, configuration or
1498
+ git error. run exits with its command's status. With --json, an error is
1499
+ also printed to stdout as { "schemaVersion", "error": { "kind", "message" } },
1500
+ kind one of usage, config, git or other.
1501
+
1502
+ Examples:
1503
+ bivium plan origin/main --json
1504
+ bivium why tests/Button.test.ts src/Button.svelte --format chain
1505
+ bivium check --json`;
1506
+ var WHITESPACE = /\s+/;
1507
+ var VALUED = new Set([
1508
+ "--config",
1509
+ "--cwd",
1510
+ "--suite",
1511
+ "--base",
1512
+ "--format",
1513
+ "--max-unknown",
1514
+ "--top"
1515
+ ]);
1516
+ var COMMON = ["--config", "--cwd", "--no-cache"];
1517
+ var FLAGS = {
1518
+ plan: [...COMMON, "--json", "--github"],
1519
+ run: [...COMMON, "--suite"],
1520
+ why: [...COMMON, "--base", "--json", "--format", "--all"],
1521
+ check: [...COMMON, "--base", "--max-unknown", "--json"],
1522
+ graph: [...COMMON, "--suite", "--top", "--json"]
1523
+ };
1524
+ var POSITIONAL = {
1525
+ plan: 1,
1526
+ run: 1,
1527
+ why: 2,
1528
+ check: 0,
1529
+ graph: 0
1530
+ };
1531
+ var SCHEMA_VERSION = 1;
1532
+ function usageError(message) {
1533
+ return new BiviumError("usage", message);
1534
+ }
1535
+ function unknownOption(command, flag) {
1536
+ const known = FLAGS[command] ?? [];
1537
+ const others = Object.keys(FLAGS).filter((other) => other !== command && FLAGS[other]?.includes(flag));
1538
+ const hint = others.length > 0 ? ` (${others.join(" and ")} ${others.length === 1 ? "takes" : "take"} it)` : didYouMean(flag, known);
1539
+ return usageError(`bivium ${command}: unknown option ${flag}${hint}`);
1540
+ }
1541
+ function parseArgs(command, argv) {
1542
+ const known = FLAGS[command] ?? [];
1543
+ const flags = new Map;
1544
+ const positional = [];
1545
+ for (let i = 0;i < argv.length; i++) {
1546
+ const arg = argv[i];
1547
+ if (arg === undefined)
1548
+ continue;
1549
+ if (!arg.startsWith("-") || arg === "-") {
1550
+ positional.push(arg);
1551
+ continue;
1552
+ }
1553
+ const equals = arg.startsWith("--") ? arg.indexOf("=") : -1;
1554
+ const flag = equals === -1 ? arg : arg.slice(0, equals);
1555
+ if (!known.includes(flag))
1556
+ throw unknownOption(command, flag);
1557
+ if (!VALUED.has(flag)) {
1558
+ const on = equals === -1 ? "true" : arg.slice(equals + 1);
1559
+ if (on !== "true" && on !== "false") {
1560
+ throw usageError(`bivium ${command}: ${flag} is a switch: give it alone, or as ${flag}=true or ${flag}=false`);
1561
+ }
1562
+ if (on === "true")
1563
+ flags.set(flag, "");
1564
+ continue;
1565
+ }
1566
+ const value = equals === -1 ? argv[++i] : arg.slice(equals + 1);
1567
+ if (value === undefined || value === "" || value.startsWith("--")) {
1568
+ throw usageError(`bivium: ${flag} needs a value`);
1569
+ }
1570
+ flags.set(flag, value);
1571
+ }
1572
+ if (positional.length > (POSITIONAL[command] ?? 0)) {
1573
+ throw usageError(`bivium ${command}: unexpected ${positional.at(-1)}`);
1574
+ }
1575
+ return { flags, positional };
1576
+ }
1577
+ function commandFor(run, files) {
1578
+ const words = run.split(WHITESPACE).filter(Boolean);
1579
+ const at = words.indexOf("{files}");
1580
+ if (at === -1)
1581
+ return [...words, ...files];
1582
+ return [...words.slice(0, at), ...files, ...words.slice(at + 1)];
1583
+ }
1584
+ function logSelection(label, selection, total, forced) {
1585
+ const files = total === 1 ? "file" : "files";
1586
+ let count;
1587
+ if (selection.mode === "some") {
1588
+ count = `${selection.files.length} of ${total} ${files}`;
1589
+ } else if (selection.mode === "none")
1590
+ count = "none";
1591
+ else if (forced)
1592
+ count = "all (full run)";
1593
+ else
1594
+ count = `all ${total} ${files} (each reaches a change)`;
1595
+ console.log(`${label}: ${count}`);
1596
+ if (selection.mode === "some") {
1597
+ for (const file of selection.files)
1598
+ console.log(` ${file}`);
1599
+ }
1600
+ }
1601
+ async function logContext(base, config, computed) {
1602
+ const mergeBase = (await computed.mergeBase()).slice(0, 7);
1603
+ const count = computed.changed.length;
1604
+ const changed = `${count} changed ${count === 1 ? "file" : "files"}`;
1605
+ const file = config.file ? `, config ${config.file}` : "";
1606
+ console.log(`Against ${base} (merge base ${mergeBase}): ${changed}${file}`);
1607
+ }
1608
+ function logPlan({ plan, narrowed }) {
1609
+ for (const reason of plan.reasons)
1610
+ console.log(`Full run: ${reason}`);
1611
+ for (const line of plan.packages)
1612
+ console.log(line);
1613
+ for (const line of plan.settings)
1614
+ console.log(line);
1615
+ for (const { narrower, result } of narrowed) {
1616
+ if ("note" in result && result.note) {
1617
+ console.log(`${narrower.name}: ${result.note}`);
1618
+ }
1619
+ }
1620
+ for (const [name, selection] of Object.entries(plan.suites)) {
1621
+ const total = plan.totals[name] ?? 0;
1622
+ logSelection(`${name} tests`, selection, total, plan.full.includes(name));
1623
+ }
1624
+ }
1625
+ function githubOutput() {
1626
+ const output = process.env.GITHUB_OUTPUT;
1627
+ if (!output) {
1628
+ throw usageError("bivium plan: --github writes to $GITHUB_OUTPUT, which is not set (it is in a GitHub Actions step)");
1629
+ }
1630
+ return output;
1631
+ }
1632
+ function writeOutputs(output, config, { plan }) {
1633
+ const lines = config.suites.map((suite) => `${suite.output}=${formatSelection(plan.suites[suite.name])}
1634
+ `);
1635
+ appendFileSync(output, lines.join(""));
1636
+ }
1637
+ function json(value) {
1638
+ return JSON.stringify({ schemaVersion: SCHEMA_VERSION, ...value }, null, 2);
1639
+ }
1640
+ function findSuite(config, name) {
1641
+ if (name === undefined)
1642
+ return;
1643
+ const suite = config.suites.find((candidate) => candidate.name === name);
1644
+ if (suite)
1645
+ return suite;
1646
+ const names = config.suites.map((candidate) => candidate.name);
1647
+ throw usageError(`bivium: no suite "${name}"${didYouMean(name, names)}; the config has ${names.join(", ")}`);
1648
+ }
1649
+ function real(path) {
1650
+ try {
1651
+ return realpathSync(path);
1652
+ } catch {
1653
+ const parent = dirname(path);
1654
+ return parent === path ? path : join3(real(parent), basename(path));
1655
+ }
1656
+ }
1657
+ function repoPath(root, arg, known) {
1658
+ const absolute = resolve(arg);
1659
+ const realRoot = real(root);
1660
+ const mappings = [
1661
+ relative(root, absolute),
1662
+ relative(realRoot, join3(real(dirname(absolute)), basename(absolute))),
1663
+ relative(realRoot, real(absolute))
1664
+ ].map((path) => path.split("\\").join("/")).filter((path) => !(path.startsWith("..") || isAbsolute2(path)));
1665
+ const fromCwd = mappings.find(known) ?? mappings[0];
1666
+ if (isAbsolute2(arg))
1667
+ return fromCwd ?? arg;
1668
+ const asWritten = posix3.normalize(arg.split("\\").join("/"));
1669
+ if (known(asWritten))
1670
+ return asWritten;
1671
+ return fromCwd !== undefined && known(fromCwd) ? fromCwd : asWritten;
1672
+ }
1673
+ async function inspect(command, { flags, positional }) {
1674
+ const format = flags.get("--format") ?? "tree";
1675
+ if (format !== "json" && !isFormat(format)) {
1676
+ throw usageError(`bivium why: --format takes tree, chain, source or json${didYouMean(format, ["tree", "chain", "source", "json"])}`);
1677
+ }
1678
+ const maxFlag = flags.get("--max-unknown");
1679
+ const max = maxFlag === undefined ? undefined : Number(maxFlag);
1680
+ if (max !== undefined && !Number.isInteger(max)) {
1681
+ throw usageError("bivium check: --max-unknown takes a whole number");
1682
+ }
1683
+ const [testArg, fileArg] = positional;
1684
+ if (command === "why" && testArg === undefined) {
1685
+ throw usageError("bivium why: which test? bivium why <test> [file]");
1686
+ }
1687
+ const { root, base, config } = await prepare({
1688
+ cwd: flags.get("--cwd"),
1689
+ base: flags.get("--base") ?? (command === "check" ? "HEAD" : undefined),
1690
+ configFile: flags.get("--config")
1691
+ });
1692
+ const computed = await computePlan(root, base, config, {
1693
+ ...flags.has("--no-cache") && { cache: false }
1694
+ });
1695
+ if (command === "check") {
1696
+ const report = await check(root, config, computed);
1697
+ const ok = !failed(report, max);
1698
+ console.log(flags.has("--json") ? json({ ok, summary: summarize(report), ...report }) : formatReport(report, max));
1699
+ return ok ? 0 : 1;
1700
+ }
1701
+ const inGraph = (path) => computed.graph.has(path);
1702
+ const isTest = (path) => config.suites.some((suite) => suite.isTest(path));
1703
+ const test = repoPath(root, testArg ?? "", (path) => inGraph(path) && isTest(path));
1704
+ const file = fileArg === undefined ? undefined : repoPath(root, fileArg, inGraph);
1705
+ if (!isTest(test) || !inGraph(test)) {
1706
+ const tests = [...computed.graph.keys()].filter(isTest);
1707
+ throw usageError(inGraph(test) ? `bivium why: ${test} is no suite's test: name a test first, as in bivium why <test> ${test}` : `bivium why: no test ${test}${didYouMean(test, tests)}`);
1708
+ }
1709
+ if (file !== undefined && !inGraph(file)) {
1710
+ throw usageError(`bivium why: no file ${file}${didYouMean(file, computed.graph.keys())}`);
1711
+ }
1712
+ const explanation = await explain(root, config, computed, test, file, {
1713
+ all: flags.has("--all")
1714
+ });
1715
+ console.log(flags.has("--json") || format === "json" ? json(explanation) : formatExplanation(explanation, format));
1716
+ return 0;
1717
+ }
1718
+ async function graphCommand({ flags }) {
1719
+ const top = Number(flags.get("--top") ?? "10");
1720
+ if (!Number.isInteger(top) || top < 0) {
1721
+ throw usageError("bivium graph: --top takes a whole number");
1722
+ }
1723
+ const { root, base, config } = await prepare({
1724
+ cwd: flags.get("--cwd"),
1725
+ base: "HEAD",
1726
+ configFile: flags.get("--config")
1727
+ });
1728
+ const one = findSuite(config, flags.get("--suite"));
1729
+ const suites = one ? [one] : config.suites;
1730
+ const { graph } = await computePlan(root, base, config, {
1731
+ ...flags.has("--no-cache") && { cache: false }
1732
+ });
1733
+ const report = graphReport(graph, suites);
1734
+ console.log(flags.has("--json") ? json(report) : formatGraph(report, top));
1735
+ return 0;
1736
+ }
1737
+ async function runCommand(command, { flags, positional }) {
1738
+ const output = flags.has("--github") ? githubOutput() : undefined;
1739
+ const { root, base, config } = await prepare({
1740
+ cwd: flags.get("--cwd"),
1741
+ base: positional[0],
1742
+ configFile: flags.get("--config")
1743
+ });
1744
+ const suite = findSuite(config, flags.get("--suite")) ?? config.suites[0];
1745
+ if (suite === undefined)
1746
+ throw new BiviumError("config", "bivium: no suites");
1747
+ if (command === "run" && !suite.run) {
1748
+ throw usageError(`bivium run: suite "${suite.name}" has no run command: add suites.${suite.name}.run to the config`);
1749
+ }
1750
+ const computed = await computePlan(root, base, config, {
1751
+ ...flags.has("--no-cache") && { cache: false },
1752
+ ...command === "run" && { suites: [suite.name] },
1753
+ mergeBase: true
1754
+ });
1755
+ if (command === "plan") {
1756
+ if (flags.has("--json")) {
1757
+ const { suites, reasons, causes, totals, packages } = computed.plan;
1758
+ const narrowed = computed.narrowed.map((ran) => ({
1759
+ name: ran.narrower.name,
1760
+ result: ran.result
1761
+ }));
1762
+ console.log(json({
1763
+ base,
1764
+ mergeBase: await computed.mergeBase(),
1765
+ config: config.file,
1766
+ changed: computed.changed,
1767
+ suites,
1768
+ reasons,
1769
+ causes,
1770
+ totals,
1771
+ packages,
1772
+ narrowed
1773
+ }));
1774
+ } else {
1775
+ await logContext(base, config, computed);
1776
+ logPlan(computed);
1777
+ }
1778
+ if (output !== undefined)
1779
+ writeOutputs(output, config, computed);
1780
+ return 0;
1781
+ }
1782
+ await logContext(base, config, computed);
1783
+ logPlan(computed);
1784
+ const selection = computed.plan.suites[suite.name];
1785
+ if (selection === undefined || selection.mode === "none") {
1786
+ console.log(`No ${suite.name} tests affected against ${base}; skipping.`);
1787
+ return 0;
1788
+ }
1789
+ const [program, ...args] = commandFor(suite.run ?? "", selection.mode === "some" ? selection.files : []);
1790
+ const result = spawnSync(program, args, { cwd: root, stdio: "inherit" });
1791
+ return result.status ?? 1;
1792
+ }
1793
+ function commandAt(argv) {
1794
+ for (let i = 0;i < argv.length; i++) {
1795
+ const arg = argv[i];
1796
+ if (arg === undefined)
1797
+ continue;
1798
+ if (!arg.startsWith("-"))
1799
+ return i;
1800
+ if (VALUED.has(arg))
1801
+ i++;
1802
+ }
1803
+ return -1;
1804
+ }
1805
+ var COMMANDS = Object.keys(FLAGS);
1806
+ function wantsJson(argv) {
1807
+ return argv.some((arg, i) => arg === "--json" || arg === "--json=true" || arg === "--format=json" || arg === "--format" && argv[i + 1] === "json");
1808
+ }
1809
+ function fail(argv, kind, message) {
1810
+ console.error(message);
1811
+ if (wantsJson(argv))
1812
+ console.log(json({ error: { kind, message } }));
1813
+ return 2;
1814
+ }
1815
+ async function main(argv) {
1816
+ if (argv.includes("--help") || argv.includes("-h")) {
1817
+ console.log(USAGE);
1818
+ return 0;
1819
+ }
1820
+ if (argv.includes("--version") || argv.includes("-v")) {
1821
+ console.log(version);
1822
+ return 0;
1823
+ }
1824
+ const at = commandAt(argv);
1825
+ const command = at === -1 ? undefined : argv[at];
1826
+ if (command === "help") {
1827
+ console.log(USAGE);
1828
+ return 0;
1829
+ }
1830
+ if (command === undefined) {
1831
+ return fail(argv, "usage", `bivium: which command? ${COMMANDS.join(", ")} (bivium --help for usage)`);
1832
+ }
1833
+ if (!(command in FLAGS)) {
1834
+ return fail(argv, "usage", `bivium: unknown command "${command}"${didYouMean(command, COMMANDS)}; the commands are ${COMMANDS.join(", ")} (bivium --help for usage)`);
1835
+ }
1836
+ const rest = [...argv.slice(0, at), ...argv.slice(at + 1)];
1837
+ try {
1838
+ const args = parseArgs(command, rest);
1839
+ if (command === "why" || command === "check")
1840
+ return await inspect(command, args);
1841
+ if (command === "graph")
1842
+ return await graphCommand(args);
1843
+ return await runCommand(command, args);
1844
+ } catch (error) {
1845
+ if (error instanceof BiviumError) {
1846
+ return fail(argv, error.kind, error.message);
1847
+ }
1848
+ const message = error instanceof Error ? error.message : String(error);
1849
+ return fail(argv, "other", message);
1850
+ }
1851
+ }
1852
+
1853
+ // src/cli.ts
1854
+ process.exitCode = await main(process.argv.slice(2));