bivium 0.9.0 → 0.10.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.
@@ -1,6 +1,9 @@
1
+ import {
2
+ plural2
3
+ } from "./shared-a8ebfhzf.js";
1
4
  import {
2
5
  BiviumError2
3
- } from "./shared-211m8fjt.js";
6
+ } from "./shared-118ck8qt.js";
4
7
  import {
5
8
  globToRegExp,
6
9
  matcher,
@@ -8,34 +11,245 @@ import {
8
11
  inRoot2,
9
12
  checkConfig2,
10
13
  loadConfig2
11
- } from "./shared-550cvwt2.js";
14
+ } from "./shared-px5a17nj.js";
15
+ import {
16
+ nowMs
17
+ } from "./shared-graedbt1.js";
18
+ import {
19
+ version
20
+ } from "./shared-x17wzptz.js";
12
21
 
13
- // src/env.ts
14
- function githubOutputPath() {
15
- return process.env.GITHUB_OUTPUT;
16
- }
17
- function nowMs() {
18
- return Date.now();
19
- }
20
- function environment() {
21
- return process.env;
22
- }
23
- var AGENT_ENV = [
24
- "AGENT",
25
- "AI_AGENT",
26
- "CLAUDECODE",
27
- "CODEX_CI",
28
- "CODEX_THREAD_ID"
29
- ];
30
- function agentVariable(env) {
31
- return AGENT_ENV.find((name) => {
32
- const value = env[name];
33
- return value !== undefined && value !== "" && value !== "0";
34
- });
22
+ // src/compute.ts
23
+ import { readFile as readFile3, stat } from "node:fs/promises";
24
+ import { join as join3, posix as posix6, resolve } from "node:path";
25
+
26
+ // src/cache.ts
27
+ import { existsSync } from "node:fs";
28
+ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
29
+ import { isAbsolute, join } from "node:path";
30
+ var SCANNER_VERSION = 10;
31
+ var MAGIC = "bivium-extractions";
32
+ var FILE = "extractions.json";
33
+ function isHeader(value) {
34
+ return typeof value === "object" && value !== null && "magic" in value && value.magic === MAGIC && "bivium" in value && value.bivium === version && "scanner" in value && value.scanner === SCANNER_VERSION && "rows" in value && typeof value.rows === "number" && "strings" in value && typeof value.strings === "number";
35
+ }
36
+ function cacheDir(root, cache) {
37
+ if (cache === false)
38
+ return;
39
+ if (typeof cache === "string") {
40
+ return isAbsolute(cache) ? cache : join(root, cache);
41
+ }
42
+ const modules = join(root, "node_modules");
43
+ return existsSync(modules) ? join(modules, ".cache", "bivium") : join(root, ".bivium", "cache");
35
44
  }
36
45
 
37
- // package.json
38
- var version = "0.9.0";
46
+ class ExtractionCache {
47
+ #rows = new Map;
48
+ #strings = [];
49
+ #used = new Map;
50
+ #dirty = false;
51
+ dir;
52
+ constructor(dir) {
53
+ this.dir = dir;
54
+ }
55
+ static async open(dir) {
56
+ const cache = new ExtractionCache(dir);
57
+ if (!dir)
58
+ return cache;
59
+ const text = await readFile(join(dir, FILE), "utf-8").catch(() => "");
60
+ if (text)
61
+ cache.#load(text);
62
+ return cache;
63
+ }
64
+ #load(text) {
65
+ try {
66
+ const parsed = JSON.parse(text);
67
+ if (!Array.isArray(parsed))
68
+ return;
69
+ const fields = parsed;
70
+ const [header, strings, rows] = fields;
71
+ if (!isHeader(header) || !Array.isArray(strings) || !Array.isArray(rows) || header.strings !== strings.length || header.rows !== rows.length) {
72
+ return;
73
+ }
74
+ this.#strings = strings;
75
+ for (const row of rows) {
76
+ if (Array.isArray(row) && typeof row[0] === "string") {
77
+ this.#rows.set(row[0], row);
78
+ }
79
+ }
80
+ } catch {}
81
+ }
82
+ get size() {
83
+ return this.#rows.size;
84
+ }
85
+ get(oid, format) {
86
+ const key = `${format}:${oid}`;
87
+ const used = this.#used.get(key);
88
+ if (used)
89
+ return used;
90
+ const row = this.#rows.get(key);
91
+ if (!row)
92
+ return;
93
+ let extraction;
94
+ try {
95
+ extraction = decode(row, this.#strings);
96
+ } catch {
97
+ this.#rows.delete(key);
98
+ return;
99
+ }
100
+ this.#used.set(key, extraction);
101
+ return extraction;
102
+ }
103
+ set(oid, format, extraction) {
104
+ const key = `${format}:${oid}`;
105
+ this.#used.set(key, extraction);
106
+ this.#dirty = true;
107
+ }
108
+ async save() {
109
+ if (!this.dir || !this.#dirty)
110
+ return;
111
+ const table = createStrings();
112
+ const rows = [];
113
+ for (const [key, extraction] of this.#used) {
114
+ rows.push(encode(key, extraction, table));
115
+ }
116
+ let stale = Math.floor(this.#used.size / 2);
117
+ for (const [key, row] of this.#rows) {
118
+ if (stale === 0)
119
+ break;
120
+ if (this.#used.has(key))
121
+ continue;
122
+ try {
123
+ rows.push(encode(key, decode(row, this.#strings), table));
124
+ stale--;
125
+ } catch {}
126
+ }
127
+ const header = {
128
+ magic: MAGIC,
129
+ bivium: version,
130
+ scanner: SCANNER_VERSION,
131
+ rows: rows.length,
132
+ strings: table.list.length
133
+ };
134
+ const file = join(this.dir, FILE);
135
+ const temp = `${file}.${process.pid}.${nowMs()}.tmp`;
136
+ try {
137
+ await mkdir(this.dir, { recursive: true });
138
+ const ignore = join(this.dir, ".gitignore");
139
+ if (!existsSync(ignore))
140
+ await writeFile(ignore, `*
141
+ `);
142
+ await writeFile(temp, JSON.stringify([header, table.list, rows]));
143
+ await rename(temp, file);
144
+ this.#dirty = false;
145
+ } catch {
146
+ await unlink(temp).catch(() => {
147
+ return;
148
+ });
149
+ }
150
+ }
151
+ }
152
+ function createStrings() {
153
+ const list = [];
154
+ const idsByValue = new Map;
155
+ const id = (value) => {
156
+ let found = idsByValue.get(value);
157
+ if (found === undefined) {
158
+ found = list.length;
159
+ list.push(value);
160
+ idsByValue.set(value, found);
161
+ }
162
+ return found;
163
+ };
164
+ const ids = (values) => values.length === 0 ? 0 : values.map(id);
165
+ return { list, id, ids };
166
+ }
167
+ function typeIndexes(imports) {
168
+ const indexes = [];
169
+ for (const [i, ref] of imports.entries())
170
+ if (ref.type)
171
+ indexes.push(i);
172
+ return indexes.length === 0 ? 0 : indexes;
173
+ }
174
+ function encode(key, e, table) {
175
+ const imports = e.imports.map(({ specifier, names }) => names ? [table.id(specifier), ...names.map((n) => table.id(n))] : table.id(specifier));
176
+ const barrel = e.barrel && [
177
+ [...e.barrel.names].flatMap(([name, from]) => [
178
+ table.id(name),
179
+ table.id(from)
180
+ ]),
181
+ table.ids(e.barrel.stars)
182
+ ];
183
+ return [
184
+ key,
185
+ imports.length === 0 ? 0 : imports,
186
+ table.ids(e.globs),
187
+ table.ids(e.gotos),
188
+ table.ids(e.dependsOn),
189
+ table.ids(e.reads),
190
+ table.ids(e.unknown),
191
+ e.fallback === undefined ? 0 : table.id(e.fallback),
192
+ barrel ?? 0,
193
+ typeIndexes(e.imports),
194
+ table.ids(e.lists),
195
+ table.ids(e.dependsOnEach)
196
+ ];
197
+ }
198
+ function decode(row, strings) {
199
+ const str = (id) => {
200
+ const value = typeof id === "number" ? strings[id] : undefined;
201
+ if (typeof value !== "string")
202
+ throw new Error("bad string id");
203
+ return value;
204
+ };
205
+ const list = (ids) => {
206
+ if (ids === 0)
207
+ return [];
208
+ if (!Array.isArray(ids))
209
+ throw new Error("bad list");
210
+ return ids.map(str);
211
+ };
212
+ const refs = row[1] === 0 ? [] : row[1];
213
+ if (!Array.isArray(refs))
214
+ throw new Error("bad imports");
215
+ const imports = refs.map((item) => Array.isArray(item) ? { specifier: str(item[0]), names: item.slice(1).map(str) } : { specifier: str(item) });
216
+ if (row[9] !== 0) {
217
+ if (!Array.isArray(row[9]))
218
+ throw new Error("bad types");
219
+ for (const i of row[9]) {
220
+ const ref = typeof i === "number" ? imports[i] : undefined;
221
+ if (!ref)
222
+ throw new Error("bad type index");
223
+ ref.type = true;
224
+ }
225
+ }
226
+ const extraction = {
227
+ imports,
228
+ globs: list(row[2]),
229
+ gotos: list(row[3]),
230
+ dependsOn: list(row[4]),
231
+ dependsOnEach: list(row[11]),
232
+ reads: list(row[5]),
233
+ lists: list(row[10]),
234
+ unknown: list(row[6])
235
+ };
236
+ if (row[7] !== 0)
237
+ extraction.fallback = str(row[7]);
238
+ if (row[8] !== 0) {
239
+ if (!Array.isArray(row[8]))
240
+ throw new Error("bad barrel");
241
+ const barrel = row[8];
242
+ const [pairs, stars] = barrel;
243
+ if (!Array.isArray(pairs))
244
+ throw new Error("bad barrel names");
245
+ const names = new Map;
246
+ for (let i = 0;i < pairs.length; i += 2) {
247
+ names.set(str(pairs[i]), str(pairs[i + 1]));
248
+ }
249
+ extraction.barrel = { names, stars: list(stars) };
250
+ }
251
+ return extraction;
252
+ }
39
253
 
40
254
  // src/barrel.ts
41
255
  var COMMENTS = /\/\/.*$|\/\*[\s\S]*?\*\//gm;
@@ -84,7 +298,7 @@ var UNDECLARED_READS = "reads the disk without @depends-on";
84
298
  var RELATIVE = /^\.\.?(?:\/|$)/;
85
299
  var URL_REF = /^[a-z]+:|^\/\//;
86
300
  var LIST_SEPARATOR = /[\s,]+(?![^{]*\})/;
87
- var DEPENDS_ON = /^\s*(?:\/\/|\/?\*+)\s*@depends-on\s+(.+?)\s*(?:\*\/)?\s*$/gm;
301
+ var DEPENDS_ON = /^\s*(?:\/\/|\/?\*+)\s*@depends-on(-each)?\s+(.+?)\s*(?:\*\/)?\s*$/gm;
88
302
  var READS = /^\s*(?:\/\/|\/?\*+)\s*@reads\s+(.+?)\s*(?:\*\/)?\s*$/gm;
89
303
  var LISTS = /^\s*(?:\/\/|\/?\*+)\s*@lists\s+(.+?)\s*(?:\*\/)?\s*$/gm;
90
304
  var GLOB_REGISTRY = /^\s*(?:\/\/|\/?\*+)\s*@glob-registry\b/m;
@@ -481,6 +695,19 @@ function createResolver({
481
695
  }
482
696
  const { dir, relative, scope } = last;
483
697
  const hash = specifier.startsWith("#") ? "#" : "";
698
+ if (from.endsWith(".html") && /^\/(?!\/)/.test(specifier)) {
699
+ if (relative.has(specifier))
700
+ return relative.get(specifier);
701
+ const path = `.${specifier.replace(QUERY, "")}`;
702
+ let resolved;
703
+ for (let at = dir;resolved === undefined; at = posix.dirname(at)) {
704
+ resolved = resolveRelative(at, path);
705
+ if (at === "." || at === "" || at === "/")
706
+ break;
707
+ }
708
+ relative.set(specifier, resolved);
709
+ return resolved;
710
+ }
484
711
  const isRelative = RELATIVE.test(specifier);
485
712
  const memo = isRelative ? relative : scope.resolved;
486
713
  if (memo.has(specifier))
@@ -505,6 +732,7 @@ function createLexed() {
505
732
  globs: [],
506
733
  gotos: [],
507
734
  dependsOn: [],
735
+ dependsOnEach: [],
508
736
  reads: [],
509
737
  lists: [],
510
738
  registry: false,
@@ -586,6 +814,7 @@ function openFile(source, sink) {
586
814
  function lexRange(start, stop, language = TS) {
587
815
  dialect = language;
588
816
  end = stop;
817
+ out.spans?.scripts.push(start, stop);
589
818
  let i = start;
590
819
  if (src.charCodeAt(i) === 65279)
591
820
  i++;
@@ -704,6 +933,7 @@ function template(start) {
704
933
  }
705
934
  function templatePart(start, stack) {
706
935
  const e = template(start);
936
+ out.spans?.literals.push(start, e);
707
937
  if (out.strings && !stack.includes(M_BRACKET)) {
708
938
  out.strings.push(src.slice(start, templateOpen ? e - 2 : e - 1));
709
939
  }
@@ -995,7 +1225,9 @@ function code(start, brace) {
995
1225
  last = T_PUNCT;
996
1226
  i += 2;
997
1227
  } else if (!valueEnded(last, wordStart, wordEnd, wordIsProperty) && dialect.jsx && isJsxStart(i)) {
1228
+ const element = i;
998
1229
  i = jsxElement(i);
1230
+ out.spans?.literals.push(element, i);
999
1231
  last = T_OPERAND;
1000
1232
  } else {
1001
1233
  last = T_PUNCT;
@@ -1045,6 +1277,7 @@ function numberEnd(start) {
1045
1277
  return i;
1046
1278
  }
1047
1279
  function comment(start, stop, block) {
1280
+ out.spans?.comments.push(start, stop);
1048
1281
  if (nextAt < start)
1049
1282
  nextAt = indexOrEnd("@", start);
1050
1283
  while (nextAt < stop) {
@@ -1075,7 +1308,10 @@ function annotations(start, stop) {
1075
1308
  const prefix = src.slice(lineStart, start);
1076
1309
  const text = (BLANK.test(prefix) ? prefix : "x") + src.slice(start, stop);
1077
1310
  for (const match of text.matchAll(DEPENDS_ON)) {
1078
- out.dependsOn.push(...captured(match, 1).split(LIST_SEPARATOR).filter(Boolean));
1311
+ const globs = captured(match, 2).split(LIST_SEPARATOR).filter(Boolean);
1312
+ out.dependsOn.push(...globs);
1313
+ if (match[1] !== undefined)
1314
+ out.dependsOnEach.push(...globs);
1079
1315
  }
1080
1316
  for (const match of text.matchAll(READS)) {
1081
1317
  out.reads.push(...captured(match, 1).split(LIST_SEPARATOR).filter(Boolean));
@@ -1734,7 +1970,7 @@ function ref(tag, out) {
1734
1970
  const value = match && (match[1] ?? match[2] ?? match[3]);
1735
1971
  if (value && !URL_REF.test(value)) {
1736
1972
  out.imports.push({
1737
- specifier: RELATIVE.test(value) ? value : `./${value}`
1973
+ specifier: RELATIVE.test(value) || value.startsWith("/") ? value : `./${value}`
1738
1974
  });
1739
1975
  }
1740
1976
  }
@@ -1769,6 +2005,7 @@ function extractRegex(source, html) {
1769
2005
  globs: [],
1770
2006
  gotos: [],
1771
2007
  dependsOn: [],
2008
+ dependsOnEach: [],
1772
2009
  reads: [],
1773
2010
  lists: [],
1774
2011
  unknown: []
@@ -1816,9 +2053,12 @@ function extractRegex(source, html) {
1816
2053
  result.gotos.push(captured(match, 1).trim());
1817
2054
  }
1818
2055
  }
1819
- result.dependsOn = [
1820
- ...source.includes("@depends-on") ? source.matchAll(DEPENDS_ON) : []
1821
- ].flatMap((match) => captured(match, 1).split(LIST_SEPARATOR).filter(Boolean));
2056
+ for (const match of source.includes("@depends-on") ? source.matchAll(DEPENDS_ON) : []) {
2057
+ const globs = captured(match, 2).split(LIST_SEPARATOR).filter(Boolean);
2058
+ result.dependsOn.push(...globs);
2059
+ if (match[1] !== undefined)
2060
+ result.dependsOnEach.push(...globs);
2061
+ }
1822
2062
  result.reads = [
1823
2063
  ...source.includes("@reads") ? source.matchAll(READS) : []
1824
2064
  ].flatMap((match) => captured(match, 1).split(LIST_SEPARATOR).filter(Boolean));
@@ -1896,6 +2136,7 @@ function detach(extraction) {
1896
2136
  globs: list(extraction.globs),
1897
2137
  gotos: list(extraction.gotos),
1898
2138
  dependsOn: list(extraction.dependsOn),
2139
+ dependsOnEach: list(extraction.dependsOnEach),
1899
2140
  reads: list(extraction.reads),
1900
2141
  lists: list(extraction.lists),
1901
2142
  unknown: extraction.unknown
@@ -1918,6 +2159,7 @@ function finish(path, extraction, { gotos = false } = {}) {
1918
2159
  globs: globs.map((glob) => posix2.join(dir, glob)),
1919
2160
  gotos: gotos ? extraction.gotos : [],
1920
2161
  dependsOn: extraction.dependsOn,
2162
+ dependsOnEach: extraction.dependsOnEach,
1921
2163
  reads: extraction.reads,
1922
2164
  lists: extraction.lists,
1923
2165
  unknown: extraction.unknown
@@ -1949,6 +2191,7 @@ function fromLexed(lexed) {
1949
2191
  globs,
1950
2192
  gotos: lexed.gotos,
1951
2193
  dependsOn: lexed.dependsOn,
2194
+ dependsOnEach: lexed.dependsOnEach,
1952
2195
  reads: lexed.reads,
1953
2196
  lists: lexed.lists,
1954
2197
  unknown
@@ -2153,6 +2396,9 @@ function graphFrom(files, extractions, { config, packages, tsconfigs }) {
2153
2396
  for (const glob of found.dependsOn) {
2154
2397
  addPattern(deps, globToRegExp(glob), "depends-on");
2155
2398
  }
2399
+ if (found.dependsOnEach.length > 0) {
2400
+ deps.cases = found.dependsOnEach.map(globToRegExp);
2401
+ }
2156
2402
  for (const glob of found.reads)
2157
2403
  deps.reads.push(globToRegExp(glob));
2158
2404
  if (found.lists.length > 0)
@@ -2348,13 +2594,20 @@ function reaches(graph, changed, match, options = {}) {
2348
2594
  return true;
2349
2595
  return false;
2350
2596
  }
2351
- function walksByTypes(graph, changed, options = {}) {
2597
+ function walksByTypes(graph, changed, {
2598
+ seals,
2599
+ ...options
2600
+ } = {}) {
2352
2601
  const seeds = [...changed];
2353
2602
  const walks = new Map;
2354
2603
  return (types) => {
2355
2604
  let walk = walks.get(types);
2356
2605
  if (!walk) {
2357
- walk = affectedBy(graph, seeds, { ...options, types });
2606
+ walk = affectedBy(graph, seeds, {
2607
+ ...options,
2608
+ types,
2609
+ ...seals && { sealed: types ? seals.types : seals.runtime }
2610
+ });
2358
2611
  walks.set(types, walk);
2359
2612
  }
2360
2613
  return walk;
@@ -2377,6 +2630,14 @@ function fileKind(graph, dependent, node) {
2377
2630
  return "name";
2378
2631
  return dependent.endsWith(".html") ? "html" : "import";
2379
2632
  }
2633
+ function leadsTo(parents, from, to) {
2634
+ for (let node = from;node !== undefined; ) {
2635
+ if (node === to)
2636
+ return true;
2637
+ node = parents.get(node)?.from;
2638
+ }
2639
+ return false;
2640
+ }
2380
2641
  function affectedBy(graph, changed, {
2381
2642
  includeUnknown = true,
2382
2643
  quiet = [],
@@ -2384,6 +2645,7 @@ function affectedBy(graph, changed, {
2384
2645
  layout,
2385
2646
  readers: seedReaders = true,
2386
2647
  opaque,
2648
+ sealed,
2387
2649
  until,
2388
2650
  parents
2389
2651
  } = {}) {
@@ -2393,8 +2655,18 @@ function affectedBy(graph, changed, {
2393
2655
  const affected = new Set;
2394
2656
  const queue = [];
2395
2657
  let done = false;
2658
+ let closed;
2396
2659
  const visit = (path, via) => {
2397
- if (affected.has(path) || opaque?.(path))
2660
+ if (affected.has(path)) {
2661
+ if (closed?.delete(path)) {
2662
+ queue.push(path);
2663
+ if (via && parents && !leadsTo(parents, via.from, path)) {
2664
+ parents.set(path, via);
2665
+ }
2666
+ }
2667
+ return;
2668
+ }
2669
+ if (opaque?.(path))
2398
2670
  return;
2399
2671
  affected.add(path);
2400
2672
  queue.push(path);
@@ -2426,6 +2698,9 @@ function affectedBy(graph, changed, {
2426
2698
  const changedPaths = [...changed];
2427
2699
  for (const path of changedPaths)
2428
2700
  visit(path);
2701
+ if (sealed && sealed.size > 0) {
2702
+ closed = new Set(changedPaths.filter((path) => sealed.has(path)));
2703
+ }
2429
2704
  const first = queue[0];
2430
2705
  for (const path of quiet) {
2431
2706
  visit(path);
@@ -2456,7 +2731,10 @@ function affectedBy(graph, changed, {
2456
2731
  if (path === undefined) {
2457
2732
  throw new Error("bivium: graph: walked off the queue.");
2458
2733
  }
2734
+ const only = closed?.has(path) ? sealed?.get(path) : undefined;
2459
2735
  for (const dependent of dependents.get(path) ?? []) {
2736
+ if (only && !only.has(dependent))
2737
+ continue;
2460
2738
  visit(dependent, parents && { from: path, kind: fileKind(graph, dependent, path) });
2461
2739
  }
2462
2740
  const exact = literal.size > 0 ? literal.get(path) : undefined;
@@ -2479,1465 +2757,1816 @@ function affectedBy(graph, changed, {
2479
2757
  return affected;
2480
2758
  }
2481
2759
 
2482
- // src/sorted.ts
2483
- function byCodeUnit(a, b) {
2484
- if (a === b)
2485
- return 0;
2486
- return a < b ? -1 : 1;
2760
+ // src/edits.ts
2761
+ var PRAGMA = /@(?:depends-on|reads|lists|glob-registry|vite-ignore|jsx|ts-|flow|noflow|bun|license|preserve|vitest-environment|jest-environment|ngInject)|webpack[A-Z]|turbopack[A-Z]|[#@]__[A-Z_]+__|(?:istanbul|c8|v8) ignore|svelte-ignore|sourceURL=|sourceMappingURL=|^\/\*!|^\/\/\/\s*</;
2762
+ function mayBeComment(line) {
2763
+ const text = line.trim();
2764
+ return text === "" || text.startsWith("*") || text.includes("//") || text.includes("/*") || text.includes("*/");
2765
+ }
2766
+ function mayNarrow(path, hunks) {
2767
+ if (!hunks || hunks.length === 0)
2768
+ return false;
2769
+ const adds = !path.endsWith(".svelte");
2770
+ return hunks.every((hunk) => adds && hunk.oldCount === 0 || hunk.removed.every(mayBeComment) && hunk.added.every(mayBeComment));
2487
2771
  }
2488
- function sorted(values) {
2489
- return [...values].sort(byCodeUnit);
2490
- }
2491
-
2492
- // src/terminal.ts
2493
- var asIs = (text) => text;
2494
- var PLAIN = {
2495
- good: asIs,
2496
- warn: asIs,
2497
- bad: asIs,
2498
- dim: asIs,
2499
- bold: asIs,
2500
- faint: asIs
2501
- };
2502
- function createPaint() {
2503
- const wrap = (code) => (text) => text === "" ? text : `\x1B[${code}m${text}\x1B[39m`;
2504
- return {
2505
- good: wrap(32),
2506
- warn: wrap(33),
2507
- bad: wrap(31),
2508
- dim: wrap(90),
2509
- bold: (text) => text === "" ? text : `\x1B[1m${text}\x1B[22m`,
2510
- faint: (text) => text === "" ? text : `\x1B[2m${text}\x1B[22m`
2511
- };
2512
- }
2513
- function wantsColor(forced, terminal, env, agent) {
2514
- if (forced !== undefined)
2515
- return forced;
2516
- if ((env.NO_COLOR ?? "") !== "")
2517
- return false;
2518
- const force = env.FORCE_COLOR;
2519
- if (force !== undefined && force !== "")
2520
- return force !== "0";
2521
- return terminal && !agent && !isDumb(env);
2522
- }
2523
- var isDumb = (env) => env.TERM === "dumb";
2524
- var SEPARATOR = " · ";
2525
- var branch = (index, count) => index === count - 1 ? "└ " : "├ ";
2526
- var NOTE_INDENT = " ";
2527
- function closingLine(paint, what, detail) {
2528
- return `${paint.good("✓")} ${what}${detail === undefined ? "" : paint.dim(`${SEPARATOR}${detail}`)}`;
2529
- }
2530
- function failLine(paint, what, detail) {
2531
- return `${paint.bad("✗")} ${what}${detail === undefined ? "" : paint.dim(`${SEPARATOR}${detail}`)}`;
2532
- }
2533
- function truncateWords(text, max) {
2534
- if ([...text].length <= max)
2535
- return text;
2536
- const cut = [...text].slice(0, max - 1).join("");
2537
- const space = cut.lastIndexOf(" ");
2538
- return `${(space > max / 2 ? cut.slice(0, space) : cut).replace(/[\s,;:]+$/, "")}…`;
2539
- }
2540
- var HASH_TAIL = /[-.][^-./]+\.\w+$/;
2541
- var WORD_END = /(?<=[-_.])/;
2542
- var width = (text) => [...text].length;
2543
- function truncatePath(path, max) {
2544
- if (width(path) <= max)
2545
- return path;
2546
- const parts = path.split("/");
2547
- const name = parts.pop() ?? path;
2548
- for (let keep = parts.length - 1;keep >= 0; keep--) {
2549
- const candidate = `…/${[...parts.slice(parts.length - keep), name].join("/")}`;
2550
- if (width(candidate) <= max)
2551
- return candidate;
2552
- }
2553
- const prefix = parts.length > 0 ? "…/" : "";
2554
- const tail = HASH_TAIL.exec(name)?.[0] ?? "";
2555
- const stem = name.slice(0, name.length - tail.length);
2556
- const room = max - width(prefix) - width(tail) - 1;
2557
- if (room < 4)
2558
- return `${prefix}…${[...name].slice(-(max - width(prefix) - 1)).join("")}`;
2559
- const words = stem.split(WORD_END);
2560
- const first = words[0] ?? "";
2561
- let end = "";
2562
- for (let i = words.length - 1;i > 0; i--) {
2563
- const word = words[i] ?? "";
2564
- if (width(first) + 1 + width(word + end) > room)
2565
- break;
2566
- end = word + end;
2567
- }
2568
- return end === "" ? `${prefix}${[...stem].slice(0, room).join("")}…${tail}` : `${prefix}${first}…${end}${tail}`;
2569
- }
2570
- var ESCAPE = /\x1b\[[0-9;]*m/g;
2571
- var LEADING_ESCAPE = /^\x1b\[[0-9;]*m/;
2572
- var textWidth = (text) => typeof Bun === "undefined" ? [...text.replace(ESCAPE, "")].length : Bun.stringWidth(text);
2573
- var MEASURE = 80;
2574
- function hangOf(line) {
2575
- const plain = line.replace(ESCAPE, "");
2576
- const lead = /^ */.exec(plain)?.[0].length ?? 0;
2577
- const gap = /^ *\S.*? {2,}(?=\S)/.exec(plain);
2578
- return gap ? textWidth(gap[0]) : lead;
2579
- }
2580
- function splitAt(line, columns) {
2581
- let seen = 0;
2582
- let i = 0;
2583
- while (i < line.length && seen < columns) {
2584
- const escape = LEADING_ESCAPE.exec(line.slice(i));
2585
- if (escape) {
2586
- i += escape[0].length;
2587
- continue;
2772
+ var LINES = /[^\n]*\n|[^\n]+$/g;
2773
+ function baseOf(head, hunks) {
2774
+ const lines = head.match(LINES) ?? [];
2775
+ const ended = (texts, open) => texts.map((text, i) => open && i === texts.length - 1 ? text : `${text}
2776
+ `);
2777
+ for (let h = hunks.length - 1;h >= 0; h--) {
2778
+ const hunk = hunks[h];
2779
+ if (!hunk)
2780
+ return;
2781
+ const { removed, added, oldCount, newCount, newStart } = hunk;
2782
+ if (removed.length !== oldCount || added.length !== newCount) {
2783
+ return;
2588
2784
  }
2589
- const ch = String.fromCodePoint(line.codePointAt(i) ?? 32);
2590
- seen += textWidth(ch);
2591
- i += ch.length;
2592
- }
2593
- return [line.slice(0, i), line.slice(i)];
2594
- }
2595
- var fitTerminal = (text, terminal, columns) => terminal ? fitWidth(text, Math.min(MEASURE, columns || MEASURE)) : text;
2596
- function fitWidth(text, width) {
2597
- return text.split(`
2598
- `).flatMap((line) => {
2599
- if (textWidth(line) <= width)
2600
- return [line];
2601
- let hang = hangOf(line);
2602
- if (hang > width / 2)
2603
- hang = /^ */.exec(line.replace(ESCAPE, ""))?.[0].length ?? 0;
2604
- const [head, rest] = splitAt(line, hang);
2605
- const room = Math.max(1, width - hang);
2606
- const lines = [];
2607
- let current = "";
2608
- const words = [];
2609
- for (const word of rest.split(/ +/)) {
2610
- const last = words.at(-1);
2611
- if (last !== undefined && last.replace(ESCAPE, "") === "·") {
2612
- words[words.length - 1] = `${last} ${word}`;
2613
- } else if (word !== "")
2614
- words.push(word);
2615
- }
2616
- for (const word of words) {
2617
- const next = current === "" ? word : `${current} ${word}`;
2618
- if (current !== "" && textWidth(next) > room) {
2619
- lines.push(current);
2620
- current = word;
2621
- } else {
2622
- current = next;
2623
- }
2785
+ const at = newCount === 0 ? newStart : newStart - 1;
2786
+ const now = ended(added, hunk.addedOpen);
2787
+ for (let i = 0;i < now.length; i++) {
2788
+ if (lines[at + i] !== now[i])
2789
+ return;
2624
2790
  }
2625
- if (current !== "")
2626
- lines.push(current);
2627
- return lines.map((part, k) => (k === 0 ? head : " ".repeat(hang)) + part);
2628
- }).join(`
2629
- `);
2791
+ lines.splice(at, newCount, ...ended(removed, hunk.removedOpen));
2792
+ }
2793
+ return lines.join("");
2794
+ }
2795
+ var EDITABLE = /\.(?:svelte|[cm]?[jt]sx?)$/;
2796
+ function isEditable(path) {
2797
+ return EDITABLE.test(path);
2798
+ }
2799
+ function spansOf(source, host, dialect) {
2800
+ const sink = createLexed();
2801
+ const spans = { comments: [], scripts: [], literals: [] };
2802
+ sink.spans = spans;
2803
+ try {
2804
+ openFile(source, sink);
2805
+ if (host)
2806
+ lexHost(source, sink, "svelte");
2807
+ else
2808
+ lexRange(0, source.length, dialect);
2809
+ } catch {
2810
+ return;
2811
+ }
2812
+ return spans;
2813
+ }
2814
+ function rangesOf(flat) {
2815
+ const ranges = [];
2816
+ for (let i = 0;i + 1 < flat.length; i += 2) {
2817
+ ranges.push([flat[i] ?? 0, flat[i + 1] ?? 0]);
2818
+ }
2819
+ return ranges.sort((a, b) => a[0] - b[0]);
2630
2820
  }
2631
- var RULE = "\x00rule";
2632
- function aligned(table, rightColumns = [], paintRule = asIs, indent = " ") {
2633
- const blank = (cell) => cell === "" || cell === RULE;
2634
- const used = new Set(table.flatMap((row) => row.flatMap((cell, i) => blank(cell) ? [] : [i])));
2635
- const keep = (row) => row.filter((_, i) => used.has(i));
2636
- const rows = table.map(keep);
2637
- const right = [...used].sort((a, b) => a - b).flatMap((column, i) => rightColumns.includes(column) ? [i] : []);
2638
- const cellWidth = (cell) => cell === RULE ? 0 : textWidth(cell);
2639
- const widths = [];
2640
- for (const row of rows) {
2641
- for (const [i, cell] of row.entries()) {
2642
- if (i === row.length - 1 && !right.includes(i))
2821
+ var SPACE = /[\t\n\v\f\r ]/g;
2822
+ function isSpace2(c) {
2823
+ return c === 32 || c >= 9 && c <= 13;
2824
+ }
2825
+ var LINE_END = /[\n\r\u2028\u2029]/;
2826
+ function codeOf(source, spans) {
2827
+ const kept = rangesOf(spans.literals);
2828
+ const dropped = [];
2829
+ for (const range of rangesOf(spans.comments)) {
2830
+ if (PRAGMA.test(source.slice(range[0], range[1])))
2831
+ kept.push(range);
2832
+ else
2833
+ dropped.push(range);
2834
+ }
2835
+ kept.sort((a, b) => a[0] - b[0]);
2836
+ let out = "";
2837
+ let at = 0;
2838
+ let k = 0;
2839
+ let d = 0;
2840
+ for (const [start, stop] of rangesOf(spans.scripts)) {
2841
+ let i = start;
2842
+ while (i < stop) {
2843
+ while (k < kept.length && (kept[k]?.[1] ?? 0) <= i)
2844
+ k++;
2845
+ while (d < dropped.length && (dropped[d]?.[0] ?? 0) < i)
2846
+ d++;
2847
+ const range = kept[k];
2848
+ if (range && range[0] <= i) {
2849
+ i = range[1];
2850
+ continue;
2851
+ }
2852
+ const limit = range ? Math.min(range[0], stop) : stop;
2853
+ SPACE.lastIndex = i;
2854
+ const space = SPACE.exec(source)?.index ?? limit;
2855
+ const run = Math.min(space, dropped[d]?.[0] ?? limit, limit);
2856
+ if (run === limit) {
2857
+ i = limit;
2643
2858
  continue;
2644
- widths[i] = Math.max(widths[i] ?? 0, cellWidth(cell));
2859
+ }
2860
+ let j = run;
2861
+ let lineBreak = false;
2862
+ let comment = false;
2863
+ for (;; ) {
2864
+ const note = dropped[d];
2865
+ if (note && note[0] === j) {
2866
+ comment = true;
2867
+ lineBreak ||= LINE_END.test(source.slice(j, note[1]));
2868
+ j = note[1];
2869
+ d++;
2870
+ continue;
2871
+ }
2872
+ const c = source.charCodeAt(j);
2873
+ if (j >= stop || !isSpace2(c))
2874
+ break;
2875
+ lineBreak ||= c === 10 || c === 13;
2876
+ j++;
2877
+ }
2878
+ const edge = run === start || j === stop;
2879
+ const continued = source.charCodeAt(run - 1) === 92;
2880
+ if (!continued && (lineBreak || comment)) {
2881
+ out += source.slice(at, run);
2882
+ if (!edge)
2883
+ out += lineBreak ? `
2884
+ ` : " ";
2885
+ at = j;
2886
+ }
2887
+ i = j;
2645
2888
  }
2646
2889
  }
2647
- const pad = (cell, i) => " ".repeat(Math.max(0, (widths[i] ?? 0) - cellWidth(cell)));
2648
- const columnsWidth = (from, to) => widths.slice(from, to).reduce((sum, w) => sum + w + 2, 0);
2649
- return rows.map((row) => {
2650
- const first = row.indexOf(RULE);
2651
- if (first !== -1) {
2652
- const last = row.lastIndexOf(RULE);
2653
- const line = "─".repeat(columnsWidth(first, last + 1) - 2);
2654
- return `${indent}${" ".repeat(columnsWidth(0, first))}${paintRule(line)}`;
2655
- }
2656
- return `${indent}${row.map((cell, i) => right.includes(i) ? pad(cell, i) + cell : i === row.length - 1 ? cell : cell + pad(cell, i)).join(" ")}`.trimEnd();
2657
- });
2890
+ return out + source.slice(at);
2658
2891
  }
2659
- var headerRow = (paint, cells) => cells.map((cell) => paint.faint(cell));
2660
- var plural = (count, one, many = `${one}s`) => `${count} ${count === 1 ? one : many}`;
2661
- var SILENT = { step: () => {}, clear: () => {} };
2662
- var BAR_WIDTH = 20;
2663
- var CLEAR_LINE = "\r\x1B[2K";
2664
- function createProgress(write, paint, nowMs) {
2665
- const startMs = nowMs();
2666
- let text = "";
2667
- let doneRatio = 0;
2668
- const render = () => {
2669
- const done = Math.round(Math.min(1, Math.max(0, doneRatio)) * BAR_WIDTH);
2670
- const bar = paint.good("━".repeat(done)) + paint.dim("─".repeat(BAR_WIDTH - done));
2671
- const seconds = Math.floor((nowMs() - startMs) / 1000);
2672
- write(`${CLEAR_LINE}${bar} ${text}${paint.dim(` · ${seconds} s`)}`);
2673
- };
2674
- const timer = setInterval(render, 1000);
2675
- timer.unref();
2676
- return {
2677
- step(next, ratio) {
2678
- text = next;
2679
- doneRatio = ratio;
2680
- render();
2681
- },
2682
- clear() {
2683
- clearInterval(timer);
2684
- write(CLEAR_LINE);
2892
+ var SCRIPTS = /<script\b[\s\S]*?<\/script\s*>/gi;
2893
+ function markupOf(source, { scripts }) {
2894
+ let out = "";
2895
+ let at = 0;
2896
+ for (const [start, stop] of rangesOf(scripts)) {
2897
+ out += source.slice(at, start);
2898
+ at = stop;
2899
+ }
2900
+ return out + source.slice(at);
2901
+ }
2902
+ var CONTINUES = new Set([
2903
+ "as",
2904
+ "catch",
2905
+ "else",
2906
+ "finally",
2907
+ "in",
2908
+ "instanceof",
2909
+ "of",
2910
+ "satisfies",
2911
+ "while"
2912
+ ]);
2913
+ var IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
2914
+ var WORD_START = /[A-Za-z_$]/;
2915
+ var WORD_PART = /[\w$]/;
2916
+ var RESERVED = new Set([
2917
+ "arguments",
2918
+ "await",
2919
+ "break",
2920
+ "case",
2921
+ "catch",
2922
+ "class",
2923
+ "const",
2924
+ "continue",
2925
+ "debugger",
2926
+ "default",
2927
+ "delete",
2928
+ "do",
2929
+ "else",
2930
+ "enum",
2931
+ "eval",
2932
+ "export",
2933
+ "extends",
2934
+ "false",
2935
+ "finally",
2936
+ "for",
2937
+ "function",
2938
+ "if",
2939
+ "implements",
2940
+ "import",
2941
+ "in",
2942
+ "instanceof",
2943
+ "interface",
2944
+ "let",
2945
+ "new",
2946
+ "null",
2947
+ "package",
2948
+ "private",
2949
+ "protected",
2950
+ "public",
2951
+ "return",
2952
+ "static",
2953
+ "super",
2954
+ "switch",
2955
+ "this",
2956
+ "throw",
2957
+ "true",
2958
+ "try",
2959
+ "typeof",
2960
+ "var",
2961
+ "void",
2962
+ "while",
2963
+ "with",
2964
+ "yield"
2965
+ ]);
2966
+ var LITERAL_WORDS = new Set([
2967
+ "Infinity",
2968
+ "NaN",
2969
+ "false",
2970
+ "null",
2971
+ "true",
2972
+ "undefined"
2973
+ ]);
2974
+ var NUMBER = /^(?:0[xX][\da-fA-F]+(?:_[\da-fA-F]+)*|0[oO][0-7]+(?:_[0-7]+)*|0[bB][01]+(?:_[01]+)*|(?:0|[1-9]\d*(?:_\d+)*)(?:\.(?:\d+(?:_\d+)*)?)?(?:[eE][+-]?\d+(?:_\d+)*)?|\.\d+(?:_\d+)*(?:[eE][+-]?\d+(?:_\d+)*)?)$/;
2975
+ var NUMBER_TOKEN = /(?:[eE][+-]|[\w.])*/y;
2976
+ var HEX = /[\da-fA-F]/;
2977
+ var PUNCT = "=;,:[]{}()+-*/%!~|<>.";
2978
+ var DOUBLED = "+-*=";
2979
+ function escapeEnd(text, i) {
2980
+ const c = text[i + 1];
2981
+ if (c === undefined)
2982
+ return -1;
2983
+ if (c >= "1" && c <= "9")
2984
+ return -1;
2985
+ if (c === "0")
2986
+ return /\d/.test(text[i + 2] ?? "") ? -1 : i + 2;
2987
+ if (c === "x") {
2988
+ return HEX.test(text[i + 2] ?? "") && HEX.test(text[i + 3] ?? "") ? i + 4 : -1;
2989
+ }
2990
+ if (c === "u") {
2991
+ if (text[i + 2] === "{") {
2992
+ const close = text.indexOf("}", i + 3);
2993
+ const digits = text.slice(i + 3, close);
2994
+ return close !== -1 && /^[\da-fA-F]{1,6}$/.test(digits) && Number.parseInt(digits, 16) <= 1114111 ? close + 1 : -1;
2995
+ }
2996
+ for (let k = 2;k < 6; k++) {
2997
+ if (!HEX.test(text[i + k] ?? ""))
2998
+ return -1;
2685
2999
  }
2686
- };
2687
- }
2688
-
2689
- // src/lockfile.ts
2690
- import { posix as posix3 } from "node:path";
2691
-
2692
- // src/yaml.ts
2693
- var COMMENT = /\s+#.*$/;
2694
- var KEY_END = /:(?: |$)/;
2695
- var EMPTY_MAP = /^\{\s*\}(?:\s+#.*)?$/;
2696
- var EMPTY_LIST = /^\[\s*\](?:\s+#.*)?$/;
2697
- var UNSUPPORTED = /^[&*!|>%@`]/;
2698
-
2699
- class YamlError extends Error {
2700
- }
2701
- function fail2(line, message) {
2702
- throw new YamlError(`${message} at line ${line?.number ?? "end"}`);
3000
+ return i + 6;
3001
+ }
3002
+ if (c === "\r" && text[i + 2] === `
3003
+ `)
3004
+ return i + 3;
3005
+ return i + 2;
2703
3006
  }
2704
- function linesOf(text) {
2705
- const lines = [];
2706
- for (const [i, raw] of text.split(`
2707
- `).entries()) {
2708
- const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
2709
- const content = line.trimStart();
2710
- if (content === "" || content.startsWith("#"))
3007
+ function quotedEnd(text, i) {
3008
+ const quote = text.charAt(i);
3009
+ let j = i + 1;
3010
+ for (;; ) {
3011
+ const c = text.charAt(j);
3012
+ if (c === "")
3013
+ return -1;
3014
+ if (c === quote)
3015
+ return j + 1;
3016
+ if (c === "\\") {
3017
+ j = escapeEnd(text, j);
3018
+ if (j === -1)
3019
+ return -1;
2711
3020
  continue;
2712
- const indent = line.length - content.length;
2713
- if (line.slice(0, indent).includes("\t")) {
2714
- fail2({ indent, text: content, number: i + 1 }, "a tab in indentation");
2715
3021
  }
2716
- lines.push({ indent, text: content.trimEnd(), number: i + 1 });
3022
+ const opens = quote === "`" ? c === "$" && text[j + 1] === "{" : c === `
3023
+ ` || c === "\r";
3024
+ if (opens)
3025
+ return -1;
3026
+ j++;
2717
3027
  }
2718
- return lines;
2719
3028
  }
2720
- function quoteEnd(text, start) {
2721
- const quote = text[start];
2722
- for (let i = start + 1;i < text.length; i++) {
2723
- if (quote === "'" && text[i] === "'") {
2724
- if (text[i + 1] === "'")
2725
- i++;
2726
- else
2727
- return i + 1;
2728
- } else if (quote === '"' && text[i] === "\\")
3029
+ function tokensOf(text) {
3030
+ const tokens = [];
3031
+ let i = 0;
3032
+ while (i < text.length) {
3033
+ const c = text.charAt(i);
3034
+ const code = text.charCodeAt(i);
3035
+ if (code === 32 || code >= 9 && code <= 13) {
2729
3036
  i++;
2730
- else if (quote === '"' && text[i] === '"')
2731
- return i + 1;
3037
+ } else if (c === "/" && (text[i + 1] === "/" || text[i + 1] === "*")) {
3038
+ const block = text[i + 1] === "*";
3039
+ const end = block ? text.indexOf("*/", i + 2) : text.indexOf(`
3040
+ `, i);
3041
+ if (block && end === -1)
3042
+ return;
3043
+ const stop = end === -1 ? text.length : end + (block ? 2 : 0);
3044
+ if (PRAGMA.test(text.slice(i, stop)))
3045
+ return;
3046
+ i = stop;
3047
+ } else if (WORD_START.test(c)) {
3048
+ let j = i + 1;
3049
+ while (j < text.length && WORD_PART.test(text.charAt(j)))
3050
+ j++;
3051
+ tokens.push({ kind: "word", text: text.slice(i, j) });
3052
+ i = j;
3053
+ } else if (c >= "0" && c <= "9" || c === "." && /\d/.test(text[i + 1] ?? "")) {
3054
+ NUMBER_TOKEN.lastIndex = i;
3055
+ NUMBER_TOKEN.exec(text);
3056
+ const number = text.slice(i, NUMBER_TOKEN.lastIndex);
3057
+ if (!NUMBER.test(number))
3058
+ return;
3059
+ tokens.push({ kind: "number", text: number });
3060
+ i = NUMBER_TOKEN.lastIndex;
3061
+ } else if (c === '"' || c === "'" || c === "`") {
3062
+ const j = quotedEnd(text, i);
3063
+ if (j === -1)
3064
+ return;
3065
+ tokens.push({ kind: "string", text: text.slice(i, j) });
3066
+ i = j;
3067
+ } else if (PUNCT.includes(c)) {
3068
+ const next = text[i + 1];
3069
+ if (DOUBLED.includes(c) && next === c || c === "=" && next === ">" || c === ">" && next === "=") {
3070
+ return;
3071
+ }
3072
+ tokens.push({ kind: "punct", text: c });
3073
+ i++;
3074
+ } else {
3075
+ return;
3076
+ }
2732
3077
  }
2733
- return -1;
3078
+ return tokens;
2734
3079
  }
2735
- function unquote(quoted) {
2736
- if (quoted.startsWith("'"))
2737
- return quoted.slice(1, -1).replaceAll("''", "'");
2738
- const value = JSON.parse(quoted);
2739
- if (typeof value !== "string")
2740
- throw new YamlError("bad quoted scalar");
2741
- return value;
3080
+ function declaredNames(tokens, typescript) {
3081
+ let k = 0;
3082
+ const peek = (offset = 0) => tokens[k + offset];
3083
+ const is = (text, offset = 0) => peek(offset)?.text === text;
3084
+ const typeArguments = () => {
3085
+ k++;
3086
+ for (;; ) {
3087
+ if (!type())
3088
+ return false;
3089
+ if (!is(","))
3090
+ break;
3091
+ k++;
3092
+ }
3093
+ if (!is(">"))
3094
+ return false;
3095
+ k++;
3096
+ return true;
3097
+ };
3098
+ const type = () => {
3099
+ if (is("|"))
3100
+ k++;
3101
+ for (;; ) {
3102
+ const token = peek();
3103
+ if (!token)
3104
+ return false;
3105
+ if (token.kind === "word") {
3106
+ k++;
3107
+ while (is(".") && peek(1)?.kind === "word")
3108
+ k += 2;
3109
+ if (is("<") && !typeArguments())
3110
+ return false;
3111
+ } else if (token.kind === "number" || token.kind === "string") {
3112
+ k++;
3113
+ } else {
3114
+ return false;
3115
+ }
3116
+ while (is("[") && is("]", 1))
3117
+ k += 2;
3118
+ if (!is("|"))
3119
+ return true;
3120
+ k++;
3121
+ }
3122
+ };
3123
+ const operand = () => {
3124
+ while (is("-") || is("+") || is("!") || is("~"))
3125
+ k++;
3126
+ const token = peek();
3127
+ if (!token)
3128
+ return false;
3129
+ if (token.kind === "number" || token.kind === "string") {
3130
+ k++;
3131
+ return true;
3132
+ }
3133
+ if (token.kind === "word") {
3134
+ if (!LITERAL_WORDS.has(token.text))
3135
+ return false;
3136
+ k++;
3137
+ return true;
3138
+ }
3139
+ if (token.text === "(") {
3140
+ k++;
3141
+ if (!expression() || !is(")"))
3142
+ return false;
3143
+ k++;
3144
+ return true;
3145
+ }
3146
+ if (token.text === "[") {
3147
+ k++;
3148
+ while (!is("]")) {
3149
+ if (!expression())
3150
+ return false;
3151
+ if (is(","))
3152
+ k++;
3153
+ else if (!is("]"))
3154
+ return false;
3155
+ }
3156
+ k++;
3157
+ return true;
3158
+ }
3159
+ if (token.text === "{") {
3160
+ k++;
3161
+ while (!is("}")) {
3162
+ const key = peek();
3163
+ if (!key || key.kind === "punct" || !is(":", 1))
3164
+ return false;
3165
+ if (key.text === "__proto__" || key.text.slice(1, -1) === "__proto__") {
3166
+ return false;
3167
+ }
3168
+ k += 2;
3169
+ if (!expression())
3170
+ return false;
3171
+ if (is(","))
3172
+ k++;
3173
+ else if (!is("}"))
3174
+ return false;
3175
+ }
3176
+ k++;
3177
+ return true;
3178
+ }
3179
+ return false;
3180
+ };
3181
+ const expression = () => {
3182
+ if (!operand())
3183
+ return false;
3184
+ while (is("+") || is("-") || is("*") || is("/") || is("%")) {
3185
+ k++;
3186
+ if (!operand())
3187
+ return false;
3188
+ }
3189
+ return true;
3190
+ };
3191
+ const names = [];
3192
+ while (k < tokens.length) {
3193
+ if (!is("export"))
3194
+ return;
3195
+ const keyword = peek(1)?.text;
3196
+ if (keyword !== "const" && keyword !== "let" && keyword !== "var") {
3197
+ return;
3198
+ }
3199
+ k += 2;
3200
+ for (;; ) {
3201
+ const name = peek();
3202
+ if (!name || name.kind !== "word" || !IDENTIFIER.test(name.text) || RESERVED.has(name.text) || names.includes(name.text)) {
3203
+ return;
3204
+ }
3205
+ names.push(name.text);
3206
+ k++;
3207
+ if (typescript && is(":")) {
3208
+ k++;
3209
+ if (!type())
3210
+ return;
3211
+ }
3212
+ if (is("=")) {
3213
+ k++;
3214
+ if (!expression())
3215
+ return;
3216
+ if (typescript && is("as") && is("const", 1))
3217
+ k += 2;
3218
+ } else if (keyword === "const") {
3219
+ return;
3220
+ }
3221
+ if (is(",")) {
3222
+ k++;
3223
+ continue;
3224
+ }
3225
+ if (!is(";"))
3226
+ return;
3227
+ k++;
3228
+ break;
3229
+ }
3230
+ }
3231
+ return names.length > 0 ? names : undefined;
2742
3232
  }
2743
- function flowEnd(text, line) {
2744
- let depth = 0;
2745
- for (let i = 0;i < text.length; i++) {
2746
- const c = text[i];
2747
- if (c === "'" || c === '"') {
2748
- const end = quoteEnd(text, i);
2749
- if (end === -1)
2750
- fail2(line, "an unterminated string");
2751
- i = end - 1;
2752
- } else if (c === "{" || c === "[")
2753
- depth++;
2754
- else if (c === "}" || c === "]") {
2755
- if (--depth === 0)
2756
- return i + 1;
3233
+ function lastCode(text, { comments }) {
3234
+ let i = text.length - 1;
3235
+ let c = comments.length - 2;
3236
+ for (;; ) {
3237
+ while (i >= 0 && /\s/.test(text.charAt(i)))
3238
+ i--;
3239
+ while (c >= 0 && (comments[c] ?? 0) > i)
3240
+ c -= 2;
3241
+ if (c >= 0 && (comments[c + 1] ?? 0) - 1 === i) {
3242
+ i = (comments[c] ?? 0) - 1;
3243
+ c -= 2;
3244
+ continue;
2757
3245
  }
3246
+ return text.charAt(i);
2758
3247
  }
2759
- return fail2(line, "a flow collection over several lines");
2760
3248
  }
2761
- function scalar(text, line) {
2762
- if (text.startsWith("'") || text.startsWith('"')) {
2763
- const end = quoteEnd(text, 0);
2764
- if (end === -1)
2765
- fail2(line, "an unterminated string");
2766
- if (text.slice(end).replace(COMMENT, "").trim() !== "") {
2767
- fail2(line, "text after a quoted scalar");
3249
+ function firstWord(text, { comments }) {
3250
+ let i = 0;
3251
+ let c = 0;
3252
+ for (;; ) {
3253
+ while (i < text.length && /\s/.test(text.charAt(i)))
3254
+ i++;
3255
+ while (c < comments.length && (comments[c] ?? 0) < i)
3256
+ c += 2;
3257
+ if (comments[c] === i) {
3258
+ i = comments[c + 1] ?? text.length;
3259
+ continue;
2768
3260
  }
2769
- return unquote(text.slice(0, end));
3261
+ break;
2770
3262
  }
2771
- if (text.startsWith("{") || text.startsWith("[")) {
2772
- const end = flowEnd(text, line);
2773
- if (text.slice(end).replace(COMMENT, "").trim() !== "") {
2774
- fail2(line, "text after a flow collection");
3263
+ if (i === text.length)
3264
+ return "";
3265
+ const match = /^[A-Za-z_$][\w$]*/.exec(text.slice(i, i + 64));
3266
+ return match?.[0];
3267
+ }
3268
+ function hasWord(text, word) {
3269
+ for (let at = text.indexOf(word);at !== -1; at = text.indexOf(word, at + 1)) {
3270
+ if (!WORD_PART.test(text.charAt(at - 1)) && !WORD_PART.test(text.charAt(at + word.length))) {
3271
+ return true;
2775
3272
  }
2776
- return text.slice(0, end);
2777
3273
  }
2778
- if (UNSUPPORTED.test(text))
2779
- fail2(line, `unsupported syntax "${text[0]}"`);
2780
- return text.replace(COMMENT, "");
3274
+ return false;
2781
3275
  }
2782
- function keyOf(text, line) {
2783
- if (text.startsWith("'") || text.startsWith('"')) {
2784
- const end = quoteEnd(text, 0);
2785
- if (end === -1)
2786
- fail2(line, "an unterminated key");
2787
- if (text[end] !== ":")
2788
- return;
2789
- return { key: unquote(text.slice(0, end)), rest: text.slice(end + 1) };
3276
+ function addedExports(base, head, dialect, source) {
3277
+ if (head.length <= base.length)
3278
+ return;
3279
+ const before = base.split(`
3280
+ `);
3281
+ const after = head.split(`
3282
+ `);
3283
+ let prefix = 0;
3284
+ while (prefix < before.length && before[prefix] === after[prefix])
3285
+ prefix++;
3286
+ let suffix = 0;
3287
+ while (suffix < before.length - prefix && before[before.length - 1 - suffix] === after[after.length - 1 - suffix]) {
3288
+ suffix++;
3289
+ }
3290
+ if (prefix + suffix !== before.length)
3291
+ return;
3292
+ const block = after.slice(prefix, after.length - suffix).join(`
3293
+ `);
3294
+ const above = before.slice(0, prefix).join(`
3295
+ `);
3296
+ const below = before.slice(prefix).join(`
3297
+ `);
3298
+ const aboveSpans = spansOf(above, false, dialect);
3299
+ const belowSpans = spansOf(below, false, dialect);
3300
+ if (!aboveSpans || !belowSpans || !spansOf(block, false, dialect)) {
3301
+ return;
2790
3302
  }
2791
- const colon = text.search(KEY_END);
2792
- if (colon === -1)
3303
+ const end = lastCode(above, aboveSpans);
3304
+ if (end !== "" && end !== ";" && end !== "}")
2793
3305
  return;
2794
- return { key: text.slice(0, colon), rest: text.slice(colon + 1) };
3306
+ const next = firstWord(below, belowSpans);
3307
+ if (next === undefined || CONTINUES.has(next))
3308
+ return;
3309
+ const tokens = tokensOf(block);
3310
+ const names = tokens && declaredNames(tokens, !dialect.jsx || dialect.tsx);
3311
+ if (!names || names.some((name) => hasWord(source, name)))
3312
+ return;
3313
+ return names;
2795
3314
  }
2796
- function parseYaml(text) {
2797
- const lines = linesOf(text);
2798
- let at = 0;
2799
- function block(indent) {
2800
- const first = lines[at];
2801
- if (!first || first.indent !== indent)
2802
- return "";
2803
- return first.text === "-" || first.text.startsWith("- ") ? sequence(indent) : mapping(indent, {});
3315
+ function scriptEdit(path, base, head) {
3316
+ const host = path.endsWith(".svelte");
3317
+ if (host && base.replace(SCRIPTS, "") !== head.replace(SCRIPTS, "")) {
3318
+ return {};
2804
3319
  }
2805
- function value(rest, indent, line) {
2806
- const text = rest.trim();
2807
- if (EMPTY_MAP.test(text))
2808
- return {};
2809
- if (EMPTY_LIST.test(text))
2810
- return [];
2811
- if (text !== "" && !text.startsWith("#"))
2812
- return scalar(text, line);
2813
- const next = lines[at];
2814
- return next && next.indent > indent ? block(next.indent) : "";
3320
+ const dialect = host ? TS : dialectOf(path);
3321
+ const baseSpans = spansOf(base, host, dialect);
3322
+ const headSpans = spansOf(head, host, dialect);
3323
+ if (!baseSpans || !headSpans)
3324
+ return {};
3325
+ if (host && markupOf(base, baseSpans) !== markupOf(head, headSpans)) {
3326
+ return {};
2815
3327
  }
2816
- function mapping(indent, into) {
2817
- for (let line = lines[at];line; line = lines[at]) {
2818
- if (line.indent < indent)
2819
- break;
2820
- if (line.indent > indent)
2821
- fail2(line, "unexpected indentation");
2822
- const entry = keyOf(line.text, line);
2823
- if (!entry)
2824
- fail2(line, "a line that isn't a key");
2825
- if (Object.hasOwn(into, entry.key))
2826
- fail2(line, "a duplicate key");
2827
- at++;
2828
- into[entry.key] = value(entry.rest, indent, line);
3328
+ const edit = {};
3329
+ const baseCode = codeOf(base, baseSpans);
3330
+ const headCode = codeOf(head, headSpans);
3331
+ if (baseCode === headCode) {
3332
+ edit.runtime = { kind: "comments" };
3333
+ return edit;
3334
+ }
3335
+ if (host)
3336
+ return edit;
3337
+ const names = addedExports(baseCode, headCode, dialect, base);
3338
+ if (names)
3339
+ edit.runtime = { kind: "exports", names };
3340
+ const typed = addedExports(base, head, dialect, base);
3341
+ if (typed)
3342
+ edit.types = { kind: "exports", names: typed };
3343
+ return edit;
3344
+ }
3345
+ function observersOf(graph, file, edit, extractions, resolvesTo) {
3346
+ const names = edit.kind === "exports" ? edit.names : [];
3347
+ const observers = new Set;
3348
+ for (const importer of importersOf(graph, file)) {
3349
+ const hash = importer.lastIndexOf("#");
3350
+ if (hash !== -1) {
3351
+ if (names.includes(importer.slice(hash + 1)))
3352
+ observers.add(importer);
3353
+ continue;
2829
3354
  }
2830
- return into;
3355
+ const deps = graph.get(importer);
3356
+ const extraction = extractions.get(importer);
3357
+ const observes = !extraction || deps?.setup?.has(file) === true || deps?.pages?.has(file) === true || extraction.imports.some((ref) => (ref.specifier.includes("?") || edit.kind === "exports" && (ref.names === undefined || ref.names.some((name) => names.includes(name)))) && resolvesTo(importer, ref.specifier));
3358
+ if (observes)
3359
+ observers.add(importer);
2831
3360
  }
2832
- function sequence(indent) {
2833
- const items = [];
2834
- for (let line = lines[at];line; line = lines[at]) {
2835
- if (line.indent < indent)
2836
- break;
2837
- if (line.indent > indent)
2838
- fail2(line, "unexpected indentation");
2839
- if (line.text !== "-" && !line.text.startsWith("- "))
2840
- break;
2841
- at++;
2842
- const text = line.text.slice(1).trimStart();
2843
- const inner = { ...line, indent: line.indent + 2, text };
2844
- if (text !== "" && keyOf(text, line)) {
2845
- lines.splice(at, 0, inner);
2846
- items.push(mapping(inner.indent, {}));
2847
- } else {
2848
- items.push(value(text, indent, line));
2849
- }
3361
+ return observers;
3362
+ }
3363
+ function sealsOf(graph, edits, extractions, createResolver) {
3364
+ let resolve;
3365
+ const runtime = new Map;
3366
+ const typed = new Map;
3367
+ for (const [file, edit] of edits) {
3368
+ const resolvesTo = (importer, specifier) => {
3369
+ resolve ??= createResolver();
3370
+ const resolved = resolve(importer, specifier);
3371
+ return resolved !== undefined && "files" in resolved && resolved.files.includes(file);
3372
+ };
3373
+ if (edit.runtime) {
3374
+ runtime.set(file, observersOf(graph, file, edit.runtime, extractions, resolvesTo));
3375
+ }
3376
+ if (edit.types) {
3377
+ typed.set(file, observersOf(graph, file, edit.types, extractions, resolvesTo));
2850
3378
  }
2851
- return items;
2852
3379
  }
2853
- const document = block(0);
2854
- const left = lines[at];
2855
- if (left)
2856
- fail2(left, "unexpected indentation");
2857
- return document;
3380
+ return { runtime, types: typed };
2858
3381
  }
2859
3382
 
2860
- // src/lockfile.ts
2861
- var DEP_FIELDS2 = [
2862
- "dependencies",
2863
- "devDependencies",
2864
- "peerDependencies",
2865
- "optionalDependencies"
2866
- ];
2867
- function isRecord2(value) {
2868
- return typeof value === "object" && value !== null && !Array.isArray(value);
3383
+ // src/git.ts
3384
+ import { spawn } from "node:child_process";
3385
+ import { readFile as readFile2 } from "node:fs/promises";
3386
+ import { join as join2 } from "node:path";
3387
+
3388
+ // src/sorted.ts
3389
+ function byCodeUnit(a, b) {
3390
+ if (a === b)
3391
+ return 0;
3392
+ return a < b ? -1 : 1;
2869
3393
  }
2870
- function isStringRecord2(value) {
2871
- return isRecord2(value) && Object.values(value).every((item) => typeof item === "string");
3394
+ function sorted(values) {
3395
+ return [...values].sort(byCodeUnit);
2872
3396
  }
2873
- var STRING_OR_TRAILING_COMMA = /"(?:[^"\\]|\\.)*"|,(\s*[}\]])/g;
2874
- function parseLenient(text) {
2875
- return JSON.parse(text.replace(STRING_OR_TRAILING_COMMA, (match, close) => close ?? match));
3397
+
3398
+ // src/git.ts
3399
+ function git(cwd, ...args) {
3400
+ return new Promise((resolve, reject) => {
3401
+ const child = spawn("git", args, { cwd });
3402
+ const chunks = [];
3403
+ const errors = [];
3404
+ child.stdout.on("data", (chunk) => chunks.push(chunk));
3405
+ child.stderr.on("data", (chunk) => errors.push(chunk));
3406
+ child.on("error", reject);
3407
+ child.on("close", (status) => {
3408
+ resolve({
3409
+ status: status ?? 1,
3410
+ stdout: Buffer.concat(chunks).toString("utf-8"),
3411
+ stderr: Buffer.concat(errors).toString("utf-8")
3412
+ });
3413
+ });
3414
+ });
2876
3415
  }
2877
- function specsOf(value) {
2878
- const specs = new Map;
2879
- for (const field of DEP_FIELDS2) {
2880
- const deps = value[field];
2881
- if (deps === undefined)
2882
- continue;
2883
- if (!isStringRecord2(deps))
2884
- return;
2885
- specs.set(field, new Map(Object.entries(deps)));
3416
+ async function gitOrThrow(cwd, ...args) {
3417
+ const result = await git(cwd, ...args);
3418
+ if (result.status !== 0) {
3419
+ const said = result.stderr.trim().split(`
3420
+ `)[0];
3421
+ throw new BiviumError2("BV_GIT_FAILED", `bivium: git ${args.join(" ")} failed${said ? `: ${said}` : ""}`);
2886
3422
  }
2887
- return specs;
3423
+ return result.stdout;
2888
3424
  }
2889
- function restOf(value, skip) {
2890
- return JSON.stringify(Object.entries(value).filter(([key]) => !skip.includes(key)));
3425
+ function lines(output) {
3426
+ return output.split(`
3427
+ `).filter(Boolean);
2891
3428
  }
2892
- function install(packages, name, entry, version, info) {
2893
- const installed = packages.get(name) ?? {
2894
- entries: [],
2895
- versions: [],
2896
- dependencies: new Set,
2897
- bin: false
2898
- };
2899
- if (info?.bin !== undefined || info?.hasBin === true || info?.hasBin === "true") {
2900
- installed.bin = true;
2901
- }
2902
- installed.entries.push(JSON.stringify(entry));
2903
- if (!installed.versions.includes(version))
2904
- installed.versions.push(version);
2905
- for (const field of [
2906
- "dependencies",
2907
- "optionalDependencies",
2908
- "peerDependencies"
2909
- ]) {
2910
- const deps = info?.[field];
2911
- if (isRecord2(deps)) {
2912
- for (const dep of Object.keys(deps))
2913
- installed.dependencies.add(dep);
3429
+ var INDEX_ENTRY = /^(\S) (\d{6}) ([0-9a-f]+) (\d)\t(.*)$/;
3430
+ var RAW_ENTRY = /^:(\d{6}) \d{6} ([0-9a-f]+) [0-9a-f]+ ([A-Z])\d*\t(.*)$/;
3431
+ var PATCH = [
3432
+ "-p",
3433
+ "-U0",
3434
+ "--no-color",
3435
+ "--no-ext-diff",
3436
+ "--no-textconv",
3437
+ "--src-prefix=a/",
3438
+ "--dst-prefix=b/"
3439
+ ];
3440
+ var HUNK = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
3441
+ function parseDiff(output) {
3442
+ const all = output.split(`
3443
+ `);
3444
+ const raw = [];
3445
+ let i = 0;
3446
+ for (;i < all.length; i++) {
3447
+ const line = all[i] ?? "";
3448
+ if (!line.startsWith(":"))
3449
+ break;
3450
+ raw.push(line);
3451
+ }
3452
+ const hunks = new Map;
3453
+ let file;
3454
+ let hunk;
3455
+ let last = "";
3456
+ for (;i < all.length; i++) {
3457
+ const line = all[i] ?? "";
3458
+ if (line.startsWith("diff --git ")) {
3459
+ file = undefined;
3460
+ hunk = undefined;
3461
+ } else if (!file) {
3462
+ if (line.startsWith("+++ b/")) {
3463
+ file = [];
3464
+ hunks.set(line.slice(6), file);
3465
+ }
3466
+ } else if (line.startsWith("@@ ")) {
3467
+ const [, , oldCount, newStart, newCount] = HUNK.exec(line) ?? [];
3468
+ if (newStart === undefined) {
3469
+ throw new Error(`git diff: unexpected line ${line}`);
3470
+ }
3471
+ hunk = {
3472
+ oldCount: Number(oldCount ?? 1),
3473
+ newStart: Number(newStart),
3474
+ newCount: Number(newCount ?? 1),
3475
+ removed: [],
3476
+ added: [],
3477
+ removedOpen: false,
3478
+ addedOpen: false
3479
+ };
3480
+ file.push(hunk);
3481
+ } else if (hunk && line.startsWith("-")) {
3482
+ hunk.removed.push(line.slice(1));
3483
+ last = "-";
3484
+ } else if (hunk && line.startsWith("+")) {
3485
+ hunk.added.push(line.slice(1));
3486
+ last = "+";
3487
+ } else if (hunk && line.startsWith("\\")) {
3488
+ if (last === "-")
3489
+ hunk.removedOpen = true;
3490
+ else
3491
+ hunk.addedOpen = true;
2914
3492
  }
2915
3493
  }
2916
- packages.set(name, installed);
3494
+ return { raw, hunks };
2917
3495
  }
2918
- function installedName(key) {
2919
- const [name = key, scope] = key.split("/").reverse();
2920
- return scope?.startsWith("@") ? `${scope}/${name}` : name;
2921
- }
2922
- function parseBunLock(text) {
2923
- const value = parseLenient(text);
2924
- if (!isRecord2(value))
2925
- return;
2926
- const { packages, workspaces } = value;
2927
- if (!isRecord2(packages) || !isRecord2(workspaces))
2928
- return;
2929
- const lockfile = {
2930
- packages: new Map,
2931
- workspaces: new Map,
2932
- rest: restOf(value, ["packages", "workspaces"])
2933
- };
2934
- for (const [key, entry] of Object.entries(packages)) {
2935
- if (!Array.isArray(entry) || typeof entry[0] !== "string")
2936
- return;
2937
- const ident = entry[0];
2938
- const at = ident.indexOf("@", 1);
2939
- const version = at === -1 ? "" : ident.slice(at + 1);
2940
- install(lockfile.packages, installedName(key), entry, version, entry.find(isRecord2));
3496
+ async function missingHistory(cwd, base) {
3497
+ const [known, forked, shallow] = await Promise.all([
3498
+ git(cwd, "rev-parse", "--verify", "--quiet", `${base}^{commit}`),
3499
+ git(cwd, "merge-base", base, "HEAD"),
3500
+ git(cwd, "rev-parse", "--is-shallow-repository")
3501
+ ]);
3502
+ const fix = shallow.stdout.trim() === "true" ? " The clone is shallow: fetch the history (actions/checkout: `fetch-depth: 0`)." : "";
3503
+ if (known.status !== 0) {
3504
+ return new BiviumError2("BV_GIT_NO_BASE", `bivium: no commit ${base} here to diff against: fetch it.${fix}`);
2941
3505
  }
2942
- for (const [dir, workspace] of Object.entries(workspaces)) {
2943
- const specs = isRecord2(workspace) ? specsOf(workspace) : undefined;
2944
- if (!specs)
2945
- return;
2946
- lockfile.workspaces.set(dir === "" ? "." : dir, specs);
3506
+ if (forked.status !== 0) {
3507
+ 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}`);
2947
3508
  }
2948
- return lockfile;
3509
+ return;
2949
3510
  }
2950
- var NODE_MODULES = "node_modules/";
2951
- function parsePackageLock(text) {
2952
- const value = JSON.parse(text);
2953
- if (!isRecord2(value) || !isRecord2(value.packages))
2954
- return;
2955
- const { lockfileVersion } = value;
2956
- if (lockfileVersion !== 2 && lockfileVersion !== 3)
2957
- return;
2958
- const lockfile = {
2959
- packages: new Map,
2960
- workspaces: new Map,
2961
- rest: restOf(value, ["packages", "dependencies", "name", "version"])
2962
- };
2963
- for (const [key, entry] of Object.entries(value.packages)) {
2964
- if (!isRecord2(entry))
2965
- return;
2966
- const at = key.lastIndexOf(NODE_MODULES);
2967
- if (at !== -1 && (at === 0 || key[at - 1] === "/")) {
2968
- const version = typeof entry.version === "string" ? entry.version : "";
2969
- const name = key.slice(at + NODE_MODULES.length);
2970
- install(lockfile.packages, name, entry, version, entry);
2971
- continue;
3511
+ function mergeBaseOf(cwd, base) {
3512
+ let pending;
3513
+ return () => {
3514
+ if (pending === undefined) {
3515
+ pending = gitOrThrow(cwd, "merge-base", base, "HEAD").then((out) => out.trim());
3516
+ pending.catch(() => {
3517
+ return;
3518
+ });
2972
3519
  }
2973
- const specs = specsOf(entry);
2974
- if (!specs)
2975
- return;
2976
- lockfile.workspaces.set(key === "" ? "." : key, specs);
2977
- }
2978
- return lockfile;
2979
- }
2980
- function pnpmKey(key) {
2981
- const bare = key.startsWith("/") ? key.slice(1) : key;
2982
- const at = bare.indexOf("@", 1);
2983
- if (at === -1)
2984
- return;
2985
- return { name: bare.slice(0, at), version: withoutPeers(bare.slice(at + 1)) };
2986
- }
2987
- function withoutPeers(version) {
2988
- const paren = version.indexOf("(");
2989
- return paren === -1 ? version : version.slice(0, paren);
3520
+ return pending;
3521
+ };
2990
3522
  }
2991
- var YAML_DOCUMENT = /^---[ \t]*$/m;
2992
- var PNPM_VERSION = /^[69]\./;
2993
- var PNPM_DEP_FIELDS = [
2994
- "dependencies",
2995
- "devDependencies",
2996
- "optionalDependencies"
2997
- ];
2998
- function parsePnpmLock(text) {
2999
- const docs = text.split(YAML_DOCUMENT).filter((doc) => doc.trim() !== "").map(parseYaml);
3000
- const main = docs.findLast((doc) => isRecord2(doc) && typeof doc.lockfileVersion === "string");
3001
- if (!isRecord2(main))
3002
- return;
3003
- const { lockfileVersion, packages = {}, snapshots = {} } = main;
3004
- if (typeof lockfileVersion !== "string")
3005
- return;
3006
- if (!PNPM_VERSION.test(lockfileVersion))
3007
- return;
3008
- if (!isRecord2(packages) || !isRecord2(snapshots))
3009
- return;
3010
- const workspaces = isRecord2(main.importers);
3011
- const importers = isRecord2(main.importers) ? main.importers : { ".": main };
3012
- const lockfile = {
3013
- packages: new Map,
3014
- workspaces: new Map,
3015
- rest: JSON.stringify([
3016
- restOf(main, ["importers", "packages", "snapshots", ...PNPM_DEP_FIELDS]),
3017
- ...docs.filter((doc) => doc !== main)
3018
- ])
3523
+ async function readRevision(cwd, base, roots, {
3524
+ blobs = false,
3525
+ mergeBase: eager = false
3526
+ } = {}) {
3527
+ const mergeBase = mergeBaseOf(cwd, base);
3528
+ if (eager)
3529
+ mergeBase();
3530
+ const diffArgs = ["--no-renames", "--merge-base", base];
3531
+ const [listing, diff, staged] = await Promise.all([
3532
+ gitOrThrow(cwd, "ls-files", "-s", "-v", "-o", "--exclude-standard"),
3533
+ gitOrThrow(cwd, "diff", "--raw", "--no-abbrev", ...PATCH, ...diffArgs),
3534
+ gitOrThrow(cwd, "diff", "--cached", "--name-only", ...diffArgs)
3535
+ ]).catch(async (error) => {
3536
+ throw await missingHistory(cwd, base) ?? error;
3537
+ });
3538
+ const entries = lines(listing);
3539
+ const untracked = [];
3540
+ for (const line of entries) {
3541
+ if (line.startsWith("? "))
3542
+ untracked.push(line.slice(2));
3543
+ }
3544
+ const before = new Map;
3545
+ const diffed = [];
3546
+ const layout = new Set(untracked);
3547
+ const { raw, hunks } = parseDiff(diff);
3548
+ for (const line of raw) {
3549
+ const [, mode, oid, status, path] = RAW_ENTRY.exec(line) ?? [];
3550
+ if (mode === undefined || oid === undefined || status === undefined || path === undefined) {
3551
+ throw new Error(`git diff: unexpected line ${line}`);
3552
+ }
3553
+ diffed.push(path);
3554
+ if (status === "A" || status === "D")
3555
+ layout.add(path);
3556
+ if (status === "A")
3557
+ before.set(path, undefined);
3558
+ else if ("MTD".includes(status) && mode !== "160000") {
3559
+ before.set(path, oid);
3560
+ }
3561
+ }
3562
+ const reads = new Map;
3563
+ const readBase = (path) => {
3564
+ let read = reads.get(path);
3565
+ if (read === undefined) {
3566
+ read = readBaseOnce(path);
3567
+ reads.set(path, read);
3568
+ }
3569
+ return read;
3019
3570
  };
3020
- const restOfImporters = [];
3021
- for (const [dir, importer] of Object.entries(importers)) {
3022
- if (!isRecord2(importer))
3023
- return;
3024
- const specs = new Map;
3025
- for (const field of PNPM_DEP_FIELDS) {
3026
- const deps = importer[field];
3027
- if (deps === undefined)
3028
- continue;
3029
- if (!isRecord2(deps))
3030
- return;
3031
- const declared = new Map;
3032
- for (const [name, dep] of Object.entries(deps)) {
3033
- if (!isRecord2(dep) || typeof dep.specifier !== "string") {
3034
- return;
3035
- }
3036
- declared.set(name, dep.specifier);
3037
- const version = typeof dep.version === "string" ? dep.version : "";
3038
- install(lockfile.packages, name, [dir, field, version], withoutPeers(version), {});
3571
+ const readBaseOnce = (path) => {
3572
+ if (!before.has(path)) {
3573
+ if (present.has(path)) {
3574
+ return readFile2(join2(cwd, path), "utf-8").catch(() => mergeBase().then((commit) => show(cwd, `${commit}:${path}`)));
3039
3575
  }
3040
- specs.set(field, declared);
3576
+ return mergeBase().then((commit) => show(cwd, `${commit}:${path}`));
3041
3577
  }
3042
- lockfile.workspaces.set(dir, specs);
3043
- if (workspaces) {
3044
- const settings = restOf(importer, PNPM_DEP_FIELDS);
3045
- if (settings !== "[]")
3046
- restOfImporters.push([dir, settings]);
3578
+ const oid = before.get(path);
3579
+ return oid === undefined ? Promise.resolve(undefined) : show(cwd, oid);
3580
+ };
3581
+ const changed = [...new Set([...diffed, ...untracked])];
3582
+ const dirty = new Set([...changed, ...lines(staged)]);
3583
+ const underRoots = (path) => roots.some((root) => inRoot2(path, root));
3584
+ const files = new Set;
3585
+ const tracked = new Set;
3586
+ const present = new Set;
3587
+ const oids = new Map;
3588
+ for (const line of entries) {
3589
+ const entry = INDEX_ENTRY.exec(line);
3590
+ if (!entry) {
3591
+ if (line.startsWith("? ") && underRoots(line.slice(2))) {
3592
+ files.add(line.slice(2));
3593
+ }
3594
+ continue;
3047
3595
  }
3048
- }
3049
- lockfile.rest += JSON.stringify(restOfImporters);
3050
- for (const section of [packages, snapshots]) {
3051
- for (const [key, entry] of Object.entries(section)) {
3052
- const parsed = pnpmKey(key);
3053
- if (!parsed)
3054
- return;
3055
- const info = isRecord2(entry) ? entry : undefined;
3056
- install(lockfile.packages, parsed.name, [key, entry], parsed.version, info);
3596
+ const [, tag, mode, oid, stage, path] = entry;
3597
+ if (tag === undefined || mode === undefined || oid === undefined || stage === undefined || path === undefined) {
3598
+ throw new Error(`bivium: git: unexpected ls-files line ${line}.`);
3057
3599
  }
3600
+ tracked.add(path);
3601
+ if (mode === "160000" || !underRoots(path))
3602
+ continue;
3603
+ files.add(path);
3604
+ if (dirty.has(path) || stage !== "0" || tag !== "H")
3605
+ continue;
3606
+ if (mode !== "100644" && mode !== "100755")
3607
+ continue;
3608
+ present.add(path);
3609
+ if (blobs)
3610
+ oids.set(path, oid);
3058
3611
  }
3059
- return lockfile;
3612
+ return {
3613
+ files: sorted(files),
3614
+ listed: [...tracked, ...untracked],
3615
+ changed,
3616
+ layout,
3617
+ mergeBase,
3618
+ readBase,
3619
+ hunks,
3620
+ blobs: oids,
3621
+ present
3622
+ };
3060
3623
  }
3061
- var FORMATS = new Map([
3062
- ["bun.lock", parseBunLock],
3063
- ["package-lock.json", parsePackageLock],
3064
- ["pnpm-lock.yaml", parsePnpmLock]
3065
- ]);
3066
- var UNREAD = ["bun.lockb", "npm-shrinkwrap.json", "yarn.lock"];
3067
- function parse(file, text) {
3068
- const format = FORMATS.get(file);
3069
- if (text === undefined || !format)
3070
- return;
3071
- try {
3072
- return format(text);
3073
- } catch {
3074
- return;
3075
- }
3624
+ async function show(cwd, object) {
3625
+ const result = await git(cwd, "show", object);
3626
+ return result.status === 0 ? result.stdout : undefined;
3076
3627
  }
3077
- function describe(name, before, after) {
3078
- if (before === undefined)
3079
- return `${name} ${after} added`;
3080
- if (after === undefined)
3081
- return `${name} ${before} removed`;
3082
- return before === after ? `${name} ${after}, entry changed` : `${name} ${before} → ${after}`;
3628
+ async function defaultBase(cwd) {
3629
+ const head = await git(cwd, "symbolic-ref", "--short", "refs/remotes/origin/HEAD");
3630
+ if (head.status === 0 && head.stdout.trim())
3631
+ return head.stdout.trim();
3632
+ const refs = ["origin/main", "origin/master", "main", "master"];
3633
+ const found = await Promise.all(refs.map((ref) => git(cwd, "rev-parse", "--verify", "--quiet", ref)));
3634
+ const branch = refs[found.findIndex((result) => result.status === 0)];
3635
+ if (branch)
3636
+ return branch;
3637
+ 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`);
3083
3638
  }
3084
- function versions(installed) {
3085
- return installed && sorted(installed.versions).join(", ");
3639
+
3640
+ // src/lockfile.ts
3641
+ import { posix as posix3 } from "node:path";
3642
+
3643
+ // src/yaml.ts
3644
+ var COMMENT = /\s+#.*$/;
3645
+ var KEY_END = /:(?: |$)/;
3646
+ var EMPTY_MAP = /^\{\s*\}(?:\s+#.*)?$/;
3647
+ var EMPTY_LIST = /^\[\s*\](?:\s+#.*)?$/;
3648
+ var UNSUPPORTED = /^[&*!|>%@`]/;
3649
+
3650
+ class YamlError extends Error {
3086
3651
  }
3087
- function specChanges(before, after) {
3088
- const changed = new Map;
3089
- for (const field of DEP_FIELDS2) {
3090
- const a = before?.get(field);
3091
- const b = after?.get(field);
3092
- for (const name of new Set([...a?.keys() ?? [], ...b?.keys() ?? []])) {
3093
- if (a?.get(name) !== b?.get(name) && !changed.has(name)) {
3094
- changed.set(name, [a?.get(name), b?.get(name)]);
3095
- }
3096
- }
3097
- }
3098
- return changed;
3652
+ function fail2(line, message) {
3653
+ throw new YamlError(`${message} at line ${line?.number ?? "end"}`);
3099
3654
  }
3100
- function lockfileChanges(file, base, head) {
3101
- const changes = [];
3102
- const names = new Set([...base.packages.keys(), ...head.packages.keys()]);
3103
- for (const name of names) {
3104
- const before = base.packages.get(name);
3105
- const after = head.packages.get(name);
3106
- const same = before !== undefined && after !== undefined && sorted(before.entries).join(`
3107
- `) === sorted(after.entries).join(`
3108
- `);
3109
- if (same)
3655
+ function linesOf(text) {
3656
+ const lines = [];
3657
+ for (const [i, raw] of text.split(`
3658
+ `).entries()) {
3659
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
3660
+ const content = line.trimStart();
3661
+ if (content === "" || content.startsWith("#"))
3110
3662
  continue;
3111
- changes.push({
3112
- name,
3113
- detail: `${file}: ${describe(name, versions(before), versions(after))}`,
3114
- file
3115
- });
3116
- }
3117
- const resolved = new Set(changes.map((change) => change.name));
3118
- const dirs = new Set([...base.workspaces.keys(), ...head.workspaces.keys()]);
3119
- for (const dir of dirs) {
3120
- const declared = specChanges(base.workspaces.get(dir), head.workspaces.get(dir));
3121
- for (const [name, [before, after]] of declared) {
3122
- if (resolved.has(name))
3123
- continue;
3124
- resolved.add(name);
3125
- changes.push({
3126
- name,
3127
- detail: `${file}: ${describe(`${name} range`, before, after)}`,
3128
- file
3129
- });
3663
+ const indent = line.length - content.length;
3664
+ if (line.slice(0, indent).includes("\t")) {
3665
+ fail2({ indent, text: content, number: i + 1 }, "a tab in indentation");
3130
3666
  }
3667
+ lines.push({ indent, text: content.trimEnd(), number: i + 1 });
3131
3668
  }
3132
- return changes;
3133
- }
3134
- var MANIFEST = /(?:^|\/)package\.json$/;
3135
- function parseManifest(text) {
3136
- if (text === undefined)
3137
- return;
3138
- try {
3139
- const value = JSON.parse(text);
3140
- return isRecord2(value) ? value : undefined;
3141
- } catch {
3142
- return;
3143
- }
3669
+ return lines;
3144
3670
  }
3145
- async function readPackageDiff(changed, listed, base, head) {
3146
- const lockfiles = changed.filter((file) => FORMATS.has(file));
3147
- const manifests = changed.filter((file) => MANIFEST.test(file));
3148
- if (lockfiles.length === 0 && manifests.length === 0)
3149
- return;
3150
- const read = (path) => Promise.all([base(path), head(path)]);
3151
- const known = [...FORMATS.keys()];
3152
- const [lockTexts, manifestTexts] = await Promise.all([
3153
- Promise.all(known.map(async (file) => {
3154
- if (lockfiles.includes(file))
3155
- return [file, ...await read(file)];
3156
- const text = await head(file);
3157
- return [file, text, text];
3158
- })),
3159
- Promise.all(manifests.map(async (file) => [file, ...await read(file)]))
3160
- ]);
3161
- const diff = {
3162
- files: new Map,
3163
- changes: [],
3164
- dependents: new Map,
3165
- declared: new Set,
3166
- bins: new Set
3167
- };
3168
- const present = new Map;
3169
- for (const [file, baseText, headText] of lockTexts) {
3170
- const after = parse(file, headText);
3171
- if (headText !== undefined)
3172
- present.set(file, after);
3173
- const before = parse(file, baseText);
3174
- for (const lockfile of [before, after]) {
3175
- if (!lockfile)
3176
- continue;
3177
- for (const [name, installed] of lockfile.packages) {
3178
- if (installed.bin)
3179
- diff.bins.add(name);
3180
- for (const dependency of installed.dependencies) {
3181
- const set = diff.dependents.get(dependency) ?? new Set;
3182
- set.add(name);
3183
- diff.dependents.set(dependency, set);
3184
- }
3185
- }
3186
- for (const specs of lockfile.workspaces.values()) {
3187
- for (const deps of specs.values()) {
3188
- for (const name of deps.keys())
3189
- diff.declared.add(name);
3190
- }
3191
- }
3192
- }
3193
- if (!lockfiles.includes(file))
3194
- continue;
3195
- if (baseText === undefined || headText === undefined) {
3196
- diff.files.set(file, baseText === undefined ? "added" : "deleted");
3197
- } else if (!(before && after)) {
3198
- diff.files.set(file, "can't parse it");
3199
- } else if (before.rest === after.rest) {
3200
- diff.files.set(file, undefined);
3201
- diff.changes.push(...lockfileChanges(file, before, after));
3202
- } else {
3203
- diff.files.set(file, "a setting other than the packages changed");
3671
+ function quoteEnd(text, start) {
3672
+ const quote = text[start];
3673
+ for (let i = start + 1;i < text.length; i++) {
3674
+ if (quote === "'" && text[i] === "'") {
3675
+ if (text[i + 1] === "'")
3676
+ i++;
3677
+ else
3678
+ return i + 1;
3679
+ } else if (quote === '"' && text[i] === "\\")
3680
+ i++;
3681
+ else if (quote === '"' && text[i] === '"')
3682
+ return i + 1;
3683
+ }
3684
+ return -1;
3685
+ }
3686
+ function unquote(quoted) {
3687
+ if (quoted.startsWith("'"))
3688
+ return quoted.slice(1, -1).replaceAll("''", "'");
3689
+ const value = JSON.parse(quoted);
3690
+ if (typeof value !== "string")
3691
+ throw new YamlError("bad quoted scalar");
3692
+ return value;
3693
+ }
3694
+ function flowEnd(text, line) {
3695
+ let depth = 0;
3696
+ for (let i = 0;i < text.length; i++) {
3697
+ const c = text[i];
3698
+ if (c === "'" || c === '"') {
3699
+ const end = quoteEnd(text, i);
3700
+ if (end === -1)
3701
+ fail2(line, "an unterminated string");
3702
+ i = end - 1;
3703
+ } else if (c === "{" || c === "[")
3704
+ depth++;
3705
+ else if (c === "}" || c === "]") {
3706
+ if (--depth === 0)
3707
+ return i + 1;
3204
3708
  }
3205
3709
  }
3206
- const unread = UNREAD.some((file) => listed.includes(file));
3207
- for (const [file, beforeText, afterText] of manifestTexts) {
3208
- const before = parseManifest(beforeText);
3209
- const after = parseManifest(afterText);
3210
- if (!(before && after) || unread || present.size === 0)
3211
- continue;
3212
- const others = (record) => restOf(record, DEP_FIELDS2);
3213
- const specsBefore = specsOf(before);
3214
- const specsAfter = specsOf(after);
3215
- if (others(before) !== others(after) || !specsBefore || !specsAfter) {
3216
- continue;
3710
+ return fail2(line, "a flow collection over several lines");
3711
+ }
3712
+ function scalar(text, line) {
3713
+ if (text.startsWith("'") || text.startsWith('"')) {
3714
+ const end = quoteEnd(text, 0);
3715
+ if (end === -1)
3716
+ fail2(line, "an unterminated string");
3717
+ if (text.slice(end).replace(COMMENT, "").trim() !== "") {
3718
+ fail2(line, "text after a quoted scalar");
3217
3719
  }
3218
- const dir = posix3.dirname(file);
3219
- const declared = specChanges(specsBefore, specsAfter);
3220
- const recorded = [...present.values()].every((lockfile) => {
3221
- const specs = lockfile?.workspaces.get(dir);
3222
- if (!specs)
3223
- return false;
3224
- return [...declared.keys()].every((name) => DEP_FIELDS2.every((field) => specs.get(field)?.get(name) === specsAfter.get(field)?.get(name)));
3225
- });
3226
- if (!recorded)
3227
- continue;
3228
- diff.files.set(file, undefined);
3229
- for (const [name, [from, to]] of declared) {
3230
- diff.declared.add(name);
3231
- diff.changes.push({
3232
- name,
3233
- detail: `${file}: ${describe(`${name} range`, from, to)}`,
3234
- file
3235
- });
3720
+ return unquote(text.slice(0, end));
3721
+ }
3722
+ if (text.startsWith("{") || text.startsWith("[")) {
3723
+ const end = flowEnd(text, line);
3724
+ if (text.slice(end).replace(COMMENT, "").trim() !== "") {
3725
+ fail2(line, "text after a flow collection");
3236
3726
  }
3727
+ return text.slice(0, end);
3237
3728
  }
3238
- return diff;
3729
+ if (UNSUPPORTED.test(text))
3730
+ fail2(line, `unsupported syntax "${text[0]}"`);
3731
+ return text.replace(COMMENT, "");
3239
3732
  }
3240
- function packageSeeds(graph, config, diff, files) {
3241
- const result = { seeds: new Map, notes: [], reasons: [] };
3242
- const { isLoadedByName } = config;
3243
- const loadedOtherwise = (name) => isLoadedByName === undefined || diff.bins.has(name) || isLoadedByName(name);
3244
- const tested = new Map;
3245
- const reachesTest = (name) => {
3246
- let found = tested.get(name);
3247
- if (found === undefined) {
3248
- const node = `pkg:${name}`;
3249
- found = graph.has(node) && config.suites.some((suite) => reaches(graph, [node], suite.isTest, {
3250
- includeUnknown: false,
3251
- types: suite.types
3252
- }));
3253
- tested.set(name, found);
3254
- }
3255
- return found;
3256
- };
3257
- const changes = diff.changes.filter((change) => files.includes(change.file)).sort((a, b) => byCodeUnit(a.name, b.name));
3258
- const unused = new Map;
3259
- const seen = new Set;
3260
- for (const change of changes) {
3261
- const { name, detail } = change;
3262
- if (seen.has(name))
3263
- continue;
3264
- seen.add(name);
3265
- const closure = new Set([name]);
3266
- const queue = [name];
3267
- for (const queued of queue) {
3268
- for (const dependent of diff.dependents.get(queued) ?? []) {
3269
- if (closure.has(dependent))
3270
- continue;
3271
- closure.add(dependent);
3272
- queue.push(dependent);
3273
- }
3733
+ function keyOf(text, line) {
3734
+ if (text.startsWith("'") || text.startsWith('"')) {
3735
+ const end = quoteEnd(text, 0);
3736
+ if (end === -1)
3737
+ fail2(line, "an unterminated key");
3738
+ if (text[end] !== ":")
3739
+ return;
3740
+ return { key: unquote(text.slice(0, end)), rest: text.slice(end + 1) };
3741
+ }
3742
+ const colon = text.search(KEY_END);
3743
+ if (colon === -1)
3744
+ return;
3745
+ return { key: text.slice(0, colon), rest: text.slice(colon + 1) };
3746
+ }
3747
+ function parseYaml(text) {
3748
+ const lines = linesOf(text);
3749
+ let at = 0;
3750
+ function block(indent) {
3751
+ const first = lines[at];
3752
+ if (!first || first.indent !== indent)
3753
+ return "";
3754
+ return first.text === "-" || first.text.startsWith("- ") ? sequence(indent) : mapping(indent, {});
3755
+ }
3756
+ function value(rest, indent, line) {
3757
+ const text = rest.trim();
3758
+ if (EMPTY_MAP.test(text))
3759
+ return {};
3760
+ if (EMPTY_LIST.test(text))
3761
+ return [];
3762
+ if (text !== "" && !text.startsWith("#"))
3763
+ return scalar(text, line);
3764
+ const next = lines[at];
3765
+ return next && next.indent > indent ? block(next.indent) : "";
3766
+ }
3767
+ function mapping(indent, into) {
3768
+ for (let line = lines[at];line; line = lines[at]) {
3769
+ if (line.indent < indent)
3770
+ break;
3771
+ if (line.indent > indent)
3772
+ fail2(line, "unexpected indentation");
3773
+ const entry = keyOf(line.text, line);
3774
+ if (!entry)
3775
+ fail2(line, "a line that isn't a key");
3776
+ if (Object.hasOwn(into, entry.key))
3777
+ fail2(line, "a duplicate key");
3778
+ at++;
3779
+ into[entry.key] = value(entry.rest, indent, line);
3274
3780
  }
3275
- const through = [];
3276
- let covered = true;
3277
- let importOnly = false;
3278
- for (const user of closure) {
3279
- const node = `pkg:${user}`;
3280
- const imported = graph.has(node);
3281
- if (imported) {
3282
- through.push(user);
3283
- if (!result.seeds.has(node)) {
3284
- result.seeds.set(node, user === name ? detail : `${detail}, which ${user} depends on`);
3285
- }
3286
- }
3287
- const entry = imported || diff.declared.has(user) || !diff.dependents.has(user);
3288
- if (!entry || reachesTest(user) || config.isInert(user))
3289
- continue;
3290
- if (loadedOtherwise(user)) {
3291
- covered = false;
3292
- const list = unused.get(user) ?? [];
3293
- if (user === name)
3294
- list.unshift(change);
3295
- else
3296
- list.push(change);
3297
- unused.set(user, list);
3781
+ return into;
3782
+ }
3783
+ function sequence(indent) {
3784
+ const items = [];
3785
+ for (let line = lines[at];line; line = lines[at]) {
3786
+ if (line.indent < indent)
3787
+ break;
3788
+ if (line.indent > indent)
3789
+ fail2(line, "unexpected indentation");
3790
+ if (line.text !== "-" && !line.text.startsWith("- "))
3791
+ break;
3792
+ at++;
3793
+ const text = line.text.slice(1).trimStart();
3794
+ const inner = { ...line, indent: line.indent + 2, text };
3795
+ if (text !== "" && keyOf(text, line)) {
3796
+ lines.splice(at, 0, inner);
3797
+ items.push(mapping(inner.indent, {}));
3298
3798
  } else {
3299
- importOnly = true;
3799
+ items.push(value(text, indent, line));
3300
3800
  }
3301
3801
  }
3302
- if (!covered)
3303
- continue;
3304
- if (through.length === 0) {
3305
- result.notes.push(`${detail}, ${importOnly ? "imported by no test" : "inert"}`);
3306
- continue;
3307
- }
3308
- const others = through.filter((user) => user !== name);
3309
- const shown = others.slice(0, 3).join(", ");
3310
- const rest = others.length > 3 ? ` and ${others.length - 3} more` : "";
3311
- result.notes.push(others.length === 0 ? detail : `${detail}, through ${shown}${rest}`);
3312
- }
3313
- for (const user of sorted(unused.keys())) {
3314
- const [first, ...more] = unused.get(user) ?? [];
3315
- if (!first)
3316
- continue;
3317
- const own = first.name === user;
3318
- const also = more.length === 0 ? "" : ` (and ${more.length} more ${more.length === 1 ? "package" : "packages"} ${user} depends on)`;
3319
- result.reasons.push({
3320
- package: user,
3321
- file: first.file,
3322
- message: own ? `${first.detail}${also}, and no test imports it` : `${first.detail}, which ${user} depends on${also}, and no test imports ${user}`
3323
- });
3802
+ return items;
3324
3803
  }
3325
- return result;
3804
+ const document = block(0);
3805
+ const left = lines[at];
3806
+ if (left)
3807
+ fail2(left, "unexpected indentation");
3808
+ return document;
3326
3809
  }
3327
3810
 
3328
- // src/plan.ts
3329
- function formatSelection(selection) {
3330
- return selection.mode === "some" ? selection.files.join(" ") : selection.mode;
3811
+ // src/lockfile.ts
3812
+ var DEP_FIELDS2 = [
3813
+ "dependencies",
3814
+ "devDependencies",
3815
+ "peerDependencies",
3816
+ "optionalDependencies"
3817
+ ];
3818
+ function isRecord2(value) {
3819
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3331
3820
  }
3332
- function select(affected, tests) {
3333
- const files = tests.filter((file) => affected.has(file));
3334
- if (files.length === 0)
3335
- return { mode: "none" };
3336
- if (files.length === tests.length)
3337
- return { mode: "all" };
3338
- return { mode: "some", files };
3821
+ function isStringRecord2(value) {
3822
+ return isRecord2(value) && Object.values(value).every((item) => typeof item === "string");
3339
3823
  }
3340
- function classify(graph, changed, config, packages, settings) {
3341
- const causes = [];
3342
- const all = config.suites.map((suite) => suite.name);
3343
- const runAll = (cause) => causes.push({ ...cause, suites: all });
3344
- const relevant = [];
3345
- const quiet = [];
3346
- const packageFiles = [];
3347
- const settingFiles = [];
3348
- for (const file of changed) {
3349
- const read = graph.has(file);
3350
- const ignored = config.isIgnored(file);
3351
- if (!read && ignored)
3352
- continue;
3353
- const wired = config.suites.filter((suite) => suite.isWiring(file));
3354
- const diffed = packages?.files.has(file) ?? false;
3355
- if (config.isSelf(file)) {
3356
- runAll({
3357
- kind: "self",
3358
- file,
3359
- message: `${file}: test selector changed`
3360
- });
3361
- continue;
3362
- }
3363
- for (const suite of wired) {
3364
- causes.push({
3365
- kind: "wiring",
3366
- suites: [suite.name],
3367
- file,
3368
- message: `${file}: wires the ${suite.name} suite`
3369
- });
3370
- }
3371
- if (wired.length > 0 && !diffed)
3824
+ var STRING_OR_TRAILING_COMMA = /"(?:[^"\\]|\\.)*"|,(\s*[}\]])/g;
3825
+ function parseLenient(text) {
3826
+ return JSON.parse(text.replace(STRING_OR_TRAILING_COMMA, (match, close) => close ?? match));
3827
+ }
3828
+ function specsOf(value) {
3829
+ const specs = new Map;
3830
+ for (const field of DEP_FIELDS2) {
3831
+ const deps = value[field];
3832
+ if (deps === undefined)
3372
3833
  continue;
3373
- if (diffed) {
3374
- const reason = packages?.files.get(file);
3375
- if (reason === undefined) {
3376
- packageFiles.push(file);
3377
- } else {
3378
- runAll({ kind: "lockfile", file, message: `${file}: ${reason}` });
3379
- }
3380
- } else if (read || config.roots.some((root) => inRoot2(file, root))) {
3381
- if (ignored)
3382
- quiet.push(file);
3383
- else
3384
- ((settings?.has(file)) ? settingFiles : relevant).push(file);
3385
- } else {
3386
- runAll({
3387
- kind: "outside",
3388
- file,
3389
- message: `${file}: outside the dependency graph`
3390
- });
3834
+ if (!isStringRecord2(deps))
3835
+ return;
3836
+ specs.set(field, new Map(Object.entries(deps)));
3837
+ }
3838
+ return specs;
3839
+ }
3840
+ function restOf(value, skip) {
3841
+ return JSON.stringify(Object.entries(value).filter(([key]) => !skip.includes(key)));
3842
+ }
3843
+ function install(packages, name, entry, version, info) {
3844
+ const installed = packages.get(name) ?? {
3845
+ entries: [],
3846
+ versions: [],
3847
+ dependencies: new Set,
3848
+ bin: false
3849
+ };
3850
+ if (info?.bin !== undefined || info?.hasBin === true || info?.hasBin === "true") {
3851
+ installed.bin = true;
3852
+ }
3853
+ installed.entries.push(JSON.stringify(entry));
3854
+ if (!installed.versions.includes(version))
3855
+ installed.versions.push(version);
3856
+ for (const field of [
3857
+ "dependencies",
3858
+ "optionalDependencies",
3859
+ "peerDependencies"
3860
+ ]) {
3861
+ const deps = info?.[field];
3862
+ if (isRecord2(deps)) {
3863
+ for (const dep of Object.keys(deps))
3864
+ installed.dependencies.add(dep);
3391
3865
  }
3392
3866
  }
3393
- return { relevant, quiet, packageFiles, settingFiles, causes };
3394
- }
3395
- function narrowedWalk(graph, seeds, {
3396
- quiet,
3397
- layout,
3398
- types
3399
- }, coarse, narrowings) {
3400
- const matched = new Set(narrowings.flatMap((narrowing) => narrowing.matched));
3401
- const fine = affectedBy(graph, seeds.filter((seed) => !matched.has(seed)), { quiet, layout, types });
3402
- for (const narrowing of narrowings) {
3403
- const walk = affectedBy(graph, [...narrowing.matched, ...narrowing.seeds], {
3404
- opaque: narrowing.narrower.opaque,
3405
- layout,
3406
- types
3407
- });
3408
- for (const node of walk)
3409
- fine.add(node);
3867
+ packages.set(name, installed);
3868
+ }
3869
+ function installedName(key) {
3870
+ const [name = key, scope] = key.split("/").reverse();
3871
+ return scope?.startsWith("@") ? `${scope}/${name}` : name;
3872
+ }
3873
+ function parseBunLock(text) {
3874
+ const value = parseLenient(text);
3875
+ if (!isRecord2(value))
3876
+ return;
3877
+ const { packages, workspaces } = value;
3878
+ if (!isRecord2(packages) || !isRecord2(workspaces))
3879
+ return;
3880
+ const lockfile = {
3881
+ packages: new Map,
3882
+ workspaces: new Map,
3883
+ rest: restOf(value, ["packages", "workspaces"])
3884
+ };
3885
+ for (const [key, entry] of Object.entries(packages)) {
3886
+ if (!Array.isArray(entry) || typeof entry[0] !== "string")
3887
+ return;
3888
+ const ident = entry[0];
3889
+ const at = ident.indexOf("@", 1);
3890
+ const version = at === -1 ? "" : ident.slice(at + 1);
3891
+ install(lockfile.packages, installedName(key), entry, version, entry.find(isRecord2));
3892
+ }
3893
+ for (const [dir, workspace] of Object.entries(workspaces)) {
3894
+ const specs = isRecord2(workspace) ? specsOf(workspace) : undefined;
3895
+ if (!specs)
3896
+ return;
3897
+ lockfile.workspaces.set(dir === "" ? "." : dir, specs);
3410
3898
  }
3411
- return new Set([...fine].filter((node) => coarse.has(node)));
3899
+ return lockfile;
3412
3900
  }
3413
- function orphanOf(graph, config, suite, file) {
3414
- if (!suite.roots.some((root) => inRoot2(file, root)))
3901
+ var NODE_MODULES = "node_modules/";
3902
+ function parsePackageLock(text) {
3903
+ const value = JSON.parse(text);
3904
+ if (!isRecord2(value) || !isRecord2(value.packages))
3415
3905
  return;
3416
- const wired = (path) => suite.isTest(path) || suite.isPage(path);
3417
- if (reaches(graph, [file], wired, {
3418
- includeUnknown: false,
3419
- types: suite.types || DECLARATION.test(file)
3420
- })) {
3906
+ const { lockfileVersion } = value;
3907
+ if (lockfileVersion !== 2 && lockfileVersion !== 3)
3421
3908
  return;
3909
+ const lockfile = {
3910
+ packages: new Map,
3911
+ workspaces: new Map,
3912
+ rest: restOf(value, ["packages", "dependencies", "name", "version"])
3913
+ };
3914
+ for (const [key, entry] of Object.entries(value.packages)) {
3915
+ if (!isRecord2(entry))
3916
+ return;
3917
+ const at = key.lastIndexOf(NODE_MODULES);
3918
+ if (at !== -1 && (at === 0 || key[at - 1] === "/")) {
3919
+ const version = typeof entry.version === "string" ? entry.version : "";
3920
+ const name = key.slice(at + NODE_MODULES.length);
3921
+ install(lockfile.packages, name, entry, version, entry);
3922
+ continue;
3923
+ }
3924
+ const specs = specsOf(entry);
3925
+ if (!specs)
3926
+ return;
3927
+ lockfile.workspaces.set(key === "" ? "." : key, specs);
3422
3928
  }
3423
- const deleted = !graph.has(file);
3424
- if (deleted && suite.isTest(file))
3929
+ return lockfile;
3930
+ }
3931
+ function pnpmKey(key) {
3932
+ const bare = key.startsWith("/") ? key.slice(1) : key;
3933
+ const at = bare.indexOf("@", 1);
3934
+ if (at === -1)
3425
3935
  return;
3426
- if (deleted && config.isImportOnly(file))
3936
+ return { name: bare.slice(0, at), version: withoutPeers(bare.slice(at + 1)) };
3937
+ }
3938
+ function withoutPeers(version) {
3939
+ const paren = version.indexOf("(");
3940
+ return paren === -1 ? version : version.slice(0, paren);
3941
+ }
3942
+ var YAML_DOCUMENT = /^---[ \t]*$/m;
3943
+ var PNPM_VERSION = /^[69]\./;
3944
+ var PNPM_DEP_FIELDS = [
3945
+ "dependencies",
3946
+ "devDependencies",
3947
+ "optionalDependencies"
3948
+ ];
3949
+ function parsePnpmLock(text) {
3950
+ const docs = text.split(YAML_DOCUMENT).filter((doc) => doc.trim() !== "").map(parseYaml);
3951
+ const main = docs.findLast((doc) => isRecord2(doc) && typeof doc.lockfileVersion === "string");
3952
+ if (!isRecord2(main))
3427
3953
  return;
3428
- if (suite.isNonInput(file))
3954
+ const { lockfileVersion, packages = {}, snapshots = {} } = main;
3955
+ if (typeof lockfileVersion !== "string")
3429
3956
  return;
3430
- const typed = !suite.types && reaches(graph, [file], suite.isTest, { includeUnknown: false });
3431
- return { typed };
3432
- }
3433
- function planTests(graph, changed, config, {
3434
- barrelNames = [],
3435
- layout = new Set,
3436
- narrowed = [],
3437
- packages,
3438
- settings
3439
- } = {}) {
3440
- const { relevant, quiet, packageFiles, settingFiles, causes } = classify(graph, changed, config, packages, settings);
3441
- const settingCauses = new Map;
3442
- const settingNotes = [];
3443
- for (const file of settingFiles) {
3444
- const change = settings?.get(file);
3445
- if (!change)
3446
- continue;
3447
- settingNotes.push(change.note);
3448
- for (const seed of change.seeds) {
3449
- if (!settingCauses.has(seed)) {
3450
- settingCauses.set(seed, `governed by ${file}, which changed`);
3957
+ if (!PNPM_VERSION.test(lockfileVersion))
3958
+ return;
3959
+ if (!isRecord2(packages) || !isRecord2(snapshots))
3960
+ return;
3961
+ const workspaces = isRecord2(main.importers);
3962
+ const importers = isRecord2(main.importers) ? main.importers : { ".": main };
3963
+ const lockfile = {
3964
+ packages: new Map,
3965
+ workspaces: new Map,
3966
+ rest: JSON.stringify([
3967
+ restOf(main, ["importers", "packages", "snapshots", ...PNPM_DEP_FIELDS]),
3968
+ ...docs.filter((doc) => doc !== main)
3969
+ ])
3970
+ };
3971
+ const restOfImporters = [];
3972
+ for (const [dir, importer] of Object.entries(importers)) {
3973
+ if (!isRecord2(importer))
3974
+ return;
3975
+ const specs = new Map;
3976
+ for (const field of PNPM_DEP_FIELDS) {
3977
+ const deps = importer[field];
3978
+ if (deps === undefined)
3979
+ continue;
3980
+ if (!isRecord2(deps))
3981
+ return;
3982
+ const declared = new Map;
3983
+ for (const [name, dep] of Object.entries(deps)) {
3984
+ if (!isRecord2(dep) || typeof dep.specifier !== "string") {
3985
+ return;
3986
+ }
3987
+ declared.set(name, dep.specifier);
3988
+ const version = typeof dep.version === "string" ? dep.version : "";
3989
+ install(lockfile.packages, name, [dir, field, version], withoutPeers(version), {});
3451
3990
  }
3991
+ specs.set(field, declared);
3452
3992
  }
3453
- }
3454
- const bumped = packages && packageFiles.length > 0 ? packageSeeds(graph, config, packages, packageFiles) : { seeds: new Map, notes: [], reasons: [] };
3455
- const all = config.suites.map((suite) => suite.name);
3456
- for (const unused of bumped.reasons) {
3457
- causes.push({ kind: "package", suites: all, ...unused });
3458
- }
3459
- const seeds = [
3460
- ...relevant,
3461
- ...settingFiles,
3462
- ...settingCauses.keys(),
3463
- ...barrelNames,
3464
- ...packageFiles,
3465
- ...bumped.seeds.keys()
3466
- ];
3467
- const affected = walksByTypes(graph, seeds, { quiet, layout });
3468
- const nodes = [...graph.keys()];
3469
- const tests = new Map(config.suites.map((suite) => [suite.name, nodes.filter(suite.isTest)]));
3470
- for (const suite of config.suites) {
3471
- for (const file of relevant) {
3472
- const orphan = orphanOf(graph, config, suite, file);
3473
- if (!orphan)
3474
- continue;
3475
- const { typed } = orphan;
3476
- causes.push({
3477
- kind: "orphan",
3478
- suites: [suite.name],
3479
- file,
3480
- message: `${file}: no ${suite.name} test imports it${typed ? " (only type imports reach it: list it in the suite's `nonInputs` if nothing loads it at runtime)" : ""}`
3481
- });
3993
+ lockfile.workspaces.set(dir, specs);
3994
+ if (workspaces) {
3995
+ const settings = restOf(importer, PNPM_DEP_FIELDS);
3996
+ if (settings !== "[]")
3997
+ restOfImporters.push([dir, settings]);
3482
3998
  }
3483
3999
  }
3484
- const narrowings = new Map;
3485
- for (const { narrower, result } of narrowed) {
3486
- const matched = relevant.filter(narrower.match);
3487
- if (matched.length === 0)
3488
- continue;
3489
- if ("all" in result) {
3490
- causes.push({
3491
- kind: "narrower",
3492
- suites: narrower.suites,
3493
- narrower: narrower.name,
3494
- message: `${narrower.name}: ${result.all}`
3495
- });
3496
- continue;
4000
+ lockfile.rest += JSON.stringify(restOfImporters);
4001
+ for (const section of [packages, snapshots]) {
4002
+ for (const [key, entry] of Object.entries(section)) {
4003
+ const parsed = pnpmKey(key);
4004
+ if (!parsed)
4005
+ return;
4006
+ const info = isRecord2(entry) ? entry : undefined;
4007
+ install(lockfile.packages, parsed.name, [key, entry], parsed.version, info);
3497
4008
  }
3498
- for (const name of narrower.suites) {
3499
- const list = narrowings.get(name) ?? [];
3500
- list.push({ matched, narrower, seeds: result.seeds });
3501
- narrowings.set(name, list);
4009
+ }
4010
+ return lockfile;
4011
+ }
4012
+ var FORMATS = new Map([
4013
+ ["bun.lock", parseBunLock],
4014
+ ["package-lock.json", parsePackageLock],
4015
+ ["pnpm-lock.yaml", parsePnpmLock]
4016
+ ]);
4017
+ var UNREAD = ["bun.lockb", "npm-shrinkwrap.json", "yarn.lock"];
4018
+ function parse(file, text) {
4019
+ const format = FORMATS.get(file);
4020
+ if (text === undefined || !format)
4021
+ return;
4022
+ try {
4023
+ return format(text);
4024
+ } catch {
4025
+ return;
4026
+ }
4027
+ }
4028
+ function describe(name, before, after) {
4029
+ if (before === undefined)
4030
+ return `${name} ${after} added`;
4031
+ if (after === undefined)
4032
+ return `${name} ${before} removed`;
4033
+ return before === after ? `${name} ${after}, entry changed` : `${name} ${before} → ${after}`;
4034
+ }
4035
+ function versions(installed) {
4036
+ return installed && sorted(installed.versions).join(", ");
4037
+ }
4038
+ function specChanges(before, after) {
4039
+ const changed = new Map;
4040
+ for (const field of DEP_FIELDS2) {
4041
+ const a = before?.get(field);
4042
+ const b = after?.get(field);
4043
+ for (const name of new Set([...a?.keys() ?? [], ...b?.keys() ?? []])) {
4044
+ if (a?.get(name) !== b?.get(name) && !changed.has(name)) {
4045
+ changed.set(name, [a?.get(name), b?.get(name)]);
4046
+ }
3502
4047
  }
3503
4048
  }
3504
- const full = new Set(causes.flatMap((cause) => cause.suites));
3505
- const suites = {};
3506
- for (const suite of config.suites) {
3507
- if (full.has(suite.name)) {
3508
- suites[suite.name] = { mode: "all" };
4049
+ return changed;
4050
+ }
4051
+ function lockfileChanges(file, base, head) {
4052
+ const changes = [];
4053
+ const names = new Set([...base.packages.keys(), ...head.packages.keys()]);
4054
+ for (const name of names) {
4055
+ const before = base.packages.get(name);
4056
+ const after = head.packages.get(name);
4057
+ const same = before !== undefined && after !== undefined && sorted(before.entries).join(`
4058
+ `) === sorted(after.entries).join(`
4059
+ `);
4060
+ if (same)
3509
4061
  continue;
4062
+ changes.push({
4063
+ name,
4064
+ detail: `${file}: ${describe(name, versions(before), versions(after))}`,
4065
+ file
4066
+ });
4067
+ }
4068
+ const resolved = new Set(changes.map((change) => change.name));
4069
+ const dirs = new Set([...base.workspaces.keys(), ...head.workspaces.keys()]);
4070
+ for (const dir of dirs) {
4071
+ const declared = specChanges(base.workspaces.get(dir), head.workspaces.get(dir));
4072
+ for (const [name, [before, after]] of declared) {
4073
+ if (resolved.has(name))
4074
+ continue;
4075
+ resolved.add(name);
4076
+ changes.push({
4077
+ name,
4078
+ detail: `${file}: ${describe(`${name} range`, before, after)}`,
4079
+ file
4080
+ });
3510
4081
  }
3511
- const coarse = affected(suite.types);
3512
- const narrowing = narrowings.get(suite.name);
3513
- suites[suite.name] = select(narrowing ? narrowedWalk(graph, seeds, { quiet, layout, types: suite.types }, coarse, narrowing) : coarse, tests.get(suite.name) ?? []);
3514
4082
  }
3515
- return {
3516
- suites,
3517
- reasons: causes.map((cause) => cause.message),
3518
- causes,
3519
- totals: Object.fromEntries(config.suites.map((suite) => [
3520
- suite.name,
3521
- tests.get(suite.name)?.length ?? 0
3522
- ])),
3523
- full: [...full],
3524
- packages: bumped.notes,
3525
- settings: settingNotes,
3526
- settingCauses,
3527
- seeds,
3528
- quiet,
3529
- layout,
3530
- packageCauses: bumped.seeds,
3531
- narrowings
3532
- };
3533
- }
3534
-
3535
- // src/compute.ts
3536
- import { readFile as readFile3, stat } from "node:fs/promises";
3537
- import { join as join3, posix as posix6, resolve } from "node:path";
3538
-
3539
- // src/cache.ts
3540
- import { existsSync } from "node:fs";
3541
- import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3542
- import { isAbsolute, join } from "node:path";
3543
- var SCANNER_VERSION = 9;
3544
- var MAGIC = "bivium-extractions";
3545
- var FILE = "extractions.json";
3546
- function isHeader(value) {
3547
- return typeof value === "object" && value !== null && "magic" in value && value.magic === MAGIC && "bivium" in value && value.bivium === version && "scanner" in value && value.scanner === SCANNER_VERSION && "rows" in value && typeof value.rows === "number" && "strings" in value && typeof value.strings === "number";
4083
+ return changes;
3548
4084
  }
3549
- function cacheDir(root, cache) {
3550
- if (cache === false)
4085
+ var MANIFEST = /(?:^|\/)package\.json$/;
4086
+ function parseManifest(text) {
4087
+ if (text === undefined)
4088
+ return;
4089
+ try {
4090
+ const value = JSON.parse(text);
4091
+ return isRecord2(value) ? value : undefined;
4092
+ } catch {
3551
4093
  return;
3552
- if (typeof cache === "string") {
3553
- return isAbsolute(cache) ? cache : join(root, cache);
3554
4094
  }
3555
- const modules = join(root, "node_modules");
3556
- return existsSync(modules) ? join(modules, ".cache", "bivium") : join(root, ".bivium", "cache");
3557
4095
  }
3558
-
3559
- class ExtractionCache {
3560
- #rows = new Map;
3561
- #strings = [];
3562
- #used = new Map;
3563
- #dirty = false;
3564
- dir;
3565
- constructor(dir) {
3566
- this.dir = dir;
3567
- }
3568
- static async open(dir) {
3569
- const cache = new ExtractionCache(dir);
3570
- if (!dir)
3571
- return cache;
3572
- const text = await readFile(join(dir, FILE), "utf-8").catch(() => "");
3573
- if (text)
3574
- cache.#load(text);
3575
- return cache;
3576
- }
3577
- #load(text) {
3578
- try {
3579
- const parsed = JSON.parse(text);
3580
- if (!Array.isArray(parsed))
3581
- return;
3582
- const fields = parsed;
3583
- const [header, strings, rows] = fields;
3584
- if (!isHeader(header) || !Array.isArray(strings) || !Array.isArray(rows) || header.strings !== strings.length || header.rows !== rows.length) {
3585
- return;
4096
+ function isPackageFile(file) {
4097
+ return FORMATS.has(file) || MANIFEST.test(file);
4098
+ }
4099
+ async function readPackageDiff(changed, listed, base, head) {
4100
+ const lockfiles = changed.filter((file) => FORMATS.has(file));
4101
+ const manifests = changed.filter((file) => MANIFEST.test(file));
4102
+ if (lockfiles.length === 0 && manifests.length === 0)
4103
+ return;
4104
+ const read = (path) => Promise.all([base(path), head(path)]);
4105
+ const known = [...FORMATS.keys()];
4106
+ const [lockTexts, manifestTexts] = await Promise.all([
4107
+ Promise.all(known.map(async (file) => {
4108
+ if (lockfiles.includes(file))
4109
+ return [file, ...await read(file)];
4110
+ const text = await head(file);
4111
+ return [file, text, text];
4112
+ })),
4113
+ Promise.all(manifests.map(async (file) => [file, ...await read(file)]))
4114
+ ]);
4115
+ const diff = {
4116
+ files: new Map,
4117
+ changes: [],
4118
+ dependents: new Map,
4119
+ declared: new Set,
4120
+ bins: new Set
4121
+ };
4122
+ const present = new Map;
4123
+ for (const [file, baseText, headText] of lockTexts) {
4124
+ const after = parse(file, headText);
4125
+ if (headText !== undefined)
4126
+ present.set(file, after);
4127
+ const before = parse(file, baseText);
4128
+ for (const lockfile of [before, after]) {
4129
+ if (!lockfile)
4130
+ continue;
4131
+ for (const [name, installed] of lockfile.packages) {
4132
+ if (installed.bin)
4133
+ diff.bins.add(name);
4134
+ for (const dependency of installed.dependencies) {
4135
+ const set = diff.dependents.get(dependency) ?? new Set;
4136
+ set.add(name);
4137
+ diff.dependents.set(dependency, set);
4138
+ }
3586
4139
  }
3587
- this.#strings = strings;
3588
- for (const row of rows) {
3589
- if (Array.isArray(row) && typeof row[0] === "string") {
3590
- this.#rows.set(row[0], row);
4140
+ for (const specs of lockfile.workspaces.values()) {
4141
+ for (const deps of specs.values()) {
4142
+ for (const name of deps.keys())
4143
+ diff.declared.add(name);
3591
4144
  }
3592
4145
  }
3593
- } catch {}
3594
- }
3595
- get size() {
3596
- return this.#rows.size;
3597
- }
3598
- get(oid, format) {
3599
- const key = `${format}:${oid}`;
3600
- const used = this.#used.get(key);
3601
- if (used)
3602
- return used;
3603
- const row = this.#rows.get(key);
3604
- if (!row)
3605
- return;
3606
- let extraction;
3607
- try {
3608
- extraction = decode(row, this.#strings);
3609
- } catch {
3610
- this.#rows.delete(key);
3611
- return;
3612
4146
  }
3613
- this.#used.set(key, extraction);
3614
- return extraction;
3615
- }
3616
- set(oid, format, extraction) {
3617
- const key = `${format}:${oid}`;
3618
- this.#used.set(key, extraction);
3619
- this.#dirty = true;
3620
- }
3621
- async save() {
3622
- if (!this.dir || !this.#dirty)
3623
- return;
3624
- const table = createStrings();
3625
- const rows = [];
3626
- for (const [key, extraction] of this.#used) {
3627
- rows.push(encode(key, extraction, table));
4147
+ if (!lockfiles.includes(file))
4148
+ continue;
4149
+ if (baseText === undefined || headText === undefined) {
4150
+ diff.files.set(file, baseText === undefined ? "added" : "deleted");
4151
+ } else if (!(before && after)) {
4152
+ diff.files.set(file, "can't parse it");
4153
+ } else if (before.rest === after.rest) {
4154
+ diff.files.set(file, undefined);
4155
+ diff.changes.push(...lockfileChanges(file, before, after));
4156
+ } else {
4157
+ diff.files.set(file, "a setting other than the packages changed");
3628
4158
  }
3629
- let stale = Math.floor(this.#used.size / 2);
3630
- for (const [key, row] of this.#rows) {
3631
- if (stale === 0)
3632
- break;
3633
- if (this.#used.has(key))
3634
- continue;
3635
- try {
3636
- rows.push(encode(key, decode(row, this.#strings), table));
3637
- stale--;
3638
- } catch {}
4159
+ }
4160
+ const unread = UNREAD.some((file) => listed.includes(file));
4161
+ for (const [file, beforeText, afterText] of manifestTexts) {
4162
+ const before = parseManifest(beforeText);
4163
+ const after = parseManifest(afterText);
4164
+ if (!(before && after) || unread || present.size === 0)
4165
+ continue;
4166
+ const others = (record) => restOf(record, DEP_FIELDS2);
4167
+ const specsBefore = specsOf(before);
4168
+ const specsAfter = specsOf(after);
4169
+ if (others(before) !== others(after) || !specsBefore || !specsAfter) {
4170
+ continue;
3639
4171
  }
3640
- const header = {
3641
- magic: MAGIC,
3642
- bivium: version,
3643
- scanner: SCANNER_VERSION,
3644
- rows: rows.length,
3645
- strings: table.list.length
3646
- };
3647
- const file = join(this.dir, FILE);
3648
- const temp = `${file}.${process.pid}.${nowMs()}.tmp`;
3649
- try {
3650
- await mkdir(this.dir, { recursive: true });
3651
- const ignore = join(this.dir, ".gitignore");
3652
- if (!existsSync(ignore))
3653
- await writeFile(ignore, `*
3654
- `);
3655
- await writeFile(temp, JSON.stringify([header, table.list, rows]));
3656
- await rename(temp, file);
3657
- this.#dirty = false;
3658
- } catch {
3659
- await unlink(temp).catch(() => {
3660
- return;
4172
+ const dir = posix3.dirname(file);
4173
+ const declared = specChanges(specsBefore, specsAfter);
4174
+ const recorded = [...present.values()].every((lockfile) => {
4175
+ const specs = lockfile?.workspaces.get(dir);
4176
+ if (!specs)
4177
+ return false;
4178
+ return [...declared.keys()].every((name) => DEP_FIELDS2.every((field) => specs.get(field)?.get(name) === specsAfter.get(field)?.get(name)));
4179
+ });
4180
+ if (!recorded)
4181
+ continue;
4182
+ diff.files.set(file, undefined);
4183
+ for (const [name, [from, to]] of declared) {
4184
+ diff.declared.add(name);
4185
+ diff.changes.push({
4186
+ name,
4187
+ detail: `${file}: ${describe(`${name} range`, from, to)}`,
4188
+ file
3661
4189
  });
3662
4190
  }
3663
4191
  }
4192
+ return diff;
3664
4193
  }
3665
- function createStrings() {
3666
- const list = [];
3667
- const idsByValue = new Map;
3668
- const id = (value) => {
3669
- let found = idsByValue.get(value);
4194
+ function packageSeeds(graph, config, diff, files) {
4195
+ const result = { seeds: new Map, notes: [], reasons: [] };
4196
+ const { isLoadedByName } = config;
4197
+ const loadedOtherwise = (name) => isLoadedByName === undefined || diff.bins.has(name) || isLoadedByName(name);
4198
+ const tested = new Map;
4199
+ const reachesTest = (name) => {
4200
+ let found = tested.get(name);
3670
4201
  if (found === undefined) {
3671
- found = list.length;
3672
- list.push(value);
3673
- idsByValue.set(value, found);
4202
+ const node = `pkg:${name}`;
4203
+ found = graph.has(node) && config.suites.some((suite) => reaches(graph, [node], suite.isTest, {
4204
+ includeUnknown: false,
4205
+ types: suite.types
4206
+ }));
4207
+ tested.set(name, found);
3674
4208
  }
3675
4209
  return found;
3676
4210
  };
3677
- const ids = (values) => values.length === 0 ? 0 : values.map(id);
3678
- return { list, id, ids };
3679
- }
3680
- function typeIndexes(imports) {
3681
- const indexes = [];
3682
- for (const [i, ref] of imports.entries())
3683
- if (ref.type)
3684
- indexes.push(i);
3685
- return indexes.length === 0 ? 0 : indexes;
3686
- }
3687
- function encode(key, e, table) {
3688
- const imports = e.imports.map(({ specifier, names }) => names ? [table.id(specifier), ...names.map((n) => table.id(n))] : table.id(specifier));
3689
- const barrel = e.barrel && [
3690
- [...e.barrel.names].flatMap(([name, from]) => [
3691
- table.id(name),
3692
- table.id(from)
3693
- ]),
3694
- table.ids(e.barrel.stars)
3695
- ];
3696
- return [
3697
- key,
3698
- imports.length === 0 ? 0 : imports,
3699
- table.ids(e.globs),
3700
- table.ids(e.gotos),
3701
- table.ids(e.dependsOn),
3702
- table.ids(e.reads),
3703
- table.ids(e.unknown),
3704
- e.fallback === undefined ? 0 : table.id(e.fallback),
3705
- barrel ?? 0,
3706
- typeIndexes(e.imports),
3707
- table.ids(e.lists)
3708
- ];
3709
- }
3710
- function decode(row, strings) {
3711
- const str = (id) => {
3712
- const value = typeof id === "number" ? strings[id] : undefined;
3713
- if (typeof value !== "string")
3714
- throw new Error("bad string id");
3715
- return value;
3716
- };
3717
- const list = (ids) => {
3718
- if (ids === 0)
3719
- return [];
3720
- if (!Array.isArray(ids))
3721
- throw new Error("bad list");
3722
- return ids.map(str);
3723
- };
3724
- const refs = row[1] === 0 ? [] : row[1];
3725
- if (!Array.isArray(refs))
3726
- throw new Error("bad imports");
3727
- const imports = refs.map((item) => Array.isArray(item) ? { specifier: str(item[0]), names: item.slice(1).map(str) } : { specifier: str(item) });
3728
- if (row[9] !== 0) {
3729
- if (!Array.isArray(row[9]))
3730
- throw new Error("bad types");
3731
- for (const i of row[9]) {
3732
- const ref = typeof i === "number" ? imports[i] : undefined;
3733
- if (!ref)
3734
- throw new Error("bad type index");
3735
- ref.type = true;
4211
+ const changes = diff.changes.filter((change) => files.includes(change.file)).sort((a, b) => byCodeUnit(a.name, b.name));
4212
+ const unused = new Map;
4213
+ const seen = new Set;
4214
+ for (const change of changes) {
4215
+ const { name, detail } = change;
4216
+ if (seen.has(name))
4217
+ continue;
4218
+ seen.add(name);
4219
+ const closure = new Set([name]);
4220
+ const queue = [name];
4221
+ for (const queued of queue) {
4222
+ for (const dependent of diff.dependents.get(queued) ?? []) {
4223
+ if (closure.has(dependent))
4224
+ continue;
4225
+ closure.add(dependent);
4226
+ queue.push(dependent);
4227
+ }
3736
4228
  }
3737
- }
3738
- const extraction = {
3739
- imports,
3740
- globs: list(row[2]),
3741
- gotos: list(row[3]),
3742
- dependsOn: list(row[4]),
3743
- reads: list(row[5]),
3744
- lists: list(row[10]),
3745
- unknown: list(row[6])
3746
- };
3747
- if (row[7] !== 0)
3748
- extraction.fallback = str(row[7]);
3749
- if (row[8] !== 0) {
3750
- if (!Array.isArray(row[8]))
3751
- throw new Error("bad barrel");
3752
- const barrel = row[8];
3753
- const [pairs, stars] = barrel;
3754
- if (!Array.isArray(pairs))
3755
- throw new Error("bad barrel names");
3756
- const names = new Map;
3757
- for (let i = 0;i < pairs.length; i += 2) {
3758
- names.set(str(pairs[i]), str(pairs[i + 1]));
4229
+ const through = [];
4230
+ let covered = true;
4231
+ let importOnly = false;
4232
+ for (const user of closure) {
4233
+ const node = `pkg:${user}`;
4234
+ const imported = graph.has(node);
4235
+ if (imported) {
4236
+ through.push(user);
4237
+ if (!result.seeds.has(node)) {
4238
+ result.seeds.set(node, user === name ? detail : `${detail}, which ${user} depends on`);
4239
+ }
4240
+ }
4241
+ const entry = imported || diff.declared.has(user) || !diff.dependents.has(user);
4242
+ if (!entry || reachesTest(user) || config.isInert(user))
4243
+ continue;
4244
+ if (loadedOtherwise(user)) {
4245
+ covered = false;
4246
+ const list = unused.get(user) ?? [];
4247
+ if (user === name)
4248
+ list.unshift(change);
4249
+ else
4250
+ list.push(change);
4251
+ unused.set(user, list);
4252
+ } else {
4253
+ importOnly = true;
4254
+ }
3759
4255
  }
3760
- extraction.barrel = { names, stars: list(stars) };
4256
+ if (!covered)
4257
+ continue;
4258
+ if (through.length === 0) {
4259
+ result.notes.push(`${detail}, ${importOnly ? "imported by no test" : "inert"}`);
4260
+ continue;
4261
+ }
4262
+ const others = through.filter((user) => user !== name);
4263
+ const shown = others.slice(0, 3).join(", ");
4264
+ const rest = others.length > 3 ? ` and ${others.length - 3} more` : "";
4265
+ result.notes.push(others.length === 0 ? detail : `${detail}, through ${shown}${rest}`);
3761
4266
  }
3762
- return extraction;
4267
+ for (const user of sorted(unused.keys())) {
4268
+ const [first, ...more] = unused.get(user) ?? [];
4269
+ if (!first)
4270
+ continue;
4271
+ const own = first.name === user;
4272
+ const also = more.length === 0 ? "" : ` (and ${more.length} more ${more.length === 1 ? "package" : "packages"} ${user} depends on)`;
4273
+ result.reasons.push({
4274
+ package: user,
4275
+ file: first.file,
4276
+ message: own ? `${first.detail}${also}, and no test imports it` : `${first.detail}, which ${user} depends on${also}, and no test imports ${user}`
4277
+ });
4278
+ }
4279
+ return result;
3763
4280
  }
3764
4281
 
3765
- // src/git.ts
3766
- import { spawn } from "node:child_process";
3767
- import { readFile as readFile2 } from "node:fs/promises";
3768
- import { join as join2 } from "node:path";
3769
- function git(cwd, ...args) {
3770
- return new Promise((resolve, reject) => {
3771
- const child = spawn("git", args, { cwd });
3772
- const chunks = [];
3773
- const errors = [];
3774
- child.stdout.on("data", (chunk) => chunks.push(chunk));
3775
- child.stderr.on("data", (chunk) => errors.push(chunk));
3776
- child.on("error", reject);
3777
- child.on("close", (status) => {
3778
- resolve({
3779
- status: status ?? 1,
3780
- stdout: Buffer.concat(chunks).toString("utf-8"),
3781
- stderr: Buffer.concat(errors).toString("utf-8")
4282
+ // src/plan.ts
4283
+ function formatSelection(selection) {
4284
+ return selection.mode === "some" ? selection.files.join(" ") : selection.mode;
4285
+ }
4286
+ function select(affected, tests) {
4287
+ const files = tests.filter((file) => affected.has(file));
4288
+ if (files.length === 0)
4289
+ return { mode: "none" };
4290
+ if (files.length === tests.length)
4291
+ return { mode: "all" };
4292
+ return { mode: "some", files };
4293
+ }
4294
+ function classify(graph, changed, config, packages, settings) {
4295
+ const causes = [];
4296
+ const all = config.suites.map((suite) => suite.name);
4297
+ const runAll = (cause) => causes.push({ ...cause, suites: all });
4298
+ const relevant = [];
4299
+ const quiet = [];
4300
+ const packageFiles = [];
4301
+ const settingFiles = [];
4302
+ for (const file of changed) {
4303
+ const read = graph.has(file);
4304
+ const ignored = config.isIgnored(file);
4305
+ if (!read && ignored)
4306
+ continue;
4307
+ const wired = config.suites.filter((suite) => suite.isWiring(file));
4308
+ const diffed = packages?.files.has(file) ?? false;
4309
+ if (config.isSelf(file)) {
4310
+ runAll({
4311
+ kind: "self",
4312
+ file,
4313
+ message: `${file}: test selector changed`
3782
4314
  });
3783
- });
3784
- });
4315
+ continue;
4316
+ }
4317
+ for (const suite of wired) {
4318
+ causes.push({
4319
+ kind: "wiring",
4320
+ suites: [suite.name],
4321
+ file,
4322
+ message: `${file}: wires the ${suite.name} suite`
4323
+ });
4324
+ }
4325
+ if (wired.length > 0 && !diffed)
4326
+ continue;
4327
+ if (diffed) {
4328
+ const reason = packages?.files.get(file);
4329
+ if (reason === undefined) {
4330
+ packageFiles.push(file);
4331
+ } else {
4332
+ runAll({ kind: "lockfile", file, message: `${file}: ${reason}` });
4333
+ }
4334
+ } else if (read || config.roots.some((root) => inRoot2(file, root))) {
4335
+ if (ignored)
4336
+ quiet.push(file);
4337
+ else
4338
+ ((settings?.has(file)) ? settingFiles : relevant).push(file);
4339
+ } else {
4340
+ runAll({
4341
+ kind: "outside",
4342
+ file,
4343
+ message: `${file}: outside the dependency graph`
4344
+ });
4345
+ }
4346
+ }
4347
+ return { relevant, quiet, packageFiles, settingFiles, causes };
3785
4348
  }
3786
- async function gitOrThrow(cwd, ...args) {
3787
- const result = await git(cwd, ...args);
3788
- if (result.status !== 0) {
3789
- const said = result.stderr.trim().split(`
3790
- `)[0];
3791
- throw new BiviumError2("BV_GIT_FAILED", `bivium: git ${args.join(" ")} failed${said ? `: ${said}` : ""}`);
4349
+ function narrowedWalk(graph, seeds, {
4350
+ quiet,
4351
+ layout,
4352
+ types,
4353
+ sealed
4354
+ }, coarse, narrowings) {
4355
+ const matched = new Set(narrowings.flatMap((narrowing) => narrowing.matched));
4356
+ const fine = affectedBy(graph, seeds.filter((seed) => !matched.has(seed)), { quiet, layout, types, sealed });
4357
+ for (const narrowing of narrowings) {
4358
+ const walk = affectedBy(graph, [...narrowing.matched, ...narrowing.seeds], {
4359
+ opaque: narrowing.narrower.opaque,
4360
+ layout,
4361
+ types
4362
+ });
4363
+ for (const node of walk)
4364
+ fine.add(node);
3792
4365
  }
3793
- return result.stdout;
3794
- }
3795
- function lines(output) {
3796
- return output.split(`
3797
- `).filter(Boolean);
4366
+ return new Set([...fine].filter((node) => coarse.has(node)));
3798
4367
  }
3799
- var INDEX_ENTRY = /^(\S) (\d{6}) ([0-9a-f]+) (\d)\t(.*)$/;
3800
- var RAW_ENTRY = /^:(\d{6}) \d{6} ([0-9a-f]+) [0-9a-f]+ ([A-Z])\d*\t(.*)$/;
3801
- async function missingHistory(cwd, base) {
3802
- const [known, forked, shallow] = await Promise.all([
3803
- git(cwd, "rev-parse", "--verify", "--quiet", `${base}^{commit}`),
3804
- git(cwd, "merge-base", base, "HEAD"),
3805
- git(cwd, "rev-parse", "--is-shallow-repository")
3806
- ]);
3807
- const fix = shallow.stdout.trim() === "true" ? " The clone is shallow: fetch the history (actions/checkout: `fetch-depth: 0`)." : "";
3808
- if (known.status !== 0) {
3809
- return new BiviumError2("BV_GIT_NO_BASE", `bivium: no commit ${base} here to diff against: fetch it.${fix}`);
3810
- }
3811
- if (forked.status !== 0) {
3812
- 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}`);
4368
+ function orphanOf(graph, config, suite, file) {
4369
+ if (!suite.roots.some((root) => inRoot2(file, root)))
4370
+ return;
4371
+ const wired = (path) => suite.isTest(path) || suite.isPage(path);
4372
+ if (reaches(graph, [file], wired, {
4373
+ includeUnknown: false,
4374
+ types: suite.types || DECLARATION.test(file)
4375
+ })) {
4376
+ return;
3813
4377
  }
3814
- return;
4378
+ const deleted = !graph.has(file);
4379
+ if (deleted && suite.isTest(file))
4380
+ return;
4381
+ if (deleted && config.isImportOnly(file))
4382
+ return;
4383
+ if (suite.isNonInput(file))
4384
+ return;
4385
+ const typed = !suite.types && reaches(graph, [file], suite.isTest, { includeUnknown: false });
4386
+ return { typed };
3815
4387
  }
3816
- function mergeBaseOf(cwd, base) {
3817
- let pending;
3818
- return () => {
3819
- if (pending === undefined) {
3820
- pending = gitOrThrow(cwd, "merge-base", base, "HEAD").then((out) => out.trim());
3821
- pending.catch(() => {
3822
- return;
3823
- });
4388
+ function selectCases(graph, nodes, selected, reached, reachedOtherwise) {
4389
+ const some = {};
4390
+ const totals = new Map;
4391
+ const listed = new Set;
4392
+ for (const test of selected) {
4393
+ const deps = graph.get(test);
4394
+ const patterns = deps?.cases;
4395
+ if (!deps || !patterns)
4396
+ continue;
4397
+ const all = nodes.filter((node) => node !== test && !node.startsWith("pkg:") && !node.includes("#") && patterns.some((re) => re.test(node)));
4398
+ if (all.length === 0)
4399
+ continue;
4400
+ const hits = deps.unknown.length === 0 && !reachedOtherwise(test, new Set(all)) ? all.filter((node) => reached.has(node)) : all;
4401
+ if (hits.length > 0 && hits.length < all.length) {
4402
+ some[test] = hits;
4403
+ totals.set(test, all.length);
3824
4404
  }
3825
- return pending;
3826
- };
4405
+ for (const node of hits.length > 0 ? hits : all)
4406
+ listed.add(node);
4407
+ }
4408
+ return Object.keys(some).length > 0 ? { some, totals, list: sorted(listed) } : { some, totals };
3827
4409
  }
3828
- async function readRevision(cwd, base, roots, {
3829
- blobs = false,
3830
- mergeBase: eager = false
4410
+ function planTests(graph, changed, config, {
4411
+ barrelNames = [],
4412
+ layout = new Set,
4413
+ narrowed = [],
4414
+ packages,
4415
+ settings,
4416
+ edits,
4417
+ seals
3831
4418
  } = {}) {
3832
- const mergeBase = mergeBaseOf(cwd, base);
3833
- if (eager)
3834
- mergeBase();
3835
- const diffArgs = ["--no-renames", "--merge-base", base];
3836
- const [listing, diff, staged] = await Promise.all([
3837
- gitOrThrow(cwd, "ls-files", "-s", "-v", "-o", "--exclude-standard"),
3838
- gitOrThrow(cwd, "diff", "--raw", "--no-abbrev", ...diffArgs),
3839
- gitOrThrow(cwd, "diff", "--cached", "--name-only", ...diffArgs)
3840
- ]).catch(async (error) => {
3841
- throw await missingHistory(cwd, base) ?? error;
3842
- });
3843
- const entries = lines(listing);
3844
- const untracked = [];
3845
- for (const line of entries) {
3846
- if (line.startsWith("? "))
3847
- untracked.push(line.slice(2));
3848
- }
3849
- const before = new Map;
3850
- const diffed = [];
3851
- const layout = new Set(untracked);
3852
- for (const line of lines(diff)) {
3853
- const [, mode, oid, status, path] = RAW_ENTRY.exec(line) ?? [];
3854
- if (mode === undefined || oid === undefined || status === undefined || path === undefined) {
3855
- throw new Error(`git diff: unexpected line ${line}`);
3856
- }
3857
- diffed.push(path);
3858
- if (status === "A" || status === "D")
3859
- layout.add(path);
3860
- if (status === "A")
3861
- before.set(path, undefined);
3862
- else if ("MTD".includes(status) && mode !== "160000") {
3863
- before.set(path, oid);
4419
+ const { relevant, quiet, packageFiles, settingFiles, causes } = classify(graph, changed, config, packages, settings);
4420
+ const settingCauses = new Map;
4421
+ const settingNotes = [];
4422
+ for (const file of settingFiles) {
4423
+ const change = settings?.get(file);
4424
+ if (!change)
4425
+ continue;
4426
+ settingNotes.push(change.note);
4427
+ for (const seed of change.seeds) {
4428
+ if (!settingCauses.has(seed)) {
4429
+ settingCauses.set(seed, `governed by ${file}, which changed`);
4430
+ }
3864
4431
  }
3865
4432
  }
3866
- const reads = new Map;
3867
- const readBase = (path) => {
3868
- let read = reads.get(path);
3869
- if (read === undefined) {
3870
- read = readBaseOnce(path);
3871
- reads.set(path, read);
3872
- }
3873
- return read;
3874
- };
3875
- const readBaseOnce = (path) => {
3876
- if (!before.has(path)) {
3877
- if (present.has(path)) {
3878
- return readFile2(join2(cwd, path), "utf-8").catch(() => mergeBase().then((commit) => show(cwd, `${commit}:${path}`)));
3879
- }
3880
- return mergeBase().then((commit) => show(cwd, `${commit}:${path}`));
4433
+ const bumped = packages && packageFiles.length > 0 ? packageSeeds(graph, config, packages, packageFiles) : { seeds: new Map, notes: [], reasons: [] };
4434
+ const all = config.suites.map((suite) => suite.name);
4435
+ for (const unused of bumped.reasons) {
4436
+ causes.push({ kind: "package", suites: all, ...unused });
4437
+ }
4438
+ const seeds = [
4439
+ ...relevant,
4440
+ ...settingFiles,
4441
+ ...settingCauses.keys(),
4442
+ ...barrelNames,
4443
+ ...packageFiles,
4444
+ ...bumped.seeds.keys()
4445
+ ];
4446
+ const { notes: editNotes, sealed } = sealedSeeds(relevant.filter((file) => !settingCauses.has(file)), edits, seals);
4447
+ const affected = walksByTypes(graph, seeds, {
4448
+ quiet,
4449
+ layout,
4450
+ seals: sealed
4451
+ });
4452
+ const sealedFor = (types) => types ? sealed.types : sealed.runtime;
4453
+ const nodes = [...graph.keys()];
4454
+ const tests = new Map(config.suites.map((suite) => [suite.name, nodes.filter(suite.isTest)]));
4455
+ for (const suite of config.suites) {
4456
+ for (const file of relevant) {
4457
+ const orphan = orphanOf(graph, config, suite, file);
4458
+ if (!orphan)
4459
+ continue;
4460
+ const { typed } = orphan;
4461
+ causes.push({
4462
+ kind: "orphan",
4463
+ suites: [suite.name],
4464
+ file,
4465
+ message: `${file}: no ${suite.name} test imports it${typed ? " (only type imports reach it: list it in the suite's `nonInputs` if nothing loads it at runtime)" : ""}`
4466
+ });
3881
4467
  }
3882
- const oid = before.get(path);
3883
- return oid === undefined ? Promise.resolve(undefined) : show(cwd, oid);
3884
- };
3885
- const changed = [...new Set([...diffed, ...untracked])];
3886
- const dirty = new Set([...changed, ...lines(staged)]);
3887
- const underRoots = (path) => roots.some((root) => inRoot2(path, root));
3888
- const files = new Set;
3889
- const tracked = new Set;
3890
- const present = new Set;
3891
- const oids = new Map;
3892
- for (const line of entries) {
3893
- const entry = INDEX_ENTRY.exec(line);
3894
- if (!entry) {
3895
- if (line.startsWith("? ") && underRoots(line.slice(2))) {
3896
- files.add(line.slice(2));
3897
- }
4468
+ }
4469
+ const narrowings = new Map;
4470
+ for (const { narrower, result } of narrowed) {
4471
+ const matched = relevant.filter(narrower.match);
4472
+ if (matched.length === 0)
4473
+ continue;
4474
+ if ("all" in result) {
4475
+ causes.push({
4476
+ kind: "narrower",
4477
+ suites: narrower.suites,
4478
+ narrower: narrower.name,
4479
+ message: `${narrower.name}: ${result.all}`
4480
+ });
3898
4481
  continue;
3899
4482
  }
3900
- const [, tag, mode, oid, stage, path] = entry;
3901
- if (tag === undefined || mode === undefined || oid === undefined || stage === undefined || path === undefined) {
3902
- throw new Error(`bivium: git: unexpected ls-files line ${line}.`);
4483
+ for (const name of narrower.suites) {
4484
+ const list = narrowings.get(name) ?? [];
4485
+ list.push({ matched, narrower, seeds: result.seeds });
4486
+ narrowings.set(name, list);
3903
4487
  }
3904
- tracked.add(path);
3905
- if (mode === "160000" || !underRoots(path))
3906
- continue;
3907
- files.add(path);
3908
- if (dirty.has(path) || stage !== "0" || tag !== "H")
4488
+ }
4489
+ const full = new Set(causes.flatMap((cause) => cause.suites));
4490
+ const suites = {};
4491
+ const cases = {};
4492
+ const caseTotals = new Map;
4493
+ const caseLists = new Map;
4494
+ let unknown;
4495
+ for (const suite of config.suites) {
4496
+ cases[suite.name] = {};
4497
+ if (full.has(suite.name)) {
4498
+ suites[suite.name] = { mode: "all" };
3909
4499
  continue;
3910
- if (mode !== "100644" && mode !== "100755")
4500
+ }
4501
+ const coarse = affected(suite.types);
4502
+ const narrowing = narrowings.get(suite.name);
4503
+ const reached = narrowing ? narrowedWalk(graph, seeds, { quiet, layout, types: suite.types, sealed: sealedFor(suite.types) }, coarse, narrowing) : coarse;
4504
+ const suiteTests = tests.get(suite.name) ?? [];
4505
+ const selection = select(reached, suiteTests);
4506
+ suites[suite.name] = selection;
4507
+ if (selection.mode === "none")
3911
4508
  continue;
3912
- present.add(path);
3913
- if (blobs)
3914
- oids.set(path, oid);
4509
+ const chosen = selectCases(graph, nodes, selection.mode === "some" ? selection.files : suiteTests, reached, (test, walls) => {
4510
+ unknown ??= nodes.filter((node) => (graph.get(node)?.unknown.length ?? 0) > 0);
4511
+ return reaches(graph, [...seeds, ...seeds.length > 0 ? unknown : []], (node) => node === test, {
4512
+ quiet,
4513
+ layout,
4514
+ types: suite.types,
4515
+ sealed: sealedFor(suite.types),
4516
+ includeUnknown: false,
4517
+ opaque: (node) => walls.has(node)
4518
+ });
4519
+ });
4520
+ cases[suite.name] = chosen.some;
4521
+ for (const [test, total] of chosen.totals)
4522
+ caseTotals.set(test, total);
4523
+ if (chosen.list)
4524
+ caseLists.set(suite.name, chosen.list);
3915
4525
  }
3916
4526
  return {
3917
- files: sorted(files),
3918
- listed: [...tracked, ...untracked],
3919
- changed,
4527
+ suites,
4528
+ reasons: causes.map((cause) => cause.message),
4529
+ causes,
4530
+ totals: Object.fromEntries(config.suites.map((suite) => [
4531
+ suite.name,
4532
+ tests.get(suite.name)?.length ?? 0
4533
+ ])),
4534
+ full: [...full],
4535
+ packages: bumped.notes,
4536
+ settings: settingNotes,
4537
+ settingCauses,
4538
+ seeds,
4539
+ quiet,
3920
4540
  layout,
3921
- mergeBase,
3922
- readBase,
3923
- blobs: oids,
3924
- present
4541
+ packageCauses: bumped.seeds,
4542
+ narrowings,
4543
+ cases,
4544
+ caseTotals,
4545
+ caseLists,
4546
+ edits: editNotes,
4547
+ sealed
3925
4548
  };
3926
4549
  }
3927
- async function show(cwd, object) {
3928
- const result = await git(cwd, "show", object);
3929
- return result.status === 0 ? result.stdout : undefined;
3930
- }
3931
- async function defaultBase(cwd) {
3932
- const head = await git(cwd, "symbolic-ref", "--short", "refs/remotes/origin/HEAD");
3933
- if (head.status === 0 && head.stdout.trim())
3934
- return head.stdout.trim();
3935
- const refs = ["origin/main", "origin/master", "main", "master"];
3936
- const found = await Promise.all(refs.map((ref) => git(cwd, "rev-parse", "--verify", "--quiet", ref)));
3937
- const branch = refs[found.findIndex((result) => result.status === 0)];
3938
- if (branch)
3939
- return branch;
3940
- 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`);
4550
+ function sealedSeeds(files, edits, seals) {
4551
+ const notes = [];
4552
+ const kept = (all) => {
4553
+ const seal = new Map;
4554
+ for (const file of files) {
4555
+ const observers = all?.get(file);
4556
+ if (observers)
4557
+ seal.set(file, observers);
4558
+ }
4559
+ return seal;
4560
+ };
4561
+ const sealed = { runtime: kept(seals?.runtime), types: kept(seals?.types) };
4562
+ for (const file of files) {
4563
+ const edit = edits?.get(file);
4564
+ const shown = edit?.runtime ?? edit?.types;
4565
+ if (!shown)
4566
+ continue;
4567
+ notes.push(shown.kind === "comments" ? `${file}: only comments or line breaks changed` : `${file}: only adds ${shown.names.length === 1 ? "the export" : "the exports"} ${shown.names.join(", ")}`);
4568
+ }
4569
+ return { notes, sealed };
3941
4570
  }
3942
4571
 
3943
4572
  // src/settings.ts
@@ -4175,7 +4804,7 @@ async function settingChanges({
4175
4804
  const what = manifest ? "resolve or run" : "resolve or compile";
4176
4805
  result.set(file, {
4177
4806
  seeds,
4178
- note: `${file}: changes how the ${plural(seeds.length, "file")} it governs ${what}`
4807
+ note: `${file}: changes how the ${plural2(seeds.length, "file")} it governs ${what}`
4179
4808
  });
4180
4809
  }
4181
4810
  return result;
@@ -4361,6 +4990,8 @@ async function computePlan2(root, base, config, {
4361
4990
  }),
4362
4991
  ExtractionCache.open(dir)
4363
4992
  ]);
4993
+ const editable = revision.changed.filter((file) => isEditable(file) && !revision.layout.has(file) && mayNarrow(file, revision.hunks.get(file)));
4994
+ const editPending = Promise.all(editable.map((file) => readIfFile(join3(root, file)))).catch(() => []);
4364
4995
  if (revision.changed.some((file) => config.narrowers.some((narrower) => narrower.match(file)))) {
4365
4996
  revision.mergeBase();
4366
4997
  }
@@ -4408,13 +5039,38 @@ async function computePlan2(root, base, config, {
4408
5039
  return names.map((name) => `${file}#${name}`);
4409
5040
  }));
4410
5041
  const barrelNames = moved.flat();
5042
+ const edits = new Map;
5043
+ const heads = await editPending;
5044
+ for (const [i, file] of editable.entries()) {
5045
+ const after = heads[i];
5046
+ const hunks = revision.hunks.get(file);
5047
+ const before = after === undefined || !hunks ? undefined : baseOf(after, hunks);
5048
+ const extraction = extractions.get(file);
5049
+ if (before === undefined || after === undefined || !extraction)
5050
+ continue;
5051
+ if (extraction.fallback !== undefined)
5052
+ continue;
5053
+ if (extraction.barrel)
5054
+ continue;
5055
+ const edit = scriptEdit(file, before, after);
5056
+ if (edit.runtime || edit.types)
5057
+ edits.set(file, edit);
5058
+ }
5059
+ const seals = edits.size === 0 ? undefined : sealsOf(graph, edits, extractions, () => createResolver({
5060
+ files: new Set(files),
5061
+ config,
5062
+ packages,
5063
+ tsconfigs
5064
+ }));
4411
5065
  const narrowed = await runNarrowers(root, revision, graph, config, suites, packageDiff, settings);
4412
5066
  const planned = planTests(graph, revision.changed, config, {
4413
5067
  barrelNames,
4414
5068
  layout: revision.layout,
4415
5069
  narrowed,
4416
5070
  packages: packageDiff,
4417
- settings
5071
+ settings,
5072
+ edits,
5073
+ ...seals && { seals }
4418
5074
  });
4419
5075
  await saved;
4420
5076
  return {
@@ -4466,6 +5122,7 @@ async function plan2(options = {}) {
4466
5122
  });
4467
5123
  return {
4468
5124
  suites: computed.plan.suites,
5125
+ cases: computed.plan.cases,
4469
5126
  reasons: computed.plan.reasons,
4470
5127
  causes: computed.plan.causes,
4471
5128
  totals: computed.plan.totals,
@@ -4480,4 +5137,4 @@ async function plan2(options = {}) {
4480
5137
  };
4481
5138
  }
4482
5139
 
4483
- export { githubOutputPath, nowMs, environment, agentVariable, version, QUERY, UNDECLARED_READS, RELATIVE, aliasPath, createResolver, SCANNED, formatOf, extract, stringsOf, finish, gotoPage, walksByTypes, importersOf, affectedBy, sorted, PLAIN, createPaint, wantsColor, isDumb, SEPARATOR, branch, NOTE_INDENT, closingLine, failLine, truncateWords, truncatePath, textWidth, MEASURE, fitTerminal, RULE, aligned, headerRow, plural, SILENT, createProgress, formatSelection, orphanOf, readSources2, collectPackages2, extractRevision2, graphView2, computePlan2, prepare2, plan2 };
5140
+ export { QUERY, UNDECLARED_READS, RELATIVE, aliasPath, createResolver, SCANNED, formatOf, extract, stringsOf, finish, gotoPage, walksByTypes, importersOf, affectedBy, sorted, isPackageFile, formatSelection, orphanOf, readSources2, collectPackages2, extractRevision2, graphView2, computePlan2, prepare2, plan2 };