bivium 0.8.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.8.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,1407 +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);
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;
2784
+ }
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;
2790
+ }
2791
+ lines.splice(at, newCount, ...ended(removed, hunk.removedOpen));
2792
+ }
2793
+ return lines.join("");
2490
2794
  }
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
- };
2795
+ var EDITABLE = /\.(?:svelte|[cm]?[jt]sx?)$/;
2796
+ function isEditable(path) {
2797
+ return EDITABLE.test(path);
2512
2798
  }
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 textWidth = (text) => typeof Bun === "undefined" ? [...text.replace(ESCAPE, "")].length : Bun.stringWidth(text);
2572
- var MEASURE = 80;
2573
- var RULE = "\x00rule";
2574
- function aligned(table, rightColumns = [], paintRule = asIs, indent = " ") {
2575
- const blank = (cell) => cell === "" || cell === RULE;
2576
- const used = new Set(table.flatMap((row) => row.flatMap((cell, i) => blank(cell) ? [] : [i])));
2577
- const keep = (row) => row.filter((_, i) => used.has(i));
2578
- const rows = table.map(keep);
2579
- const right = [...used].sort((a, b) => a - b).flatMap((column, i) => rightColumns.includes(column) ? [i] : []);
2580
- const cellWidth = (cell) => cell === RULE ? 0 : textWidth(cell);
2581
- const widths = [];
2582
- for (const row of rows) {
2583
- for (const [i, cell] of row.entries()) {
2584
- if (i === row.length - 1 && !right.includes(i))
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]);
2820
+ }
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;
2585
2858
  continue;
2586
- 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;
2587
2888
  }
2588
2889
  }
2589
- const pad = (cell, i) => " ".repeat(Math.max(0, (widths[i] ?? 0) - cellWidth(cell)));
2590
- const columnsWidth = (from, to) => widths.slice(from, to).reduce((sum, w) => sum + w + 2, 0);
2591
- return rows.map((row) => {
2592
- const first = row.indexOf(RULE);
2593
- if (first !== -1) {
2594
- const last = row.lastIndexOf(RULE);
2595
- const line = "─".repeat(columnsWidth(first, last + 1) - 2);
2596
- return `${indent}${" ".repeat(columnsWidth(0, first))}${paintRule(line)}`;
2597
- }
2598
- return `${indent}${row.map((cell, i) => right.includes(i) ? pad(cell, i) + cell : i === row.length - 1 ? cell : cell + pad(cell, i)).join(" ")}`.trimEnd();
2599
- });
2890
+ return out + source.slice(at);
2600
2891
  }
2601
- var headerRow = (paint, cells) => cells.map((cell) => paint.faint(cell));
2602
- var plural = (count, one, many = `${one}s`) => `${count} ${count === 1 ? one : many}`;
2603
- var SILENT = { step: () => {}, clear: () => {} };
2604
- var BAR_WIDTH = 20;
2605
- var CLEAR_LINE = "\r\x1B[2K";
2606
- function createProgress(write, paint, nowMs) {
2607
- const startMs = nowMs();
2608
- let text = "";
2609
- let doneRatio = 0;
2610
- const render = () => {
2611
- const done = Math.round(Math.min(1, Math.max(0, doneRatio)) * BAR_WIDTH);
2612
- const bar = paint.good("━".repeat(done)) + paint.dim("─".repeat(BAR_WIDTH - done));
2613
- const seconds = Math.floor((nowMs() - startMs) / 1000);
2614
- write(`${CLEAR_LINE}${bar} ${text}${paint.dim(` · ${seconds} s`)}`);
2615
- };
2616
- const timer = setInterval(render, 1000);
2617
- timer.unref();
2618
- return {
2619
- step(next, ratio) {
2620
- text = next;
2621
- doneRatio = ratio;
2622
- render();
2623
- },
2624
- clear() {
2625
- clearInterval(timer);
2626
- 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;
2627
2999
  }
2628
- };
2629
- }
2630
-
2631
- // src/lockfile.ts
2632
- import { posix as posix3 } from "node:path";
2633
-
2634
- // src/yaml.ts
2635
- var COMMENT = /\s+#.*$/;
2636
- var KEY_END = /:(?: |$)/;
2637
- var EMPTY_MAP = /^\{\s*\}(?:\s+#.*)?$/;
2638
- var EMPTY_LIST = /^\[\s*\](?:\s+#.*)?$/;
2639
- var UNSUPPORTED = /^[&*!|>%@`]/;
2640
-
2641
- class YamlError extends Error {
2642
- }
2643
- function fail2(line, message) {
2644
- 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;
2645
3006
  }
2646
- function linesOf(text) {
2647
- const lines = [];
2648
- for (const [i, raw] of text.split(`
2649
- `).entries()) {
2650
- const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
2651
- const content = line.trimStart();
2652
- 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;
2653
3020
  continue;
2654
- const indent = line.length - content.length;
2655
- if (line.slice(0, indent).includes("\t")) {
2656
- fail2({ indent, text: content, number: i + 1 }, "a tab in indentation");
2657
3021
  }
2658
- 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++;
2659
3027
  }
2660
- return lines;
2661
3028
  }
2662
- function quoteEnd(text, start) {
2663
- const quote = text[start];
2664
- for (let i = start + 1;i < text.length; i++) {
2665
- if (quote === "'" && text[i] === "'") {
2666
- if (text[i + 1] === "'")
2667
- i++;
2668
- else
2669
- return i + 1;
2670
- } 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) {
2671
3036
  i++;
2672
- else if (quote === '"' && text[i] === '"')
2673
- 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
+ }
2674
3077
  }
2675
- return -1;
3078
+ return tokens;
2676
3079
  }
2677
- function unquote(quoted) {
2678
- if (quoted.startsWith("'"))
2679
- return quoted.slice(1, -1).replaceAll("''", "'");
2680
- const value = JSON.parse(quoted);
2681
- if (typeof value !== "string")
2682
- throw new YamlError("bad quoted scalar");
2683
- 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;
2684
3232
  }
2685
- function flowEnd(text, line) {
2686
- let depth = 0;
2687
- for (let i = 0;i < text.length; i++) {
2688
- const c = text[i];
2689
- if (c === "'" || c === '"') {
2690
- const end = quoteEnd(text, i);
2691
- if (end === -1)
2692
- fail2(line, "an unterminated string");
2693
- i = end - 1;
2694
- } else if (c === "{" || c === "[")
2695
- depth++;
2696
- else if (c === "}" || c === "]") {
2697
- if (--depth === 0)
2698
- 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;
2699
3245
  }
3246
+ return text.charAt(i);
2700
3247
  }
2701
- return fail2(line, "a flow collection over several lines");
2702
3248
  }
2703
- function scalar(text, line) {
2704
- if (text.startsWith("'") || text.startsWith('"')) {
2705
- const end = quoteEnd(text, 0);
2706
- if (end === -1)
2707
- fail2(line, "an unterminated string");
2708
- if (text.slice(end).replace(COMMENT, "").trim() !== "") {
2709
- 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;
2710
3260
  }
2711
- return unquote(text.slice(0, end));
3261
+ break;
2712
3262
  }
2713
- if (text.startsWith("{") || text.startsWith("[")) {
2714
- const end = flowEnd(text, line);
2715
- if (text.slice(end).replace(COMMENT, "").trim() !== "") {
2716
- 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;
2717
3272
  }
2718
- return text.slice(0, end);
2719
3273
  }
2720
- if (UNSUPPORTED.test(text))
2721
- fail2(line, `unsupported syntax "${text[0]}"`);
2722
- return text.replace(COMMENT, "");
3274
+ return false;
2723
3275
  }
2724
- function keyOf(text, line) {
2725
- if (text.startsWith("'") || text.startsWith('"')) {
2726
- const end = quoteEnd(text, 0);
2727
- if (end === -1)
2728
- fail2(line, "an unterminated key");
2729
- if (text[end] !== ":")
2730
- return;
2731
- 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;
2732
3302
  }
2733
- const colon = text.search(KEY_END);
2734
- if (colon === -1)
3303
+ const end = lastCode(above, aboveSpans);
3304
+ if (end !== "" && end !== ";" && end !== "}")
2735
3305
  return;
2736
- 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;
2737
3314
  }
2738
- function parseYaml(text) {
2739
- const lines = linesOf(text);
2740
- let at = 0;
2741
- function block(indent) {
2742
- const first = lines[at];
2743
- if (!first || first.indent !== indent)
2744
- return "";
2745
- 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 {};
2746
3319
  }
2747
- function value(rest, indent, line) {
2748
- const text = rest.trim();
2749
- if (EMPTY_MAP.test(text))
2750
- return {};
2751
- if (EMPTY_LIST.test(text))
2752
- return [];
2753
- if (text !== "" && !text.startsWith("#"))
2754
- return scalar(text, line);
2755
- const next = lines[at];
2756
- 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 {};
2757
3327
  }
2758
- function mapping(indent, into) {
2759
- for (let line = lines[at];line; line = lines[at]) {
2760
- if (line.indent < indent)
2761
- break;
2762
- if (line.indent > indent)
2763
- fail2(line, "unexpected indentation");
2764
- const entry = keyOf(line.text, line);
2765
- if (!entry)
2766
- fail2(line, "a line that isn't a key");
2767
- if (Object.hasOwn(into, entry.key))
2768
- fail2(line, "a duplicate key");
2769
- at++;
2770
- 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;
2771
3354
  }
2772
- 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);
2773
3360
  }
2774
- function sequence(indent) {
2775
- const items = [];
2776
- for (let line = lines[at];line; line = lines[at]) {
2777
- if (line.indent < indent)
2778
- break;
2779
- if (line.indent > indent)
2780
- fail2(line, "unexpected indentation");
2781
- if (line.text !== "-" && !line.text.startsWith("- "))
2782
- break;
2783
- at++;
2784
- const text = line.text.slice(1).trimStart();
2785
- const inner = { ...line, indent: line.indent + 2, text };
2786
- if (text !== "" && keyOf(text, line)) {
2787
- lines.splice(at, 0, inner);
2788
- items.push(mapping(inner.indent, {}));
2789
- } else {
2790
- items.push(value(text, indent, line));
2791
- }
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));
2792
3378
  }
2793
- return items;
2794
3379
  }
2795
- const document = block(0);
2796
- const left = lines[at];
2797
- if (left)
2798
- fail2(left, "unexpected indentation");
2799
- return document;
3380
+ return { runtime, types: typed };
2800
3381
  }
2801
3382
 
2802
- // src/lockfile.ts
2803
- var DEP_FIELDS2 = [
2804
- "dependencies",
2805
- "devDependencies",
2806
- "peerDependencies",
2807
- "optionalDependencies"
2808
- ];
2809
- function isRecord2(value) {
2810
- 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;
2811
3393
  }
2812
- function isStringRecord2(value) {
2813
- return isRecord2(value) && Object.values(value).every((item) => typeof item === "string");
3394
+ function sorted(values) {
3395
+ return [...values].sort(byCodeUnit);
2814
3396
  }
2815
- var STRING_OR_TRAILING_COMMA = /"(?:[^"\\]|\\.)*"|,(\s*[}\]])/g;
2816
- function parseLenient(text) {
2817
- 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
+ });
2818
3415
  }
2819
- function specsOf(value) {
2820
- const specs = new Map;
2821
- for (const field of DEP_FIELDS2) {
2822
- const deps = value[field];
2823
- if (deps === undefined)
2824
- continue;
2825
- if (!isStringRecord2(deps))
2826
- return;
2827
- 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}` : ""}`);
2828
3422
  }
2829
- return specs;
3423
+ return result.stdout;
2830
3424
  }
2831
- function restOf(value, skip) {
2832
- return JSON.stringify(Object.entries(value).filter(([key]) => !skip.includes(key)));
3425
+ function lines(output) {
3426
+ return output.split(`
3427
+ `).filter(Boolean);
2833
3428
  }
2834
- function install(packages, name, entry, version, info) {
2835
- const installed = packages.get(name) ?? {
2836
- entries: [],
2837
- versions: [],
2838
- dependencies: new Set,
2839
- bin: false
2840
- };
2841
- if (info?.bin !== undefined || info?.hasBin === true || info?.hasBin === "true") {
2842
- installed.bin = true;
2843
- }
2844
- installed.entries.push(JSON.stringify(entry));
2845
- if (!installed.versions.includes(version))
2846
- installed.versions.push(version);
2847
- for (const field of [
2848
- "dependencies",
2849
- "optionalDependencies",
2850
- "peerDependencies"
2851
- ]) {
2852
- const deps = info?.[field];
2853
- if (isRecord2(deps)) {
2854
- for (const dep of Object.keys(deps))
2855
- 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;
2856
3492
  }
2857
3493
  }
2858
- packages.set(name, installed);
2859
- }
2860
- function installedName(key) {
2861
- const [name = key, scope] = key.split("/").reverse();
2862
- return scope?.startsWith("@") ? `${scope}/${name}` : name;
3494
+ return { raw, hunks };
2863
3495
  }
2864
- function parseBunLock(text) {
2865
- const value = parseLenient(text);
2866
- if (!isRecord2(value))
2867
- return;
2868
- const { packages, workspaces } = value;
2869
- if (!isRecord2(packages) || !isRecord2(workspaces))
2870
- return;
2871
- const lockfile = {
2872
- packages: new Map,
2873
- workspaces: new Map,
2874
- rest: restOf(value, ["packages", "workspaces"])
2875
- };
2876
- for (const [key, entry] of Object.entries(packages)) {
2877
- if (!Array.isArray(entry) || typeof entry[0] !== "string")
2878
- return;
2879
- const ident = entry[0];
2880
- const at = ident.indexOf("@", 1);
2881
- const version = at === -1 ? "" : ident.slice(at + 1);
2882
- 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}`);
2883
3505
  }
2884
- for (const [dir, workspace] of Object.entries(workspaces)) {
2885
- const specs = isRecord2(workspace) ? specsOf(workspace) : undefined;
2886
- if (!specs)
2887
- return;
2888
- 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}`);
2889
3508
  }
2890
- return lockfile;
3509
+ return;
2891
3510
  }
2892
- var NODE_MODULES = "node_modules/";
2893
- function parsePackageLock(text) {
2894
- const value = JSON.parse(text);
2895
- if (!isRecord2(value) || !isRecord2(value.packages))
2896
- return;
2897
- const { lockfileVersion } = value;
2898
- if (lockfileVersion !== 2 && lockfileVersion !== 3)
2899
- return;
2900
- const lockfile = {
2901
- packages: new Map,
2902
- workspaces: new Map,
2903
- rest: restOf(value, ["packages", "dependencies", "name", "version"])
2904
- };
2905
- for (const [key, entry] of Object.entries(value.packages)) {
2906
- if (!isRecord2(entry))
2907
- return;
2908
- const at = key.lastIndexOf(NODE_MODULES);
2909
- if (at !== -1 && (at === 0 || key[at - 1] === "/")) {
2910
- const version = typeof entry.version === "string" ? entry.version : "";
2911
- const name = key.slice(at + NODE_MODULES.length);
2912
- install(lockfile.packages, name, entry, version, entry);
2913
- 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
+ });
2914
3519
  }
2915
- const specs = specsOf(entry);
2916
- if (!specs)
2917
- return;
2918
- lockfile.workspaces.set(key === "" ? "." : key, specs);
2919
- }
2920
- return lockfile;
2921
- }
2922
- function pnpmKey(key) {
2923
- const bare = key.startsWith("/") ? key.slice(1) : key;
2924
- const at = bare.indexOf("@", 1);
2925
- if (at === -1)
2926
- return;
2927
- return { name: bare.slice(0, at), version: withoutPeers(bare.slice(at + 1)) };
2928
- }
2929
- function withoutPeers(version) {
2930
- const paren = version.indexOf("(");
2931
- return paren === -1 ? version : version.slice(0, paren);
3520
+ return pending;
3521
+ };
2932
3522
  }
2933
- var YAML_DOCUMENT = /^---[ \t]*$/m;
2934
- var PNPM_VERSION = /^[69]\./;
2935
- var PNPM_DEP_FIELDS = [
2936
- "dependencies",
2937
- "devDependencies",
2938
- "optionalDependencies"
2939
- ];
2940
- function parsePnpmLock(text) {
2941
- const docs = text.split(YAML_DOCUMENT).filter((doc) => doc.trim() !== "").map(parseYaml);
2942
- const main = docs.findLast((doc) => isRecord2(doc) && typeof doc.lockfileVersion === "string");
2943
- if (!isRecord2(main))
2944
- return;
2945
- const { lockfileVersion, packages = {}, snapshots = {} } = main;
2946
- if (typeof lockfileVersion !== "string")
2947
- return;
2948
- if (!PNPM_VERSION.test(lockfileVersion))
2949
- return;
2950
- if (!isRecord2(packages) || !isRecord2(snapshots))
2951
- return;
2952
- const workspaces = isRecord2(main.importers);
2953
- const importers = isRecord2(main.importers) ? main.importers : { ".": main };
2954
- const lockfile = {
2955
- packages: new Map,
2956
- workspaces: new Map,
2957
- rest: JSON.stringify([
2958
- restOf(main, ["importers", "packages", "snapshots", ...PNPM_DEP_FIELDS]),
2959
- ...docs.filter((doc) => doc !== main)
2960
- ])
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;
2961
3570
  };
2962
- const restOfImporters = [];
2963
- for (const [dir, importer] of Object.entries(importers)) {
2964
- if (!isRecord2(importer))
2965
- return;
2966
- const specs = new Map;
2967
- for (const field of PNPM_DEP_FIELDS) {
2968
- const deps = importer[field];
2969
- if (deps === undefined)
2970
- continue;
2971
- if (!isRecord2(deps))
2972
- return;
2973
- const declared = new Map;
2974
- for (const [name, dep] of Object.entries(deps)) {
2975
- if (!isRecord2(dep) || typeof dep.specifier !== "string") {
2976
- return;
2977
- }
2978
- declared.set(name, dep.specifier);
2979
- const version = typeof dep.version === "string" ? dep.version : "";
2980
- 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}`)));
2981
3575
  }
2982
- specs.set(field, declared);
3576
+ return mergeBase().then((commit) => show(cwd, `${commit}:${path}`));
2983
3577
  }
2984
- lockfile.workspaces.set(dir, specs);
2985
- if (workspaces) {
2986
- const settings = restOf(importer, PNPM_DEP_FIELDS);
2987
- if (settings !== "[]")
2988
- 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;
2989
3595
  }
2990
- }
2991
- lockfile.rest += JSON.stringify(restOfImporters);
2992
- for (const section of [packages, snapshots]) {
2993
- for (const [key, entry] of Object.entries(section)) {
2994
- const parsed = pnpmKey(key);
2995
- if (!parsed)
2996
- return;
2997
- const info = isRecord2(entry) ? entry : undefined;
2998
- 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}.`);
2999
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);
3000
3611
  }
3001
- 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
+ };
3002
3623
  }
3003
- var FORMATS = new Map([
3004
- ["bun.lock", parseBunLock],
3005
- ["package-lock.json", parsePackageLock],
3006
- ["pnpm-lock.yaml", parsePnpmLock]
3007
- ]);
3008
- var UNREAD = ["bun.lockb", "npm-shrinkwrap.json", "yarn.lock"];
3009
- function parse(file, text) {
3010
- const format = FORMATS.get(file);
3011
- if (text === undefined || !format)
3012
- return;
3013
- try {
3014
- return format(text);
3015
- } catch {
3016
- return;
3017
- }
3624
+ async function show(cwd, object) {
3625
+ const result = await git(cwd, "show", object);
3626
+ return result.status === 0 ? result.stdout : undefined;
3018
3627
  }
3019
- function describe(name, before, after) {
3020
- if (before === undefined)
3021
- return `${name} ${after} added`;
3022
- if (after === undefined)
3023
- return `${name} ${before} removed`;
3024
- 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`);
3025
3638
  }
3026
- function versions(installed) {
3027
- 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 {
3028
3651
  }
3029
- function specChanges(before, after) {
3030
- const changed = new Map;
3031
- for (const field of DEP_FIELDS2) {
3032
- const a = before?.get(field);
3033
- const b = after?.get(field);
3034
- for (const name of new Set([...a?.keys() ?? [], ...b?.keys() ?? []])) {
3035
- if (a?.get(name) !== b?.get(name) && !changed.has(name)) {
3036
- changed.set(name, [a?.get(name), b?.get(name)]);
3037
- }
3038
- }
3039
- }
3040
- return changed;
3652
+ function fail2(line, message) {
3653
+ throw new YamlError(`${message} at line ${line?.number ?? "end"}`);
3041
3654
  }
3042
- function lockfileChanges(file, base, head) {
3043
- const changes = [];
3044
- const names = new Set([...base.packages.keys(), ...head.packages.keys()]);
3045
- for (const name of names) {
3046
- const before = base.packages.get(name);
3047
- const after = head.packages.get(name);
3048
- const same = before !== undefined && after !== undefined && sorted(before.entries).join(`
3049
- `) === sorted(after.entries).join(`
3050
- `);
3051
- 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("#"))
3052
3662
  continue;
3053
- changes.push({
3054
- name,
3055
- detail: `${file}: ${describe(name, versions(before), versions(after))}`,
3056
- file
3057
- });
3058
- }
3059
- const resolved = new Set(changes.map((change) => change.name));
3060
- const dirs = new Set([...base.workspaces.keys(), ...head.workspaces.keys()]);
3061
- for (const dir of dirs) {
3062
- const declared = specChanges(base.workspaces.get(dir), head.workspaces.get(dir));
3063
- for (const [name, [before, after]] of declared) {
3064
- if (resolved.has(name))
3065
- continue;
3066
- resolved.add(name);
3067
- changes.push({
3068
- name,
3069
- detail: `${file}: ${describe(`${name} range`, before, after)}`,
3070
- file
3071
- });
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");
3072
3666
  }
3667
+ lines.push({ indent, text: content.trimEnd(), number: i + 1 });
3073
3668
  }
3074
- return changes;
3075
- }
3076
- var MANIFEST = /(?:^|\/)package\.json$/;
3077
- function parseManifest(text) {
3078
- if (text === undefined)
3079
- return;
3080
- try {
3081
- const value = JSON.parse(text);
3082
- return isRecord2(value) ? value : undefined;
3083
- } catch {
3084
- return;
3085
- }
3669
+ return lines;
3086
3670
  }
3087
- async function readPackageDiff(changed, listed, base, head) {
3088
- const lockfiles = changed.filter((file) => FORMATS.has(file));
3089
- const manifests = changed.filter((file) => MANIFEST.test(file));
3090
- if (lockfiles.length === 0 && manifests.length === 0)
3091
- return;
3092
- const read = (path) => Promise.all([base(path), head(path)]);
3093
- const known = [...FORMATS.keys()];
3094
- const [lockTexts, manifestTexts] = await Promise.all([
3095
- Promise.all(known.map(async (file) => {
3096
- if (lockfiles.includes(file))
3097
- return [file, ...await read(file)];
3098
- const text = await head(file);
3099
- return [file, text, text];
3100
- })),
3101
- Promise.all(manifests.map(async (file) => [file, ...await read(file)]))
3102
- ]);
3103
- const diff = {
3104
- files: new Map,
3105
- changes: [],
3106
- dependents: new Map,
3107
- declared: new Set,
3108
- bins: new Set
3109
- };
3110
- const present = new Map;
3111
- for (const [file, baseText, headText] of lockTexts) {
3112
- const after = parse(file, headText);
3113
- if (headText !== undefined)
3114
- present.set(file, after);
3115
- const before = parse(file, baseText);
3116
- for (const lockfile of [before, after]) {
3117
- if (!lockfile)
3118
- continue;
3119
- for (const [name, installed] of lockfile.packages) {
3120
- if (installed.bin)
3121
- diff.bins.add(name);
3122
- for (const dependency of installed.dependencies) {
3123
- const set = diff.dependents.get(dependency) ?? new Set;
3124
- set.add(name);
3125
- diff.dependents.set(dependency, set);
3126
- }
3127
- }
3128
- for (const specs of lockfile.workspaces.values()) {
3129
- for (const deps of specs.values()) {
3130
- for (const name of deps.keys())
3131
- diff.declared.add(name);
3132
- }
3133
- }
3134
- }
3135
- if (!lockfiles.includes(file))
3136
- continue;
3137
- if (baseText === undefined || headText === undefined) {
3138
- diff.files.set(file, baseText === undefined ? "added" : "deleted");
3139
- } else if (!(before && after)) {
3140
- diff.files.set(file, "can't parse it");
3141
- } else if (before.rest === after.rest) {
3142
- diff.files.set(file, undefined);
3143
- diff.changes.push(...lockfileChanges(file, before, after));
3144
- } else {
3145
- 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;
3146
3708
  }
3147
3709
  }
3148
- const unread = UNREAD.some((file) => listed.includes(file));
3149
- for (const [file, beforeText, afterText] of manifestTexts) {
3150
- const before = parseManifest(beforeText);
3151
- const after = parseManifest(afterText);
3152
- if (!(before && after) || unread || present.size === 0)
3153
- continue;
3154
- const others = (record) => restOf(record, DEP_FIELDS2);
3155
- const specsBefore = specsOf(before);
3156
- const specsAfter = specsOf(after);
3157
- if (others(before) !== others(after) || !specsBefore || !specsAfter) {
3158
- 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");
3159
3719
  }
3160
- const dir = posix3.dirname(file);
3161
- const declared = specChanges(specsBefore, specsAfter);
3162
- const recorded = [...present.values()].every((lockfile) => {
3163
- const specs = lockfile?.workspaces.get(dir);
3164
- if (!specs)
3165
- return false;
3166
- return [...declared.keys()].every((name) => DEP_FIELDS2.every((field) => specs.get(field)?.get(name) === specsAfter.get(field)?.get(name)));
3167
- });
3168
- if (!recorded)
3169
- continue;
3170
- diff.files.set(file, undefined);
3171
- for (const [name, [from, to]] of declared) {
3172
- diff.declared.add(name);
3173
- diff.changes.push({
3174
- name,
3175
- detail: `${file}: ${describe(`${name} range`, from, to)}`,
3176
- file
3177
- });
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");
3178
3726
  }
3727
+ return text.slice(0, end);
3179
3728
  }
3180
- return diff;
3729
+ if (UNSUPPORTED.test(text))
3730
+ fail2(line, `unsupported syntax "${text[0]}"`);
3731
+ return text.replace(COMMENT, "");
3181
3732
  }
3182
- function packageSeeds(graph, config, diff, files) {
3183
- const result = { seeds: new Map, notes: [], reasons: [] };
3184
- const { isLoadedByName } = config;
3185
- const loadedOtherwise = (name) => isLoadedByName === undefined || diff.bins.has(name) || isLoadedByName(name);
3186
- const tested = new Map;
3187
- const reachesTest = (name) => {
3188
- let found = tested.get(name);
3189
- if (found === undefined) {
3190
- const node = `pkg:${name}`;
3191
- found = graph.has(node) && config.suites.some((suite) => reaches(graph, [node], suite.isTest, {
3192
- includeUnknown: false,
3193
- types: suite.types
3194
- }));
3195
- tested.set(name, found);
3196
- }
3197
- return found;
3198
- };
3199
- const changes = diff.changes.filter((change) => files.includes(change.file)).sort((a, b) => byCodeUnit(a.name, b.name));
3200
- const unused = new Map;
3201
- const seen = new Set;
3202
- for (const change of changes) {
3203
- const { name, detail } = change;
3204
- if (seen.has(name))
3205
- continue;
3206
- seen.add(name);
3207
- const closure = new Set([name]);
3208
- const queue = [name];
3209
- for (const queued of queue) {
3210
- for (const dependent of diff.dependents.get(queued) ?? []) {
3211
- if (closure.has(dependent))
3212
- continue;
3213
- closure.add(dependent);
3214
- queue.push(dependent);
3215
- }
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);
3216
3780
  }
3217
- const through = [];
3218
- let covered = true;
3219
- let importOnly = false;
3220
- for (const user of closure) {
3221
- const node = `pkg:${user}`;
3222
- const imported = graph.has(node);
3223
- if (imported) {
3224
- through.push(user);
3225
- if (!result.seeds.has(node)) {
3226
- result.seeds.set(node, user === name ? detail : `${detail}, which ${user} depends on`);
3227
- }
3228
- }
3229
- const entry = imported || diff.declared.has(user) || !diff.dependents.has(user);
3230
- if (!entry || reachesTest(user) || config.isInert(user))
3231
- continue;
3232
- if (loadedOtherwise(user)) {
3233
- covered = false;
3234
- const list = unused.get(user) ?? [];
3235
- if (user === name)
3236
- list.unshift(change);
3237
- else
3238
- list.push(change);
3239
- 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, {}));
3240
3798
  } else {
3241
- importOnly = true;
3799
+ items.push(value(text, indent, line));
3242
3800
  }
3243
3801
  }
3244
- if (!covered)
3245
- continue;
3246
- if (through.length === 0) {
3247
- result.notes.push(`${detail}, ${importOnly ? "imported by no test" : "inert"}`);
3248
- continue;
3249
- }
3250
- const others = through.filter((user) => user !== name);
3251
- const shown = others.slice(0, 3).join(", ");
3252
- const rest = others.length > 3 ? ` and ${others.length - 3} more` : "";
3253
- result.notes.push(others.length === 0 ? detail : `${detail}, through ${shown}${rest}`);
3254
- }
3255
- for (const user of sorted(unused.keys())) {
3256
- const [first, ...more] = unused.get(user) ?? [];
3257
- if (!first)
3258
- continue;
3259
- const own = first.name === user;
3260
- const also = more.length === 0 ? "" : ` (and ${more.length} more ${more.length === 1 ? "package" : "packages"} ${user} depends on)`;
3261
- result.reasons.push({
3262
- package: user,
3263
- file: first.file,
3264
- message: own ? `${first.detail}${also}, and no test imports it` : `${first.detail}, which ${user} depends on${also}, and no test imports ${user}`
3265
- });
3802
+ return items;
3266
3803
  }
3267
- return result;
3804
+ const document = block(0);
3805
+ const left = lines[at];
3806
+ if (left)
3807
+ fail2(left, "unexpected indentation");
3808
+ return document;
3268
3809
  }
3269
3810
 
3270
- // src/plan.ts
3271
- function formatSelection(selection) {
3272
- 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);
3273
3820
  }
3274
- function select(affected, tests) {
3275
- const files = tests.filter((file) => affected.has(file));
3276
- if (files.length === 0)
3277
- return { mode: "none" };
3278
- if (files.length === tests.length)
3279
- return { mode: "all" };
3280
- return { mode: "some", files };
3821
+ function isStringRecord2(value) {
3822
+ return isRecord2(value) && Object.values(value).every((item) => typeof item === "string");
3281
3823
  }
3282
- function classify(graph, changed, config, packages, settings) {
3283
- const causes = [];
3284
- const all = config.suites.map((suite) => suite.name);
3285
- const runAll = (cause) => causes.push({ ...cause, suites: all });
3286
- const relevant = [];
3287
- const quiet = [];
3288
- const packageFiles = [];
3289
- const settingFiles = [];
3290
- for (const file of changed) {
3291
- const read = graph.has(file);
3292
- const ignored = config.isIgnored(file);
3293
- if (!read && ignored)
3294
- continue;
3295
- const wired = config.suites.filter((suite) => suite.isWiring(file));
3296
- const diffed = packages?.files.has(file) ?? false;
3297
- if (config.isSelf(file)) {
3298
- runAll({
3299
- kind: "self",
3300
- file,
3301
- message: `${file}: test selector changed`
3302
- });
3303
- continue;
3304
- }
3305
- for (const suite of wired) {
3306
- causes.push({
3307
- kind: "wiring",
3308
- suites: [suite.name],
3309
- file,
3310
- message: `${file}: wires the ${suite.name} suite`
3311
- });
3312
- }
3313
- 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)
3314
3833
  continue;
3315
- if (diffed) {
3316
- const reason = packages?.files.get(file);
3317
- if (reason === undefined) {
3318
- packageFiles.push(file);
3319
- } else {
3320
- runAll({ kind: "lockfile", file, message: `${file}: ${reason}` });
3321
- }
3322
- } else if (read || config.roots.some((root) => inRoot2(file, root))) {
3323
- if (ignored)
3324
- quiet.push(file);
3325
- else
3326
- ((settings?.has(file)) ? settingFiles : relevant).push(file);
3327
- } else {
3328
- runAll({
3329
- kind: "outside",
3330
- file,
3331
- message: `${file}: outside the dependency graph`
3332
- });
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);
3333
3865
  }
3334
3866
  }
3335
- return { relevant, quiet, packageFiles, settingFiles, causes };
3336
- }
3337
- function narrowedWalk(graph, seeds, {
3338
- quiet,
3339
- layout,
3340
- types
3341
- }, coarse, narrowings) {
3342
- const matched = new Set(narrowings.flatMap((narrowing) => narrowing.matched));
3343
- const fine = affectedBy(graph, seeds.filter((seed) => !matched.has(seed)), { quiet, layout, types });
3344
- for (const narrowing of narrowings) {
3345
- const walk = affectedBy(graph, [...narrowing.matched, ...narrowing.seeds], {
3346
- opaque: narrowing.narrower.opaque,
3347
- layout,
3348
- types
3349
- });
3350
- for (const node of walk)
3351
- 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);
3352
3898
  }
3353
- return new Set([...fine].filter((node) => coarse.has(node)));
3899
+ return lockfile;
3354
3900
  }
3355
- function orphanOf(graph, config, suite, file) {
3356
- 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))
3357
3905
  return;
3358
- const wired = (path) => suite.isTest(path) || suite.isPage(path);
3359
- if (reaches(graph, [file], wired, {
3360
- includeUnknown: false,
3361
- types: suite.types || DECLARATION.test(file)
3362
- })) {
3906
+ const { lockfileVersion } = value;
3907
+ if (lockfileVersion !== 2 && lockfileVersion !== 3)
3363
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);
3364
3928
  }
3365
- const deleted = !graph.has(file);
3366
- 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)
3367
3935
  return;
3368
- 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))
3369
3953
  return;
3370
- if (suite.isNonInput(file))
3954
+ const { lockfileVersion, packages = {}, snapshots = {} } = main;
3955
+ if (typeof lockfileVersion !== "string")
3371
3956
  return;
3372
- const typed = !suite.types && reaches(graph, [file], suite.isTest, { includeUnknown: false });
3373
- return { typed };
3374
- }
3375
- function planTests(graph, changed, config, {
3376
- barrelNames = [],
3377
- layout = new Set,
3378
- narrowed = [],
3379
- packages,
3380
- settings
3381
- } = {}) {
3382
- const { relevant, quiet, packageFiles, settingFiles, causes } = classify(graph, changed, config, packages, settings);
3383
- const settingCauses = new Map;
3384
- const settingNotes = [];
3385
- for (const file of settingFiles) {
3386
- const change = settings?.get(file);
3387
- if (!change)
3388
- continue;
3389
- settingNotes.push(change.note);
3390
- for (const seed of change.seeds) {
3391
- if (!settingCauses.has(seed)) {
3392
- 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), {});
3393
3990
  }
3991
+ specs.set(field, declared);
3394
3992
  }
3395
- }
3396
- const bumped = packages && packageFiles.length > 0 ? packageSeeds(graph, config, packages, packageFiles) : { seeds: new Map, notes: [], reasons: [] };
3397
- const all = config.suites.map((suite) => suite.name);
3398
- for (const unused of bumped.reasons) {
3399
- causes.push({ kind: "package", suites: all, ...unused });
3400
- }
3401
- const seeds = [
3402
- ...relevant,
3403
- ...settingFiles,
3404
- ...settingCauses.keys(),
3405
- ...barrelNames,
3406
- ...packageFiles,
3407
- ...bumped.seeds.keys()
3408
- ];
3409
- const affected = walksByTypes(graph, seeds, { quiet, layout });
3410
- const nodes = [...graph.keys()];
3411
- const tests = new Map(config.suites.map((suite) => [suite.name, nodes.filter(suite.isTest)]));
3412
- for (const suite of config.suites) {
3413
- for (const file of relevant) {
3414
- const orphan = orphanOf(graph, config, suite, file);
3415
- if (!orphan)
3416
- continue;
3417
- const { typed } = orphan;
3418
- causes.push({
3419
- kind: "orphan",
3420
- suites: [suite.name],
3421
- file,
3422
- 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)" : ""}`
3423
- });
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]);
3424
3998
  }
3425
3999
  }
3426
- const narrowings = new Map;
3427
- for (const { narrower, result } of narrowed) {
3428
- const matched = relevant.filter(narrower.match);
3429
- if (matched.length === 0)
3430
- continue;
3431
- if ("all" in result) {
3432
- causes.push({
3433
- kind: "narrower",
3434
- suites: narrower.suites,
3435
- narrower: narrower.name,
3436
- message: `${narrower.name}: ${result.all}`
3437
- });
3438
- 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);
3439
4008
  }
3440
- for (const name of narrower.suites) {
3441
- const list = narrowings.get(name) ?? [];
3442
- list.push({ matched, narrower, seeds: result.seeds });
3443
- 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
+ }
3444
4047
  }
3445
4048
  }
3446
- const full = new Set(causes.flatMap((cause) => cause.suites));
3447
- const suites = {};
3448
- for (const suite of config.suites) {
3449
- if (full.has(suite.name)) {
3450
- 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)
3451
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
+ });
3452
4081
  }
3453
- const coarse = affected(suite.types);
3454
- const narrowing = narrowings.get(suite.name);
3455
- suites[suite.name] = select(narrowing ? narrowedWalk(graph, seeds, { quiet, layout, types: suite.types }, coarse, narrowing) : coarse, tests.get(suite.name) ?? []);
3456
4082
  }
3457
- return {
3458
- suites,
3459
- reasons: causes.map((cause) => cause.message),
3460
- causes,
3461
- totals: Object.fromEntries(config.suites.map((suite) => [
3462
- suite.name,
3463
- tests.get(suite.name)?.length ?? 0
3464
- ])),
3465
- full: [...full],
3466
- packages: bumped.notes,
3467
- settings: settingNotes,
3468
- settingCauses,
3469
- seeds,
3470
- quiet,
3471
- layout,
3472
- packageCauses: bumped.seeds,
3473
- narrowings
3474
- };
3475
- }
3476
-
3477
- // src/compute.ts
3478
- import { readFile as readFile3, stat } from "node:fs/promises";
3479
- import { join as join3, posix as posix6, resolve } from "node:path";
3480
-
3481
- // src/cache.ts
3482
- import { existsSync } from "node:fs";
3483
- import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3484
- import { isAbsolute, join } from "node:path";
3485
- var SCANNER_VERSION = 9;
3486
- var MAGIC = "bivium-extractions";
3487
- var FILE = "extractions.json";
3488
- function isHeader(value) {
3489
- 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;
3490
4084
  }
3491
- function cacheDir(root, cache) {
3492
- 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 {
3493
4093
  return;
3494
- if (typeof cache === "string") {
3495
- return isAbsolute(cache) ? cache : join(root, cache);
3496
4094
  }
3497
- const modules = join(root, "node_modules");
3498
- return existsSync(modules) ? join(modules, ".cache", "bivium") : join(root, ".bivium", "cache");
3499
4095
  }
3500
-
3501
- class ExtractionCache {
3502
- #rows = new Map;
3503
- #strings = [];
3504
- #used = new Map;
3505
- #dirty = false;
3506
- dir;
3507
- constructor(dir) {
3508
- this.dir = dir;
3509
- }
3510
- static async open(dir) {
3511
- const cache = new ExtractionCache(dir);
3512
- if (!dir)
3513
- return cache;
3514
- const text = await readFile(join(dir, FILE), "utf-8").catch(() => "");
3515
- if (text)
3516
- cache.#load(text);
3517
- return cache;
3518
- }
3519
- #load(text) {
3520
- try {
3521
- const parsed = JSON.parse(text);
3522
- if (!Array.isArray(parsed))
3523
- return;
3524
- const fields = parsed;
3525
- const [header, strings, rows] = fields;
3526
- if (!isHeader(header) || !Array.isArray(strings) || !Array.isArray(rows) || header.strings !== strings.length || header.rows !== rows.length) {
3527
- 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
+ }
3528
4139
  }
3529
- this.#strings = strings;
3530
- for (const row of rows) {
3531
- if (Array.isArray(row) && typeof row[0] === "string") {
3532
- 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);
3533
4144
  }
3534
4145
  }
3535
- } catch {}
3536
- }
3537
- get size() {
3538
- return this.#rows.size;
3539
- }
3540
- get(oid, format) {
3541
- const key = `${format}:${oid}`;
3542
- const used = this.#used.get(key);
3543
- if (used)
3544
- return used;
3545
- const row = this.#rows.get(key);
3546
- if (!row)
3547
- return;
3548
- let extraction;
3549
- try {
3550
- extraction = decode(row, this.#strings);
3551
- } catch {
3552
- this.#rows.delete(key);
3553
- return;
3554
4146
  }
3555
- this.#used.set(key, extraction);
3556
- return extraction;
3557
- }
3558
- set(oid, format, extraction) {
3559
- const key = `${format}:${oid}`;
3560
- this.#used.set(key, extraction);
3561
- this.#dirty = true;
3562
- }
3563
- async save() {
3564
- if (!this.dir || !this.#dirty)
3565
- return;
3566
- const table = createStrings();
3567
- const rows = [];
3568
- for (const [key, extraction] of this.#used) {
3569
- 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");
3570
4158
  }
3571
- let stale = Math.floor(this.#used.size / 2);
3572
- for (const [key, row] of this.#rows) {
3573
- if (stale === 0)
3574
- break;
3575
- if (this.#used.has(key))
3576
- continue;
3577
- try {
3578
- rows.push(encode(key, decode(row, this.#strings), table));
3579
- stale--;
3580
- } 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;
3581
4171
  }
3582
- const header = {
3583
- magic: MAGIC,
3584
- bivium: version,
3585
- scanner: SCANNER_VERSION,
3586
- rows: rows.length,
3587
- strings: table.list.length
3588
- };
3589
- const file = join(this.dir, FILE);
3590
- const temp = `${file}.${process.pid}.${nowMs()}.tmp`;
3591
- try {
3592
- await mkdir(this.dir, { recursive: true });
3593
- const ignore = join(this.dir, ".gitignore");
3594
- if (!existsSync(ignore))
3595
- await writeFile(ignore, `*
3596
- `);
3597
- await writeFile(temp, JSON.stringify([header, table.list, rows]));
3598
- await rename(temp, file);
3599
- this.#dirty = false;
3600
- } catch {
3601
- await unlink(temp).catch(() => {
3602
- 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
3603
4189
  });
3604
4190
  }
3605
4191
  }
4192
+ return diff;
3606
4193
  }
3607
- function createStrings() {
3608
- const list = [];
3609
- const idsByValue = new Map;
3610
- const id = (value) => {
3611
- 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);
3612
4201
  if (found === undefined) {
3613
- found = list.length;
3614
- list.push(value);
3615
- 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);
3616
4208
  }
3617
4209
  return found;
3618
4210
  };
3619
- const ids = (values) => values.length === 0 ? 0 : values.map(id);
3620
- return { list, id, ids };
3621
- }
3622
- function typeIndexes(imports) {
3623
- const indexes = [];
3624
- for (const [i, ref] of imports.entries())
3625
- if (ref.type)
3626
- indexes.push(i);
3627
- return indexes.length === 0 ? 0 : indexes;
3628
- }
3629
- function encode(key, e, table) {
3630
- const imports = e.imports.map(({ specifier, names }) => names ? [table.id(specifier), ...names.map((n) => table.id(n))] : table.id(specifier));
3631
- const barrel = e.barrel && [
3632
- [...e.barrel.names].flatMap(([name, from]) => [
3633
- table.id(name),
3634
- table.id(from)
3635
- ]),
3636
- table.ids(e.barrel.stars)
3637
- ];
3638
- return [
3639
- key,
3640
- imports.length === 0 ? 0 : imports,
3641
- table.ids(e.globs),
3642
- table.ids(e.gotos),
3643
- table.ids(e.dependsOn),
3644
- table.ids(e.reads),
3645
- table.ids(e.unknown),
3646
- e.fallback === undefined ? 0 : table.id(e.fallback),
3647
- barrel ?? 0,
3648
- typeIndexes(e.imports),
3649
- table.ids(e.lists)
3650
- ];
3651
- }
3652
- function decode(row, strings) {
3653
- const str = (id) => {
3654
- const value = typeof id === "number" ? strings[id] : undefined;
3655
- if (typeof value !== "string")
3656
- throw new Error("bad string id");
3657
- return value;
3658
- };
3659
- const list = (ids) => {
3660
- if (ids === 0)
3661
- return [];
3662
- if (!Array.isArray(ids))
3663
- throw new Error("bad list");
3664
- return ids.map(str);
3665
- };
3666
- const refs = row[1] === 0 ? [] : row[1];
3667
- if (!Array.isArray(refs))
3668
- throw new Error("bad imports");
3669
- const imports = refs.map((item) => Array.isArray(item) ? { specifier: str(item[0]), names: item.slice(1).map(str) } : { specifier: str(item) });
3670
- if (row[9] !== 0) {
3671
- if (!Array.isArray(row[9]))
3672
- throw new Error("bad types");
3673
- for (const i of row[9]) {
3674
- const ref = typeof i === "number" ? imports[i] : undefined;
3675
- if (!ref)
3676
- throw new Error("bad type index");
3677
- 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
+ }
3678
4228
  }
3679
- }
3680
- const extraction = {
3681
- imports,
3682
- globs: list(row[2]),
3683
- gotos: list(row[3]),
3684
- dependsOn: list(row[4]),
3685
- reads: list(row[5]),
3686
- lists: list(row[10]),
3687
- unknown: list(row[6])
3688
- };
3689
- if (row[7] !== 0)
3690
- extraction.fallback = str(row[7]);
3691
- if (row[8] !== 0) {
3692
- if (!Array.isArray(row[8]))
3693
- throw new Error("bad barrel");
3694
- const barrel = row[8];
3695
- const [pairs, stars] = barrel;
3696
- if (!Array.isArray(pairs))
3697
- throw new Error("bad barrel names");
3698
- const names = new Map;
3699
- for (let i = 0;i < pairs.length; i += 2) {
3700
- 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
+ }
3701
4255
  }
3702
- 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}`);
3703
4266
  }
3704
- 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;
3705
4280
  }
3706
4281
 
3707
- // src/git.ts
3708
- import { spawn } from "node:child_process";
3709
- import { readFile as readFile2 } from "node:fs/promises";
3710
- import { join as join2 } from "node:path";
3711
- function git(cwd, ...args) {
3712
- return new Promise((resolve, reject) => {
3713
- const child = spawn("git", args, { cwd });
3714
- const chunks = [];
3715
- const errors = [];
3716
- child.stdout.on("data", (chunk) => chunks.push(chunk));
3717
- child.stderr.on("data", (chunk) => errors.push(chunk));
3718
- child.on("error", reject);
3719
- child.on("close", (status) => {
3720
- resolve({
3721
- status: status ?? 1,
3722
- stdout: Buffer.concat(chunks).toString("utf-8"),
3723
- 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`
3724
4314
  });
3725
- });
3726
- });
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 };
3727
4348
  }
3728
- async function gitOrThrow(cwd, ...args) {
3729
- const result = await git(cwd, ...args);
3730
- if (result.status !== 0) {
3731
- const said = result.stderr.trim().split(`
3732
- `)[0];
3733
- 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);
3734
4365
  }
3735
- return result.stdout;
3736
- }
3737
- function lines(output) {
3738
- return output.split(`
3739
- `).filter(Boolean);
4366
+ return new Set([...fine].filter((node) => coarse.has(node)));
3740
4367
  }
3741
- var INDEX_ENTRY = /^(\S) (\d{6}) ([0-9a-f]+) (\d)\t(.*)$/;
3742
- var RAW_ENTRY = /^:(\d{6}) \d{6} ([0-9a-f]+) [0-9a-f]+ ([A-Z])\d*\t(.*)$/;
3743
- async function missingHistory(cwd, base) {
3744
- const [known, forked, shallow] = await Promise.all([
3745
- git(cwd, "rev-parse", "--verify", "--quiet", `${base}^{commit}`),
3746
- git(cwd, "merge-base", base, "HEAD"),
3747
- git(cwd, "rev-parse", "--is-shallow-repository")
3748
- ]);
3749
- const fix = shallow.stdout.trim() === "true" ? " The clone is shallow: fetch the history (actions/checkout: `fetch-depth: 0`)." : "";
3750
- if (known.status !== 0) {
3751
- return new BiviumError2("BV_GIT_NO_BASE", `bivium: no commit ${base} here to diff against: fetch it.${fix}`);
3752
- }
3753
- if (forked.status !== 0) {
3754
- 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;
3755
4377
  }
3756
- 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 };
3757
4387
  }
3758
- function mergeBaseOf(cwd, base) {
3759
- let pending;
3760
- return () => {
3761
- if (pending === undefined) {
3762
- pending = gitOrThrow(cwd, "merge-base", base, "HEAD").then((out) => out.trim());
3763
- pending.catch(() => {
3764
- return;
3765
- });
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);
3766
4404
  }
3767
- return pending;
3768
- };
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 };
3769
4409
  }
3770
- async function readRevision(cwd, base, roots, {
3771
- blobs = false,
3772
- 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
3773
4418
  } = {}) {
3774
- const mergeBase = mergeBaseOf(cwd, base);
3775
- if (eager)
3776
- mergeBase();
3777
- const diffArgs = ["--no-renames", "--merge-base", base];
3778
- const [listing, diff, staged] = await Promise.all([
3779
- gitOrThrow(cwd, "ls-files", "-s", "-v", "-o", "--exclude-standard"),
3780
- gitOrThrow(cwd, "diff", "--raw", "--no-abbrev", ...diffArgs),
3781
- gitOrThrow(cwd, "diff", "--cached", "--name-only", ...diffArgs)
3782
- ]).catch(async (error) => {
3783
- throw await missingHistory(cwd, base) ?? error;
3784
- });
3785
- const entries = lines(listing);
3786
- const untracked = [];
3787
- for (const line of entries) {
3788
- if (line.startsWith("? "))
3789
- untracked.push(line.slice(2));
3790
- }
3791
- const before = new Map;
3792
- const diffed = [];
3793
- const layout = new Set(untracked);
3794
- for (const line of lines(diff)) {
3795
- const [, mode, oid, status, path] = RAW_ENTRY.exec(line) ?? [];
3796
- if (mode === undefined || oid === undefined || status === undefined || path === undefined) {
3797
- throw new Error(`git diff: unexpected line ${line}`);
3798
- }
3799
- diffed.push(path);
3800
- if (status === "A" || status === "D")
3801
- layout.add(path);
3802
- if (status === "A")
3803
- before.set(path, undefined);
3804
- else if ("MTD".includes(status) && mode !== "160000") {
3805
- 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
+ }
3806
4431
  }
3807
4432
  }
3808
- const reads = new Map;
3809
- const readBase = (path) => {
3810
- let read = reads.get(path);
3811
- if (read === undefined) {
3812
- read = readBaseOnce(path);
3813
- reads.set(path, read);
3814
- }
3815
- return read;
3816
- };
3817
- const readBaseOnce = (path) => {
3818
- if (!before.has(path)) {
3819
- if (present.has(path)) {
3820
- return readFile2(join2(cwd, path), "utf-8").catch(() => mergeBase().then((commit) => show(cwd, `${commit}:${path}`)));
3821
- }
3822
- 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
+ });
3823
4467
  }
3824
- const oid = before.get(path);
3825
- return oid === undefined ? Promise.resolve(undefined) : show(cwd, oid);
3826
- };
3827
- const changed = [...new Set([...diffed, ...untracked])];
3828
- const dirty = new Set([...changed, ...lines(staged)]);
3829
- const underRoots = (path) => roots.some((root) => inRoot2(path, root));
3830
- const files = new Set;
3831
- const tracked = new Set;
3832
- const present = new Set;
3833
- const oids = new Map;
3834
- for (const line of entries) {
3835
- const entry = INDEX_ENTRY.exec(line);
3836
- if (!entry) {
3837
- if (line.startsWith("? ") && underRoots(line.slice(2))) {
3838
- files.add(line.slice(2));
3839
- }
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
+ });
3840
4481
  continue;
3841
4482
  }
3842
- const [, tag, mode, oid, stage, path] = entry;
3843
- if (tag === undefined || mode === undefined || oid === undefined || stage === undefined || path === undefined) {
3844
- 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);
3845
4487
  }
3846
- tracked.add(path);
3847
- if (mode === "160000" || !underRoots(path))
3848
- continue;
3849
- files.add(path);
3850
- 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" };
3851
4499
  continue;
3852
- 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")
3853
4508
  continue;
3854
- present.add(path);
3855
- if (blobs)
3856
- 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);
3857
4525
  }
3858
4526
  return {
3859
- files: sorted(files),
3860
- listed: [...tracked, ...untracked],
3861
- 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,
3862
4540
  layout,
3863
- mergeBase,
3864
- readBase,
3865
- blobs: oids,
3866
- present
4541
+ packageCauses: bumped.seeds,
4542
+ narrowings,
4543
+ cases,
4544
+ caseTotals,
4545
+ caseLists,
4546
+ edits: editNotes,
4547
+ sealed
3867
4548
  };
3868
4549
  }
3869
- async function show(cwd, object) {
3870
- const result = await git(cwd, "show", object);
3871
- return result.status === 0 ? result.stdout : undefined;
3872
- }
3873
- async function defaultBase(cwd) {
3874
- const head = await git(cwd, "symbolic-ref", "--short", "refs/remotes/origin/HEAD");
3875
- if (head.status === 0 && head.stdout.trim())
3876
- return head.stdout.trim();
3877
- const refs = ["origin/main", "origin/master", "main", "master"];
3878
- const found = await Promise.all(refs.map((ref) => git(cwd, "rev-parse", "--verify", "--quiet", ref)));
3879
- const branch = refs[found.findIndex((result) => result.status === 0)];
3880
- if (branch)
3881
- return branch;
3882
- 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 };
3883
4570
  }
3884
4571
 
3885
4572
  // src/settings.ts
@@ -4117,7 +4804,7 @@ async function settingChanges({
4117
4804
  const what = manifest ? "resolve or run" : "resolve or compile";
4118
4805
  result.set(file, {
4119
4806
  seeds,
4120
- 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}`
4121
4808
  });
4122
4809
  }
4123
4810
  return result;
@@ -4303,6 +4990,8 @@ async function computePlan2(root, base, config, {
4303
4990
  }),
4304
4991
  ExtractionCache.open(dir)
4305
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(() => []);
4306
4995
  if (revision.changed.some((file) => config.narrowers.some((narrower) => narrower.match(file)))) {
4307
4996
  revision.mergeBase();
4308
4997
  }
@@ -4350,13 +5039,38 @@ async function computePlan2(root, base, config, {
4350
5039
  return names.map((name) => `${file}#${name}`);
4351
5040
  }));
4352
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
+ }));
4353
5065
  const narrowed = await runNarrowers(root, revision, graph, config, suites, packageDiff, settings);
4354
5066
  const planned = planTests(graph, revision.changed, config, {
4355
5067
  barrelNames,
4356
5068
  layout: revision.layout,
4357
5069
  narrowed,
4358
5070
  packages: packageDiff,
4359
- settings
5071
+ settings,
5072
+ edits,
5073
+ ...seals && { seals }
4360
5074
  });
4361
5075
  await saved;
4362
5076
  return {
@@ -4408,6 +5122,7 @@ async function plan2(options = {}) {
4408
5122
  });
4409
5123
  return {
4410
5124
  suites: computed.plan.suites,
5125
+ cases: computed.plan.cases,
4411
5126
  reasons: computed.plan.reasons,
4412
5127
  causes: computed.plan.causes,
4413
5128
  totals: computed.plan.totals,
@@ -4422,4 +5137,4 @@ async function plan2(options = {}) {
4422
5137
  };
4423
5138
  }
4424
5139
 
4425
- 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, 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 };