bivium 0.2.0 → 0.3.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/CHANGELOG.md CHANGED
@@ -1,5 +1,135 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0 — 2026-11-02
4
+
5
+ **Breaking changes**
6
+
7
+ - A changed `ignore`d file the graph reads selects only the tests that
8
+ reach it through an edge. It no longer trips the orphan rule (with
9
+ the default `root`, any ignored change ran the whole suite), and no
10
+ longer selects the tests whose dependencies are unknown, so a
11
+ docs-only change selects `none` (#31, #32).
12
+ - A suite's `root`, and `roots`, with a wildcard is an error. Both take
13
+ paths, so `root: "components/**"` matched nothing and the orphan rule
14
+ quietly stopped for it (#21).
15
+ - A usage or configuration error (no command, an unknown command,
16
+ option or suite) exits 2. It exited 1, as `check` does when it finds
17
+ problems (#40).
18
+ - `plan`'s and `check`'s text output changed (see CLI).
19
+
20
+ **Features**
21
+
22
+ - `suites.<name>.types: false` says a suite runs code: a change that
23
+ reaches its tests only through `import type`, `export type … from`,
24
+ JSDoc types or declaration files selects none of them. The default
25
+ keeps today's selection, which a type-checking suite needs. `why`
26
+ labels these edges `type` (#38).
27
+ - `suites.<name>.setup` names the files a runner loads before every
28
+ test (`setupFiles`, `--require`, `globalSetup`): every test of the
29
+ suite depends on them and on what they import (#35).
30
+ - `// @lists <glob>` selects a test when a match is added, deleted or
31
+ renamed, not when one is edited, for a test that lists files without
32
+ reading them (#25).
33
+ - An `edges` key can name generated files git doesn't list, such as
34
+ `.velite/*`: an import that resolves under it, with an extension or
35
+ as an index, lands there instead of being unresolved (#20).
36
+ - A root `pnpm-lock.yaml` (v6 or v9) is diffed like `bun.lock`. Its
37
+ settings, overrides, catalogs, patches and pnpm's own version still
38
+ run everything, as does one bivium can't read (#34).
39
+ - `loadedByName` lists the packages a test may load other than by an
40
+ import (`jsdom`, `ts-jest`). Set, any other package without a `bin`
41
+ is import-only, so a lockfile bump that reaches one no test imports
42
+ selects only its importers (#23).
43
+ - `knownUnknowns` lists the unknown nodes `check` allows, each with a
44
+ reason, and `check` fails on one it doesn't list or an entry that's
45
+ no longer unknown (#24).
46
+ - `bivium graph` ranks each suite's files by how many tests a change to
47
+ one selects; `--json` exports the graph with each node's fan-in
48
+ (#36).
49
+
50
+ **CLI**
51
+
52
+ - Options can come before the command, and `--help` or `-h` anywhere
53
+ prints usage and exits 0.
54
+ - `plan` prints each selection's scale (`unit tests: 3 of 822 files`)
55
+ and tells a full run (`all (full run)`) from every test reaching a
56
+ change. `plan --json` and `plan()` add `totals`, and `causes`, each
57
+ reason as data.
58
+ - `check` leads with counts by cause, and a fix for an unresolved
59
+ specifier names the file that's there: a sibling with another
60
+ extension, a file outside `roots`, or one git ignores.
61
+ - `why --format json` is `why --json` (#40).
62
+
63
+ **Performance**
64
+
65
+ - The walk tests each distinct pattern (`edges`, `@depends-on`,
66
+ `import.meta.glob`, `reads`) once per node it visits, however many
67
+ files declare it. With 4,000 tests and
68
+ `{ "tests/*.test.ts": "src/setup.ts" }`, a plan took 0.81 s, and now
69
+ 0.08 s (#39).
70
+ - A plan that reads files holds only what it extracted from each, not
71
+ the file's text, and reads 64 at a time. A cold plan of 7,000 files
72
+ needs a 20 MB heap on Node instead of over 64 MB, and peaks at 124 MB
73
+ of RSS instead of 285 MB (Bun: 88 MB instead of 115 MB) (#42).
74
+ - The orphan rule's walk from each changed file stops at the first test
75
+ or page it reaches, as does the lockfile check for a package a test
76
+ imports: with 350 changes in 5,900 files, the selection step took
77
+ 21.7 ms and now 8.1 ms.
78
+
79
+ **Fixes**
80
+
81
+ - An `alias` key that ends in `/` (`{ "@/": "src/" }`, as Vite
82
+ configs spell it) matches the specifiers that start with it. It
83
+ matched none (#29).
84
+ - A missing `x.js` resolves to `x.tsx` and `x.d.ts` as well as `x.ts`
85
+ (and the `.mjs` and `.cjs` variants), through `exports` and `imports`
86
+ targets too, so `@acme/ui/Button.js` reaches
87
+ `packages/ui/src/Button.ts`. A value import that finds only `x.d.ts`
88
+ is unknown: what runs isn't in the graph (#28).
89
+ - A doubled slash in a specifier resolves through `alias` and tsconfig
90
+ `paths` (#33).
91
+ - A specifier that starts with a dot but not `./` or `../` (`.velite`)
92
+ is bare, as TypeScript reads it (#20).
93
+ - An `edges` or `reads` key that names one file declares what it reads
94
+ from disk, as `@depends-on` and `@reads` do (#22).
95
+ - The lexer reads a JSX element with type arguments in `.tsx`
96
+ (`<List<string> />`) instead of falling back to the regex extractor
97
+ (#30).
98
+ - A type import from `fs` doesn't count as reading the disk, and
99
+ `check` lists an unresolved specifier once per file.
100
+
101
+ **Docs**
102
+
103
+ - The README has one table for what to do with a changed file no test
104
+ reaches, recipes for Vitest and Jest, pnpm workspaces, Playwright
105
+ and generated code, and what a plan costs in CI (#41).
106
+
107
+ ## 0.2.1 — 2026-10-28
108
+
109
+ **Performance**
110
+
111
+ - `git merge-base` runs only when something needs the commit:
112
+ `plan()`, `plan --json`, or a narrower whose files changed. Base
113
+ versions of changed files are read by the blob ID the diff names.
114
+ Git's CPU per plan drops 21 to 24% on carbon-components-svelte and
115
+ sveld.
116
+ - A bare specifier is resolved once per owning `package.json` and
117
+ nearest `tsconfig.json`, and probing checks only matching extensions:
118
+ 13 to 30% fewer instructions building the graph on real
119
+ repositories.
120
+ - The lexer's first pass in a fresh process is 23% faster on Bun and
121
+ 32% on Node, with identical extractions.
122
+
123
+ **Fixes**
124
+
125
+ - Without the cache, a file staged as new and then deleted from disk
126
+ no longer counts as present.
127
+
128
+ **Docs**
129
+
130
+ - The CI example clones with `filter: blob:none`: on
131
+ carbon-components-svelte the checkout went from 6.3 s to 3.8 s.
132
+
3
133
  ## 0.2.0 — 2026-10-27
4
134
 
5
135
  **Breaking changes**
package/README.md CHANGED
@@ -31,7 +31,7 @@ export default defineConfig({
31
31
 
32
32
  ```console
33
33
  $ bunx bivium plan
34
- unit tests: 3 files
34
+ unit tests: 3 of 12 files
35
35
  tests/Button.test.ts
36
36
  tests/Modal.test.ts
37
37
  tests/css/unknown.test.ts
@@ -45,7 +45,7 @@ A one-pass lexer reads JavaScript and TypeScript (`.js`, `.ts`, `.jsx`, `.tsx`,
45
45
 
46
46
  | It follows | As |
47
47
  |:---|:---|
48
- | Static, side-effect and dynamic imports, `export … from`, `require()` | Edges to every file the specifier can load: each extension that exists, each `exports` condition |
48
+ | Static, side-effect and dynamic imports, `export … from`, `require()` | Edges to every file the specifier can load: each extension that exists, each `exports` condition. A missing `x.js` (`.jsx`, `.mjs`, `.cjs`) is its TypeScript source, as TypeScript reads it: `x.ts`, `x.tsx` or `x.d.ts`, through any path, alias or `exports` target. A value import that finds only `x.d.ts` is unknown: what runs isn't in the graph |
49
49
  | `vi.mock()`, `vi.importActual()` and the rest of the family | Edges |
50
50
  | `import.meta.glob()` | Every matching file, now and later |
51
51
  | JSDoc `@type {import("x")}` and `@import` | Edges (TypeScript reads them) |
@@ -57,7 +57,7 @@ A one-pass lexer reads JavaScript and TypeScript (`.js`, `.ts`, `.jsx`, `.tsx`,
57
57
  | A file's own package and its ancestors' `package.json` dependencies, and builtins | `pkg:` nodes |
58
58
  | Anything else | Unknown: the file depends on every change |
59
59
 
60
- A root `bun.lock` or `package-lock.json` isn't a source file: a change to one seeds the packages it changed (see [Lockfiles](#lockfiles)).
60
+ A root `bun.lock`, `package-lock.json` or `pnpm-lock.yaml` isn't a source file: a change to one seeds the packages it changed (see [Lockfiles](#lockfiles)).
61
61
 
62
62
  A file it can't lex cleanly is read by a regex extractor instead, which over-approximates. CSS isn't scanned: generated stylesheets reach their inputs through `edges`, and a [narrower](#narrowers) can do better.
63
63
 
@@ -69,40 +69,99 @@ A file it can't lex cleanly is read by a regex extractor instead, which over-app
69
69
  |:---|:---|
70
70
  | `suites.<name>.tests` | The suite's test files |
71
71
  | `suites.<name>.run` | The command `bivium run` runs. `{files}` is replaced by the selection (nothing for `all`); without it, the files are appended |
72
- | `suites.<name>.root` | Where the orphan rule applies: a changed file here that no test of the suite reaches is wired some other way (a setup file, a runner config), so the whole suite runs. Default: the whole repository |
72
+ | `suites.<name>.root` | Where the orphan rule applies: a changed file here that no test of the suite reaches is wired some other way (a setup file, a runner config), so the whole suite runs. Paths, not globs (`e2e`, not `e2e/**`): a glob is an error. Default: the whole repository |
73
73
  | `suites.<name>.urls` | URL pattern → file pattern, for `page.goto()` calls under `root` |
74
74
  | `suites.<name>.pages` | Pages only a `goto()` opens; files only they load are wired to no test |
75
+ | `suites.<name>.setup` | Files the runner loads before every test (Vitest and Jest `setupFiles`, Mocha `--require`, Playwright `globalSetup`): every test of the suite depends on them and what they import. bivium doesn't read the runner's config, so name them here |
75
76
  | `suites.<name>.wiring` | Files whose change runs the whole suite: another harness, a runner config |
76
77
  | `suites.<name>.nonInputs` | Files under `root` the runner never reads, such as type-check inputs |
78
+ | `suites.<name>.types` | `false` when the suite runs code and can't observe types (Vitest, Jest, Playwright, `bun test`): a change that reaches its tests only through `import type`, `export type … from`, JSDoc types or a declaration file selects none of them. For the orphan rule a type-only reach counts only for a declaration file, since the runner may load any other file by name: list a types-only module under `root` in `nonInputs`. Default: `true`, which a type-checking suite (`tsc`, `vitest --typecheck`) needs. An inline `import { type A }` is always an edge: under `verbatimModuleSyntax` it still loads the module |
77
79
  | `suites.<name>.output` | The step output `plan --github` writes. Default: `<name>-tests` |
78
- | `roots` | Paths the graph reads. A changed file outside them that isn't ignored runs everything. Default: the whole repository |
79
- | `ignore` | Files no test can observe. A file some test reaches still counts |
80
- | `alias` | Specifier prefix → path, as the bundler aliases it. Tried before tsconfig `paths` and `package.json` `exports` |
81
- | `edges` | Generated file glob → its inputs, which it depends on transitively, as with `@depends-on`: `{ "dist/*.css": "styles/**" }`. In a value, `$1`, `$2`… are what the key's wildcards matched, counted from the left: `{ "examples/*/package.json": "examples/$1/**" }` |
82
- | `reads` | File glob → the files it reads as text, as with `@reads`: only a direct change to one counts, so their imports and unknowns don't spread to it. Values take `$1`… as in `edges`: `{ "tests/*.test.ts": "tests/__snapshots__/$1.test.ts.snap" }` |
80
+ | `roots` | Paths (not globs) the graph reads. A changed file outside them that isn't ignored runs everything. Default: the whole repository |
81
+ | `ignore` | Files no test can observe except through an edge (docs, stories). A change to one selects only the tests that reach it, never runs a suite by the orphan rule, and doesn't select the tests whose dependencies are unknown |
82
+ | `alias` | Specifier prefix → path, as the bundler aliases it. Tried before tsconfig `paths` and `package.json` `exports`. A key ending in `/` is the prefix, as Vite reads it: `{ "@/": "src/" }` maps `@/x` to `src/x` |
83
+ | `edges` | Generated file glob → its inputs, which it depends on transitively, as with `@depends-on`: `{ "dist/*.css": "styles/**" }`. A key may name files git doesn't list, such as a gitignored generator output (`{ ".velite/*": "content/**" }`): an import that resolves under it, by extension or as an index, lands on that file instead of being unresolved. In a value, `$1`, `$2`… are what the key's wildcards matched, counted from the left: `{ "examples/*/package.json": "examples/$1/**" }` |
84
+ | `reads` | File glob → the files it reads as text, as with `@reads`: only a direct change to one counts, so their imports and unknowns don't spread to it. An `edges` or `reads` key that names one file (no wildcard) declares what it reads, as its own `@depends-on` or `@reads` would, so its disk reads aren't unknown. Values take `$1`… as in `edges`: `{ "tests/*.test.ts": "tests/__snapshots__/$1.test.ts.snap" }` |
83
85
  | `self` | The selector's own files: a change to one runs everything. The config file is always one |
84
86
  | `importOnly` | Files only an import reaches: deleting one never orphans a suite |
85
87
  | `hermetic` | Files whose disk reads and non-literal imports reach no file of the repository: a library's `fs` calls on its caller's paths, a test that reads only the temporary files it writes. They add no unknown |
86
88
  | `barrels` | Modules that may bind named imports. Default: every module made only of re-exports |
87
89
  | `external` | Packages a dependency installs that your code imports without declaring |
88
- | `inert` | Packages no test uses except by importing them: linters, formatters, type packages (`["@biomejs/biome", "knip", "@types/*"]`). A [lockfile change](#lockfiles) that only they reach selects nothing |
90
+ | `inert` | Packages no test uses except by importing them: linters, formatters, type packages (`["@biomejs/biome", "knip", "@types/*"]`). A [lockfile change](#lockfiles) that only they reach selects nothing. With `loadedByName` set, only packages with a `bin` need listing |
91
+ | `loadedByName` | Packages a test may load other than by an import: a test environment or a plugin a config names by string (`["jsdom", "ts-jest"]`). Setting it, even to `[]`, says every other package without a `bin` is loaded only by imports, so a [lockfile change](#lockfiles) that reaches one no test imports selects only its importers. A package with a `bin` always counts as one a test may run |
89
92
  | `extensions` | Suffixes tried after a specifier |
90
93
  | `deadGlobs` | Dead globs `check` allows, each `{ file, glob, reason }`, the glob as `file` spells it |
94
+ | `knownUnknowns` | Nodes `check` allows to have unknown dependencies, each `{ file, reason }`. With it set, even to `[]` (which is `--max-unknown 0`), `check` fails on an unknown node some test reaches that it doesn't list, and on an entry that's no longer unknown, so a new unknown can't replace one that went away |
91
95
  | `narrowers` | See [Narrowers](#narrowers) |
92
96
  | `base` | The default base ref. Otherwise the upstream default branch (`origin/HEAD`, then `origin/main`, `origin/master`, `main`, `master`) |
93
97
  | `cache` | The cache's directory, or `false`. Default: `node_modules/.cache/bivium`, or `.bivium/cache` |
94
98
 
99
+ ## A change no test reaches
100
+
101
+ A changed file under a suite's `root` that no test of the suite reaches is wired some other way (a runner config, a setup file), so the whole suite runs: the orphan rule. With the default `root`, the whole repository, any file bivium can't trace to a test runs the suite, which is sound and coarse. Set `root` on every suite to the directories its tests and sources live in, and say what the rest is:
102
+
103
+ | You changed… | and want… | Use |
104
+ |:---|:---|:---|
105
+ | a file no test can observe: docs, stories, a changelog | nothing to run, unless some test imports it | `ignore` |
106
+ | a file under the suite's `root` only another tool reads: type-check inputs | nothing to run for this suite | the suite's `nonInputs` |
107
+ | a runner config or a second harness | the whole suite | the suite's `wiring` |
108
+ | a setup file the runner loads before every test, or what it imports | every test of the suite | the suite's `setup` |
109
+ | the selector's config, or its own code | everything | `self` (the config file always is) |
110
+ | a declaration file, in a suite that runs code | nothing | the suite's `types: false` |
111
+ | a types-only module only `import type` reaches, in a suite that runs code | nothing | the suite's `types: false`, and the module in its `nonInputs` |
112
+ | a file a test lists but doesn't read (a route, a story) | the test, when one is added or deleted | `// @lists <glob>` in the test |
113
+ | a file a build turns into what tests load | the tests that load the output | `edges` from the output to its inputs |
114
+
115
+ A file outside `roots` that isn't ignored runs everything: it's the backstop for wiring the graph can't see, such as a CI workflow.
116
+
117
+ ## Recipes
118
+
119
+ **Vitest or Jest.** Name the setup files the runner loads, mirror `resolve.alias` (a Vite key like `"@/"` works as written), give snapshots to their tests, and, for a suite that runs code, skip type-only edges:
120
+
121
+ ```ts
122
+ suites: {
123
+ unit: {
124
+ tests: "src/**/*.test.{ts,tsx}",
125
+ run: "vitest run {files}",
126
+ root: "src",
127
+ setup: ["src/setupTests.ts"], // vitest.config.ts `setupFiles`
128
+ wiring: ["vitest.config.ts"],
129
+ types: false,
130
+ nonInputs: ["src/**/types.ts"], // types only: nothing loads them at runtime
131
+ },
132
+ },
133
+ alias: { "@/": "src/" },
134
+ reads: { "src/**/*.test.{ts,tsx}": "src/$1__snapshots__/$2.test.$3.snap" },
135
+ ```
136
+
137
+ tsconfig `paths` (what `vite-tsconfig-paths` reads) are read without an `alias`. An extensionless `vi.mock("@/x")` resolves as an import does. A test environment the runner loads by name (`jsdom`, `happy-dom`) goes in `loadedByName` if you set it.
138
+
139
+ **pnpm workspaces.** Workspace packages resolve through their `package.json` `exports`, and a `.js` specifier into one (`@acme/ui/Button.js`) reaches its `.ts` source. A `pnpm-lock.yaml` change selects through the packages it changed. Set `roots` to the packages and apps whose changes the suites should see, and a suite per test runner.
140
+
141
+ **Playwright.** Map `page.goto()` URLs to the pages they open with `urls`, list pages only a `goto()` opens in `pages`, and name `playwright.config.ts` in `wiring`:
142
+
143
+ ```ts
144
+ e2e: {
145
+ tests: "e2e/**/*.spec.ts",
146
+ root: "e2e",
147
+ urls: { "/*": "e2e/fixtures/*.html" },
148
+ wiring: ["playwright.config.ts"],
149
+ },
150
+ ```
151
+
152
+ **Generated code.** A content or type generator that writes into a gitignored directory (`.velite`, `.contentlayer/generated`) is an `edges` entry from what it writes to what it reads: `{ ".velite/*": ["content/**", "velite.config.ts"] }`. An import of `#velite` or `../.velite` then reaches the content, and not every change.
153
+
95
154
  ## Lockfiles
96
155
 
97
- A dependency bump changes a lockfile, which no file imports. When a root `bun.lock` or `package-lock.json` (v2 or v3) changes, bivium diffs it against the merge base and seeds the walk with the `pkg:` nodes of the packages whose entries changed, and of every package that depends on one, so a `svelte` bump selects what imports `svelte`, or a package built on it. A `package.json` whose only change is to dependencies the lockfile records the same way counts as those packages changing.
156
+ A dependency bump changes a lockfile, which no file imports. When a root `bun.lock`, `package-lock.json` (v2 or v3) or `pnpm-lock.yaml` (v6 or v9) changes, bivium diffs it against the merge base and seeds the walk with the `pkg:` nodes of the packages whose entries changed, and of every package that depends on one, so a `svelte` bump selects what imports `svelte`, or a package built on it. A `package.json` whose only change is to dependencies the lockfile records the same way counts as those packages changing.
98
157
 
99
- A changed package can also be used in ways the graph can't see: a CLI a test spawns, a runner, a type package. So when a change reaches a package that a `package.json` declares, or that some file imports, and that no test imports, everything runs, with the reason (`bun.lock: playwright 1.63.0 → 1.64.0, and no test imports it`), unless the package is `inert`. Everything also runs for a lockfile bivium can't parse, one whose settings other than its packages changed (`overrides`, patches), and a `package.json` change the lockfile doesn't record. Other lockfiles (`pnpm-lock.yaml`, `yarn.lock`, `bun.lockb`) are files like any other: outside the roots, a change to one runs everything.
158
+ A changed package can also be used in ways the graph can't see: a CLI a test spawns, a runner, a type package. So when a change reaches a package that a `package.json` declares, or that some file imports, and that no test imports, everything runs, with the reason (`bun.lock: playwright 1.63.0 → 1.64.0, and no test imports it`), unless the package is `inert`. With `loadedByName` set, only a package with a `bin` in the lockfile, or one it lists, counts as used that way: a bump that reaches a library only a CMS config imports selects nothing. Everything also runs for a lockfile bivium can't parse, one whose settings other than its packages changed (`overrides`, patches, pnpm's `settings`, `catalogs`, or the version of pnpm itself), and a `package.json` change the lockfile doesn't record. Other lockfiles (`yarn.lock`, `bun.lockb`) are files like any other: outside the roots, a change to one runs everything.
100
159
 
101
160
  ```console
102
161
  $ bunx bivium plan
103
162
  bun.lock: @biomejs/biome 2.5.14 → 2.6.3, inert
104
163
  bun.lock: svelte 5.57.1 → 5.57.2
105
- unit tests: 4 files
164
+ unit tests: 4 of 12 files
106
165
  …
107
166
  ```
108
167
 
@@ -110,22 +169,24 @@ unit tests: 4 files
110
169
 
111
170
  | Comment | Meaning |
112
171
  |:---|:---|
113
- | `// @depends-on <glob> [glob…]` | Inputs that aren't imports: files a script reads, a tool it spawns. Transitive. A file that reads the disk without one is unknown, unless it's `hermetic` |
172
+ | `// @depends-on <glob> [glob…]` | Inputs that aren't imports: files a script reads, a tool it spawns. Transitive. A file that reads the disk without one (or `@reads`, or `@lists`) is unknown, unless it's `hermetic` |
114
173
  | `// @reads <glob> [glob…]` | Files read as text. Only a direct change to one counts, not a change to what it imports. The config's `reads` says the same for files that can't hold a comment |
174
+ | `// @lists <glob> [glob…]` | Files whose names it lists, not their contents: a convention test that checks every route has a handler. Only adding, deleting or renaming one counts; an edit doesn't select it, and doesn't run its suite by the orphan rule either |
115
175
  | `// @glob-registry` | This file's `import.meta.glob` is a lookup table and adds no edges: whatever loads an entry names it itself |
116
176
 
117
177
  ## CLI
118
178
 
119
179
  | Command | Does |
120
180
  |:---|:---|
121
- | `bivium plan [base] [--json] [--github]` | Prints each suite's selection: `all`, `none` or the files, and why a suite runs in full. `--json` adds the base, merge base, changed files, narrower results and changed packages. `--github` also writes each suite's selection to `$GITHUB_OUTPUT` |
181
+ | `bivium plan [base] [--json] [--github]` | Prints each suite's selection (`none`, the files out of how many, `all` files when each reaches a change, or `all (full run)`) and why a suite runs in full. `--json` adds the base, merge base, changed files, narrower results, changed packages, each suite's test count (`totals`), and the reasons as data (`causes`, each a `FullRunCause`: `{ kind, suites, file?, package?, narrower?, message }`). `--github` also writes each suite's selection to `$GITHUB_OUTPUT` |
122
182
  | `bivium run [base] [--suite <name>]` | Runs the suite's `run` command with its selection (default: the first suite), or skips it when nothing is affected |
123
- | `bivium why <test> [file] [--format tree\|chain\|source] [--all]` | The shortest chain of edges from a changed file, or from `file`, to the test, with what spells each edge and the line it's on, and how many other changes reach the test. `--format tree` (the default) draws it from the test; `chain` reads from the change to the test; `source` prints each hop's line of source. `--all` shows every change's chain. For a test that isn't selected, it says what the file's chains reach instead |
124
- | `bivium check [--max-unknown <n>]` | Lists every node with unknown dependencies, with where and how to fix each cause, and fails when more than `n` of them reach a test. A node no test depends on is listed apart and not counted: plans only run tests, so it widens nothing. Also lists `tsconfig.json` files that don't parse, and [dead globs](#dead-globs), and fails on one `deadGlobs` doesn't allow or on an entry that matches none |
183
+ | `bivium why <test> [file] [--format tree\|chain\|source\|json] [--all]` | The shortest chain of edges from a changed file, or from `file`, to the test, with what spells each edge and the line it's on, and how many other changes reach the test. `--format tree` (the default) draws it from the test; `chain` reads from the change to the test; `source` prints each hop's line of source; `json` (or `--json`) prints the chain as data. `--all` shows every change's chain. For a test that isn't selected, it says what the file's chains reach instead |
184
+ | `bivium check [--max-unknown <n>] [--json]` | Counts what it found by cause first, then lists every node with unknown dependencies, with where and how to fix each cause, and fails when more than `n` of them reach a test, or on one `knownUnknowns` doesn't list. A node no test depends on is listed apart and not counted: plans only run tests, so it widens nothing. Also lists `tsconfig.json` files that don't parse, and [dead globs](#dead-globs), and fails on one `deadGlobs` doesn't allow or on an entry that matches none. `--json` prints the report as data |
185
+ | `bivium graph [--suite <name>] [--top <n>] [--json]` | How many of each suite's tests a change to each file selects through the graph (leaving out the tests that run on any change, which it counts apart): the `n` files that reach the most, and how files spread from none to every test. A few hub files that reach most tests are what make plans wide. `--json` prints each suite's `total` and `everyChange` tests, and every node with its `imports` and `importers` (file edges), `fanIn` per suite and whether it's `unknown` |
125
186
 
126
- `--config`, `--cwd` and `--no-cache` work with every command, and `why` and `check` take `--base <ref>`. An unknown option, or an unknown `--format`, is an error.
187
+ `--config`, `--cwd` and `--no-cache` work with every command, before or after it, and `why` and `check` take `--base <ref>`. `--help` (or `-h`) prints usage. An unknown command, option or `--format` is an error. Exit status: 0 when done, 1 when `check` finds problems, 2 for a usage or configuration error; `run` exits with its command's status.
127
188
 
128
- `why` names each edge by what spells it: `import`, `goto` (a page `page.goto()` opens), `html` (a module an HTML page loads: `script[src]`, `link[href]`, `iframe[src]` or an inline script's import), `name` (a named import bound to a barrel name) and `export` (the file that exports it), `glob` (`import.meta.glob`), `depends-on`, `edges` (the config's) and `reads`.
189
+ `why` names each edge by what spells it: `import`, `type` (an `import type`, `export type … from`, JSDoc type, or an edge to or from a declaration file), `setup` (a suite's setup file), `goto` (a page `page.goto()` opens), `html` (a module an HTML page loads: `script[src]`, `link[href]`, `iframe[src]` or an inline script's import), `name` (a named import bound to a barrel name) and `export` (the file that exports it), `glob` (`import.meta.glob`), `depends-on`, `edges` (the config's), `reads` and `lists`.
129
190
 
130
191
  ```console
131
192
  $ bunx bivium why e2e/accordion.test.ts
@@ -178,7 +239,7 @@ tests/e2e.test.ts runs on every change
178
239
 
179
240
  ## Dead globs
180
241
 
181
- A typo'd `@depends-on`, or one pointing only at files the planner skips, looks fine and never selects its file. `check` evaluates every `@depends-on`, `@reads` and `import.meta.glob` pattern, and every `edges` and `reads` value, against every file git lists (tracked and untracked, inside the roots or not) and reports one that:
242
+ A typo'd `@depends-on`, or one pointing only at files the planner skips, looks fine and never selects its file. `check` evaluates every `@depends-on`, `@reads`, `@lists` and `import.meta.glob` pattern, every `edges` and `reads` value, and every suite's `setup`, against every file git lists (tracked and untracked, inside the roots or not) and reports one that:
182
243
 
183
244
  | Problem | Means |
184
245
  |:---|:---|
@@ -207,7 +268,10 @@ jobs:
207
268
  steps:
208
269
  - uses: actions/checkout@v7
209
270
  with:
271
+ # History for the merge base, without old file contents: git
272
+ # fetches the few a plan reads (a changed barrel or lockfile).
210
273
  fetch-depth: 0
274
+ filter: blob:none
211
275
  - uses: oven-sh/setup-bun@v2
212
276
  - id: merge-base
213
277
  run: echo "sha=$(git merge-base origin/main HEAD)" >> "$GITHUB_OUTPUT"
@@ -230,6 +294,15 @@ jobs:
230
294
 
231
295
  The cache holds what bivium extracted from each file, keyed by git blob, so a warm plan reads only the files a branch changed. Key it on the merge base: a pull request can restore caches from the default branch, whose run at that commit is the one to hit. Without `node_modules`, the cache lives in `.bivium/cache`; it writes a `.gitignore` so it never shows up as a change.
232
296
 
297
+ What a plan costs, measured on an Apple M-series laptop under load (median of five, wall time):
298
+
299
+ | Repository | Files | Bun, no cache | Bun, warm | Node 24, no cache | Node 24, warm | Cache |
300
+ |:---|---:|---:|---:|---:|---:|---:|
301
+ | carbon-components-svelte | 4,680 | 0.15 s | 0.09 s | 0.27 s | 0.13 s | 452 KB |
302
+ | generated TypeScript, 23 MB | 7,000 | 0.14 s | 0.08 s | 0.30 s | 0.12 s | 896 KB |
303
+
304
+ So the cache is optional at this size, `bunx --bun` is worth it, and planning inside a test job (no extra job, no install) costs well under a second. A cold plan of the generated repository peaks at 88 MB of RSS on Bun and 124 MB on Node.
305
+
233
306
  ## Narrowers
234
307
 
235
308
  Some changes reach every test through a generated file: every page loads the compiled stylesheet, so any style edit selects every e2e test. A narrower replaces such a change's coarse seeds with finer ones from a semantic diff, such as the sources that render a changed CSS rule.
@@ -262,7 +335,7 @@ const result = await plan({ config, base: "origin/main" });
262
335
  result.suites.unit; // { mode: "some", files: [...] }; result.suites.e2e is a type error
263
336
  ```
264
337
 
265
- `plan(options?)` takes `cwd`, `base`, `config` (default: the config file in `cwd`) and `cache`, and returns each suite's selection, the reasons, the packages a lockfile change seeded or found inert, the base, merge base and changed files, and what each narrower returned. Given a config, the suite names carry through to the result's type. The package exports only `plan`, `defineConfig` and their types.
338
+ `plan(options?)` takes `cwd`, `base`, `config` (default: the config file in `cwd`) and `cache`, and returns each suite's selection, its test count, the reasons as sentences and as data, the packages a lockfile change seeded or found inert, the base, merge base and changed files, and what each narrower returned. Given a config, the suite names carry through to the result's type. The package exports only `plan`, `defineConfig` and their types.
266
339
 
267
340
  ## Compared with
268
341
 
package/cli.js CHANGED
@@ -1,42 +1,62 @@
1
1
  #!/usr/bin/env node
2
- import{version,globToRegExp,sorted,createResolver,SCANNED,formatOf,extract,finish,gotoPage,affectedBy,formatSelection,computePlan,prepare}from"./shared-01am1xsp.js";import{spawnSync}from"node:child_process";import{appendFileSync}from"node:fs";import{readFile}from"node:fs/promises";import{isAbsolute,join}from"node:path";var DISK_READ=/\bfrom\s*["'](?:node:)?(?:fs|fs\/promises|child_process)["']|\brequire\s*\(\s*["'](?:node:)?(?:fs|fs\/promises|child_process)["']|\bBun\.(?:file|Glob|spawn)/,NON_LITERAL_IMPORT=/\b(?:import|require|vi\.(?:mock|doMock|unmock|importActual|importMock))\s*(?:<[^>]*>)?\(\s*(?!["'][^"'`$]*["']\s*[,)])/,GLOB_CALL=/\bimport\.meta\.glob/,QUOTED_CAUSE=/"([^"]+)"/,LOADS=/\b(?:import|export|from|require|mock|doMock|unmock|importActual|importMock)\b|\b(?:src|href)\s*=/,GOTO_CALL=/\bgoto\s*\(/;function lineAt(source,index){let line=1;for(let i=source.indexOf(`
2
+ import{version,globToRegExp,sorted,QUERY,UNDECLARED_READS,RELATIVE,aliasPath,createResolver,SCANNED,formatOf,extract,finish,gotoPage,walksByTypes,importersOf,affectedBy,formatSelection,computePlan,prepare}from"./shared-qem76en8.js";import{spawnSync}from"node:child_process";import{appendFileSync}from"node:fs";import{statSync}from"node:fs";import{join as join2,posix}from"node:path";import{readFile}from"node:fs/promises";import{isAbsolute,join}from"node:path";var DISK_READ=/\bfrom\s*["'](?:node:)?(?:fs|fs\/promises|child_process)["']|\brequire\s*\(\s*["'](?:node:)?(?:fs|fs\/promises|child_process)["']|\bBun\.(?:file|Glob|spawn)/,NON_LITERAL_IMPORT=/\b(?:import|require|vi\.(?:mock|doMock|unmock|importActual|importMock))\s*(?:<[^>]*>)?\(\s*(?!["'][^"'`$]*["']\s*[,)])/,GLOB_CALL=/\bimport\.meta\.glob/,QUOTED_CAUSE=/"([^"]+)"/,LOADS=/\b(?:import|export|from|require|mock|doMock|unmock|importActual|importMock)\b|\b(?:src|href)\s*=/,GOTO_CALL=/\bgoto\s*\(/;function lineAt(source,index){let line=1;for(let i=source.indexOf(`
3
3
  `);i!==-1&&i<index;i=source.indexOf(`
4
4
  `,i+1))line++;return line}function lineOf(source,needle){let index=typeof needle==="string"?source.indexOf(needle):source.search(needle);return index===-1?void 0:lineAt(source,index)}function commentRanges(source){let ranges=[];for(let i=0;i<source.length;i++){let c=source[i];if(c==='"'||c==="'"){while(++i<source.length&&source[i]!==c&&source[i]!==`
5
5
  `)if(source[i]==="\\")i++}else if(c==="`"){while(++i<source.length&&source[i]!=="`")if(source[i]==="\\")i++}else if(source.startsWith("//",i)){let end=source.indexOf(`
6
6
  `,i);ranges.push([i,end===-1?source.length:end]),i=end===-1?source.length:end}else if(source.startsWith("/*",i)||source.startsWith("<!--",i)){let close=c==="/"?"*/":"-->",end=source.indexOf(close,i+2),stop=end===-1?source.length:end+close.length;ranges.push([i,stop]),i=stop-1}}return ranges}function lineTextAt(source,index){let start=source.lastIndexOf(`
7
7
  `,index-1)+1,end=source.indexOf(`
8
- `,index);return source.slice(start,end===-1?source.length:end)}function bestLine(source,needles,near){let comments,inComment=(index)=>(comments??=commentRanges(source),comments.some(([start,end])=>index>=start&&index<end)),code,any;for(let needle of needles)for(let index=source.indexOf(needle);index!==-1;index=source.indexOf(needle,index+1)){if(any??=index,inComment(index))continue;if(near===void 0||near.test(lineTextAt(source,index)))return lineAt(source,index);code??=index}let found=code??any;return found===void 0?void 0:lineAt(source,found)}function specifierLine(source,specifier){let quoted=['"',"'","`"].map((quote)=>`${quote}${specifier}${quote}`);return bestLine(source,quoted,LOADS)??bestLine(source,[specifier])}function gotoLine(source,argument,page){return(argument===void 0?void 0:bestLine(source,[argument],GOTO_CALL))??bestLine(source,[page.slice(page.lastIndexOf("/")+1)],GOTO_CALL)}function callLine(source,call){return bestLine(source,[call])}function causeLine(source,cause){if(cause.startsWith("unresolved ")){let specifier=QUOTED_CAUSE.exec(cause)?.[1];return specifier===void 0?void 0:specifierLine(source,specifier)}if(cause==="non-literal dynamic import")return lineOf(source,NON_LITERAL_IMPORT);if(cause==="non-literal glob import")return lineOf(source,GLOB_CALL);if(cause==="reads the disk without @depends-on")return lineOf(source,DISK_READ);if(cause.startsWith("non-literal goto("))return lineOf(source,cause.slice(12,-1));let url=QUOTED_CAUSE.exec(cause)?.[1];return url===void 0?void 0:lineOf(source,url)}function textLine(source,text){return lineOf(source,text)}function annotationLine(source,tag,glob){let index=source.split(`
8
+ `,index);return source.slice(start,end===-1?source.length:end)}function bestLine(source,needles,near){let comments,inComment=(index)=>(comments??=commentRanges(source),comments.some(([start,end])=>index>=start&&index<end)),code,any;for(let needle of needles)for(let index=source.indexOf(needle);index!==-1;index=source.indexOf(needle,index+1)){if(any??=index,inComment(index))continue;if(near===void 0||near.test(lineTextAt(source,index)))return lineAt(source,index);code??=index}let found=code??any;return found===void 0?void 0:lineAt(source,found)}function specifierLine(source,specifier){let quoted=['"',"'","`"].map((quote)=>`${quote}${specifier}${quote}`);return bestLine(source,quoted,LOADS)??bestLine(source,[specifier])}function gotoLine(source,argument,page){return(argument===void 0?void 0:bestLine(source,[argument],GOTO_CALL))??bestLine(source,[page.slice(page.lastIndexOf("/")+1)],GOTO_CALL)}function callLine(source,call){return bestLine(source,[call])}function causeLine(source,cause){if(cause.startsWith("unresolved ")){let specifier=QUOTED_CAUSE.exec(cause)?.[1];return specifier===void 0?void 0:specifierLine(source,specifier)}if(cause==="non-literal dynamic import")return lineOf(source,NON_LITERAL_IMPORT);if(cause==="non-literal glob import")return lineOf(source,GLOB_CALL);if(cause===UNDECLARED_READS)return lineOf(source,DISK_READ);if(cause.startsWith("non-literal goto("))return lineOf(source,cause.slice(12,-1));let url=QUOTED_CAUSE.exec(cause)?.[1];return url===void 0?void 0:lineOf(source,url)}function textLine(source,text){return lineOf(source,text)}function annotationLine(source,tag,glob){let index=source.split(`
9
9
  `).findIndex((line)=>line.includes(tag)&&line.includes(glob));return index===-1?void 0:index+1}function lineText(source,line){let start=0;for(let n=1;n<line;n++){let next=source.indexOf(`
10
10
  `,start);if(next===-1)return"";start=next+1}let end=source.indexOf(`
11
- `,start);return source.slice(start,end===-1?source.length:end).trim()}async function sourceOf(root,file){try{return await readFile(isAbsolute(file)?file:join(root,file),"utf-8")}catch{return}}function fileOf(node){let hash=node.indexOf("#");return hash===-1?node:node.slice(0,hash)}async function causesOf(root,computed,node){let file=fileOf(node),source=await sourceOf(root,file);return(computed.graph.get(node)?.unknown??[]).map((cause)=>{if(source===void 0)return{cause};let line=causeLine(source,cause);return line===void 0?{cause}:{cause,at:`${file}:${line}`,text:lineText(source,line)}})}var EXAMPLES=3,TAGS={"depends-on":"@depends-on",reads:"@reads",glob:"import.meta.glob",edges:"edges"},QUOTED=/"([^"]+)"/;function fixFor(cause){if(cause.startsWith("unresolved ")){let specifier=QUOTED.exec(cause)?.[1]??"";if(specifier.startsWith("./%sveltekit.assets%/"))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";if(specifier.startsWith("."))return"no file at that path: fix the import, or add an `edges` entry if a build generates it";if(specifier.startsWith("#"))return"map it in the `imports` of the file's package.json, or with `alias`";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`"}if(cause==="non-literal dynamic import")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";if(cause==="non-literal glob import")return"pass `import.meta.glob` literal patterns";if(cause==="reads the disk without @depends-on")return"name what it reads: `// @depends-on <glob>`, or `// @reads <glob>` for files read as text; list the file in `hermetic` if it reads no file of the repository";if(cause.startsWith("non-literal goto("))return"pass `goto()` a literal URL, or a template whose path before `?` or `#` is literal";if(cause.startsWith("missing fixture "))return"no page at that URL: fix the URL, or the suite's `urls`";if(cause.startsWith("goto("))return"map the URL to a file with the suite's `urls`";return"see the cause"}function declaredGlobs(node,extraction){let relative=finish(node,extraction).globs;return[...extraction.dependsOn.map((glob)=>({kind:"depends-on",glob,pattern:globToRegExp(glob)})),...extraction.reads.map((glob)=>({kind:"reads",glob,pattern:globToRegExp(glob)})),...extraction.globs.map((glob,i)=>({kind:"glob",glob,pattern:globToRegExp(relative[i])}))]}function problemOf(matches,ignored){if(matches===0)return"matches nothing";if(ignored===0)return;return ignored===matches?"matches only ignored files":"partly ignored"}function deadOf(node,kind,glob,patterns,listed,skipped){let matches=listed.filter((file)=>patterns.some((re)=>re.test(file))),ignored=sorted(matches.filter(skipped)),problem=problemOf(matches.length,ignored.length);if(problem===void 0)return;return{node,kind,glob,problem,matches:matches.length,ignored:ignored.length,examples:ignored.slice(0,EXAMPLES),fix:problem==="matches nothing"?"fix the path":"point it at files the selector reads, or allowlist it in `deadGlobs` with a reason"}}function configDeadGlobs(config,{graph,listed},skipped){let file=config.file??"the config",found=[],entries=[...config.generated.map((map)=>["edges",map]),...config.reads.map((map)=>["reads",map])];for(let[kind,map]of entries){let patterns=map.values.map(()=>new Map),matched=!1;for(let node of graph.keys()){let targets=map.targets(node);if(!targets)continue;matched=!0;for(let[i,re]of targets.entries())patterns[i]?.set(re.source,re)}if(!matched){found.push({node:file,kind,glob:map.key,problem:"matches nothing",matches:0,ignored:0,examples:[],fix:"fix the path: no file the graph reads matches it"});continue}for(let[i,glob]of map.values.entries()){let expanded=[...patterns[i]?.values()??[]],dead=deadOf(file,kind,glob,expanded,listed,skipped);if(dead)found.push(dead)}}return found}async function findDeadGlobs(root,config,computed){let{graph,extractions,listed}=computed,skipped=(file)=>config.isIgnored(file)&&!graph.has(file),found=[];for(let node of graph.keys()){let extraction=extractions.get(node);if(!extraction)continue;for(let{kind,glob,pattern}of declaredGlobs(node,extraction)){let dead=deadOf(node,kind,glob,[pattern],listed,skipped);if(dead)found.push(dead)}}let configured=configDeadGlobs(config,computed,skipped),nodes=[...new Set([...found.map(({node})=>node),...configured.map(({node})=>node)])],texts=await Promise.all(nodes.map((node)=>sourceOf(root,node))),sources=new Map(nodes.map((node,i)=>[node,texts[i]])),locate=(dead,line)=>{let source=sources.get(dead.node),at=source===void 0?void 0:line(source);return at===void 0?dead:{...dead,at:`${dead.node}:${at}`}};return[...found.map((dead)=>locate(dead,(source)=>dead.kind==="glob"?specifierLine(source,dead.glob):annotationLine(source,TAGS[dead.kind],dead.glob))),...configured.map((dead)=>locate(dead,(source)=>specifierLine(source,dead.glob)))]}async function check(root,config,computed){let nodes=[...computed.graph].filter(([,deps])=>deps.unknown.length>0).map(([node])=>node),isTest=(node)=>config.suites.some((suite)=>suite.isTest(node)),unknown=await Promise.all(nodes.map(async(node)=>({node,causes:(await causesOf(root,computed,node)).map(({cause,at})=>at===void 0?{cause,fix:fixFor(cause)}:{cause,at,fix:fixFor(cause)}),tests:sorted([...affectedBy(computed.graph,[node],{includeUnknown:!1,readers:!1})].filter(isTest))}))),fallbacks=[...computed.fallbacks].map(([file,reason])=>({file,reason})),dead=await findDeadGlobs(root,config,computed),allows=(entry,found)=>entry.file===found.node&&entry.glob===found.glob;return{unknown,fallbacks,unparsedTsconfigs:computed.unparsedTsconfigs,deadGlobs:dead.filter((found)=>!config.deadGlobs.some((entry)=>allows(entry,found))),staleDeadGlobs:config.deadGlobs.filter((entry)=>!dead.some((found)=>allows(entry,found))).map((entry)=>({...entry,fix:"remove the entry: its glob is no longer dead"}))}}function summary({problem,matches,ignored,examples}){if(problem==="matches nothing")return problem;let shown=[...examples,...ignored>examples.length?["…"]:[]],count=problem==="partly ignored"?`${ignored} of ${matches}`:`${ignored}`;return`${problem} (${count}: ${shown.join(", ")})`}function widening(report){return report.unknown.filter((node)=>node.tests.length>0)}function pushUnknown(lines,{node,causes,tests}){lines.push(node);for(let{cause,at,fix}of causes)lines.push(` ✗ ${cause}${at?` ${at}`:""}`,` fix: ${fix}`);if(tests.length>0){let more=tests.length>3?`, and ${tests.length-3} more`:"";lines.push(` runs on any change: ${tests.slice(0,3).join(", ")}${more}`)}}function formatReport(report,max){let lines=[],widen=widening(report);for(let unknown of widen)pushUnknown(lines,unknown);let idle=report.unknown.filter((node)=>node.tests.length===0);if(idle.length>0){lines.push("","Unknown, but no test depends on them, so they widen nothing:");for(let unknown of idle)pushUnknown(lines,unknown)}if(report.fallbacks.length>0){lines.push("","Read by the regex extractor, which the lexer couldn't read:");for(let{file,reason}of report.fallbacks)lines.push(` ${file}: ${reason}`)}if(report.unparsedTsconfigs.length>0){lines.push("","tsconfig files that don't parse, whose `paths` are ignored:");for(let{file,reason}of report.unparsedTsconfigs)lines.push(` ${file}: ${reason}`)}if(report.deadGlobs.length>0){lines.push("","Dead globs: a change to what they match, or to some of it, selects nothing:");let node;for(let dead of report.deadGlobs){if(dead.node!==node)lines.push(` ${dead.node}`);node=dead.node,lines.push(` ✗ ${dead.kind} ${dead.glob}: ${summary(dead)}${dead.at?` ${dead.at}`:""}`,` fix: ${dead.fix}`)}}if(report.staleDeadGlobs.length>0){lines.push("","`deadGlobs` entries that match no dead glob:");for(let{file,glob,fix}of report.staleDeadGlobs)lines.push(` ${file}: ${glob}`,` fix: ${fix}`)}let count=widen.length,limit=max===void 0?"":` (at most ${max})`;if(lines.push("",`${count} ${count===1?"node":"nodes"} with unknown dependencies ${count===1?"reaches":"reach"} a test${limit}: each such test runs on any change.`),idle.length>0)lines.push(`${idle.length} more no test reaches.`);let dead=report.deadGlobs.length,stale=report.staleDeadGlobs.length;if(dead>0)lines.push(`${dead} dead ${dead===1?"glob":"globs"} not in \`deadGlobs\`.`);if(stale>0)lines.push(`${stale} stale \`deadGlobs\` ${stale===1?"entry":"entries"}.`);return lines.join(`
12
- `).trimStart()}var CONFIG_EDGES="edges in the config",CONFIG_READS="reads in the config";async function edgeAt(context,node,via){if(via.kind==="edges")return{at:CONFIG_EDGES};if(via.kind==="unknown")return{};let file=fileOf(node),source=SCANNED.test(file)?await sourceOf(context.root,file):void 0,configured=(maps)=>maps.some((map)=>map.targets(node)?.some((re)=>re.test(via.from)));if(via.kind==="reads"&&configured(context.config.reads)){if(!(source!==void 0&&extract(formatOf(file),source).reads.some((glob)=>globToRegExp(glob).test(via.from))))return{at:CONFIG_READS}}if(source===void 0)return{};let line=edgeLine(context,node,via,source);return line===void 0?{}:{at:`${file}:${line}`,text:lineText(source,line)}}function edgeLine({config,resolve},node,via,source){let file=fileOf(node),extraction=extract(formatOf(file),source),matches=(glob)=>globToRegExp(glob).test(via.from);if(via.kind==="reads"||via.kind==="depends-on"){let tag=`@${via.kind}`,glob=(via.kind==="reads"?extraction.reads:extraction.dependsOn).find(matches);return(glob===void 0?void 0:annotationLine(source,tag,glob))??textLine(source,tag)}if(via.kind==="glob"){let relative=finish(file,extraction).globs,glob=extraction.globs.find((_,i)=>matches(relative[i]));return(glob===void 0?void 0:specifierLine(source,glob))??callLine(source,"import.meta.glob")}let target=fileOf(via.from);if(via.kind==="goto"){let argument=extraction.gotos.find((candidate)=>gotoPage(config,file,candidate)===target);return gotoLine(source,argument,target)}let loads=(specifier)=>{let resolved=resolve(file,specifier);return resolved!==void 0&&"files"in resolved&&resolved.files.includes(target)};if(via.kind==="export"){let barrel=extraction.barrel;if(!barrel)return;let own=barrel.names.get(node.slice(node.indexOf("#")+1)),specifier=[...own===void 0?[]:[own],...barrel.names.values(),...barrel.stars].find(loads);return specifier===void 0?void 0:specifierLine(source,specifier)}let imported=extraction.imports.find(({specifier})=>loads(specifier));return imported===void 0?void 0:specifierLine(source,imported.specifier)}function rootCause(computed,rootNode,from){if(from!==void 0)return"given";if(computed.changed.includes(rootNode))return"changed";let bumped=computed.plan.packageCauses.get(rootNode);if(bumped!==void 0)return bumped;if(computed.barrelNames.includes(rootNode))return"barrel name moved";for(let{narrower,result}of computed.narrowed)if("seeds"in result&&result.seeds.includes(rootNode))return`seeded by the ${narrower.name} narrower`;return"changed"}function walks(computed,suite,from){let{plan,graph}=computed;if(from!==void 0)return[{seeds:[from],opaque:void 0}];let narrowings=plan.narrowings.get(suite);if(!narrowings)return[{seeds:plan.seeds,opaque:void 0}];let matched=new Set(narrowings.flatMap((narrowing)=>narrowing.matched));return[{seeds:plan.seeds.filter((seed)=>!matched.has(seed)),opaque:void 0},...narrowings.map((narrowing)=>({seeds:[...narrowing.matched,...narrowing.seeds].filter((seed)=>graph.has(seed)||computed.changed.includes(seed)),opaque:narrowing.narrower.opaque}))]}function shortestChain(computed,candidates,test){for(let walk of candidates){let parents=new Map;if(!affectedBy(computed.graph,walk.seeds,{opaque:walk.opaque,parents}).has(test))continue;let edges=[],node=test;for(let via=parents.get(node);via;via=parents.get(node))if(edges.push([node,via]),node=via.from,via.kind==="unknown")break;return{edges,root:node}}return}function reachers(computed,candidates,test,except){let found=new Set;for(let{seeds,opaque}of candidates)for(let seed of seeds){if(seed===except||found.has(seed))continue;if(affectedBy(computed.graph,[seed],{opaque}).has(test))found.add(seed)}return sorted(found)}async function chainOf(context,{edges,root},from){let last=edges.at(-1),[links,causes]=await Promise.all([Promise.all(edges.map(async([node,via])=>({node,kind:via.kind,...await edgeAt(context,node,via)}))),last?.[1].kind==="unknown"?causesOf(context.root,context.computed,last[0]):[]]);return{links,root,cause:rootCause(context.computed,root,from),unknown:causes.map((cause)=>({...cause,fix:fixFor(cause.cause)}))}}function unselected(config,computed,suite,from){let changed=computed.changed.length;if(from===void 0)return{kind:"unselected",suite,changed};let reached=sorted(affectedBy(computed.graph,[from],{includeUnknown:!1})),reaches={},example;for(let{name,isTest}of config.suites){let tests=reached.filter((node)=>isTest(node));if(tests.length===0)continue;if(reaches[name]=tests.length,name===suite||example===void 0)example=tests[0]}return{kind:"unselected",suite,from,changed,reaches,...example!==void 0&&{example}}}async function explain(root,config,computed,test,from,{all=!1}={}){let suite=config.suites.find((candidate)=>candidate.isTest(test));if(!suite)throw Error(`bivium why: ${test} is no suite's test`);if(!computed.graph.has(test))throw Error(`bivium why: no file ${test}`);if(from===void 0&&computed.plan.full.includes(suite.name))return{kind:"full",suite:suite.name,reasons:computed.plan.reasons};let candidates=walks(computed,suite.name,from),found=shortestChain(computed,candidates,test);if(!found)return unselected(config,computed,suite.name,from);let context={root,config,computed,resolve:createResolver({files:new Set(computed.graph.keys()),config,packages:computed.packages,tsconfigs:computed.tsconfigs})},everything=found.edges.at(-1)?.[1].kind==="unknown",more=from!==void 0||everything?[]:reachers(computed,candidates,test,found.root),[chain,others]=await Promise.all([chainOf(context,found,from),Promise.all((all?more:[]).map((seed)=>{let alone=candidates.map((walk)=>({...walk,seeds:walk.seeds.filter((candidate)=>candidate===seed)})),other=shortestChain(computed,alone,test);return other&&chainOf(context,other,void 0)}))]);return{kind:"chain",suite:suite.name,test,...chain,more,others:others.filter((other)=>other!==void 0)}}var FORMATS=["tree","chain","source"];function isFormat(value){return FORMATS.some((format)=>format===value)}var VERBS={import:"imported by",goto:"opened by",html:"loaded by page",name:"imported by",glob:"globbed by","depends-on":"depended on by",edges:"an input of",reads:"read as text by",unknown:"depends on every change"},LIST=3;function plural(count,one,many){return`${count} ${count===1?one:many}`}function nameOf(node){return node.slice(node.indexOf("#")+1)}function aligned(rows){let width=Math.max(0,...rows.filter(([,at])=>at!==void 0).map(([text])=>text.length));return rows.map(([text,at])=>at===void 0?text:`${text.padEnd(width)} ${at}`)}function tree(test,chain){let rows=[[test,void 0]],width=Math.max(0,...chain.links.filter((link)=>link.kind!=="unknown").map((link)=>link.kind.length)),indent="";for(let[i,link]of chain.links.entries()){let next=chain.links[i+1]?.node??chain.root;if(link.kind==="unknown"){rows.push([`${indent}└─ depends on every change:`,void 0]);for(let{cause,at}of chain.unknown)rows.push([`${indent} ✗ ${cause}`,at]);indent+=" ",rows.push([`${indent}└─ ${next}`,void 0]),indent+=" ";break}rows.push([`${indent}└─ ${link.kind.padEnd(width)} ${next}`,link.at]),indent+=" "}return rows.push([`${indent}● ${chain.cause}`,void 0]),aligned(rows)}function verbOf(link){return link.kind==="export"?`exported as ${nameOf(link.node)}`:VERBS[link.kind]}function whereOf(link){if(link.kind==="edges")return`${link.node} (${CONFIG_EDGES})`;return link.at??link.node}function steps(links){let rows=[...links].reverse().map((link)=>[verbOf(link),whereOf(link)]),width=Math.max(0,...rows.map(([verb])=>verb.length));return rows.map(([verb,where],i)=>`${verb.padEnd(width)} ${where}${i===rows.length-1?" ← selected":""}`)}function header({root,cause}){if(cause==="changed")return`${root} changed`;if(cause==="given")return`if ${root} changes`;return`${root}: ${cause}`}function chained(test,chain){let unknownAt=chain.links.findIndex((link)=>link.kind==="unknown");if(unknownAt===-1)return[header(chain),...steps(chain.links).map((step)=>` ${step}`)];let node=chain.links[unknownAt].node,where=chain.unknown.map(({at})=>at??node),width=Math.max(0,...where.map((at)=>at.length)),lines=[`${test} runs on every change`];for(let[i,{cause,fix}]of chain.unknown.entries())lines.push(` because ${where[i].padEnd(width)} ${cause}`,` fix: ${fix}`);if(unknownAt>0)lines.push(` reached via ${node}`,...steps(chain.links.slice(0,unknownAt)).map((step)=>` ${step}`));return lines}var LINE_NUMBER=/:(\d+)$/;function lineNumber(at){return at===void 0?void 0:LINE_NUMBER.exec(at)?.[1]}function sourced(test,chain){let unknownAt=chain.links.findIndex((link)=>link.kind==="unknown"),hops=unknownAt===-1?chain.links:chain.links.slice(0,unknownAt),numbers=[...chain.links,...chain.unknown].map(({at})=>lineNumber(at)),width=Math.max(0,...numbers.map((n)=>n?.length??0)),gutter=" ".repeat(width),cited=(at,text)=>{let n=lineNumber(at);return n===void 0||text===void 0?[]:[`${n.padStart(width)} | ${text}`]},count=plural(hops.length,"hop","hops"),lines=unknownAt===-1?[`selected: ${test} ← ${chain.root} (${count}${chain.cause==="changed"?"":`, ${chain.cause}`})`]:[`selected: ${test} ← every change (${unknownAt===0?"its dependencies can't be read":`${count} to ${chain.links[unknownAt].node}, whose dependencies can't be read`})`];lines.push("");for(let link of hops){let where=link.kind==="edges"?link.node:link.at??link.node,kind=link.kind==="edges"?CONFIG_EDGES:link.kind;lines.push(`${gutter}--> ${where} ${kind}`,...cited(link.at,link.text))}if(unknownAt===-1)return lines.push(`${gutter}● ${chain.root}: ${chain.cause}`),lines;let node=chain.links[unknownAt].node;for(let{cause,at,text,fix}of chain.unknown)lines.push(`${gutter}✗ ${at??node} ${cause}`,...cited(at,text),`${gutter} = fix: ${fix}`);return lines}var RENDER={tree,chain:chained,source:sourced};function moreLine(more,all){let shown=more.slice(0,LIST).join(", "),rest=more.length>LIST?", …":"";return`+ ${plural(more.length,"more change reaches","more changes reach")} this test: ${shown}${rest}${all?"":" (--all shows each chain)"}`}function unselectedMessage(explanation){let{from,changed,reaches,example}=explanation;if(from===void 0)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.`;let counts=Object.entries(reaches??{}).map(([suite,count])=>`${count} ${suite}`),total=Object.values(reaches??{}).reduce((a,b)=>a+b,0);return[`Not selected by a change to ${from}: no chain reaches it.`,total===0?"Its chains reach no test.":`Its chains reach ${plural(total,"test","tests")} (${counts.join(", ")}), such as ${example}.`].join(`
11
+ `,start);return source.slice(start,end===-1?source.length:end).trim()}async function sourceOf(root,file){try{return await readFile(isAbsolute(file)?file:join(root,file),"utf-8")}catch{return}}function fileOf(node){let hash=node.indexOf("#");return hash===-1?node:node.slice(0,hash)}async function causesOf(root,computed,node){let file=fileOf(node),source=await sourceOf(root,file);return(computed.graph.get(node)?.unknown??[]).map((cause)=>{if(source===void 0)return{cause};let line=causeLine(source,cause);return line===void 0?{cause}:{cause,at:`${file}:${line}`,text:lineText(source,line)}})}var EXAMPLES=3,TAGS={"depends-on":"@depends-on",reads:"@reads",lists:"@lists",glob:"import.meta.glob",edges:"edges",setup:"setup"},QUOTED=/"([^"]+)"/;function fixFor(cause){if(cause.startsWith("unresolved ")){let specifier=QUOTED.exec(cause)?.[1]??"";if(specifier.startsWith("./%sveltekit.assets%/"))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";if(RELATIVE.test(specifier))return"no file at that path: fix the import, or add an `edges` entry if a build generates it";if(specifier.startsWith("#"))return"map it in the `imports` of the file's package.json, or with `alias`";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`"}if(cause.startsWith("only declarations for "))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";if(cause==="non-literal dynamic import")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";if(cause==="non-literal glob import")return"pass `import.meta.glob` literal patterns";if(cause===UNDECLARED_READS)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";if(cause.startsWith("non-literal goto("))return"pass `goto()` a literal URL, or a template whose path before `?` or `#` is literal";if(cause.startsWith("missing fixture "))return"no page at that URL: fix the URL, or the suite's `urls`";if(cause.startsWith("goto("))return"map the URL to a file with the suite's `urls`";return"see the cause"}function isFile(path){return statSync(path,{throwIfNoEntry:!1})?.isFile()??!1}function stemOf(path){let slash=path.lastIndexOf("/"),dot=path.indexOf(".",slash+2);return dot===-1?path:path.slice(0,dot)}function nearMisses(root,config,{graph,listed}){let stems,listedSet=new Set(listed),siblings=(path)=>{if(!stems){stems=new Map;for(let file of listed){let stem=stemOf(file),list=stems.get(stem);list?list.push(file):stems.set(stem,[file])}}return stems.get(stemOf(path))??[]},candidates=(base)=>[base,...config.extensions.map((ext)=>base+ext),...config.extensions.map((ext)=>`${base}/index${ext}`)];return(node,cause)=>{if(!cause.startsWith("unresolved "))return;let specifier=(QUOTED.exec(cause)?.[1]??"").replace(QUERY,""),base=RELATIVE.test(specifier)?posix.join(posix.dirname(fileOf(node)),specifier):config.alias.map((alias)=>aliasPath(alias,specifier)).find((path)=>path!==void 0);if(base===void 0||base.startsWith("../"))return;let tried=candidates(base),outside=tried.find((path)=>listedSet.has(path)&&!graph.has(path));if(outside!==void 0)return`${outside} exists, but outside \`roots\`: add it to \`roots\``;let unlisted=tried.find((path)=>isFile(join2(root,path)));if(unlisted!==void 0&&!listedSet.has(unlisted))return`${unlisted} exists, but git doesn't list it (ignored?): if a build writes it, name it in \`edges\` with its inputs`;let sibling=siblings(base).find((file)=>graph.has(file));if(sibling!==void 0)return`${sibling} exists: import it by that name, or add its extension to \`extensions\``;return}}function declaredGlobs(node,extraction){let relative=finish(node,extraction).globs;return[...extraction.dependsOn.map((glob)=>({kind:"depends-on",glob,pattern:globToRegExp(glob)})),...extraction.reads.map((glob)=>({kind:"reads",glob,pattern:globToRegExp(glob)})),...extraction.lists.map((glob)=>({kind:"lists",glob,pattern:globToRegExp(glob)})),...extraction.globs.map((glob,i)=>({kind:"glob",glob,pattern:globToRegExp(relative[i])}))]}function problemOf(matches,ignored){if(matches===0)return"matches nothing";if(ignored===0)return;return ignored===matches?"matches only ignored files":"partly ignored"}function deadOf(node,kind,glob,patterns,listed,skipped){let matches=listed.filter((file)=>patterns.some((re)=>re.test(file))),ignored=sorted(matches.filter(skipped)),problem=problemOf(matches.length,ignored.length);if(problem===void 0)return;return{node,kind,glob,problem,matches:matches.length,ignored:ignored.length,examples:ignored.slice(0,EXAMPLES),fix:problem==="matches nothing"?"fix the path":"point it at files the selector reads, or allowlist it in `deadGlobs` with a reason"}}function configDeadGlobs(config,{graph,listed},skipped){let file=config.file??"the config",found=[],entries=[...config.generated.map((map)=>["edges",map]),...config.reads.map((map)=>["reads",map])];for(let[kind,map]of entries){let patterns=map.values.map(()=>new Map),matched=!1;for(let node of graph.keys()){let targets=map.targets(node);if(!targets)continue;matched=!0;for(let[i,re]of targets.entries())patterns[i]?.set(re.source,re)}if(!matched){found.push({node:file,kind,glob:map.key,problem:"matches nothing",matches:0,ignored:0,examples:[],fix:"fix the path: no file the graph reads matches it"});continue}for(let[i,glob]of map.values.entries()){let expanded=[...patterns[i]?.values()??[]],dead=deadOf(file,kind,glob,expanded,listed,skipped);if(dead)found.push(dead)}}for(let suite of config.suites)for(let glob of suite.setup){let pattern=globToRegExp(glob),dead=deadOf(file,"setup",glob,[pattern],listed,skipped);if(dead)found.push(dead)}return found}async function findDeadGlobs(root,config,computed){let{graph,extractions,listed}=computed,skipped=(file)=>config.isIgnored(file)&&!graph.has(file),found=[];for(let node of graph.keys()){let extraction=extractions.get(node);if(!extraction)continue;for(let{kind,glob,pattern}of declaredGlobs(node,extraction)){let dead=deadOf(node,kind,glob,[pattern],listed,skipped);if(dead)found.push(dead)}}let configured=configDeadGlobs(config,computed,skipped),nodes=[...new Set([...found.map(({node})=>node),...configured.map(({node})=>node)])],texts=await Promise.all(nodes.map((node)=>sourceOf(root,node))),sources=new Map(nodes.map((node,i)=>[node,texts[i]])),locate=(dead,line)=>{let source=sources.get(dead.node),at=source===void 0?void 0:line(source);return at===void 0?dead:{...dead,at:`${dead.node}:${at}`}};return[...found.map((dead)=>locate(dead,(source)=>dead.kind==="glob"?specifierLine(source,dead.glob):annotationLine(source,TAGS[dead.kind],dead.glob))),...configured.map((dead)=>locate(dead,(source)=>specifierLine(source,dead.glob)))]}async function check(root,config,computed){let nodes=[...computed.graph].filter(([,deps])=>deps.unknown.length>0).map(([node])=>node),testsOf=(node)=>{let reach=walksByTypes(computed.graph,[node],{includeUnknown:!1,readers:!1}),found=new Set;for(let suite of config.suites)for(let test of reach(suite.types))if(suite.isTest(test))found.add(test);return sorted(found)},nearMiss=nearMisses(root,config,computed),known=new Map((config.knownUnknowns??[]).map((entry)=>[entry.file,entry.reason])),unknown=await Promise.all(nodes.map(async(node)=>{let causes=(await causesOf(root,computed,node)).map(({cause,at})=>{let fix=nearMiss(node,cause)??fixFor(cause);return at===void 0?{cause,fix}:{cause,at,fix}}),reason=known.get(node),entry={node,causes,tests:testsOf(node)};if(reason!==void 0)entry.known=reason;return entry})),fallbacks=[...computed.fallbacks].map(([file,reason])=>({file,reason})),dead=await findDeadGlobs(root,config,computed),allows=(entry,found)=>entry.file===found.node&&entry.glob===found.glob;return{unknown,fallbacks,unparsedTsconfigs:computed.unparsedTsconfigs,deadGlobs:dead.filter((found)=>!config.deadGlobs.some((entry)=>allows(entry,found))),unlistedUnknowns:config.knownUnknowns?unknown.filter((entry)=>entry.tests.length>0&&entry.known===void 0).map((entry)=>entry.node):[],staleKnownUnknowns:(config.knownUnknowns??[]).filter((entry)=>!nodes.includes(entry.file)).map((entry)=>({...entry,fix:"remove the entry: its dependencies are known now"})),staleDeadGlobs:config.deadGlobs.filter((entry)=>!dead.some((found)=>allows(entry,found))).map((entry)=>({...entry,fix:"remove the entry: its glob is no longer dead"}))}}function summary({problem,matches,ignored,examples}){if(problem==="matches nothing")return problem;let shown=[...examples,...ignored>examples.length?["…"]:[]],count=problem==="partly ignored"?`${ignored} of ${matches}`:`${ignored}`;return`${problem} (${count}: ${shown.join(", ")})`}function widening(report){return report.unknown.filter((node)=>node.tests.length>0)}function failed(report,max){return max!==void 0&&widening(report).length>max||report.unlistedUnknowns.length>0||report.staleKnownUnknowns.length>0||report.deadGlobs.length>0||report.staleDeadGlobs.length>0}function pushUnknown(lines,{node,causes,tests,known}){lines.push(known===void 0?node:`${node} (known: ${known})`);for(let{cause,at,fix}of causes)lines.push(` ✗ ${cause}${at?` ${at}`:""}`,` fix: ${fix}`);if(tests.length>0){let more=tests.length>3?`, and ${tests.length-3} more`:"";lines.push(` runs on any change: ${tests.slice(0,3).join(", ")}${more}`)}}function categoryOf(cause){if(cause.startsWith("unresolved ")){let specifier=QUOTED.exec(cause)?.[1]??"";if(RELATIVE.test(specifier))return"unresolved relative import";if(specifier.startsWith("#"))return"unresolved # import";return"unresolved bare import (a package, alias or path)"}if(cause.startsWith("only declarations for "))return"a .js import with only its declarations there";if(cause.startsWith("non-literal goto("))return"non-literal goto()";if(cause.startsWith("goto("))return"goto() URL no `urls` pattern maps";if(cause.startsWith("missing fixture "))return"goto() of a missing page";return cause}var POSITION=/(?: in <>)? at \d+.*$/,BLANK_LINES=/\n{3,}/g;function counted(counts){return[...counts].sort(([a,x],[b,y])=>y-x||(a<b?-1:1)).map(([what,count])=>`${count} ${what}`)}function summaryLines(report){let widen=widening(report),lines=[];if(widen.length>0){let tests=new Set(widen.flatMap((node)=>node.tests));lines.push(`${plural(widen.length,"node")} with unknown dependencies ${widen.length===1?"reaches":"reach"} ${plural(tests.size,"test")}, which ${tests.size===1?"runs":"run"} on any change:`);let causes=new Map;for(let node of widen)for(let category of new Set(node.causes.map(({cause})=>categoryOf(cause))))causes.set(category,(causes.get(category)??0)+1);lines.push(...counted(causes).map((line)=>` ${line}`))}let idle=report.unknown.length-widen.length;if(idle>0)lines.push(`${plural(idle,"more node")} with unknown dependencies no test reaches`);if(report.fallbacks.length>0){let reasons=new Map;for(let{reason}of report.fallbacks){let what=reason.replace(POSITION,"");reasons.set(what,(reasons.get(what)??0)+1)}lines.push(`${plural(report.fallbacks.length,"file")} read by the regex extractor: ${counted(reasons).join(", ")}`)}let problems=[[report.unparsedTsconfigs.length,"tsconfig file that doesn't parse","tsconfig files that don't parse"],[report.deadGlobs.length,"dead glob","dead globs"],[report.staleDeadGlobs.length,"stale `deadGlobs` entry","stale `deadGlobs` entries"],[report.unlistedUnknowns.length,"unknown not in `knownUnknowns`","unknowns not in `knownUnknowns`"],[report.staleKnownUnknowns.length,"stale `knownUnknowns` entry","stale `knownUnknowns` entries"]];for(let[count,one,many]of problems)if(count>0)lines.push(plural(count,one,many));return lines.length===0?[]:["Summary:",...lines.map((line)=>` ${line}`),""]}function plural(count,one,many=`${one}s`){return`${count} ${count===1?one:many}`}function formatReport(report,max){let lines=summaryLines(report),widen=widening(report);for(let unknown of widen)pushUnknown(lines,unknown);let idle=report.unknown.filter((node)=>node.tests.length===0);if(idle.length>0){lines.push("","Unknown, but no test depends on them, so they widen nothing:");for(let unknown of idle)pushUnknown(lines,unknown)}if(report.fallbacks.length>0){lines.push("","Read by the regex extractor, which the lexer couldn't read:");for(let{file,reason}of report.fallbacks)lines.push(` ${file}: ${reason}`)}if(report.unparsedTsconfigs.length>0){lines.push("","tsconfig files that don't parse, whose `paths` are ignored:");for(let{file,reason}of report.unparsedTsconfigs)lines.push(` ${file}: ${reason}`)}if(report.deadGlobs.length>0){lines.push("","Dead globs: a change to what they match, or to some of it, selects nothing:");let node;for(let dead of report.deadGlobs){if(dead.node!==node)lines.push(` ${dead.node}`);node=dead.node,lines.push(` ✗ ${dead.kind} ${dead.glob}: ${summary(dead)}${dead.at?` ${dead.at}`:""}`,` fix: ${dead.fix}`)}}if(report.staleDeadGlobs.length>0){lines.push("","`deadGlobs` entries that match no dead glob:");for(let{file,glob,fix}of report.staleDeadGlobs)lines.push(` ${file}: ${glob}`,` fix: ${fix}`)}if(report.staleKnownUnknowns.length>0){lines.push("","`knownUnknowns` entries whose dependencies are known:");for(let{file,fix}of report.staleKnownUnknowns)lines.push(` ${file}`,` fix: ${fix}`)}let count=widen.length,limit=max===void 0?"":` (at most ${max})`;lines.push("",`${count} ${count===1?"node":"nodes"} with unknown dependencies ${count===1?"reaches":"reach"} a test${limit}: each such test runs on any change.`);let unlisted=report.unlistedUnknowns.length;if(unlisted>0)lines.push(`${unlisted} of them not in \`knownUnknowns\`: fix ${unlisted===1?"it":"them"}, or list ${unlisted===1?"it":"them"} with a reason.`);if(idle.length>0)lines.push(`${idle.length} more no test reaches.`);let staleKnown=report.staleKnownUnknowns.length;if(staleKnown>0)lines.push(`${plural(staleKnown,"stale `knownUnknowns` entry","stale `knownUnknowns` entries")}.`);let dead=report.deadGlobs.length,stale=report.staleDeadGlobs.length;if(dead>0)lines.push(`${plural(dead,"dead glob")} not in \`deadGlobs\`.`);if(stale>0)lines.push(`${plural(stale,"stale `deadGlobs` entry","stale `deadGlobs` entries")}.`);return lines.join(`
12
+ `).replace(BLANK_LINES,`
13
+
14
+ `).trimStart()}function fanIn(graph,suite){let ids=new Map,nodes=[...graph.keys()];for(let[i,node]of nodes.entries())ids.set(node,i);let matches=new Map,matching=(re)=>{let found=matches.get(re.source);if(!found){found=[];for(let[i,node]of nodes.entries())if(re.test(node))found.push(i);matches.set(re.source,found)}return found},forward=[],direct=[];for(let node of nodes){let deps=graph.get(node),out=[],read=[];if(deps){for(let file of deps.files){if(!suite.types&&deps.types?.has(file))continue;let id=ids.get(file);if(id!==void 0)out.push(id)}for(let re of deps.patterns)out.push(...matching(re));for(let re of[...deps.reads,...deps.lists??[]])read.push(...matching(re))}forward.push(out),direct.push(read)}let counts=new Uint32Array(nodes.length),stamp=new Int32Array(nodes.length).fill(-1),stack=[];for(let[t,test]of nodes.entries()){if(!suite.isTest(test))continue;let reached=[],visit=(id)=>{if(stamp[id]===t)return;stamp[id]=t,reached.push(id)};visit(t),stack.push(t);while(stack.length>0){let at=stack.pop()??0;for(let next of forward[at]){if(stamp[next]===t)continue;visit(next),stack.push(next)}}for(let id of[...reached])for(let read of direct[id])visit(read);for(let id of reached)counts[id]++}let result=new Map;for(let[i,node]of nodes.entries())result.set(node,counts[i]);return result}function graphReport(graph,suites){let counts=suites.map((suite)=>[suite.name,fanIn(graph,suite)]),unknown=[...graph].filter(([,deps])=>deps.unknown.length>0).map(([node])=>node),everyChange=walksByTypes(graph,unknown,{includeUnknown:!1,readers:!1});return{suites:Object.fromEntries(suites.map((suite)=>[suite.name,{total:[...graph.keys()].filter(suite.isTest).length,everyChange:sorted(everyChange(suite.types)).filter(suite.isTest)}])),nodes:[...graph].map(([node,deps])=>({node,imports:sorted(deps.files),importers:sorted(importersOf(graph,node)),fanIn:Object.fromEntries(counts.map(([name,count])=>[name,count.get(node)??0])),unknown:deps.unknown.length>0}))}}function buckets(total){let list=[[0,0],[1,1]];for(let low=2,high=10;low<total;low=high+1,high*=10)list.push([low,Math.min(high,total-1)]);if(total>1)list.push([total,total]);return list}function formatGraph(report,top){let lines=[],files=report.nodes.filter(({node})=>!node.startsWith("pkg:")&&!node.includes("#"));for(let[name,{total:tests,everyChange}]of Object.entries(report.suites)){let any=everyChange.length;lines.push(`${name}: ${plural(tests,"test")}${any>0?`; ${any} run on any change (\`bivium check\` says why)`:""}`);let 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)),width=Math.max(String(tests).length,5);if(ranked.length>0){lines.push(` ${"tests".padStart(width)} file`);for(let[id,count]of ranked.slice(0,top))lines.push(` ${String(count).padStart(width)} ${id}`);if(ranked.length>top)lines.push(` … ${ranked.length-top} more (--top <n> shows more)`)}lines.push(` files by how many ${name} tests a change to one selects:`);let rows=buckets(tests).map(([low,high])=>{let label=low===high?String(low):`${low}–${high}`,count=files.filter(({fanIn:reach})=>{let n=reach[name]??0;return n>=low&&n<=high}).length;return[label,count]}),labelWidth=Math.max(...rows.map(([label])=>label.length));for(let[label,count]of rows)lines.push(` ${label.padStart(labelWidth)} ${count}`)}return lines.join(`
15
+ `)}var CONFIG_EDGES="edges in the config",CONFIG_SETUP="setup in the config",CONFIGURED={edges:CONFIG_EDGES,setup:CONFIG_SETUP},CONFIG_READS="reads in the config";async function edgeAt(context,node,via){let spelled=CONFIGURED[via.kind];if(spelled!==void 0)return{at:spelled};if(via.kind==="unknown")return{};let file=fileOf(node),source=SCANNED.test(file)?await sourceOf(context.root,file):void 0,configured=(maps)=>maps.some((map)=>map.targets(node)?.some((re)=>re.test(via.from)));if(via.kind==="reads"&&configured(context.config.reads)){if(!(source!==void 0&&extract(formatOf(file),source).reads.some((glob)=>globToRegExp(glob).test(via.from))))return{at:CONFIG_READS}}if(source===void 0)return{};let line=edgeLine(context,node,via,source);return line===void 0?{}:{at:`${file}:${line}`,text:lineText(source,line)}}function edgeLine({config,resolve},node,via,source){let file=fileOf(node),extraction=extract(formatOf(file),source),matches=(glob)=>globToRegExp(glob).test(via.from);if(via.kind==="reads"||via.kind==="depends-on"||via.kind==="lists"){let tag=`@${via.kind}`,glob={reads:extraction.reads,"depends-on":extraction.dependsOn,lists:extraction.lists}[via.kind].find(matches);return(glob===void 0?void 0:annotationLine(source,tag,glob))??textLine(source,tag)}if(via.kind==="glob"){let relative=finish(file,extraction).globs,glob=extraction.globs.find((_,i)=>matches(relative[i]));return(glob===void 0?void 0:specifierLine(source,glob))??callLine(source,"import.meta.glob")}let target=fileOf(via.from);if(via.kind==="goto"){let argument=extraction.gotos.find((candidate)=>gotoPage(config,file,candidate)===target);return gotoLine(source,argument,target)}let loads=(specifier)=>{let resolved=resolve(file,specifier);return resolved!==void 0&&"files"in resolved&&resolved.files.includes(target)};if(via.kind==="export"){let barrel=extraction.barrel;if(!barrel)return;let own=barrel.names.get(node.slice(node.indexOf("#")+1)),specifier=[...own===void 0?[]:[own],...barrel.names.values(),...barrel.stars].find(loads);return specifier===void 0?void 0:specifierLine(source,specifier)}let imported=extraction.imports.find(({specifier})=>loads(specifier));return imported===void 0?void 0:specifierLine(source,imported.specifier)}function rootCause(computed,rootNode,from){if(from!==void 0)return"given";if(computed.changed.includes(rootNode))return"changed";let bumped=computed.plan.packageCauses.get(rootNode);if(bumped!==void 0)return bumped;if(computed.barrelNames.includes(rootNode))return"barrel name moved";for(let{narrower,result}of computed.narrowed)if("seeds"in result&&result.seeds.includes(rootNode))return`seeded by the ${narrower.name} narrower`;return"changed"}function walks(computed,{name,types},from){let{plan,graph}=computed;if(from!==void 0)return[{seeds:[from],opaque:void 0,types}];let{quiet,layout}=plan,narrowings=plan.narrowings.get(name);if(!narrowings)return[{seeds:plan.seeds,quiet,layout,opaque:void 0,types}];let matched=new Set(narrowings.flatMap((narrowing)=>narrowing.matched));return[{seeds:plan.seeds.filter((seed)=>!matched.has(seed)),quiet,layout,opaque:void 0,types},...narrowings.map((narrowing)=>({seeds:[...narrowing.matched,...narrowing.seeds].filter((seed)=>graph.has(seed)||computed.changed.includes(seed)),opaque:narrowing.narrower.opaque,layout,types}))]}function shortestChain(computed,candidates,test){for(let{seeds,...options}of candidates){let parents=new Map;if(!affectedBy(computed.graph,seeds,{...options,parents}).has(test))continue;let edges=[],node=test;for(let via=parents.get(node);via;via=parents.get(node))if(edges.push([node,via]),node=via.from,via.kind==="unknown")break;return{edges,root:node}}return}function reachers(computed,candidates,test,except){let found=new Set,unseen=(seed)=>seed!==except&&!found.has(seed);for(let{seeds,quiet=[],...options}of candidates){for(let seed of seeds.filter(unseen))if(affectedBy(computed.graph,[seed],options).has(test))found.add(seed);for(let seed of quiet.filter(unseen))if(affectedBy(computed.graph,[],{...options,quiet:[seed]}).has(test))found.add(seed)}return sorted(found)}async function chainOf(context,{edges,root},from){let last=edges.at(-1),[links,causes]=await Promise.all([Promise.all(edges.map(async([node,via])=>({node,kind:via.kind,...await edgeAt(context,node,via)}))),last?.[1].kind==="unknown"?causesOf(context.root,context.computed,last[0]):[]]);return{links,root,cause:rootCause(context.computed,root,from),unknown:causes.map((cause)=>({...cause,fix:fixFor(cause.cause)}))}}function unselected(config,computed,suite,from){let changed=computed.changed.length;if(from===void 0)return{kind:"unselected",suite,changed};let reachedBy=walksByTypes(computed.graph,[from],{includeUnknown:!1}),reaches={},example;for(let{name,isTest,types}of config.suites){let tests=sorted(reachedBy(types)).filter((node)=>isTest(node));if(tests.length===0)continue;if(reaches[name]=tests.length,name===suite||example===void 0)example=tests[0]}return{kind:"unselected",suite,from,changed,reaches,...example!==void 0&&{example}}}async function explain(root,config,computed,test,from,{all=!1}={}){let suite=config.suites.find((candidate)=>candidate.isTest(test));if(!suite)throw Error(`bivium why: ${test} is no suite's test`);if(!computed.graph.has(test))throw Error(`bivium why: no file ${test}`);if(from===void 0&&computed.plan.full.includes(suite.name))return{kind:"full",suite:suite.name,reasons:computed.plan.reasons};let candidates=walks(computed,suite,from),found=shortestChain(computed,candidates,test);if(!found)return unselected(config,computed,suite.name,from);let context={root,config,computed,resolve:createResolver({files:new Set(computed.graph.keys()),config,packages:computed.packages,tsconfigs:computed.tsconfigs})},everything=found.edges.at(-1)?.[1].kind==="unknown",more=from!==void 0||everything?[]:reachers(computed,candidates,test,found.root),[chain,others]=await Promise.all([chainOf(context,found,from),Promise.all((all?more:[]).map((seed)=>{let alone=candidates.map((walk)=>({...walk,seeds:walk.seeds.filter((candidate)=>candidate===seed),quiet:walk.quiet?.filter((candidate)=>candidate===seed)})),other=shortestChain(computed,alone,test);return other&&chainOf(context,other,void 0)}))]);return{kind:"chain",suite:suite.name,test,...chain,more,others:others.filter((other)=>other!==void 0)}}var FORMATS=["tree","chain","source"];function isFormat(value){return FORMATS.some((format)=>format===value)}var VERBS={import:"imported by",type:"type-imported by",setup:"a setup file of",goto:"opened by",html:"loaded by page",name:"imported by",glob:"globbed by","depends-on":"depended on by",edges:"an input of",reads:"read as text by",lists:"listed by",unknown:"depends on every change"},LIST=3;function nameOf(node){return node.slice(node.indexOf("#")+1)}function aligned(rows){let width=Math.max(0,...rows.filter(([,at])=>at!==void 0).map(([text])=>text.length));return rows.map(([text,at])=>at===void 0?text:`${text.padEnd(width)} ${at}`)}function tree(test,chain){let rows=[[test,void 0]],width=Math.max(0,...chain.links.filter((link)=>link.kind!=="unknown").map((link)=>link.kind.length)),indent="";for(let[i,link]of chain.links.entries()){let next=chain.links[i+1]?.node??chain.root;if(link.kind==="unknown"){rows.push([`${indent}└─ depends on every change:`,void 0]);for(let{cause,at}of chain.unknown)rows.push([`${indent} ✗ ${cause}`,at]);indent+=" ",rows.push([`${indent}└─ ${next}`,void 0]),indent+=" ";break}rows.push([`${indent}└─ ${link.kind.padEnd(width)} ${next}`,link.at]),indent+=" "}return rows.push([`${indent}● ${chain.cause}`,void 0]),aligned(rows)}function verbOf(link){return link.kind==="export"?`exported as ${nameOf(link.node)}`:VERBS[link.kind]}function whereOf(link){let configured=CONFIGURED[link.kind];if(configured!==void 0)return`${link.node} (${configured})`;return link.at??link.node}function steps(links){let rows=[...links].reverse().map((link)=>[verbOf(link),whereOf(link)]),width=Math.max(0,...rows.map(([verb])=>verb.length));return rows.map(([verb,where],i)=>`${verb.padEnd(width)} ${where}${i===rows.length-1?" ← selected":""}`)}function header({root,cause}){if(cause==="changed")return`${root} changed`;if(cause==="given")return`if ${root} changes`;return`${root}: ${cause}`}function chained(test,chain){let unknownAt=chain.links.findIndex((link)=>link.kind==="unknown");if(unknownAt===-1)return[header(chain),...steps(chain.links).map((step)=>` ${step}`)];let node=chain.links[unknownAt].node,where=chain.unknown.map(({at})=>at??node),width=Math.max(0,...where.map((at)=>at.length)),lines=[`${test} runs on every change`];for(let[i,{cause,fix}]of chain.unknown.entries())lines.push(` because ${where[i].padEnd(width)} ${cause}`,` fix: ${fix}`);if(unknownAt>0)lines.push(` reached via ${node}`,...steps(chain.links.slice(0,unknownAt)).map((step)=>` ${step}`));return lines}var LINE_NUMBER=/:(\d+)$/;function lineNumber(at){return at===void 0?void 0:LINE_NUMBER.exec(at)?.[1]}function sourced(test,chain){let unknownAt=chain.links.findIndex((link)=>link.kind==="unknown"),hops=unknownAt===-1?chain.links:chain.links.slice(0,unknownAt),numbers=[...chain.links,...chain.unknown].map(({at})=>lineNumber(at)),width=Math.max(0,...numbers.map((n)=>n?.length??0)),gutter=" ".repeat(width),cited=(at,text)=>{let n=lineNumber(at);return n===void 0||text===void 0?[]:[`${n.padStart(width)} | ${text}`]},count=plural(hops.length,"hop","hops"),lines=unknownAt===-1?[`selected: ${test} ← ${chain.root} (${count}${chain.cause==="changed"?"":`, ${chain.cause}`})`]:[`selected: ${test} ← every change (${unknownAt===0?"its dependencies can't be read":`${count} to ${chain.links[unknownAt].node}, whose dependencies can't be read`})`];lines.push("");for(let link of hops){let configured=CONFIGURED[link.kind],where=configured===void 0?link.at??link.node:link.node,kind=configured??link.kind;lines.push(`${gutter}--> ${where} ${kind}`,...cited(link.at,link.text))}if(unknownAt===-1)return lines.push(`${gutter}● ${chain.root}: ${chain.cause}`),lines;let node=chain.links[unknownAt].node;for(let{cause,at,text,fix}of chain.unknown)lines.push(`${gutter}✗ ${at??node} ${cause}`,...cited(at,text),`${gutter} = fix: ${fix}`);return lines}var RENDER={tree,chain:chained,source:sourced};function moreLine(more,all){let shown=more.slice(0,LIST).join(", "),rest=more.length>LIST?", …":"";return`+ ${plural(more.length,"more change reaches","more changes reach")} this test: ${shown}${rest}${all?"":" (--all shows each chain)"}`}function unselectedMessage(explanation){let{from,changed,reaches,example}=explanation;if(from===void 0)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.`;let counts=Object.entries(reaches??{}).map(([suite,count])=>`${count} ${suite}`),total=Object.values(reaches??{}).reduce((a,b)=>a+b,0);return[`Not selected by a change to ${from}: no chain reaches it.`,total===0?"Its chains reach no test.":`Its chains reach ${plural(total,"test","tests")} (${counts.join(", ")}), such as ${example}.`].join(`
13
16
  `)}function formatExplanation(explanation,format="tree"){if(explanation.kind==="full")return[`The ${explanation.suite} suite runs in full:`,...explanation.reasons.map((reason)=>` ${reason}`)].join(`
14
17
  `);if(explanation.kind==="unselected")return unselectedMessage(explanation);let{test,more,others}=explanation,render=RENDER[format],lines=render(test,explanation);if(more.length>0)lines.push(moreLine(more,others.length>0));for(let other of others)lines.push("",...render(test,other));return lines.join(`
15
18
  `)}var USAGE=`Usage:
16
19
  bivium plan [base] [--json] [--github] print the tests a change can affect
17
20
  bivium run [base] [--suite <name>] run a suite's selected tests
18
21
  bivium why <test> [file] [--base <ref>] the chain from a change (or file) to a test
19
- [--format <f>] [--all]
20
- bivium check [--max-unknown <n>] what the graph can't read, and dead globs
22
+ [--format <f>] [--all] [--json]
23
+ bivium check [--max-unknown <n>] [--json]
24
+ what the graph can't read, and dead globs
25
+ bivium graph [--suite <name>] [--top <n>] [--json]
26
+ each file's test fan-in, and the graph
21
27
  bivium --version print the version
28
+ bivium --help print this
22
29
 
23
30
  base defaults to the config's base, else the upstream default branch.
31
+ Options go before or after the command.
24
32
 
25
33
  Options:
26
34
  --config <file> config file (default: bivium.config.{ts,mts,mjs,js,json})
27
35
  --cwd <dir> repository (default: the current directory)
28
36
  --no-cache read every file; don't read or write the extraction cache
29
- --suite <name> for run: the suite (default: the first one)
30
- --json for plan: print the plan as JSON, with its reasons
37
+ --suite <name> for run: the suite (default: the first one); for graph:
38
+ only this suite (default: every one)
39
+ --json for plan, why, check and graph: print JSON
31
40
  --github for plan: also write each suite's selection to
32
41
  $GITHUB_OUTPUT as <output>=all|none|<files>
33
42
  --base <ref> for why and check: the base ref
34
43
  --format <f> for why: tree (default), chain (from the change to the
35
- test) or source (each hop's line of source)
44
+ test), source (each hop's line of source) or json
36
45
  --all for why: every change's chain to the test, not only the
37
46
  shortest
38
47
  --max-unknown <n> for check: fail when more unknown nodes than this reach
39
- a test`,WHITESPACE=/\s+/,VALUED=new Set(["--config","--cwd","--suite","--base","--format","--max-unknown"]),COMMON=["--config","--cwd","--no-cache"],FLAGS={plan:[...COMMON,"--json","--github"],run:[...COMMON,"--suite"],why:[...COMMON,"--base","--json","--format","--all"],check:[...COMMON,"--base","--max-unknown","--json"]},POSITIONAL={plan:1,run:1,why:2,check:0};function parseArgs(command,argv){let known=FLAGS[command]??[],flags=new Map,positional=[];for(let i=0;i<argv.length;i++){let arg=argv[i];if(!arg.startsWith("--")){positional.push(arg);continue}if(!known.includes(arg))throw Error(`bivium ${command}: unknown option ${arg}`);if(!VALUED.has(arg)){flags.set(arg,"");continue}let value=argv[++i];if(value===void 0||value.startsWith("--"))throw Error(`bivium: ${arg} needs a value`);flags.set(arg,value)}if(positional.length>(POSITIONAL[command]??0))throw Error(`bivium ${command}: unexpected ${positional.at(-1)}`);return{flags,positional}}function commandFor(run,files){let words=run.split(WHITESPACE).filter(Boolean),at=words.indexOf("{files}");if(at===-1)return[...words,...files];return[...words.slice(0,at),...files,...words.slice(at+1)]}function logSelection(label,selection){let count=selection.mode==="some"?`${selection.files.length} files`:selection.mode;if(console.log(`${label}: ${count}`),selection.mode==="some")for(let file of selection.files)console.log(` ${file}`)}function logPlan({plan,narrowed}){for(let reason of plan.reasons)console.log(`Full run: ${reason}`);for(let line of plan.packages)console.log(line);for(let{narrower,result}of narrowed)if("note"in result&&result.note)console.log(`${narrower.name}: ${result.note}`);for(let[name,selection]of Object.entries(plan.suites))logSelection(`${name} tests`,selection)}function writeOutputs(config,{plan}){let output=process.env.GITHUB_OUTPUT;if(!output)throw Error("bivium: GITHUB_OUTPUT is not set");let lines=config.suites.map((suite)=>`${suite.output}=${formatSelection(plan.suites[suite.name])}
40
- `);appendFileSync(output,lines.join(""))}async function inspect(command,{flags,positional}){let format=flags.get("--format")??"tree";if(!isFormat(format))throw Error("bivium why: --format takes tree, chain or source");let{root,base,config}=await prepare({cwd:flags.get("--cwd"),base:flags.get("--base")??(command==="check"?"HEAD":void 0),configFile:flags.get("--config")}),computed=await computePlan(root,base,config,{...flags.has("--no-cache")&&{cache:!1}});if(command==="check"){let maxFlag=flags.get("--max-unknown"),max=maxFlag===void 0?void 0:Number(maxFlag);if(max!==void 0&&!Number.isInteger(max))throw Error("bivium check: --max-unknown takes a whole number");let report=await check(root,config,computed);return console.log(flags.has("--json")?JSON.stringify(report,null,2):formatReport(report,max)),max!==void 0&&widening(report).length>max||report.deadGlobs.length>0||report.staleDeadGlobs.length>0?1:0}let[test,file]=positional;if(test===void 0)throw Error("bivium why: which test?");let explanation=await explain(root,config,computed,test,file,{all:flags.has("--all")});return console.log(flags.has("--json")?JSON.stringify(explanation,null,2):formatExplanation(explanation,format)),0}async function runCommand(command,{flags,positional}){let{root,base,config}=await prepare({cwd:flags.get("--cwd"),base:positional[0],configFile:flags.get("--config")}),suiteName=flags.get("--suite"),suite=suiteName===void 0?config.suites[0]:config.suites.find((candidate)=>candidate.name===suiteName);if(!suite)return console.error(`bivium: no suite "${suiteName}"`),1;let computed=await computePlan(root,base,config,{...flags.has("--no-cache")&&{cache:!1},...command==="run"&&{suites:[suite.name]}});if(command==="plan"){if(flags.has("--json")){let{suites,reasons,packages}=computed.plan,narrowed=computed.narrowed.map((ran)=>({name:ran.narrower.name,result:ran.result}));console.log(JSON.stringify({base,mergeBase:computed.mergeBase,changed:computed.changed,suites,reasons,packages,narrowed},null,2))}else logPlan(computed);if(flags.has("--github"))writeOutputs(config,computed);return 0}if(logPlan(computed),!suite.run)return console.error(`bivium: suite "${suite.name}" has no run command`),1;let selection=computed.plan.suites[suite.name];if(selection.mode==="none")return console.log(`No ${suite.name} tests affected against ${base}; skipping.`),0;let[program,...args]=commandFor(suite.run,selection.mode==="some"?selection.files:[]);return spawnSync(program,args,{cwd:root,stdio:"inherit"}).status??1}async function main(argv){let[command,...rest]=argv;if(command==="--version"||command==="-v")return console.log(version),0;if(!command||command==="help"||rest.includes("--help"))return console.log(USAGE),command?0:1;if(!(command in FLAGS))return console.error(`bivium: unknown command "${command}"
48
+ a test
49
+ --top <n> for graph: how many files to list per suite (default: 10)
50
+
51
+ Exit status: 0 done; 1 check found problems; 2 a usage or configuration
52
+ error. run exits with its command's status.
53
+
54
+ Examples:
55
+ bivium plan origin/main --json
56
+ bivium why tests/Button.test.ts src/Button.svelte --format chain
57
+ bivium check --json`,WHITESPACE=/\s+/,VALUED=new Set(["--config","--cwd","--suite","--base","--format","--max-unknown","--top"]),COMMON=["--config","--cwd","--no-cache"],FLAGS={plan:[...COMMON,"--json","--github"],run:[...COMMON,"--suite"],why:[...COMMON,"--base","--json","--format","--all"],check:[...COMMON,"--base","--max-unknown","--json"],graph:[...COMMON,"--suite","--top","--json"]},POSITIONAL={plan:1,run:1,why:2,check:0,graph:0};function parseArgs(command,argv){let known=FLAGS[command]??[],flags=new Map,positional=[];for(let i=0;i<argv.length;i++){let arg=argv[i];if(!arg.startsWith("--")){positional.push(arg);continue}if(!known.includes(arg))throw Error(`bivium ${command}: unknown option ${arg}`);if(!VALUED.has(arg)){flags.set(arg,"");continue}let value=argv[++i];if(value===void 0||value.startsWith("--"))throw Error(`bivium: ${arg} needs a value`);flags.set(arg,value)}if(positional.length>(POSITIONAL[command]??0))throw Error(`bivium ${command}: unexpected ${positional.at(-1)}`);return{flags,positional}}function commandFor(run,files){let words=run.split(WHITESPACE).filter(Boolean),at=words.indexOf("{files}");if(at===-1)return[...words,...files];return[...words.slice(0,at),...files,...words.slice(at+1)]}function logSelection(label,selection,total,forced){let files=total===1?"file":"files",count;if(selection.mode==="some")count=`${selection.files.length} of ${total} ${files}`;else if(selection.mode==="none")count="none";else if(forced)count="all (full run)";else count=`all ${total} ${files} (each reaches a change)`;if(console.log(`${label}: ${count}`),selection.mode==="some")for(let file of selection.files)console.log(` ${file}`)}function logPlan({plan,narrowed}){for(let reason of plan.reasons)console.log(`Full run: ${reason}`);for(let line of plan.packages)console.log(line);for(let{narrower,result}of narrowed)if("note"in result&&result.note)console.log(`${narrower.name}: ${result.note}`);for(let[name,selection]of Object.entries(plan.suites)){let total=plan.totals[name]??0;logSelection(`${name} tests`,selection,total,plan.full.includes(name))}}function writeOutputs(config,{plan}){let output=process.env.GITHUB_OUTPUT;if(!output)throw Error("bivium: GITHUB_OUTPUT is not set");let lines=config.suites.map((suite)=>`${suite.output}=${formatSelection(plan.suites[suite.name])}
58
+ `);appendFileSync(output,lines.join(""))}async function inspect(command,{flags,positional}){let format=flags.get("--format")??"tree";if(format!=="json"&&!isFormat(format))throw Error("bivium why: --format takes tree, chain, source or json");let{root,base,config}=await prepare({cwd:flags.get("--cwd"),base:flags.get("--base")??(command==="check"?"HEAD":void 0),configFile:flags.get("--config")}),computed=await computePlan(root,base,config,{...flags.has("--no-cache")&&{cache:!1}});if(command==="check"){let maxFlag=flags.get("--max-unknown"),max=maxFlag===void 0?void 0:Number(maxFlag);if(max!==void 0&&!Number.isInteger(max))throw Error("bivium check: --max-unknown takes a whole number");let report=await check(root,config,computed);return console.log(flags.has("--json")?JSON.stringify(report,null,2):formatReport(report,max)),failed(report,max)?1:0}let[test,file]=positional;if(test===void 0)throw Error("bivium why: which test?");let explanation=await explain(root,config,computed,test,file,{all:flags.has("--all")});return console.log(flags.has("--json")||format==="json"?JSON.stringify(explanation,null,2):formatExplanation(explanation,format)),0}async function graphCommand({flags}){let top=Number(flags.get("--top")??"10");if(!Number.isInteger(top)||top<0)throw Error("bivium graph: --top takes a whole number");let{root,base,config}=await prepare({cwd:flags.get("--cwd"),base:"HEAD",configFile:flags.get("--config")}),name=flags.get("--suite"),suites=name===void 0?config.suites:config.suites.filter((suite)=>suite.name===name);if(suites.length===0)throw Error(`bivium: no suite "${name}"`);let{graph}=await computePlan(root,base,config,{...flags.has("--no-cache")&&{cache:!1}}),report=graphReport(graph,suites);return console.log(flags.has("--json")?JSON.stringify(report,null,2):formatGraph(report,top)),0}async function runCommand(command,{flags,positional}){let{root,base,config}=await prepare({cwd:flags.get("--cwd"),base:positional[0],configFile:flags.get("--config")}),suiteName=flags.get("--suite"),suite=suiteName===void 0?config.suites[0]:config.suites.find((candidate)=>candidate.name===suiteName);if(!suite)throw Error(`bivium: no suite "${suiteName}"`);let computed=await computePlan(root,base,config,{...flags.has("--no-cache")&&{cache:!1},...command==="run"&&{suites:[suite.name]},mergeBase:command==="plan"&&flags.has("--json")});if(command==="plan"){if(flags.has("--json")){let{suites,reasons,causes,totals,packages}=computed.plan,narrowed=computed.narrowed.map((ran)=>({name:ran.narrower.name,result:ran.result}));console.log(JSON.stringify({base,mergeBase:await computed.mergeBase(),changed:computed.changed,suites,reasons,causes,totals,packages,narrowed},null,2))}else logPlan(computed);if(flags.has("--github"))writeOutputs(config,computed);return 0}if(logPlan(computed),!suite.run)throw Error(`bivium: suite "${suite.name}" has no run command`);let selection=computed.plan.suites[suite.name];if(selection.mode==="none")return console.log(`No ${suite.name} tests affected against ${base}; skipping.`),0;let[program,...args]=commandFor(suite.run,selection.mode==="some"?selection.files:[]);return spawnSync(program,args,{cwd:root,stdio:"inherit"}).status??1}function commandAt(argv){for(let i=0;i<argv.length;i++){let arg=argv[i];if(!arg.startsWith("-"))return i;if(VALUED.has(arg))i++}return-1}async function main(argv){if(argv.includes("--help")||argv.includes("-h"))return console.log(USAGE),0;if(argv.includes("--version")||argv.includes("-v"))return console.log(version),0;let at=commandAt(argv),command=at===-1?void 0:argv[at];if(command==="help")return console.log(USAGE),0;if(command===void 0){let first=argv[0],why=first===void 0?"":`unknown option ${first}
59
+
60
+ `;return console.error(`bivium: ${why}${USAGE}`),2}if(!(command in FLAGS))return console.error(`bivium: unknown command "${command}"
41
61
 
42
- ${USAGE}`),1;try{let args=parseArgs(command,rest);if(command==="why"||command==="check")return await inspect(command,args);return await runCommand(command,args)}catch(error){return console.error(error instanceof Error?error.message:String(error)),2}}process.exitCode=await main(process.argv.slice(2));
62
+ ${USAGE}`),2;let rest=[...argv.slice(0,at),...argv.slice(at+1)];try{let args=parseArgs(command,rest);if(command==="why"||command==="check")return await inspect(command,args);if(command==="graph")return await graphCommand(args);return await runCommand(command,args)}catch(error){return console.error(error instanceof Error?error.message:String(error)),2}}process.exitCode=await main(process.argv.slice(2));