bivium 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -328,7 +328,7 @@ With `--json`, an error is also printed to stdout as JSON,
328
328
  so a pipeline that parses stdout gets an object either way:
329
329
 
330
330
  ```json
331
- { "schemaVersion": 1, "error": { "kind": "git", "message": "bivium: no commit nosuchref here to diff against: fetch it." } }
331
+ { "schemaVersion": 1, "error": { "kind": "git", "code": "BV_GIT_NO_BASE", "message": "bivium: no commit nosuchref here to diff against: fetch it." } }
332
332
  ```
333
333
 
334
334
  `kind` is `usage` (bivium was called wrong),
@@ -337,6 +337,11 @@ so a pipeline that parses stdout gets an object either way:
337
337
  lists every unknown key at once), `git`
338
338
  (the base or its history is missing, or git refused, in its own words)
339
339
  or `other`.
340
+ `code` names the failure, such as `BV_UNKNOWN_OPTION`
341
+ or `BV_CONFIG_INVALID`, and never changes meaning:
342
+ the `BiviumErrorCode` type lists them all, each with what it means.
343
+ From the library, `plan()` throws a `BiviumError` with the same `code`
344
+ and `kind`.
340
345
 
341
346
  ### From an agent
342
347
 
@@ -349,7 +354,7 @@ or `other`.
349
354
  - `bivium check --json` gives `ok` and a `summary` of what widens plans,
350
355
  then each node with a `fix`.
351
356
  - Read the exit status first: 0 done, 1 `check` found problems,
352
- 2 an error, with `error.kind` in the JSON.
357
+ 2 an error, with `error.kind` and `error.code` in the JSON.
353
358
 
354
359
  `why` names each edge by what spells it:
355
360
  `import`, `type`
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  version,
4
- BiviumError,
4
+ githubOutputPath,
5
+ BiviumError2,
5
6
  didYouMean,
6
7
  globToRegExp,
7
8
  inRoot,
@@ -100,26 +101,33 @@ function fanIn(graph, suite) {
100
101
  };
101
102
  visit(t);
102
103
  stack.push(t);
103
- while (stack.length > 0) {
104
- const at = stack.pop() ?? 0;
105
- for (const next of forward[at]) {
104
+ for (let at = stack.pop();at !== undefined; at = stack.pop()) {
105
+ for (const next of byId(forward, at)) {
106
106
  if (stamp[next] === t)
107
107
  continue;
108
108
  visit(next);
109
109
  stack.push(next);
110
110
  }
111
111
  }
112
- for (const id of [...reached])
113
- for (const read of direct[id])
112
+ for (const id of [...reached]) {
113
+ for (const read of byId(direct, id))
114
114
  visit(read);
115
+ }
115
116
  for (const id of reached)
116
- counts[id]++;
117
+ counts[id] = byId(counts, id) + 1;
117
118
  }
118
119
  const result = new Map;
119
120
  for (const [i, node] of nodes.entries())
120
- result.set(node, counts[i]);
121
+ result.set(node, byId(counts, i));
121
122
  return result;
122
123
  }
124
+ function byId(list, id) {
125
+ const value = list[id];
126
+ if (value === undefined) {
127
+ throw new Error(`bivium: fanin: no node with id ${id}.`);
128
+ }
129
+ return value;
130
+ }
123
131
  function graphReport(graph, suites) {
124
132
  const counts = suites.map((suite) => [suite.name, fanIn(graph, suite)]);
125
133
  const unknown = [...graph].filter(([, deps]) => deps.unknown.length > 0).map(([node]) => node);
@@ -584,11 +592,13 @@ function declaredGlobs(node, extraction) {
584
592
  glob,
585
593
  pattern: globToRegExp(glob)
586
594
  })),
587
- ...extraction.globs.map((glob, i) => ({
588
- kind: "glob",
589
- glob,
590
- pattern: globToRegExp(relative[i])
591
- }))
595
+ ...extraction.globs.map((glob, i) => {
596
+ const path = relative[i];
597
+ if (path === undefined) {
598
+ throw new Error(`bivium: check: no resolved path for glob ${glob}.`);
599
+ }
600
+ return { kind: "glob", glob, pattern: globToRegExp(path) };
601
+ })
592
602
  ];
593
603
  }
594
604
  function problemOf(matches, ignored) {
@@ -1088,7 +1098,7 @@ function edgeLine({ config, resolve }, node, via, source) {
1088
1098
  }
1089
1099
  if (via.kind === "glob") {
1090
1100
  const relative = finish(file, extraction).globs;
1091
- const glob = extraction.globs.find((_, i) => matches(relative[i]));
1101
+ const glob = extraction.globs[relative.findIndex(matches)];
1092
1102
  return (glob === undefined ? undefined : specifierLine(source, glob)) ?? callLine(source, "import.meta.glob");
1093
1103
  }
1094
1104
  const target = fileOf(via.from);
@@ -1138,11 +1148,11 @@ function rootCause(computed, rootNode, from) {
1138
1148
  function walks(computed, { name, types }, from) {
1139
1149
  const { plan, graph } = computed;
1140
1150
  if (from !== undefined)
1141
- return [{ seeds: [from], opaque: undefined, types }];
1151
+ return [{ seeds: [from], types }];
1142
1152
  const { quiet, layout } = plan;
1143
1153
  const narrowings = plan.narrowings.get(name);
1144
1154
  if (!narrowings) {
1145
- return [{ seeds: plan.seeds, quiet, layout, opaque: undefined, types }];
1155
+ return [{ seeds: plan.seeds, quiet, layout, types }];
1146
1156
  }
1147
1157
  const matched = new Set(narrowings.flatMap((narrowing) => narrowing.matched));
1148
1158
  return [
@@ -1150,7 +1160,6 @@ function walks(computed, { name, types }, from) {
1150
1160
  seeds: plan.seeds.filter((seed) => !matched.has(seed)),
1151
1161
  quiet,
1152
1162
  layout,
1153
- opaque: undefined,
1154
1163
  types
1155
1164
  },
1156
1165
  ...narrowings.map((narrowing) => ({
@@ -1244,10 +1253,12 @@ function unselected(config, computed, suite, from) {
1244
1253
  }
1245
1254
  async function explain(root, config, computed, test, from, { all = false } = {}) {
1246
1255
  const suite = config.suites.find((candidate) => candidate.isTest(test));
1247
- if (!suite)
1248
- throw new Error(`bivium why: ${test} is no suite's test`);
1249
- if (!computed.graph.has(test))
1250
- throw new Error(`bivium why: no file ${test}`);
1256
+ if (!suite) {
1257
+ throw new BiviumError2("BV_UNKNOWN_TEST", `bivium why: ${test} is no suite's test`);
1258
+ }
1259
+ if (!computed.graph.has(test)) {
1260
+ throw new BiviumError2("BV_UNKNOWN_FILE", `bivium why: no file ${test}`);
1261
+ }
1251
1262
  if (from === undefined && computed.plan.full.includes(suite.name)) {
1252
1263
  return { kind: "full", suite: suite.name, reasons: computed.plan.reasons };
1253
1264
  }
@@ -1274,10 +1285,12 @@ async function explain(root, config, computed, test, from, { all = false } = {})
1274
1285
  const alone = candidates.map((walk) => ({
1275
1286
  ...walk,
1276
1287
  seeds: walk.seeds.filter((candidate) => candidate === seed),
1277
- quiet: walk.quiet?.filter((candidate) => candidate === seed)
1288
+ ...walk.quiet && {
1289
+ quiet: walk.quiet.filter((candidate) => candidate === seed)
1290
+ }
1278
1291
  }));
1279
1292
  const other = shortestChain(computed, alone, test);
1280
- return other && chainOf(context, other, undefined);
1293
+ return other === undefined ? Promise.resolve(undefined) : chainOf(context, other, undefined);
1281
1294
  }))
1282
1295
  ]);
1283
1296
  return {
@@ -1360,15 +1373,16 @@ function header({ root, cause }) {
1360
1373
  }
1361
1374
  function chained(test, chain) {
1362
1375
  const unknownAt = chain.links.findIndex((link) => link.kind === "unknown");
1363
- if (unknownAt === -1) {
1376
+ const unknownLink = chain.links[unknownAt];
1377
+ if (unknownLink === undefined) {
1364
1378
  return [header(chain), ...steps(chain.links).map((step) => ` ${step}`)];
1365
1379
  }
1366
- const node = chain.links[unknownAt].node;
1380
+ const node = unknownLink.node;
1367
1381
  const where = chain.unknown.map(({ at }) => at ?? node);
1368
1382
  const width = Math.max(0, ...where.map((at) => at.length));
1369
1383
  const lines = [`${test} runs on every change`];
1370
- for (const [i, { cause, fix }] of chain.unknown.entries()) {
1371
- lines.push(` because ${where[i].padEnd(width)} ${cause}`, ` fix: ${fix}`);
1384
+ for (const { at, cause, fix } of chain.unknown) {
1385
+ lines.push(` because ${(at ?? node).padEnd(width)} ${cause}`, ` fix: ${fix}`);
1372
1386
  }
1373
1387
  if (unknownAt > 0) {
1374
1388
  lines.push(` reached via ${node}`, ...steps(chain.links.slice(0, unknownAt)).map((step) => ` ${step}`));
@@ -1381,7 +1395,8 @@ function lineNumber(at) {
1381
1395
  }
1382
1396
  function sourced(test, chain) {
1383
1397
  const unknownAt = chain.links.findIndex((link) => link.kind === "unknown");
1384
- const hops = unknownAt === -1 ? chain.links : chain.links.slice(0, unknownAt);
1398
+ const unknownLink = chain.links[unknownAt];
1399
+ const hops = unknownLink === undefined ? chain.links : chain.links.slice(0, unknownAt);
1385
1400
  const numbers = [...chain.links, ...chain.unknown].map(({ at }) => lineNumber(at));
1386
1401
  const width = Math.max(0, ...numbers.map((n) => n?.length ?? 0));
1387
1402
  const gutter = " ".repeat(width);
@@ -1390,10 +1405,10 @@ function sourced(test, chain) {
1390
1405
  return n === undefined || text === undefined ? [] : [`${n.padStart(width)} | ${text}`];
1391
1406
  };
1392
1407
  const count = plural(hops.length, "hop", "hops");
1393
- const lines = unknownAt === -1 ? [
1408
+ const lines = unknownLink === undefined ? [
1394
1409
  `selected: ${test} ← ${chain.root} (${count}${chain.cause === "changed" ? "" : `, ${chain.cause}`})`
1395
1410
  ] : [
1396
- `selected: ${test} ← every change (${unknownAt === 0 ? "its dependencies can't be read" : `${count} to ${chain.links[unknownAt].node}, whose dependencies can't be read`})`
1411
+ `selected: ${test} ← every change (${unknownAt === 0 ? "its dependencies can't be read" : `${count} to ${unknownLink.node}, whose dependencies can't be read`})`
1397
1412
  ];
1398
1413
  lines.push("");
1399
1414
  for (const link of hops) {
@@ -1402,11 +1417,11 @@ function sourced(test, chain) {
1402
1417
  const kind = configured ?? link.kind;
1403
1418
  lines.push(`${gutter}--> ${where} ${kind}`, ...cited(link.at, link.text));
1404
1419
  }
1405
- if (unknownAt === -1) {
1420
+ if (unknownLink === undefined) {
1406
1421
  lines.push(`${gutter}● ${chain.root}: ${chain.cause}`);
1407
1422
  return lines;
1408
1423
  }
1409
- const node = chain.links[unknownAt].node;
1424
+ const node = unknownLink.node;
1410
1425
  for (const { cause, at, text, fix } of chain.unknown) {
1411
1426
  lines.push(`${gutter}✗ ${at ?? node} ${cause}`, ...cited(at, text), `${gutter} = fix: ${fix}`);
1412
1427
  }
@@ -1529,14 +1544,14 @@ var POSITIONAL = {
1529
1544
  graph: 0
1530
1545
  };
1531
1546
  var SCHEMA_VERSION = 1;
1532
- function usageError(message) {
1533
- return new BiviumError("usage", message);
1547
+ function usageError(code, message) {
1548
+ return new BiviumError2(code, message);
1534
1549
  }
1535
1550
  function unknownOption(command, flag) {
1536
1551
  const known = FLAGS[command] ?? [];
1537
1552
  const others = Object.keys(FLAGS).filter((other) => other !== command && FLAGS[other]?.includes(flag));
1538
1553
  const hint = others.length > 0 ? ` (${others.join(" and ")} ${others.length === 1 ? "takes" : "take"} it)` : didYouMean(flag, known);
1539
- return usageError(`bivium ${command}: unknown option ${flag}${hint}`);
1554
+ return usageError("BV_UNKNOWN_OPTION", `bivium ${command}: unknown option ${flag}${hint}`);
1540
1555
  }
1541
1556
  function parseArgs(command, argv) {
1542
1557
  const known = FLAGS[command] ?? [];
@@ -1557,7 +1572,7 @@ function parseArgs(command, argv) {
1557
1572
  if (!VALUED.has(flag)) {
1558
1573
  const on = equals === -1 ? "true" : arg.slice(equals + 1);
1559
1574
  if (on !== "true" && on !== "false") {
1560
- throw usageError(`bivium ${command}: ${flag} is a switch: give it alone, or as ${flag}=true or ${flag}=false`);
1575
+ throw usageError("BV_BAD_OPTION_VALUE", `bivium ${command}: ${flag} is a switch: give it alone, or as ${flag}=true or ${flag}=false`);
1561
1576
  }
1562
1577
  if (on === "true")
1563
1578
  flags.set(flag, "");
@@ -1565,12 +1580,12 @@ function parseArgs(command, argv) {
1565
1580
  }
1566
1581
  const value = equals === -1 ? argv[++i] : arg.slice(equals + 1);
1567
1582
  if (value === undefined || value === "" || value.startsWith("--")) {
1568
- throw usageError(`bivium: ${flag} needs a value`);
1583
+ throw usageError("BV_BAD_OPTION_VALUE", `bivium: ${flag} needs a value`);
1569
1584
  }
1570
1585
  flags.set(flag, value);
1571
1586
  }
1572
1587
  if (positional.length > (POSITIONAL[command] ?? 0)) {
1573
- throw usageError(`bivium ${command}: unexpected ${positional.at(-1)}`);
1588
+ throw usageError("BV_UNEXPECTED_ARGUMENT", `bivium ${command}: unexpected ${positional.at(-1)}`);
1574
1589
  }
1575
1590
  return { flags, positional };
1576
1591
  }
@@ -1623,15 +1638,21 @@ function logPlan({ plan, narrowed }) {
1623
1638
  }
1624
1639
  }
1625
1640
  function githubOutput() {
1626
- const output = process.env.GITHUB_OUTPUT;
1641
+ const output = githubOutputPath();
1627
1642
  if (!output) {
1628
- throw usageError("bivium plan: --github writes to $GITHUB_OUTPUT, which is not set (it is in a GitHub Actions step)");
1643
+ throw usageError("BV_NO_GITHUB_OUTPUT", "bivium plan: --github writes to $GITHUB_OUTPUT, which is not set (it is in a GitHub Actions step)");
1629
1644
  }
1630
1645
  return output;
1631
1646
  }
1632
1647
  function writeOutputs(output, config, { plan }) {
1633
- const lines = config.suites.map((suite) => `${suite.output}=${formatSelection(plan.suites[suite.name])}
1634
- `);
1648
+ const lines = config.suites.map((suite) => {
1649
+ const selection = plan.suites[suite.name];
1650
+ if (selection === undefined) {
1651
+ throw new BiviumError2("BV_INTERNAL", `bivium: plan: no selection for suite "${suite.name}".`);
1652
+ }
1653
+ return `${suite.output}=${formatSelection(selection)}
1654
+ `;
1655
+ });
1635
1656
  appendFileSync(output, lines.join(""));
1636
1657
  }
1637
1658
  function json(value) {
@@ -1644,7 +1665,7 @@ function findSuite(config, name) {
1644
1665
  if (suite)
1645
1666
  return suite;
1646
1667
  const names = config.suites.map((candidate) => candidate.name);
1647
- throw usageError(`bivium: no suite "${name}"${didYouMean(name, names)}; the config has ${names.join(", ")}`);
1668
+ throw usageError("BV_UNKNOWN_SUITE", `bivium: no suite "${name}"${didYouMean(name, names)}; the config has ${names.join(", ")}`);
1648
1669
  }
1649
1670
  function real(path) {
1650
1671
  try {
@@ -1673,16 +1694,16 @@ function repoPath(root, arg, known) {
1673
1694
  async function inspect(command, { flags, positional }) {
1674
1695
  const format = flags.get("--format") ?? "tree";
1675
1696
  if (format !== "json" && !isFormat(format)) {
1676
- throw usageError(`bivium why: --format takes tree, chain, source or json${didYouMean(format, ["tree", "chain", "source", "json"])}`);
1697
+ throw usageError("BV_BAD_OPTION_VALUE", `bivium why: --format takes tree, chain, source or json${didYouMean(format, ["tree", "chain", "source", "json"])}`);
1677
1698
  }
1678
1699
  const maxFlag = flags.get("--max-unknown");
1679
1700
  const max = maxFlag === undefined ? undefined : Number(maxFlag);
1680
1701
  if (max !== undefined && !Number.isInteger(max)) {
1681
- throw usageError("bivium check: --max-unknown takes a whole number");
1702
+ throw usageError("BV_BAD_OPTION_VALUE", "bivium check: --max-unknown takes a whole number");
1682
1703
  }
1683
1704
  const [testArg, fileArg] = positional;
1684
1705
  if (command === "why" && testArg === undefined) {
1685
- throw usageError("bivium why: which test? bivium why <test> [file]");
1706
+ throw usageError("BV_MISSING_ARGUMENT", "bivium why: which test? bivium why <test> [file]");
1686
1707
  }
1687
1708
  const { root, base, config } = await prepare({
1688
1709
  cwd: flags.get("--cwd"),
@@ -1704,10 +1725,10 @@ async function inspect(command, { flags, positional }) {
1704
1725
  const file = fileArg === undefined ? undefined : repoPath(root, fileArg, inGraph);
1705
1726
  if (!isTest(test) || !inGraph(test)) {
1706
1727
  const tests = [...computed.graph.keys()].filter(isTest);
1707
- throw usageError(inGraph(test) ? `bivium why: ${test} is no suite's test: name a test first, as in bivium why <test> ${test}` : `bivium why: no test ${test}${didYouMean(test, tests)}`);
1728
+ throw usageError(inGraph(test) ? "BV_UNKNOWN_TEST" : "BV_UNKNOWN_FILE", inGraph(test) ? `bivium why: ${test} is no suite's test: name a test first, as in bivium why <test> ${test}` : `bivium why: no test ${test}${didYouMean(test, tests)}`);
1708
1729
  }
1709
1730
  if (file !== undefined && !inGraph(file)) {
1710
- throw usageError(`bivium why: no file ${file}${didYouMean(file, computed.graph.keys())}`);
1731
+ throw usageError("BV_UNKNOWN_FILE", `bivium why: no file ${file}${didYouMean(file, computed.graph.keys())}`);
1711
1732
  }
1712
1733
  const explanation = await explain(root, config, computed, test, file, {
1713
1734
  all: flags.has("--all")
@@ -1718,7 +1739,7 @@ async function inspect(command, { flags, positional }) {
1718
1739
  async function graphCommand({ flags }) {
1719
1740
  const top = Number(flags.get("--top") ?? "10");
1720
1741
  if (!Number.isInteger(top) || top < 0) {
1721
- throw usageError("bivium graph: --top takes a whole number");
1742
+ throw usageError("BV_BAD_OPTION_VALUE", "bivium graph: --top takes a whole number");
1722
1743
  }
1723
1744
  const { root, base, config } = await prepare({
1724
1745
  cwd: flags.get("--cwd"),
@@ -1742,10 +1763,11 @@ async function runCommand(command, { flags, positional }) {
1742
1763
  configFile: flags.get("--config")
1743
1764
  });
1744
1765
  const suite = findSuite(config, flags.get("--suite")) ?? config.suites[0];
1745
- if (suite === undefined)
1746
- throw new BiviumError("config", "bivium: no suites");
1766
+ if (suite === undefined) {
1767
+ throw new BiviumError2("BV_CONFIG_INVALID", "bivium config: no suites");
1768
+ }
1747
1769
  if (command === "run" && !suite.run) {
1748
- throw usageError(`bivium run: suite "${suite.name}" has no run command: add suites.${suite.name}.run to the config`);
1770
+ throw usageError("BV_NO_RUN_COMMAND", `bivium run: suite "${suite.name}" has no run command: add suites.${suite.name}.run to the config`);
1749
1771
  }
1750
1772
  const computed = await computePlan(root, base, config, {
1751
1773
  ...flags.has("--no-cache") && { cache: false },
@@ -1787,6 +1809,9 @@ async function runCommand(command, { flags, positional }) {
1787
1809
  return 0;
1788
1810
  }
1789
1811
  const [program, ...args] = commandFor(suite.run ?? "", selection.mode === "some" ? selection.files : []);
1812
+ if (program === undefined) {
1813
+ throw usageError("BV_NO_RUN_COMMAND", `bivium run: suite "${suite.name}" has no run command: add suites.${suite.name}.run to the config`);
1814
+ }
1790
1815
  const result = spawnSync(program, args, { cwd: root, stdio: "inherit" });
1791
1816
  return result.status ?? 1;
1792
1817
  }
@@ -1806,10 +1831,12 @@ var COMMANDS = Object.keys(FLAGS);
1806
1831
  function wantsJson(argv) {
1807
1832
  return argv.some((arg, i) => arg === "--json" || arg === "--json=true" || arg === "--format=json" || arg === "--format" && argv[i + 1] === "json");
1808
1833
  }
1809
- function fail(argv, kind, message) {
1810
- console.error(message);
1811
- if (wantsJson(argv))
1812
- console.log(json({ error: { kind, message } }));
1834
+ function fail(argv, error) {
1835
+ console.error(error.message);
1836
+ if (wantsJson(argv)) {
1837
+ const { kind, code, message } = error;
1838
+ console.log(json({ error: { kind, code, message } }));
1839
+ }
1813
1840
  return 2;
1814
1841
  }
1815
1842
  async function main(argv) {
@@ -1828,10 +1855,10 @@ async function main(argv) {
1828
1855
  return 0;
1829
1856
  }
1830
1857
  if (command === undefined) {
1831
- return fail(argv, "usage", `bivium: which command? ${COMMANDS.join(", ")} (bivium --help for usage)`);
1858
+ return fail(argv, usageError("BV_MISSING_ARGUMENT", `bivium: which command? ${COMMANDS.join(", ")} (bivium --help for usage)`));
1832
1859
  }
1833
1860
  if (!(command in FLAGS)) {
1834
- return fail(argv, "usage", `bivium: unknown command "${command}"${didYouMean(command, COMMANDS)}; the commands are ${COMMANDS.join(", ")} (bivium --help for usage)`);
1861
+ return fail(argv, usageError("BV_UNKNOWN_COMMAND", `bivium: unknown command "${command}"${didYouMean(command, COMMANDS)}; the commands are ${COMMANDS.join(", ")} (bivium --help for usage)`));
1835
1862
  }
1836
1863
  const rest = [...argv.slice(0, at), ...argv.slice(at + 1)];
1837
1864
  try {
@@ -1842,11 +1869,10 @@ async function main(argv) {
1842
1869
  return await graphCommand(args);
1843
1870
  return await runCommand(command, args);
1844
1871
  } catch (error) {
1845
- if (error instanceof BiviumError) {
1846
- return fail(argv, error.kind, error.message);
1847
- }
1872
+ if (error instanceof BiviumError2)
1873
+ return fail(argv, error);
1848
1874
  const message = error instanceof Error ? error.message : String(error);
1849
- return fail(argv, "other", message);
1875
+ return fail(argv, new BiviumError2("BV_INTERNAL", message, { cause: error }));
1850
1876
  }
1851
1877
  }
1852
1878
 
@@ -278,3 +278,55 @@ export interface FullRunCause<Suite extends string = string> {
278
278
  }
279
279
  /** Types a config. Returns it unchanged. */
280
280
  export declare function defineConfig<Suite extends string>(config: Config<Suite>): Config<Suite>;
281
+ /** An error bivium names: its `code` says which failure, its `kind` what to do. */
282
+ export declare class BiviumError extends Error {
283
+ readonly code: BiviumErrorCode;
284
+ readonly kind: BiviumErrorKind;
285
+ constructor(code: BiviumErrorCode, message: string, options?: ErrorOptions);
286
+ }
287
+ /**
288
+ * Which failure it is, stable across releases: a code is never reused for
289
+ * another meaning, and `--json` prints it as `error.code`.
290
+ */
291
+ export type BiviumErrorCode =
292
+ /** No command, or `why` without a test. */
293
+ "BV_MISSING_ARGUMENT"
294
+ /** A command bivium doesn't have. */
295
+ | "BV_UNKNOWN_COMMAND"
296
+ /** An option the command doesn't take. */
297
+ | "BV_UNKNOWN_OPTION"
298
+ /** An option's value is missing or of the wrong form. */
299
+ | "BV_BAD_OPTION_VALUE"
300
+ /** More arguments than the command takes. */
301
+ | "BV_UNEXPECTED_ARGUMENT"
302
+ /** A suite the config doesn't define. */
303
+ | "BV_UNKNOWN_SUITE"
304
+ /** A path that is no suite's test. */
305
+ | "BV_UNKNOWN_TEST"
306
+ /** A path that names no file of the graph. */
307
+ | "BV_UNKNOWN_FILE"
308
+ /** `run` for a suite with no `run` command. */
309
+ | "BV_NO_RUN_COMMAND"
310
+ /** `plan --github` outside a GitHub Actions step. */
311
+ | "BV_NO_GITHUB_OUTPUT"
312
+ /** No config file where bivium looked. */
313
+ | "BV_CONFIG_NOT_FOUND"
314
+ /** The config file failed to load: a syntax error, or one it throws. */
315
+ | "BV_CONFIG_UNREADABLE"
316
+ /** The config loaded, but a key is unknown or a value is invalid. */
317
+ | "BV_CONFIG_INVALID"
318
+ /** The base to diff against isn't here, or there's no default branch. */
319
+ | "BV_GIT_NO_BASE"
320
+ /** The base and HEAD share no commit here. */
321
+ | "BV_GIT_NO_MERGE_BASE"
322
+ /** A git command failed; the message carries git's own words. */
323
+ | "BV_GIT_FAILED"
324
+ /** A failure bivium didn't anticipate: a bug, or the environment. */
325
+ | "BV_INTERNAL";
326
+ /**
327
+ * What a caller does about an error: `usage`, bivium was called wrong;
328
+ * `config`, the config can't be found, read, or is invalid; `git`, git
329
+ * refused or the history is missing; `other`, a failure bivium didn't
330
+ * name. Every kind exits 2.
331
+ */
332
+ export type BiviumErrorKind = "usage" | "config" | "git" | "other";
@@ -1,8 +1,10 @@
1
1
  import {
2
+ BiviumError2,
2
3
  defineConfig2,
3
4
  plan2
4
5
  } from "./shared.js";
5
6
  export {
7
+ BiviumError2 as BiviumError,
6
8
  defineConfig2 as defineConfig,
7
9
  plan2 as plan
8
10
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bivium",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Run only the tests a change can affect, and never miss one.",
5
5
  "license": "MIT",
6
6
  "author": "Eric Liu (https://github.com/metonym)",
@@ -23,22 +23,18 @@
23
23
  "zero-dependency"
24
24
  ],
25
25
  "type": "module",
26
- "main": "./dist/index.js",
27
- "types": "./dist/index.d.ts",
26
+ "main": "./index.js",
27
+ "types": "./index.d.ts",
28
28
  "exports": {
29
29
  ".": {
30
- "types": "./dist/index.d.ts",
31
- "default": "./dist/index.js"
30
+ "types": "./index.d.ts",
31
+ "default": "./index.js"
32
32
  },
33
33
  "./package.json": "./package.json"
34
34
  },
35
35
  "bin": {
36
- "bivium": "./dist/cli.js"
36
+ "bivium": "cli.js"
37
37
  },
38
- "files": [
39
- "dist",
40
- "docs"
41
- ],
42
38
  "engines": {
43
39
  "node": ">=22"
44
40
  },
@@ -8,10 +8,18 @@ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
8
8
  import { isAbsolute, join } from "node:path";
9
9
 
10
10
  // package.json
11
- var version = "0.5.0";
11
+ var version = "0.6.0";
12
+
13
+ // src/env.ts
14
+ function githubOutputPath() {
15
+ return process.env.GITHUB_OUTPUT;
16
+ }
17
+ function nowMs() {
18
+ return Date.now();
19
+ }
12
20
 
13
21
  // src/cache.ts
14
- var SCANNER_VERSION = 6;
22
+ var SCANNER_VERSION = 7;
15
23
  var MAGIC = "bivium-extractions";
16
24
  var FILE = "extractions.json";
17
25
  function isHeader(value) {
@@ -50,7 +58,8 @@ class ExtractionCache {
50
58
  const parsed = JSON.parse(text);
51
59
  if (!Array.isArray(parsed))
52
60
  return;
53
- const [header, strings, rows] = parsed;
61
+ const fields = parsed;
62
+ const [header, strings, rows] = fields;
54
63
  if (!isHeader(header) || !Array.isArray(strings) || !Array.isArray(rows) || header.strings !== strings.length || header.rows !== rows.length) {
55
64
  return;
56
65
  }
@@ -91,7 +100,7 @@ class ExtractionCache {
91
100
  async save() {
92
101
  if (!this.dir || !this.#dirty)
93
102
  return;
94
- const table = new Strings;
103
+ const table = createStrings();
95
104
  const rows = [];
96
105
  for (const [key, extraction] of this.#used) {
97
106
  rows.push(encode(key, extraction, table));
@@ -115,7 +124,7 @@ class ExtractionCache {
115
124
  strings: table.list.length
116
125
  };
117
126
  const file = join(this.dir, FILE);
118
- const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
127
+ const temp = `${file}.${process.pid}.${nowMs()}.tmp`;
119
128
  try {
120
129
  await mkdir(this.dir, { recursive: true });
121
130
  const ignore = join(this.dir, ".gitignore");
@@ -132,22 +141,20 @@ class ExtractionCache {
132
141
  }
133
142
  }
134
143
  }
135
-
136
- class Strings {
137
- list = [];
138
- #ids = new Map;
139
- id(value) {
140
- let id = this.#ids.get(value);
141
- if (id === undefined) {
142
- id = this.list.length;
143
- this.list.push(value);
144
- this.#ids.set(value, id);
144
+ function createStrings() {
145
+ const list = [];
146
+ const idsByValue = new Map;
147
+ const id = (value) => {
148
+ let found = idsByValue.get(value);
149
+ if (found === undefined) {
150
+ found = list.length;
151
+ list.push(value);
152
+ idsByValue.set(value, found);
145
153
  }
146
- return id;
147
- }
148
- ids(values) {
149
- return values.length === 0 ? 0 : values.map((value) => this.id(value));
150
- }
154
+ return found;
155
+ };
156
+ const ids = (values) => values.length === 0 ? 0 : values.map(id);
157
+ return { list, id, ids };
151
158
  }
152
159
  function typeIndexes(imports) {
153
160
  const indexes = [];
@@ -221,7 +228,8 @@ function decode(row, strings) {
221
228
  if (row[8] !== 0) {
222
229
  if (!Array.isArray(row[8]))
223
230
  throw new Error("bad barrel");
224
- const [pairs, stars] = row[8];
231
+ const barrel = row[8];
232
+ const [pairs, stars] = barrel;
225
233
  if (!Array.isArray(pairs))
226
234
  throw new Error("bad barrel names");
227
235
  const names = new Map;
@@ -239,11 +247,33 @@ import { isAbsolute as isAbsolute2, join as join2, relative, resolve } from "nod
239
247
  import { pathToFileURL } from "node:url";
240
248
 
241
249
  // src/errors.ts
242
- class BiviumError extends Error {
250
+ var KINDS = {
251
+ BV_MISSING_ARGUMENT: "usage",
252
+ BV_UNKNOWN_COMMAND: "usage",
253
+ BV_UNKNOWN_OPTION: "usage",
254
+ BV_BAD_OPTION_VALUE: "usage",
255
+ BV_UNEXPECTED_ARGUMENT: "usage",
256
+ BV_UNKNOWN_SUITE: "usage",
257
+ BV_UNKNOWN_TEST: "usage",
258
+ BV_UNKNOWN_FILE: "usage",
259
+ BV_NO_RUN_COMMAND: "usage",
260
+ BV_NO_GITHUB_OUTPUT: "usage",
261
+ BV_CONFIG_NOT_FOUND: "config",
262
+ BV_CONFIG_UNREADABLE: "config",
263
+ BV_CONFIG_INVALID: "config",
264
+ BV_GIT_NO_BASE: "git",
265
+ BV_GIT_NO_MERGE_BASE: "git",
266
+ BV_GIT_FAILED: "git",
267
+ BV_INTERNAL: "other"
268
+ };
269
+
270
+ class BiviumError2 extends Error {
271
+ code;
243
272
  kind;
244
- constructor(kind, message, options) {
273
+ constructor(code, message, options) {
245
274
  super(message, options);
246
- this.kind = kind;
275
+ this.code = code;
276
+ this.kind = KINDS[code];
247
277
  }
248
278
  }
249
279
  function distance(a, b) {
@@ -300,7 +330,7 @@ function compile(glob, {
300
330
  return capture ? `(${body})` : body;
301
331
  };
302
332
  for (let i = 0;i < glob.length; i++) {
303
- const char = glob[i];
333
+ const char = glob.charAt(i);
304
334
  if (captures && char === "$" && DIGIT.test(glob[i + 1] ?? "")) {
305
335
  let end = i + 1;
306
336
  while (DIGIT.test(glob[end] ?? ""))
@@ -401,6 +431,12 @@ function isInertOf(inert) {
401
431
  const listed = matcher(inert);
402
432
  return (name) => name === "bivium" || listed(name);
403
433
  }
434
+ function optional(key, value) {
435
+ const out = {};
436
+ if (value !== undefined)
437
+ out[key] = value;
438
+ return out;
439
+ }
404
440
  function resolveConfig(config) {
405
441
  const names = Object.keys(config.suites);
406
442
  if (names.length === 0)
@@ -408,7 +444,7 @@ function resolveConfig(config) {
408
444
  const suites = Object.entries(config.suites).map(([name, suite]) => ({
409
445
  name,
410
446
  isTest: matcher(suite.tests),
411
- run: suite.run,
447
+ ...optional("run", suite.run),
412
448
  roots: list(suite.root, ["."]).map(normalizeRoot),
413
449
  urls: Object.entries(suite.urls ?? {}).map(([key, targets]) => ({
414
450
  key,
@@ -458,8 +494,8 @@ function resolveConfig(config) {
458
494
  extensions: config.extensions ?? DEFAULT_EXTENSIONS,
459
495
  deadGlobs: config.deadGlobs ?? [],
460
496
  ...config.knownUnknowns && { knownUnknowns: config.knownUnknowns },
461
- base: config.base,
462
- cache: config.cache
497
+ ...optional("base", config.base),
498
+ ...optional("cache", config.cache)
463
499
  };
464
500
  }
465
501
  function inRoot(file, root) {
@@ -574,15 +610,15 @@ function checkSuite(name, value) {
574
610
  const globs = "a glob or a list of globs";
575
611
  return {
576
612
  tests,
577
- run: field(value, "run", isString, at, "a command"),
578
- root: paths(value, "root", at),
579
- urls: field(value, "urls", isGlobsRecord, at, "a map of URL patterns"),
580
- pages: field(value, "pages", isGlobs, at, globs),
581
- wiring: field(value, "wiring", isGlobs, at, globs),
582
- setup: field(value, "setup", isGlobs, at, globs),
583
- nonInputs: field(value, "nonInputs", isGlobs, at, globs),
584
- output: field(value, "output", isString, at, "an output name"),
585
- types: field(value, "types", isBoolean, at, "a boolean")
613
+ ...optional("run", field(value, "run", isString, at, "a command")),
614
+ ...optional("root", paths(value, "root", at)),
615
+ ...optional("urls", field(value, "urls", isGlobsRecord, at, "a map of URL patterns")),
616
+ ...optional("pages", field(value, "pages", isGlobs, at, globs)),
617
+ ...optional("wiring", field(value, "wiring", isGlobs, at, globs)),
618
+ ...optional("setup", field(value, "setup", isGlobs, at, globs)),
619
+ ...optional("nonInputs", field(value, "nonInputs", isGlobs, at, globs)),
620
+ ...optional("output", field(value, "output", isString, at, "an output name")),
621
+ ...optional("types", field(value, "types", isBoolean, at, "a boolean"))
586
622
  };
587
623
  }
588
624
  var WILDCARD = /[*?{}[\]]/;
@@ -628,7 +664,7 @@ function checkNarrower(value, at) {
628
664
  name,
629
665
  match,
630
666
  opaque,
631
- suites,
667
+ ...optional("suites", suites),
632
668
  narrow: async (context) => {
633
669
  const result = await Reflect.apply(narrow, value, [context]);
634
670
  return checkResult(result);
@@ -707,24 +743,24 @@ ${unknown.map((key) => ` ${key}`).join(`
707
743
  checkCaptures("reads", reads);
708
744
  return {
709
745
  suites,
710
- narrowers: narrowers?.map((narrower, i) => checkNarrower(narrower, `narrowers[${i}]`)),
711
- roots: paths(value, "roots", ""),
712
- ignore: field(value, "ignore", isGlobs, "", globs),
713
- alias: field(value, "alias", isStringRecord, "", "a map of paths"),
714
- edges,
715
- reads,
716
- self: field(value, "self", isGlobs, "", globs),
717
- importOnly: field(value, "importOnly", isGlobs, "", globs),
718
- hermetic: field(value, "hermetic", isGlobs, "", globs),
719
- barrels: field(value, "barrels", isGlobs, "", globs),
720
- external: field(value, "external", isStrings, "", "a list of packages"),
721
- inert: field(value, "inert", isGlobs, "", globs),
722
- loadedByName: field(value, "loadedByName", isGlobs, "", globs),
723
- extensions: field(value, "extensions", isStrings, "", "a list"),
724
- deadGlobs: deadGlobs?.map((entry, i) => checkDeadGlob(entry, `deadGlobs[${i}]`)),
725
- knownUnknowns: knownUnknowns?.map((entry, i) => checkKnownUnknown(entry, `knownUnknowns[${i}]`)),
726
- base: field(value, "base", isString, "", "a ref"),
727
- cache: field(value, "cache", isCache, "", "a directory or a boolean")
746
+ ...optional("narrowers", narrowers?.map((narrower, i) => checkNarrower(narrower, `narrowers[${i}]`))),
747
+ ...optional("roots", paths(value, "roots", "")),
748
+ ...optional("ignore", field(value, "ignore", isGlobs, "", globs)),
749
+ ...optional("alias", field(value, "alias", isStringRecord, "", "a map of paths")),
750
+ ...optional("edges", edges),
751
+ ...optional("reads", reads),
752
+ ...optional("self", field(value, "self", isGlobs, "", globs)),
753
+ ...optional("importOnly", field(value, "importOnly", isGlobs, "", globs)),
754
+ ...optional("hermetic", field(value, "hermetic", isGlobs, "", globs)),
755
+ ...optional("barrels", field(value, "barrels", isGlobs, "", globs)),
756
+ ...optional("external", field(value, "external", isStrings, "", "a list of packages")),
757
+ ...optional("inert", field(value, "inert", isGlobs, "", globs)),
758
+ ...optional("loadedByName", field(value, "loadedByName", isGlobs, "", globs)),
759
+ ...optional("extensions", field(value, "extensions", isStrings, "", "a list")),
760
+ ...optional("deadGlobs", deadGlobs?.map((entry, i) => checkDeadGlob(entry, `deadGlobs[${i}]`))),
761
+ ...optional("knownUnknowns", knownUnknowns?.map((entry, i) => checkKnownUnknown(entry, `knownUnknowns[${i}]`))),
762
+ ...optional("base", field(value, "base", isString, "", "a ref")),
763
+ ...optional("cache", field(value, "cache", isCache, "", "a directory or a boolean"))
728
764
  };
729
765
  }
730
766
  var CONFIG_FILES = [
@@ -744,16 +780,25 @@ var CONFIG_PREFIX = /^bivium config: /;
744
780
  async function loadConfig(root, path) {
745
781
  const file = path === undefined ? CONFIG_FILES.map((name) => join2(root, name)).find((f) => existsSync2(f)) : resolve(process.cwd(), path);
746
782
  if (!file || !existsSync2(file)) {
747
- throw new BiviumError("config", path ? `bivium: no config found at ${path}` : `bivium: no config found in ${root}: looked for ${CONFIG_FILES.join(", ")} (--config names another file, --cwd another repository)`);
783
+ throw new BiviumError2("BV_CONFIG_NOT_FOUND", path ? `bivium: no config found at ${path}` : `bivium: no config found in ${root}: looked for ${CONFIG_FILES.join(", ")} (--config names another file, --cwd another repository)`);
748
784
  }
749
785
  const inside = relative(root, file);
750
786
  const shown = inside.startsWith("..") || isAbsolute2(inside) ? file : inside;
787
+ const named = (code, error) => {
788
+ const message = error instanceof Error ? error.message : String(error);
789
+ return new BiviumError2(code, `bivium config: ${shown}: ${message.replace(CONFIG_PREFIX, "")}`, { cause: error });
790
+ };
791
+ let raw;
792
+ try {
793
+ raw = await readConfig(file);
794
+ } catch (error) {
795
+ throw named("BV_CONFIG_UNREADABLE", error);
796
+ }
751
797
  let config;
752
798
  try {
753
- config = resolveConfig(checkConfig(await readConfig(file)));
799
+ config = resolveConfig(checkConfig(raw));
754
800
  } catch (error) {
755
- const message = error instanceof Error ? error.message : String(error);
756
- throw new BiviumError("config", `bivium config: ${shown}: ${message.replace(CONFIG_PREFIX, "")}`, { cause: error });
801
+ throw named("BV_CONFIG_INVALID", error);
757
802
  }
758
803
  return { config, file: shown };
759
804
  }
@@ -796,7 +841,7 @@ async function gitOrThrow(cwd, ...args) {
796
841
  if (result.status !== 0) {
797
842
  const said = result.stderr.trim().split(`
798
843
  `)[0];
799
- throw new BiviumError("git", `bivium: git ${args.join(" ")} failed${said ? `: ${said}` : ""}`);
844
+ throw new BiviumError2("BV_GIT_FAILED", `bivium: git ${args.join(" ")} failed${said ? `: ${said}` : ""}`);
800
845
  }
801
846
  return result.stdout;
802
847
  }
@@ -814,10 +859,10 @@ async function missingHistory(cwd, base) {
814
859
  ]);
815
860
  const fix = shallow.stdout.trim() === "true" ? " The clone is shallow: fetch the history (actions/checkout: `fetch-depth: 0`)." : "";
816
861
  if (known.status !== 0) {
817
- return new BiviumError("git", `bivium: no commit ${base} here to diff against: fetch it.${fix}`);
862
+ return new BiviumError2("BV_GIT_NO_BASE", `bivium: no commit ${base} here to diff against: fetch it.${fix}`);
818
863
  }
819
864
  if (forked.status !== 0) {
820
- return new BiviumError("git", `bivium: ${base} and HEAD share no commit here, so there's no merge base to diff against.${fix}`);
865
+ return new BiviumError2("BV_GIT_NO_MERGE_BASE", `bivium: ${base} and HEAD share no commit here, so there's no merge base to diff against.${fix}`);
821
866
  }
822
867
  return;
823
868
  }
@@ -858,10 +903,10 @@ async function readRevision(cwd, base, roots, {
858
903
  const diffed = [];
859
904
  const layout = new Set(untracked);
860
905
  for (const line of lines(diff)) {
861
- const entry = RAW_ENTRY.exec(line);
862
- if (!entry)
906
+ const [, mode, oid, status, path] = RAW_ENTRY.exec(line) ?? [];
907
+ if (mode === undefined || oid === undefined || status === undefined || path === undefined) {
863
908
  throw new Error(`git diff: unexpected line ${line}`);
864
- const [, mode, oid, status, path] = entry;
909
+ }
865
910
  diffed.push(path);
866
911
  if (status === "A" || status === "D")
867
912
  layout.add(path);
@@ -906,6 +951,9 @@ async function readRevision(cwd, base, roots, {
906
951
  continue;
907
952
  }
908
953
  const [, tag, mode, oid, stage, path] = entry;
954
+ if (tag === undefined || mode === undefined || oid === undefined || stage === undefined || path === undefined) {
955
+ throw new Error(`bivium: git: unexpected ls-files line ${line}.`);
956
+ }
909
957
  tracked.add(path);
910
958
  if (mode === "160000" || !underRoots(path))
911
959
  continue;
@@ -939,10 +987,10 @@ async function defaultBase(cwd) {
939
987
  return head.stdout.trim();
940
988
  const refs = ["origin/main", "origin/master", "main", "master"];
941
989
  const found = await Promise.all(refs.map((ref) => git(cwd, "rev-parse", "--verify", "--quiet", ref)));
942
- const branch = refs.find((_, i) => found[i].status === 0);
990
+ const branch = refs[found.findIndex((result) => result.status === 0)];
943
991
  if (branch)
944
992
  return branch;
945
- throw new BiviumError("git", `bivium: no base given and no default branch found (tried origin/HEAD, ${refs.join(", ")}): pass one, as in \`bivium plan origin/main\`, or set base in the config`);
993
+ throw new BiviumError2("BV_GIT_NO_BASE", `bivium: no base given and no default branch found (tried origin/HEAD, ${refs.join(", ")}): pass one, as in \`bivium plan origin/main\`, or set base in the config`);
946
994
  }
947
995
 
948
996
  // src/barrel.ts
@@ -1005,7 +1053,14 @@ function namedBindings(clause) {
1005
1053
  if (!named || DEFAULT_OR_NAMESPACE.test(clause.replace(NAMED_CLAUSE, ""))) {
1006
1054
  return;
1007
1055
  }
1008
- return named[1].split(",").map((part) => part.trim().replace(TYPE_PREFIX2, "").split(AS2)[0].trim()).filter(Boolean);
1056
+ return captured(named, 1).split(",").map((part) => (part.trim().replace(TYPE_PREFIX2, "").split(AS2)[0] ?? "").trim()).filter(Boolean);
1057
+ }
1058
+ function captured(match, index) {
1059
+ const value = match[index];
1060
+ if (value === undefined) {
1061
+ throw new Error(`bivium: scan: group ${index} of ${match[0]} is unset.`);
1062
+ }
1063
+ return value;
1009
1064
  }
1010
1065
 
1011
1066
  // src/resolve.ts
@@ -1060,14 +1115,14 @@ var DEP_FIELDS = [
1060
1115
  ];
1061
1116
  function packageName(specifier) {
1062
1117
  const parts = specifier.split("/");
1063
- return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
1118
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0] ?? "";
1064
1119
  }
1065
1120
  function builtin(specifier) {
1066
1121
  if (RUNTIME_BUILTIN.test(specifier)) {
1067
1122
  const name = specifier.replace(NODE_PREFIX, "");
1068
1123
  return specifier.startsWith("bun") ? specifier : `node:${name.split("/")[0]}`;
1069
1124
  }
1070
- const name = specifier.split("/")[0];
1125
+ const name = specifier.split("/")[0] ?? "";
1071
1126
  return BUILTINS.has(specifier) || BUILTINS.has(name) ? `node:${name}` : undefined;
1072
1127
  }
1073
1128
  function targets(value, out = []) {
@@ -1144,8 +1199,7 @@ function createResolver({
1144
1199
  const indexes = new Map;
1145
1200
  const byTail = [];
1146
1201
  const undotted = [];
1147
- for (let i = 0;i < extensions.length; i++) {
1148
- const ext = extensions[i];
1202
+ for (const [i, ext] of extensions.entries()) {
1149
1203
  const dot = ext.lastIndexOf(".");
1150
1204
  if (dot === -1)
1151
1205
  undotted.push(i);
@@ -1159,6 +1213,9 @@ function createResolver({
1159
1213
  }
1160
1214
  const addSuffixed = (i, file) => {
1161
1215
  const ext = extensions[i];
1216
+ if (ext === undefined) {
1217
+ throw new Error(`bivium: resolve: no extension at index ${i}.`);
1218
+ }
1162
1219
  if (!file.endsWith(ext))
1163
1220
  return;
1164
1221
  const base = file.slice(0, file.length - ext.length);
@@ -1248,7 +1305,7 @@ function createResolver({
1248
1305
  const owning = pkg === -1 ? undefined : deepestFirst[pkg];
1249
1306
  scope = {
1250
1307
  owning,
1251
- ts: ts === -1 ? undefined : tsDeepestFirst[ts][1],
1308
+ ts: ts === -1 ? undefined : tsDeepestFirst[ts]?.[1],
1252
1309
  declared: declaredIn(owning?.[0] ?? "."),
1253
1310
  resolved: new Map
1254
1311
  };
@@ -1510,7 +1567,7 @@ for (let c = 0;c < 128; c++) {
1510
1567
  IDENT[c] = 2;
1511
1568
  }
1512
1569
  function isIdentStart(c) {
1513
- return c < 128 ? (IDENT[c] & 1) !== 0 : c >= 128 && !isUnicodeSpace(c);
1570
+ return c < 128 ? ((IDENT[c] ?? 0) & 1) !== 0 : c >= 128 && !isUnicodeSpace(c);
1514
1571
  }
1515
1572
  function isIdentPart(c) {
1516
1573
  return c < 128 ? IDENT[c] !== 0 : c >= 128 && !isUnicodeSpace(c);
@@ -1634,7 +1691,8 @@ function regex(i) {
1634
1691
  return identEnd(j + 1);
1635
1692
  }
1636
1693
  function isOneOf(start, stop, words) {
1637
- if (stop - start !== words[0].length)
1694
+ const [first] = words;
1695
+ if (first === undefined || stop - start !== first.length)
1638
1696
  return false;
1639
1697
  const c = src.charCodeAt(start);
1640
1698
  for (const word of words) {
@@ -1719,7 +1777,7 @@ function code(start, brace) {
1719
1777
  let wordIsProperty = false;
1720
1778
  while (i < n) {
1721
1779
  const c = s.charCodeAt(i);
1722
- if (c < 128 ? (IDENT[c] & 1) !== 0 : !isUnicodeSpace(c)) {
1780
+ if (c < 128 ? ((IDENT[c] ?? 0) & 1) !== 0 : !isUnicodeSpace(c)) {
1723
1781
  let j = i + 1;
1724
1782
  while (j < n) {
1725
1783
  const d = s.charCodeAt(j);
@@ -1972,14 +2030,14 @@ function annotations(start, stop) {
1972
2030
  `, start - 1) + 1;
1973
2031
  const prefix = src.slice(lineStart, start);
1974
2032
  const text = (BLANK.test(prefix) ? prefix : "x") + src.slice(start, stop);
1975
- for (const [, list] of text.matchAll(DEPENDS_ON)) {
1976
- out.dependsOn.push(...list.split(LIST_SEPARATOR).filter(Boolean));
2033
+ for (const match of text.matchAll(DEPENDS_ON)) {
2034
+ out.dependsOn.push(...captured(match, 1).split(LIST_SEPARATOR).filter(Boolean));
1977
2035
  }
1978
- for (const [, list] of text.matchAll(READS)) {
1979
- out.reads.push(...list.split(LIST_SEPARATOR).filter(Boolean));
2036
+ for (const match of text.matchAll(READS)) {
2037
+ out.reads.push(...captured(match, 1).split(LIST_SEPARATOR).filter(Boolean));
1980
2038
  }
1981
- for (const [, list] of text.matchAll(LISTS)) {
1982
- out.lists.push(...list.split(LIST_SEPARATOR).filter(Boolean));
2039
+ for (const match of text.matchAll(LISTS)) {
2040
+ out.lists.push(...captured(match, 1).split(LIST_SEPARATOR).filter(Boolean));
1983
2041
  }
1984
2042
  if (GLOB_REGISTRY.test(text))
1985
2043
  out.registry = true;
@@ -2013,10 +2071,11 @@ function jsdocImport(start, at, stop) {
2013
2071
  JSDOC_IMPORT_TAG.lastIndex = at - 1;
2014
2072
  const tag = JSDOC_IMPORT_TAG.exec(src);
2015
2073
  if (tag && JSDOC_IMPORT_TAG.lastIndex <= stop) {
2016
- const clause = tag[1].replace(JSDOC_LINE_STAR, `
2074
+ const clause = captured(tag, 1).replace(JSDOC_LINE_STAR, `
2017
2075
  `);
2018
2076
  const names = clause.includes("{") ? namedBindings(clause) : undefined;
2019
- out.imports.push(names ? { specifier: tag[3], names, type: true } : { specifier: tag[3], type: true });
2077
+ const specifier = captured(tag, 3);
2078
+ out.imports.push(names ? { specifier, names, type: true } : { specifier, type: true });
2020
2079
  }
2021
2080
  return;
2022
2081
  }
@@ -2028,7 +2087,7 @@ function jsdocImport(start, at, stop) {
2028
2087
  JSDOC_IMPORT_TYPE.lastIndex = at;
2029
2088
  const type = JSDOC_IMPORT_TYPE.exec(src);
2030
2089
  if (type && JSDOC_IMPORT_TYPE.lastIndex <= stop) {
2031
- out.imports.push({ specifier: type[2], type: true });
2090
+ out.imports.push({ specifier: captured(type, 2), type: true });
2032
2091
  }
2033
2092
  }
2034
2093
  function record(specifier, names, disk, type = false) {
@@ -2485,7 +2544,7 @@ function jsxElement(i) {
2485
2544
  p = skipTrivia(p + 1);
2486
2545
  const v = src.charCodeAt(p);
2487
2546
  if (isQuote(v)) {
2488
- const e = src.indexOf(src[p], p + 1);
2547
+ const e = src.indexOf(src.charAt(p), p + 1);
2489
2548
  if (e === -1 || e >= end)
2490
2549
  fail("unterminated JSX attribute", p);
2491
2550
  p = e + 1;
@@ -2546,7 +2605,7 @@ function tagEnd(src, i) {
2546
2605
  if (c === 62)
2547
2606
  return j + 1;
2548
2607
  if (c === 34 || c === 39) {
2549
- const e = src.indexOf(src[j], j + 1);
2608
+ const e = src.indexOf(src.charAt(j), j + 1);
2550
2609
  if (e === -1)
2551
2610
  break;
2552
2611
  j = e + 1;
@@ -2607,7 +2666,7 @@ function lexHost(src, out, host) {
2607
2666
  const generics = tag.match(GENERICS);
2608
2667
  if (generics?.index !== undefined) {
2609
2668
  const start = i + generics.index + generics[0].length;
2610
- const stop = src.indexOf(generics[1], start);
2669
+ const stop = src.indexOf(captured(generics, 1), start);
2611
2670
  if (stop !== -1 && stop < open)
2612
2671
  lexRange(start, stop, TS);
2613
2672
  }
@@ -2671,7 +2730,8 @@ function extractRegex(source, html) {
2671
2730
  unknown: []
2672
2731
  };
2673
2732
  if (html) {
2674
- for (const [, ref] of source.matchAll(HTML_REF)) {
2733
+ for (const match of source.matchAll(HTML_REF)) {
2734
+ const ref = captured(match, 1);
2675
2735
  if (!URL_REF.test(ref)) {
2676
2736
  result.imports.push({
2677
2737
  specifier: RELATIVE.test(ref) ? ref : `./${ref}`
@@ -2679,16 +2739,17 @@ function extractRegex(source, html) {
2679
2739
  }
2680
2740
  }
2681
2741
  }
2682
- for (const [, clause, specifier] of source.matchAll(STATIC_IMPORT)) {
2683
- const names = namedBindings(clause.replace(COMMENTS3, ""));
2742
+ for (const match of source.matchAll(STATIC_IMPORT)) {
2743
+ const specifier = captured(match, 2);
2744
+ const names = namedBindings(captured(match, 1).replace(COMMENTS3, ""));
2684
2745
  result.imports.push(names ? { specifier, names } : { specifier });
2685
2746
  }
2686
- for (const [, specifier] of source.matchAll(SIDE_EFFECT_IMPORT)) {
2687
- result.imports.push({ specifier });
2747
+ for (const match of source.matchAll(SIDE_EFFECT_IMPORT)) {
2748
+ result.imports.push({ specifier: captured(match, 1) });
2688
2749
  }
2689
2750
  const calls = source.includes("import(") || source.includes("require(") || source.includes("vi.");
2690
- for (const [, , specifier] of calls ? source.matchAll(CALL_WITH_LITERAL) : []) {
2691
- result.imports.push({ specifier });
2751
+ for (const match of calls ? source.matchAll(CALL_WITH_LITERAL) : []) {
2752
+ result.imports.push({ specifier: captured(match, 2) });
2692
2753
  }
2693
2754
  if (calls && (NON_LITERAL_CALL.test(source) || TEMPLATE_CALL.test(source))) {
2694
2755
  result.unknown.push("non-literal dynamic import");
@@ -2698,27 +2759,28 @@ function extractRegex(source, html) {
2698
2759
  if (globbing && globs.length !== [...source.matchAll(GLOB_CALL_ANY)].length) {
2699
2760
  result.unknown.push("non-literal glob import");
2700
2761
  }
2701
- for (const [, argument] of GLOB_REGISTRY.test(source) ? [] : globs) {
2702
- for (const [, glob] of argument.matchAll(QUOTED)) {
2762
+ for (const call of GLOB_REGISTRY.test(source) ? [] : globs) {
2763
+ for (const quoted of captured(call, 1).matchAll(QUOTED)) {
2764
+ const glob = captured(quoted, 1);
2703
2765
  if (glob.startsWith("!"))
2704
2766
  continue;
2705
2767
  result.globs.push(glob.replace(QUERY, ""));
2706
2768
  }
2707
2769
  }
2708
2770
  if (source.includes(".goto(")) {
2709
- for (const [, argument] of source.matchAll(GOTO)) {
2710
- result.gotos.push(argument.trim());
2771
+ for (const match of source.matchAll(GOTO)) {
2772
+ result.gotos.push(captured(match, 1).trim());
2711
2773
  }
2712
2774
  }
2713
2775
  result.dependsOn = [
2714
2776
  ...source.includes("@depends-on") ? source.matchAll(DEPENDS_ON) : []
2715
- ].flatMap(([, list]) => list.split(LIST_SEPARATOR).filter(Boolean));
2777
+ ].flatMap((match) => captured(match, 1).split(LIST_SEPARATOR).filter(Boolean));
2716
2778
  result.reads = [
2717
2779
  ...source.includes("@reads") ? source.matchAll(READS) : []
2718
- ].flatMap(([, list]) => list.split(LIST_SEPARATOR).filter(Boolean));
2780
+ ].flatMap((match) => captured(match, 1).split(LIST_SEPARATOR).filter(Boolean));
2719
2781
  result.lists = [
2720
2782
  ...source.includes("@lists") ? source.matchAll(LISTS) : []
2721
- ].flatMap(([, list]) => list.split(LIST_SEPARATOR).filter(Boolean));
2783
+ ].flatMap((match) => captured(match, 1).split(LIST_SEPARATOR).filter(Boolean));
2722
2784
  const disk = source.includes("fs") || source.includes("child_process") || source.includes("Bun.");
2723
2785
  if (disk && READS_DISK.test(source) && result.dependsOn.length + result.reads.length + result.lists.length === 0) {
2724
2786
  result.unknown.push(UNDECLARED_READS);
@@ -2748,7 +2810,7 @@ function extract(format, source) {
2748
2810
  lexRange(0, source.length, DIALECTS[format]);
2749
2811
  extraction = fromLexed(lexed);
2750
2812
  } catch (error) {
2751
- const fallback = error instanceof LexError ? error.message : `lexer error: ${error}`;
2813
+ const fallback = error instanceof LexError ? error.message : `lexer error: ${String(error)}`;
2752
2814
  extraction = { ...extractRegex(source, format === "html"), fallback };
2753
2815
  }
2754
2816
  if (!isHost(format)) {
@@ -2774,7 +2836,8 @@ function stringsOf(format, source) {
2774
2836
  return strings;
2775
2837
  }
2776
2838
  function own(text) {
2777
- return JSON.parse(JSON.stringify(text));
2839
+ const copy = JSON.parse(JSON.stringify(text));
2840
+ return typeof copy === "string" ? copy : text;
2778
2841
  }
2779
2842
  function detach(extraction) {
2780
2843
  const list = (texts) => texts.map(own);
@@ -3148,7 +3211,7 @@ function literalOf(re) {
3148
3211
  return;
3149
3212
  let path = "";
3150
3213
  for (let i = 1;i < source.length - 1; i++) {
3151
- const char = source[i];
3214
+ const char = source.charAt(i);
3152
3215
  if (char === "\\")
3153
3216
  path += source[++i];
3154
3217
  else if (REGEX_SYNTAX.includes(char))
@@ -3299,7 +3362,12 @@ function affectedBy(graph, changed, {
3299
3362
  const visitGroup = (group, from) => {
3300
3363
  const { nodes, kinds } = group;
3301
3364
  for (let i = 0;i < nodes.length; i++) {
3302
- visit(nodes[i], parents && { from, kind: kinds[i] });
3365
+ const node = nodes[i];
3366
+ const kind = kinds[i];
3367
+ if (node === undefined || kind === undefined) {
3368
+ throw new Error("bivium: graph: a pattern group lost a node's kind.");
3369
+ }
3370
+ visit(node, parents && { from, kind });
3303
3371
  }
3304
3372
  };
3305
3373
  const visitMatches = (groups, path) => {
@@ -3341,6 +3409,9 @@ function affectedBy(graph, changed, {
3341
3409
  };
3342
3410
  for (let at = 0;at < queue.length && !done; at++) {
3343
3411
  const path = queue[at];
3412
+ if (path === undefined) {
3413
+ throw new Error("bivium: graph: walked off the queue.");
3414
+ }
3344
3415
  for (const dependent of dependents.get(path) ?? []) {
3345
3416
  visit(dependent, parents && { from: path, kind: fileKind(graph, dependent, path) });
3346
3417
  }
@@ -3471,20 +3542,16 @@ function keyOf(text, line) {
3471
3542
  return;
3472
3543
  return { key: text.slice(0, colon), rest: text.slice(colon + 1) };
3473
3544
  }
3474
-
3475
- class Parser {
3476
- at = 0;
3477
- lines;
3478
- constructor(lines) {
3479
- this.lines = lines;
3480
- }
3481
- block(indent) {
3482
- const first = this.lines[this.at];
3545
+ function parseYaml(text) {
3546
+ const lines = linesOf(text);
3547
+ let at = 0;
3548
+ function block(indent) {
3549
+ const first = lines[at];
3483
3550
  if (!first || first.indent !== indent)
3484
3551
  return "";
3485
- return first.text === "-" || first.text.startsWith("- ") ? this.sequence(indent) : this.mapping(indent, {});
3552
+ return first.text === "-" || first.text.startsWith("- ") ? sequence(indent) : mapping(indent, {});
3486
3553
  }
3487
- value(rest, indent, line) {
3554
+ function value(rest, indent, line) {
3488
3555
  const text = rest.trim();
3489
3556
  if (EMPTY_MAP.test(text))
3490
3557
  return {};
@@ -3492,11 +3559,11 @@ class Parser {
3492
3559
  return [];
3493
3560
  if (text !== "" && !text.startsWith("#"))
3494
3561
  return scalar(text, line);
3495
- const next = this.lines[this.at];
3496
- return next && next.indent > indent ? this.block(next.indent) : "";
3562
+ const next = lines[at];
3563
+ return next && next.indent > indent ? block(next.indent) : "";
3497
3564
  }
3498
- mapping(indent, into) {
3499
- for (let line = this.lines[this.at];line; line = this.lines[this.at]) {
3565
+ function mapping(indent, into) {
3566
+ for (let line = lines[at];line; line = lines[at]) {
3500
3567
  if (line.indent < indent)
3501
3568
  break;
3502
3569
  if (line.indent > indent)
@@ -3506,40 +3573,37 @@ class Parser {
3506
3573
  fail2(line, "a line that isn't a key");
3507
3574
  if (Object.hasOwn(into, entry.key))
3508
3575
  fail2(line, "a duplicate key");
3509
- this.at++;
3510
- into[entry.key] = this.value(entry.rest, indent, line);
3576
+ at++;
3577
+ into[entry.key] = value(entry.rest, indent, line);
3511
3578
  }
3512
3579
  return into;
3513
3580
  }
3514
- sequence(indent) {
3581
+ function sequence(indent) {
3515
3582
  const items = [];
3516
- for (let line = this.lines[this.at];line; line = this.lines[this.at]) {
3583
+ for (let line = lines[at];line; line = lines[at]) {
3517
3584
  if (line.indent < indent)
3518
3585
  break;
3519
3586
  if (line.indent > indent)
3520
3587
  fail2(line, "unexpected indentation");
3521
3588
  if (line.text !== "-" && !line.text.startsWith("- "))
3522
3589
  break;
3523
- this.at++;
3590
+ at++;
3524
3591
  const text = line.text.slice(1).trimStart();
3525
3592
  const inner = { ...line, indent: line.indent + 2, text };
3526
3593
  if (text !== "" && keyOf(text, line)) {
3527
- this.lines.splice(this.at, 0, inner);
3528
- items.push(this.mapping(inner.indent, {}));
3594
+ lines.splice(at, 0, inner);
3595
+ items.push(mapping(inner.indent, {}));
3529
3596
  } else {
3530
- items.push(this.value(text, indent, line));
3597
+ items.push(value(text, indent, line));
3531
3598
  }
3532
3599
  }
3533
3600
  return items;
3534
3601
  }
3535
- }
3536
- function parseYaml(text) {
3537
- const parser = new Parser(linesOf(text));
3538
- const value = parser.block(0);
3539
- const left = parser.lines[parser.at];
3602
+ const document = block(0);
3603
+ const left = lines[at];
3540
3604
  if (left)
3541
3605
  fail2(left, "unexpected indentation");
3542
- return value;
3606
+ return document;
3543
3607
  }
3544
3608
 
3545
3609
  // src/lockfile.ts
@@ -3601,9 +3665,8 @@ function install(packages, name, entry, version, info) {
3601
3665
  packages.set(name, installed);
3602
3666
  }
3603
3667
  function installedName(key) {
3604
- const parts = key.split("/");
3605
- const last = parts.length - 1;
3606
- return last > 0 && parts[last - 1].startsWith("@") ? `${parts[last - 1]}/${parts[last]}` : parts[last];
3668
+ const [name = key, scope] = key.split("/").reverse();
3669
+ return scope?.startsWith("@") ? `${scope}/${name}` : name;
3607
3670
  }
3608
3671
  function parseBunLock(text) {
3609
3672
  const value = parseLenient(text);
@@ -3836,8 +3899,13 @@ async function readPackageDiff(changed, listed, base, head) {
3836
3899
  const read = (path) => Promise.all([base(path), head(path)]);
3837
3900
  const known = [...FORMATS.keys()];
3838
3901
  const [lockTexts, manifestTexts] = await Promise.all([
3839
- Promise.all(known.map((file) => lockfiles.includes(file) ? read(file) : head(file).then((text) => [text, text]))),
3840
- Promise.all(manifests.map(read))
3902
+ Promise.all(known.map(async (file) => {
3903
+ if (lockfiles.includes(file))
3904
+ return [file, ...await read(file)];
3905
+ const text = await head(file);
3906
+ return [file, text, text];
3907
+ })),
3908
+ Promise.all(manifests.map(async (file) => [file, ...await read(file)]))
3841
3909
  ]);
3842
3910
  const diff = {
3843
3911
  files: new Map,
@@ -3847,8 +3915,7 @@ async function readPackageDiff(changed, listed, base, head) {
3847
3915
  bins: new Set
3848
3916
  };
3849
3917
  const present = new Map;
3850
- for (const [i, file] of known.entries()) {
3851
- const [baseText, headText] = lockTexts[i];
3918
+ for (const [file, baseText, headText] of lockTexts) {
3852
3919
  const after = parse(file, headText);
3853
3920
  if (headText !== undefined)
3854
3921
  present.set(file, after);
@@ -3886,8 +3953,9 @@ async function readPackageDiff(changed, listed, base, head) {
3886
3953
  }
3887
3954
  }
3888
3955
  const unread = UNREAD.some((file) => listed.includes(file));
3889
- for (const [i, file] of manifests.entries()) {
3890
- const [before, after] = manifestTexts[i].map(parseManifest);
3956
+ for (const [file, beforeText, afterText] of manifestTexts) {
3957
+ const before = parseManifest(beforeText);
3958
+ const after = parseManifest(afterText);
3891
3959
  if (!(before && after) || unread || present.size === 0)
3892
3960
  continue;
3893
3961
  const others = (record) => restOf(record, DEP_FIELDS2);
@@ -3945,8 +4013,8 @@ function packageSeeds(graph, config, diff, files) {
3945
4013
  seen.add(name);
3946
4014
  const closure = new Set([name]);
3947
4015
  const queue = [name];
3948
- for (let at = 0;at < queue.length; at++) {
3949
- for (const dependent of diff.dependents.get(queue[at]) ?? []) {
4016
+ for (const queued of queue) {
4017
+ for (const dependent of diff.dependents.get(queued) ?? []) {
3950
4018
  if (closure.has(dependent))
3951
4019
  continue;
3952
4020
  closure.add(dependent);
@@ -4289,7 +4357,7 @@ async function readTsconfigs(files, read) {
4289
4357
  return;
4290
4358
  await Promise.all(result.read.extends.map((target) => {
4291
4359
  const path = extendsPath(file, target);
4292
- return path === undefined ? undefined : load(path, true);
4360
+ return path === undefined ? Promise.resolve() : load(path, true);
4293
4361
  }));
4294
4362
  };
4295
4363
  await Promise.all(files.map((file) => load(file, false)));
@@ -4424,10 +4492,12 @@ async function settingChanges({
4424
4492
  const tsDirs = [...tsconfigs.keys()];
4425
4493
  const packageDirs = [...packages];
4426
4494
  const candidates = changed.filter((file) => TSCONFIG.test(file) || MANIFEST2.test(file) && !accounted.has(file) || tsDirs.some((dir) => tsconfigs.get(dir)?.includes(file)));
4427
- const texts = await Promise.all(candidates.map((file) => Promise.all([base(file), head(file)])));
4495
+ const texts = await Promise.all(candidates.map(async (file) => {
4496
+ const [before, after] = await Promise.all([base(file), head(file)]);
4497
+ return { file, before, after };
4498
+ }));
4428
4499
  const result = new Map;
4429
- for (const [i, file] of candidates.entries()) {
4430
- const [before, after] = texts[i];
4500
+ for (const { file, before, after } of texts) {
4431
4501
  const manifest = MANIFEST2.test(file);
4432
4502
  const keys = changedKeys(parsed(before, !manifest), parsed(after, !manifest));
4433
4503
  const counted = keys?.filter((key) => !(manifest && METADATA.has(key)));
@@ -4491,7 +4561,10 @@ function collectPackages(rootJson, sources) {
4491
4561
  var READS_IN_FLIGHT = 64;
4492
4562
  async function inParallel(tasks, limit) {
4493
4563
  let next = 0;
4494
- const worker = () => next < tasks.length ? tasks[next++]().then(worker) : Promise.resolve();
4564
+ const worker = () => {
4565
+ const task = tasks[next++];
4566
+ return task === undefined ? Promise.resolve() : task().then(worker);
4567
+ };
4495
4568
  await Promise.all(Array.from({ length: Math.min(limit, tasks.length) }, worker));
4496
4569
  }
4497
4570
  async function isFile(path) {
@@ -4568,8 +4641,9 @@ function graphView(graph, config) {
4568
4641
  dependents: (from) => affectedBy(graph, from, { includeUnknown: false }),
4569
4642
  tests: (name) => {
4570
4643
  const suite = config.suites.find((candidate) => candidate.name === name);
4571
- if (!suite)
4572
- throw new Error(`bivium: no suite "${name}"`);
4644
+ if (!suite) {
4645
+ throw new BiviumError2("BV_UNKNOWN_SUITE", `bivium: no suite "${name}"`);
4646
+ }
4573
4647
  return nodes.filter(suite.isTest);
4574
4648
  }
4575
4649
  };
@@ -4742,4 +4816,4 @@ async function plan2(options = {}) {
4742
4816
  };
4743
4817
  }
4744
4818
 
4745
- export { version, BiviumError, didYouMean, globToRegExp, defineConfig2, inRoot, sorted, QUERY, UNDECLARED_READS, RELATIVE, aliasPath, createResolver, SCANNED, formatOf, extract, stringsOf, finish, gotoPage, walksByTypes, importersOf, affectedBy, formatSelection, orphanOf, plural, computePlan, prepare, plan2 };
4819
+ export { version, githubOutputPath, BiviumError2, didYouMean, globToRegExp, defineConfig2, inRoot, sorted, QUERY, UNDECLARED_READS, RELATIVE, aliasPath, createResolver, SCANNED, formatOf, extract, stringsOf, finish, gotoPage, walksByTypes, importersOf, affectedBy, formatSelection, orphanOf, plural, computePlan, prepare, plan2 };