bivium 0.6.2 → 0.8.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,14 +1,14 @@
1
- // src/compute.ts
2
- import { readFile as readFile3, stat } from "node:fs/promises";
3
- import { join as join4, posix as posix6, resolve as resolve2 } from "node:path";
4
-
5
- // src/cache.ts
6
- import { existsSync } from "node:fs";
7
- import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
8
- import { isAbsolute, join } from "node:path";
9
-
10
- // package.json
11
- var version = "0.6.2";
1
+ import {
2
+ BiviumError2
3
+ } from "./shared-211m8fjt.js";
4
+ import {
5
+ globToRegExp,
6
+ matcher,
7
+ resolveConfig2,
8
+ inRoot2,
9
+ checkConfig2,
10
+ loadConfig2
11
+ } from "./shared-550cvwt2.js";
12
12
 
13
13
  // src/env.ts
14
14
  function githubOutputPath() {
@@ -17,1719 +17,763 @@ function githubOutputPath() {
17
17
  function nowMs() {
18
18
  return Date.now();
19
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
+ });
35
+ }
20
36
 
21
- // src/cache.ts
22
- var SCANNER_VERSION = 8;
23
- var MAGIC = "bivium-extractions";
24
- var FILE = "extractions.json";
25
- function isHeader(value) {
26
- 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";
37
+ // package.json
38
+ var version = "0.8.0";
39
+
40
+ // src/barrel.ts
41
+ var COMMENTS = /\/\/.*$|\/\*[\s\S]*?\*\//gm;
42
+ var AS = /\s+as\s+/;
43
+ var TYPE_PREFIX = /^type\s+/;
44
+ var NAMED_EXPORT = /export\s+(?:type\s+)?\{([^}]*)\}\s*from\s*["']([^"']+)["']\s*;?/g;
45
+ var STAR_EXPORT = /export\s+(?:type\s+)?\*(?:\s+as\s+([\w$]+))?\s+from\s*["']([^"']+)["']\s*;?/g;
46
+ var BARREL_FILE = /\.[cm]?[jt]sx?$/;
47
+ var ONLY_SEPARATORS = /^[\s;]*$/;
48
+ var STARTS_WITH_EXPORT = /^(?:\s+|\/\/[^\n]*|\/\*[\s\S]*?\*\/)*export\b/;
49
+ function parseBarrel(path, source) {
50
+ return BARREL_FILE.test(path) ? parseReExports(source) : undefined;
27
51
  }
28
- function cacheDir(root, cache) {
29
- if (cache === false)
52
+ function parseReExports(source) {
53
+ if (!STARTS_WITH_EXPORT.test(source))
30
54
  return;
31
- if (typeof cache === "string") {
32
- return isAbsolute(cache) ? cache : join(root, cache);
33
- }
34
- const modules = join(root, "node_modules");
35
- return existsSync(modules) ? join(modules, ".cache", "bivium") : join(root, ".bivium", "cache");
55
+ const code = source.replace(COMMENTS, "");
56
+ const barrel = { names: new Map, stars: [] };
57
+ let rest = code.replace(NAMED_EXPORT, (_, list, from) => {
58
+ for (const part of list.split(",")) {
59
+ const name = part.trim().replace(TYPE_PREFIX, "").split(AS).pop();
60
+ if (name)
61
+ barrel.names.set(name, from);
62
+ }
63
+ return "";
64
+ });
65
+ rest = rest.replace(STAR_EXPORT, (_, name, from) => {
66
+ if (name)
67
+ barrel.names.set(name, from);
68
+ else
69
+ barrel.stars.push(from);
70
+ return "";
71
+ });
72
+ if (barrel.names.size + barrel.stars.length === 0)
73
+ return;
74
+ return ONLY_SEPARATORS.test(rest) ? barrel : undefined;
36
75
  }
37
76
 
38
- class ExtractionCache {
39
- #rows = new Map;
40
- #strings = [];
41
- #used = new Map;
42
- #dirty = false;
43
- dir;
44
- constructor(dir) {
45
- this.dir = dir;
77
+ // src/resolve.ts
78
+ import { builtinModules } from "node:module";
79
+ import { posix } from "node:path";
80
+
81
+ // src/syntax.ts
82
+ var QUERY = /[?#].*$/;
83
+ var UNDECLARED_READS = "reads the disk without @depends-on";
84
+ var RELATIVE = /^\.\.?(?:\/|$)/;
85
+ var URL_REF = /^[a-z]+:|^\/\//;
86
+ var LIST_SEPARATOR = /[\s,]+(?![^{]*\})/;
87
+ var DEPENDS_ON = /^\s*(?:\/\/|\/?\*+)\s*@depends-on\s+(.+?)\s*(?:\*\/)?\s*$/gm;
88
+ var READS = /^\s*(?:\/\/|\/?\*+)\s*@reads\s+(.+?)\s*(?:\*\/)?\s*$/gm;
89
+ var LISTS = /^\s*(?:\/\/|\/?\*+)\s*@lists\s+(.+?)\s*(?:\*\/)?\s*$/gm;
90
+ var GLOB_REGISTRY = /^\s*(?:\/\/|\/?\*+)\s*@glob-registry\b/m;
91
+ var AS2 = /\s+as\s+/;
92
+ var TYPE_PREFIX2 = /^type\s+/;
93
+ var NAMED_CLAUSE = /\{([^}]*)\}/;
94
+ var DEFAULT_OR_NAMESPACE = /^\s*[\w$*]/;
95
+ function namedBindings(clause) {
96
+ const named = NAMED_CLAUSE.exec(clause);
97
+ if (!named || DEFAULT_OR_NAMESPACE.test(clause.replace(NAMED_CLAUSE, ""))) {
98
+ return;
46
99
  }
47
- static async open(dir) {
48
- const cache = new ExtractionCache(dir);
49
- if (!dir)
50
- return cache;
51
- const text = await readFile(join(dir, FILE), "utf-8").catch(() => "");
52
- if (text)
53
- cache.#load(text);
54
- return cache;
100
+ return captured(named, 1).split(",").map((part) => (part.trim().replace(TYPE_PREFIX2, "").split(AS2)[0] ?? "").trim()).filter(Boolean);
101
+ }
102
+ function captured(match, index) {
103
+ const value = match[index];
104
+ if (value === undefined) {
105
+ throw new Error(`bivium: scan: group ${index} of ${match[0]} is unset.`);
55
106
  }
56
- #load(text) {
57
- try {
58
- const parsed = JSON.parse(text);
59
- if (!Array.isArray(parsed))
60
- return;
61
- const fields = parsed;
62
- const [header, strings, rows] = fields;
63
- if (!isHeader(header) || !Array.isArray(strings) || !Array.isArray(rows) || header.strings !== strings.length || header.rows !== rows.length) {
64
- return;
65
- }
66
- this.#strings = strings;
67
- for (const row of rows) {
68
- if (Array.isArray(row) && typeof row[0] === "string") {
69
- this.#rows.set(row[0], row);
70
- }
71
- }
72
- } catch {}
107
+ return value;
108
+ }
109
+
110
+ // src/resolve.ts
111
+ function isRecord(value) {
112
+ return typeof value === "object" && value !== null && !Array.isArray(value);
113
+ }
114
+ function isStringRecord(value) {
115
+ return isRecord(value) && Object.values(value).every((item) => typeof item === "string");
116
+ }
117
+ function toPackageJson(value) {
118
+ if (!isRecord(value))
119
+ return {};
120
+ const json = {};
121
+ if (typeof value.name === "string")
122
+ json.name = value.name;
123
+ if (value.exports !== undefined)
124
+ json.exports = value.exports;
125
+ if (isRecord(value.imports))
126
+ json.imports = value.imports;
127
+ if (typeof value.main === "string")
128
+ json.main = value.main;
129
+ const { sideEffects } = value;
130
+ if (typeof sideEffects === "boolean" || Array.isArray(sideEffects) && sideEffects.every((glob) => typeof glob === "string")) {
131
+ json.sideEffects = sideEffects;
73
132
  }
74
- get size() {
75
- return this.#rows.size;
133
+ for (const field of DEP_FIELDS) {
134
+ const deps = value[field];
135
+ if (isStringRecord(deps))
136
+ json[field] = deps;
76
137
  }
77
- get(oid, format) {
78
- const key = `${format}:${oid}`;
79
- const used = this.#used.get(key);
80
- if (used)
81
- return used;
82
- const row = this.#rows.get(key);
83
- if (!row)
84
- return;
85
- let extraction;
86
- try {
87
- extraction = decode(row, this.#strings);
88
- } catch {
89
- this.#rows.delete(key);
90
- return;
91
- }
92
- this.#used.set(key, extraction);
93
- return extraction;
138
+ return json;
139
+ }
140
+ var BUILTINS = new Set(builtinModules);
141
+ var RUNTIME_BUILTIN = /^(?:node:|bun(?:$|:))/;
142
+ var JS_EXTENSION = /\.(?:js|jsx|mjs|cjs)$/;
143
+ var TS_SOURCES = {
144
+ ".js": [".ts", ".tsx", ".d.ts"],
145
+ ".jsx": [".tsx", ".ts", ".d.ts"],
146
+ ".mjs": [".mts", ".d.mts"],
147
+ ".cjs": [".cts", ".d.cts"]
148
+ };
149
+ var NODE_PREFIX = /^node:/;
150
+ var INVALID_IMPORT_TARGET = /^[./#]/;
151
+ var SVELTEKIT_ASSETS = "./%sveltekit.assets%/";
152
+ var INDEX = "/index";
153
+ var SVELTE_CONFIGS = ["js", "mjs", "cjs", "ts", "mts"].map((ext) => `svelte.config.${ext}`);
154
+ var DEP_FIELDS = [
155
+ "dependencies",
156
+ "devDependencies",
157
+ "peerDependencies",
158
+ "optionalDependencies"
159
+ ];
160
+ function packageName(specifier) {
161
+ const parts = specifier.split("/");
162
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0] ?? "";
163
+ }
164
+ function builtin(specifier) {
165
+ if (RUNTIME_BUILTIN.test(specifier)) {
166
+ const name = specifier.replace(NODE_PREFIX, "");
167
+ return specifier.startsWith("bun") ? specifier : `node:${name.split("/")[0]}`;
94
168
  }
95
- set(oid, format, extraction) {
96
- const key = `${format}:${oid}`;
97
- this.#used.set(key, extraction);
98
- this.#dirty = true;
169
+ const name = specifier.split("/")[0] ?? "";
170
+ return BUILTINS.has(specifier) || BUILTINS.has(name) ? `node:${name}` : undefined;
171
+ }
172
+ function targets(value, out = []) {
173
+ if (typeof value === "string")
174
+ out.push(value);
175
+ else if (Array.isArray(value))
176
+ for (const item of value)
177
+ targets(item, out);
178
+ else if (value && typeof value === "object") {
179
+ for (const item of Object.values(value))
180
+ targets(item, out);
99
181
  }
100
- async save() {
101
- if (!this.dir || !this.#dirty)
102
- return;
103
- const table = createStrings();
104
- const rows = [];
105
- for (const [key, extraction] of this.#used) {
106
- rows.push(encode(key, extraction, table));
107
- }
108
- let stale = Math.floor(this.#used.size / 2);
109
- for (const [key, row] of this.#rows) {
110
- if (stale === 0)
111
- break;
112
- if (this.#used.has(key))
113
- continue;
114
- try {
115
- rows.push(encode(key, decode(row, this.#strings), table));
116
- stale--;
117
- } catch {}
118
- }
119
- const header = {
120
- magic: MAGIC,
121
- bivium: version,
122
- scanner: SCANNER_VERSION,
123
- rows: rows.length,
124
- strings: table.list.length
125
- };
126
- const file = join(this.dir, FILE);
127
- const temp = `${file}.${process.pid}.${nowMs()}.tmp`;
128
- try {
129
- await mkdir(this.dir, { recursive: true });
130
- const ignore = join(this.dir, ".gitignore");
131
- if (!existsSync(ignore))
132
- await writeFile(ignore, `*
133
- `);
134
- await writeFile(temp, JSON.stringify([header, table.list, rows]));
135
- await rename(temp, file);
136
- this.#dirty = false;
137
- } catch {
138
- await unlink(temp).catch(() => {
139
- return;
140
- });
182
+ return out;
183
+ }
184
+ function subpathMap(exports) {
185
+ if (typeof exports === "string" || Array.isArray(exports)) {
186
+ return { ".": exports };
187
+ }
188
+ if (!isRecord(exports))
189
+ return;
190
+ const bySubpath = Object.keys(exports).some((key) => key.startsWith("."));
191
+ return bySubpath ? exports : { ".": exports };
192
+ }
193
+ function mapTargets(map, subpath) {
194
+ if (subpath in map && !subpath.includes("*"))
195
+ return targets(map[subpath]);
196
+ let best;
197
+ for (const key of Object.keys(map)) {
198
+ const star = key.indexOf("*");
199
+ if (star === -1)
200
+ continue;
201
+ const prefix = key.slice(0, star);
202
+ const suffix = key.slice(star + 1);
203
+ if (subpath.length >= key.length - 1 && subpath.startsWith(prefix) && subpath.endsWith(suffix) && (!best || prefix.length > best.key.indexOf("*") || prefix.length === best.key.indexOf("*") && key.length > best.key.length)) {
204
+ best = {
205
+ key,
206
+ match: subpath.slice(prefix.length, subpath.length - suffix.length)
207
+ };
141
208
  }
142
209
  }
210
+ if (!best)
211
+ return;
212
+ const { match } = best;
213
+ return targets(map[best.key]).map((target) => target.replaceAll("*", match));
143
214
  }
144
- function createStrings() {
145
- const list = [];
146
- const idsByValue = new Map;
147
- const id = (value) => {
148
- let found = idsByValue.get(value);
149
- if (found === undefined) {
150
- found = list.length;
151
- list.push(value);
152
- idsByValue.set(value, found);
153
- }
154
- return found;
155
- };
156
- const ids = (values) => values.length === 0 ? 0 : values.map(id);
157
- return { list, id, ids };
215
+ function exportTargets(exports, subpath) {
216
+ const map = subpathMap(exports);
217
+ return map && mapTargets(map, subpath);
158
218
  }
159
- function typeIndexes(imports) {
160
- const indexes = [];
161
- for (const [i, ref] of imports.entries())
162
- if (ref.type)
163
- indexes.push(i);
164
- return indexes.length === 0 ? 0 : indexes;
219
+ function byDepth(packages) {
220
+ return [...packages].sort(([a], [b]) => b.length - a.length);
165
221
  }
166
- function encode(key, e, table) {
167
- const imports = e.imports.map(({ specifier, names }) => names ? [table.id(specifier), ...names.map((n) => table.id(n))] : table.id(specifier));
168
- const barrel = e.barrel && [
169
- [...e.barrel.names].flatMap(([name, from]) => [
170
- table.id(name),
171
- table.id(from)
172
- ]),
173
- table.ids(e.barrel.stars)
174
- ];
175
- return [
176
- key,
177
- imports.length === 0 ? 0 : imports,
178
- table.ids(e.globs),
179
- table.ids(e.gotos),
180
- table.ids(e.dependsOn),
181
- table.ids(e.reads),
182
- table.ids(e.unknown),
183
- e.fallback === undefined ? 0 : table.id(e.fallback),
184
- barrel ?? 0,
185
- typeIndexes(e.imports),
186
- table.ids(e.lists)
187
- ];
222
+ function owner(packages, file) {
223
+ return byDepth(packages).find(([dir]) => dir === "." || file.startsWith(`${dir}/`));
188
224
  }
189
- function decode(row, strings) {
190
- const str = (id) => {
191
- const value = typeof id === "number" ? strings[id] : undefined;
192
- if (typeof value !== "string")
193
- throw new Error("bad string id");
194
- return value;
195
- };
196
- const list = (ids) => {
197
- if (ids === 0)
198
- return [];
199
- if (!Array.isArray(ids))
200
- throw new Error("bad list");
201
- return ids.map(str);
202
- };
203
- const refs = row[1] === 0 ? [] : row[1];
204
- if (!Array.isArray(refs))
205
- throw new Error("bad imports");
206
- const imports = refs.map((item) => Array.isArray(item) ? { specifier: str(item[0]), names: item.slice(1).map(str) } : { specifier: str(item) });
207
- if (row[9] !== 0) {
208
- if (!Array.isArray(row[9]))
209
- throw new Error("bad types");
210
- for (const i of row[9]) {
211
- const ref = typeof i === "number" ? imports[i] : undefined;
212
- if (!ref)
213
- throw new Error("bad type index");
214
- ref.type = true;
225
+ function aliasPath([key, target], specifier) {
226
+ if (specifier !== key && !specifier.startsWith(`${key}/`))
227
+ return;
228
+ const rest = specifier.slice(key.length + 1);
229
+ if (target === ".")
230
+ return posix.normalize(rest || ".");
231
+ return posix.normalize(rest ? `${target}/${rest}` : target);
232
+ }
233
+ function createResolver({
234
+ files,
235
+ config,
236
+ packages,
237
+ tsconfigs = new Map
238
+ }) {
239
+ const generated = (path) => config.generated.some(({ pattern }) => pattern.test(path));
240
+ const { extensions } = config;
241
+ const exists = (path) => files.has(path);
242
+ const suffixed = new Map;
243
+ const indexes = new Map;
244
+ const byTail = [];
245
+ const undotted = [];
246
+ for (const [i, ext] of extensions.entries()) {
247
+ const dot = ext.lastIndexOf(".");
248
+ if (dot === -1)
249
+ undotted.push(i);
250
+ else {
251
+ const list = byTail[ext.length - dot];
252
+ if (list)
253
+ list.push(i);
254
+ else
255
+ byTail[ext.length - dot] = [i];
215
256
  }
216
257
  }
217
- const extraction = {
218
- imports,
219
- globs: list(row[2]),
220
- gotos: list(row[3]),
221
- dependsOn: list(row[4]),
222
- reads: list(row[5]),
223
- lists: list(row[10]),
224
- unknown: list(row[6])
225
- };
226
- if (row[7] !== 0)
227
- extraction.fallback = str(row[7]);
228
- if (row[8] !== 0) {
229
- if (!Array.isArray(row[8]))
230
- throw new Error("bad barrel");
231
- const barrel = row[8];
232
- const [pairs, stars] = barrel;
233
- if (!Array.isArray(pairs))
234
- throw new Error("bad barrel names");
235
- const names = new Map;
236
- for (let i = 0;i < pairs.length; i += 2) {
237
- names.set(str(pairs[i]), str(pairs[i + 1]));
258
+ const addSuffixed = (i, file) => {
259
+ const ext = extensions[i];
260
+ if (ext === undefined) {
261
+ throw new Error(`bivium: resolve: no extension at index ${i}.`);
238
262
  }
239
- extraction.barrel = { names, stars: list(stars) };
240
- }
241
- return extraction;
242
- }
243
-
244
- // src/config.ts
245
- import { existsSync as existsSync2, readFileSync } from "node:fs";
246
- import { isAbsolute as isAbsolute2, join as join2, relative, resolve } from "node:path";
247
- import { pathToFileURL } from "node:url";
248
-
249
- // src/errors.ts
250
- var KINDS = {
251
- BV_MISSING_ARGUMENT: "usage",
252
- BV_UNKNOWN_COMMAND: "usage",
253
- BV_UNKNOWN_OPTION: "usage",
254
- BV_BAD_OPTION_VALUE: "usage",
255
- BV_UNEXPECTED_ARGUMENT: "usage",
256
- BV_UNKNOWN_SUITE: "usage",
257
- BV_UNKNOWN_TEST: "usage",
258
- BV_UNKNOWN_FILE: "usage",
259
- BV_NO_RUN_COMMAND: "usage",
260
- BV_NO_GITHUB_OUTPUT: "usage",
261
- BV_CONFIG_NOT_FOUND: "config",
262
- BV_CONFIG_UNREADABLE: "config",
263
- BV_CONFIG_INVALID: "config",
264
- BV_GIT_NO_BASE: "git",
265
- BV_GIT_NO_MERGE_BASE: "git",
266
- BV_GIT_FAILED: "git",
267
- BV_INTERNAL: "other"
268
- };
269
-
270
- class BiviumError2 extends Error {
271
- code;
272
- kind;
273
- constructor(code, message, options) {
274
- super(message, options);
275
- this.code = code;
276
- this.kind = KINDS[code];
277
- }
278
- }
279
- function distance(a, b) {
280
- const width = b.length + 1;
281
- const cells = new Uint32Array((a.length + 1) * width);
282
- const d = (i, j) => cells[i * width + j] ?? 0;
283
- for (let i = 0;i <= a.length; i++)
284
- cells[i * width] = i;
285
- for (let j = 0;j <= b.length; j++)
286
- cells[j] = j;
287
- for (let i = 1;i <= a.length; i++) {
288
- for (let j = 1;j <= b.length; j++) {
289
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
290
- let best = Math.min(d(i - 1, j) + 1, d(i, j - 1) + 1, d(i - 1, j - 1) + cost);
291
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
292
- best = Math.min(best, d(i - 2, j - 2) + 1);
263
+ if (!file.endsWith(ext))
264
+ return;
265
+ const base = file.slice(0, file.length - ext.length);
266
+ const list = suffixed.get(base);
267
+ if (list)
268
+ list.push([i, file]);
269
+ else {
270
+ const created = [[i, file]];
271
+ suffixed.set(base, created);
272
+ if (base.endsWith(INDEX)) {
273
+ indexes.set(base.slice(0, -INDEX.length), created);
293
274
  }
294
- cells[i * width + j] = best;
295
275
  }
296
- }
297
- return d(a.length, b.length);
298
- }
299
- function closest(input, candidates) {
300
- const most = Math.max(1, Math.floor(input.length / 3));
301
- let best;
302
- let bestDistance = most + 1;
303
- for (const candidate of candidates) {
304
- const d = distance(input, candidate);
305
- if (d < bestDistance) {
306
- best = candidate;
307
- bestDistance = d;
276
+ };
277
+ for (const file of files) {
278
+ const dot = file.lastIndexOf(".");
279
+ if (dot !== -1) {
280
+ for (const i of byTail[file.length - dot] ?? [])
281
+ addSuffixed(i, file);
308
282
  }
283
+ for (const i of undotted)
284
+ addSuffixed(i, file);
309
285
  }
310
- return best;
311
- }
312
- function didYouMean(input, candidates) {
313
- const match = closest(input, candidates);
314
- return match === undefined ? "" : ` (did you mean ${match}?)`;
315
- }
316
-
317
- // src/glob.ts
318
- var GLOB_LITERAL = /[.+^$()|[\]\\]/g;
319
- var REGEX_SPECIAL = /[.*+?^${}()|[\]\\]/g;
320
- var DIGIT = /[0-9]/;
321
- var CAPTURE_REFERENCE = /\$(\d+)/g;
322
- function compile(glob, {
323
- capture = false,
324
- captures
325
- } = {}) {
326
- let source = "";
327
- let wildcards = 0;
328
- const group = (body) => {
329
- wildcards++;
330
- return capture ? `(${body})` : body;
331
- };
332
- for (let i = 0;i < glob.length; i++) {
333
- const char = glob.charAt(i);
334
- if (captures && char === "$" && DIGIT.test(glob[i + 1] ?? "")) {
335
- let end = i + 1;
336
- while (DIGIT.test(glob[end] ?? ""))
337
- end++;
338
- const text = captures[Number(glob.slice(i + 1, end)) - 1];
339
- source += text === undefined ? ".*" : text.replace(REGEX_SPECIAL, "\\$&");
340
- i = end - 1;
341
- } else if (char === "*" && glob[i + 1] === "*") {
342
- const slash = glob[i + 2] === "/";
343
- source += group(slash ? "(?:.*/)?" : ".*");
344
- i += slash ? 2 : 1;
345
- } else if (char === "*")
346
- source += group("[^/]*");
347
- else if (char === "?")
348
- source += group("[^/]");
349
- else if (char === "{") {
350
- wildcards++;
351
- source += capture ? "(" : "(?:";
352
- } else if (char === "}")
353
- source += ")";
354
- else if (char === ",")
355
- source += "|";
356
- else
357
- source += char.replace(GLOB_LITERAL, "\\$&");
286
+ for (const list of suffixed.values()) {
287
+ if (list.length > 1)
288
+ list.sort(([a], [b]) => a - b);
358
289
  }
359
- return { source: `^${source}$`, wildcards };
360
- }
361
- function globToRegExp(glob) {
362
- return new RegExp(compile(glob).source);
363
- }
364
- function captureGlob(glob) {
365
- const { source, wildcards } = compile(glob, { capture: true });
366
- return { pattern: new RegExp(source), wildcards };
367
- }
368
- function captureReferences(glob) {
369
- return [...glob.matchAll(CAPTURE_REFERENCE)].map((match) => Number(match[1]));
370
- }
371
- function expandGlob(glob, captures) {
372
- return new RegExp(compile(glob, { captures }).source);
373
- }
374
- function matcher(globs = []) {
375
- const list = typeof globs === "string" ? [globs] : globs;
376
- if (list.length === 0)
377
- return () => false;
378
- const res = list.map(globToRegExp);
379
- return (path) => res.some((re) => re.test(path));
380
- }
381
-
382
- // src/config.ts
383
- function defineConfig2(config) {
384
- return config;
385
- }
386
- var DEFAULT_EXTENSIONS = [
387
- ".ts",
388
- ".tsx",
389
- ".mts",
390
- ".cts",
391
- ".js",
392
- ".jsx",
393
- ".mjs",
394
- ".cjs",
395
- ".d.ts",
396
- ".svelte",
397
- ".vue",
398
- ".json"
399
- ];
400
- function list(value, fallback) {
401
- if (value === undefined)
402
- return [...fallback];
403
- return typeof value === "string" ? [value] : [...value];
404
- }
405
- var LEADING_DOT_SLASH = /^\.\//;
406
- var TRAILING_SLASHES = /\/+$/;
407
- function normalizeRoot(root) {
408
- return root.replace(LEADING_DOT_SLASH, "").replace(TRAILING_SLASHES, "") || ".";
409
- }
410
- function pathMaps(record = {}) {
411
- return Object.entries(record).map(([key, globs]) => {
412
- const { pattern, wildcards } = captureGlob(key);
413
- const values = list(globs, []);
414
- const fixed = values.map((value) => captureReferences(value).length === 0 ? globToRegExp(value) : undefined);
415
- return {
416
- key,
417
- exact: wildcards === 0,
418
- pattern,
419
- values,
420
- targets: (path) => {
421
- const match = pattern.exec(path);
422
- if (!match)
423
- return;
424
- const captures = match.slice(1);
425
- return values.map((value, i) => fixed[i] ?? expandGlob(value, captures));
290
+ const deepestFirst = byDepth(packages);
291
+ const local = new Map;
292
+ for (const [dir, json] of deepestFirst) {
293
+ if (json.name && !local.has(json.name))
294
+ local.set(json.name, dir);
295
+ }
296
+ const declaredIn = (dir) => {
297
+ const names = new Set;
298
+ for (const [pkgDir, json] of deepestFirst) {
299
+ if (pkgDir !== "." && dir !== pkgDir && !dir.startsWith(`${pkgDir}/`))
300
+ continue;
301
+ for (const field of DEP_FIELDS) {
302
+ for (const name of Object.keys(json[field] ?? {}))
303
+ names.add(name);
426
304
  }
427
- };
428
- });
429
- }
430
- function isInertOf(inert) {
431
- const listed = matcher(inert);
432
- return (name) => name === "bivium" || listed(name);
433
- }
434
- function optional(key, value) {
435
- const out = {};
436
- if (value !== undefined)
437
- out[key] = value;
438
- return out;
439
- }
440
- function resolveConfig(config) {
441
- const names = Object.keys(config.suites);
442
- if (names.length === 0)
443
- throw new Error("bivium config: no suites");
444
- const suites = Object.entries(config.suites).map(([name, suite]) => ({
445
- name,
446
- isTest: matcher(suite.tests),
447
- ...optional("run", suite.run),
448
- roots: list(suite.root, ["."]).map(normalizeRoot),
449
- urls: Object.entries(suite.urls ?? {}).map(([key, targets]) => ({
450
- key,
451
- targets: list(targets, [])
452
- })),
453
- isPage: matcher(suite.pages),
454
- isWiring: matcher(suite.wiring),
455
- isSetup: matcher(suite.setup),
456
- setup: list(suite.setup, []),
457
- isNonInput: matcher(suite.nonInputs),
458
- output: suite.output ?? `${name}-tests`,
459
- types: suite.types ?? true
460
- }));
461
- const narrowers = (config.narrowers ?? []).map((narrower) => {
462
- const unknown = narrower.suites?.find((name) => !names.includes(name));
463
- if (unknown !== undefined) {
464
- throw new Error(`bivium config: narrower ${narrower.name} names no suite ${unknown}`);
465
305
  }
466
- return {
467
- name: narrower.name,
468
- match: matcher(narrower.match),
469
- opaque: matcher(narrower.opaque),
470
- suites: [...narrower.suites ?? names],
471
- narrow: async (context) => checkResult(await narrower.narrow(context))
472
- };
473
- });
474
- return {
475
- suites,
476
- narrowers,
477
- roots: list(config.roots, ["."]).map(normalizeRoot),
478
- isIgnored: matcher(config.ignore),
479
- alias: Object.entries(config.alias ?? {}).map(([key, path]) => [
480
- key.replace(TRAILING_SLASHES, "") || key,
481
- normalizeRoot(path)
482
- ]).sort(([a], [b]) => b.length - a.length),
483
- generated: pathMaps(config.edges),
484
- reads: pathMaps(config.reads),
485
- isSelf: matcher(config.self),
486
- isImportOnly: matcher(config.importOnly),
487
- isHermetic: matcher(config.hermetic),
488
- isBarrel: config.barrels ? matcher(config.barrels) : () => true,
489
- external: new Set(config.external),
490
- isInert: isInertOf(config.inert),
491
- ...config.loadedByName !== undefined && {
492
- isLoadedByName: matcher(config.loadedByName)
493
- },
494
- extensions: config.extensions ?? DEFAULT_EXTENSIONS,
495
- deadGlobs: config.deadGlobs ?? [],
496
- ...config.knownUnknowns && { knownUnknowns: config.knownUnknowns },
497
- ...optional("base", config.base),
498
- ...optional("cache", config.cache)
306
+ return names;
499
307
  };
500
- }
501
- function inRoot(file, root) {
502
- return root === "." || file === root || file.startsWith(`${root}/`);
503
- }
504
- function isRecord(value) {
505
- return typeof value === "object" && value !== null && !Array.isArray(value);
506
- }
507
- function isStrings(value) {
508
- return Array.isArray(value) && value.every((item) => typeof item === "string");
509
- }
510
- function isGlobs(value) {
511
- return typeof value === "string" || isStrings(value);
512
- }
513
- function isStringRecord(value) {
514
- return isRecord(value) && Object.values(value).every((item) => typeof item === "string");
515
- }
516
- function isGlobsRecord(value) {
517
- return isRecord(value) && Object.values(value).every(isGlobs);
518
- }
519
- function isBoolean(value) {
520
- return typeof value === "boolean";
521
- }
522
- function isString(value) {
523
- return typeof value === "string";
524
- }
525
- function isCache(value) {
526
- return typeof value === "boolean" || typeof value === "string";
527
- }
528
- function field(record, key, is, path, expected) {
529
- const value = record[key];
530
- if (value === undefined || is(value))
531
- return value;
532
- throw new Error(`bivium config: ${path}${key} must be ${expected}`);
533
- }
534
- var SUITE_KEYS = new Set([
535
- "tests",
536
- "run",
537
- "root",
538
- "urls",
539
- "pages",
540
- "wiring",
541
- "setup",
542
- "nonInputs",
543
- "output",
544
- "types"
545
- ]);
546
- var NARROWER_KEYS = new Set(["name", "match", "opaque", "suites", "narrow"]);
547
- var DEAD_GLOB_KEYS = new Set(["file", "glob", "reason"]);
548
- var KNOWN_UNKNOWN_KEYS = new Set(["file", "reason"]);
549
- var CONFIG_KEYS = new Set([
550
- "suites",
551
- "narrowers",
552
- "roots",
553
- "ignore",
554
- "alias",
555
- "edges",
556
- "reads",
557
- "self",
558
- "importOnly",
559
- "hermetic",
560
- "barrels",
561
- "external",
562
- "inert",
563
- "loadedByName",
564
- "extensions",
565
- "deadGlobs",
566
- "knownUnknowns",
567
- "base",
568
- "cache"
569
- ]);
570
- function unknownKeys(value) {
571
- const found = [];
572
- const visit = (record, known, path) => {
573
- if (!isRecord(record))
574
- return;
575
- for (const key of Object.keys(record)) {
576
- if (!known.has(key))
577
- found.push(`${path}${key}${didYouMean(key, known)}`);
308
+ const tsSources = (path) => {
309
+ const js = JS_EXTENSION.exec(path);
310
+ if (!js)
311
+ return [];
312
+ const stem = path.slice(0, js.index);
313
+ return (TS_SOURCES[js[0]] ?? []).map((ext) => stem + ext).filter((file) => generated(file) || exists(file));
314
+ };
315
+ const exact = (path) => generated(path) || exists(path) ? [path] : tsSources(path);
316
+ const probe = (base, guess = false) => {
317
+ if (generated(base))
318
+ return [base];
319
+ const found = [];
320
+ if (exists(base))
321
+ found.push(base);
322
+ for (const [, file] of suffixed.get(base) ?? [])
323
+ found.push(file);
324
+ if (found.length === 0)
325
+ found.push(...tsSources(base));
326
+ for (const [, file] of indexes.get(base) ?? [])
327
+ found.push(file);
328
+ if (found.length === 0 && !guess && config.generated.length > 0) {
329
+ for (const ext of extensions) {
330
+ if (generated(base + ext))
331
+ found.push(base + ext);
332
+ }
333
+ for (const ext of extensions) {
334
+ if (generated(`${base}/index${ext}`))
335
+ found.push(`${base}/index${ext}`);
336
+ }
578
337
  }
338
+ return found;
579
339
  };
580
- visit(value, CONFIG_KEYS, "");
581
- if (isRecord(value.suites)) {
582
- for (const [name, suite] of Object.entries(value.suites)) {
583
- visit(suite, SUITE_KEYS, `suites.${name}.`);
340
+ const tsDeepestFirst = [...tsconfigs].sort(([a], [b]) => b.length - a.length);
341
+ const scopes = new Map;
342
+ const scopeOf = (from) => {
343
+ const contains = ([dir]) => dir === "." || from.startsWith(`${dir}/`);
344
+ const pkg = deepestFirst.findIndex(contains);
345
+ const ts = tsDeepestFirst.findIndex(contains);
346
+ const key = `${pkg} ${ts}`;
347
+ let scope = scopes.get(key);
348
+ if (!scope) {
349
+ const owning = pkg === -1 ? undefined : deepestFirst[pkg];
350
+ scope = {
351
+ owning,
352
+ ts: ts === -1 ? undefined : tsDeepestFirst[ts]?.[1],
353
+ declared: declaredIn(owning?.[0] ?? "."),
354
+ resolved: new Map
355
+ };
356
+ scopes.set(key, scope);
584
357
  }
585
- }
586
- const lists = [
587
- ["narrowers", NARROWER_KEYS],
588
- ["deadGlobs", DEAD_GLOB_KEYS],
589
- ["knownUnknowns", KNOWN_UNKNOWN_KEYS]
590
- ];
591
- for (const [key, known] of lists) {
592
- const entries = value[key];
593
- if (!Array.isArray(entries))
594
- continue;
595
- for (const [i, entry] of entries.entries()) {
596
- visit(entry, known, `${key}[${i}].`);
358
+ return scope;
359
+ };
360
+ const svelteKitRoot = (dir) => {
361
+ for (let at = dir;; at = posix.dirname(at)) {
362
+ if (at === "." || packages.has(at))
363
+ return at;
364
+ if (SVELTE_CONFIGS.some((name) => exists(`${at}/${name}`)))
365
+ return at;
597
366
  }
598
- }
599
- return found;
600
- }
601
- function checkSuite(name, value) {
602
- if (!isRecord(value)) {
603
- throw new Error(`bivium config: suites.${name} must be an object`);
604
- }
605
- const at = `suites.${name}.`;
606
- const tests = field(value, "tests", isGlobs, at, "a glob or a list of globs");
607
- if (tests === undefined || tests.length === 0) {
608
- throw new Error(`bivium config: suite ${name} has no tests`);
609
- }
610
- const globs = "a glob or a list of globs";
611
- return {
612
- tests,
613
- ...optional("run", field(value, "run", isString, at, "a command")),
614
- ...optional("root", paths(value, "root", at)),
615
- ...optional("urls", field(value, "urls", isGlobsRecord, at, "a map of URL patterns")),
616
- ...optional("pages", field(value, "pages", isGlobs, at, globs)),
617
- ...optional("wiring", field(value, "wiring", isGlobs, at, globs)),
618
- ...optional("setup", field(value, "setup", isGlobs, at, globs)),
619
- ...optional("nonInputs", field(value, "nonInputs", isGlobs, at, globs)),
620
- ...optional("output", field(value, "output", isString, at, "an output name")),
621
- ...optional("types", field(value, "types", isBoolean, at, "a boolean"))
622
367
  };
623
- }
624
- var WILDCARD = /[*?{}[\]]/;
625
- function paths(record, key, at) {
626
- const value = field(record, key, isGlobs, at, "a path or a list of paths");
627
- for (const path of typeof value === "string" ? [value] : value ?? []) {
628
- const wildcard = WILDCARD.exec(path);
629
- if (!wildcard)
630
- continue;
631
- const prefix = normalizeRoot(path.slice(0, wildcard.index));
632
- throw new Error(`bivium config: ${at}${key} takes paths, not globs: "${path}" (the directory is "${prefix}")`);
633
- }
634
- return value;
635
- }
636
- function isResult(value) {
637
- if (!isRecord(value))
638
- return false;
639
- if ("all" in value)
640
- return typeof value.all === "string";
641
- return "seeds" in value && isStrings(value.seeds) && (!("note" in value) || typeof value.note === "string");
642
- }
643
- function checkResult(value) {
644
- if (isResult(value))
645
- return value;
646
- throw new Error("returned neither { seeds: string[] } nor { all: string }");
647
- }
648
- function checkNarrower(value, at) {
649
- if (!isRecord(value)) {
650
- throw new Error(`bivium config: ${at} must be an object`);
651
- }
652
- const name = field(value, "name", isString, `${at}.`, "a string");
653
- const match = field(value, "match", isGlobs, `${at}.`, "globs");
654
- const opaque = field(value, "opaque", isGlobs, `${at}.`, "globs");
655
- const suites = field(value, "suites", isStrings, `${at}.`, "suite names");
656
- const { narrow } = value;
657
- if (name === undefined || match === undefined || opaque === undefined) {
658
- throw new Error(`bivium config: ${at} needs a name, match and opaque`);
659
- }
660
- if (typeof narrow !== "function") {
661
- throw new Error(`bivium config: ${at}.narrow must be a function`);
662
- }
663
- return {
664
- name,
665
- match,
666
- opaque,
667
- ...optional("suites", suites),
668
- narrow: async (context) => {
669
- const result = await Reflect.apply(narrow, value, [context]);
670
- return checkResult(result);
368
+ const inPackage = (dir, path) => dir === "." ? path : posix.join(dir, path);
369
+ const resolveLocal = (dir, json, subpath) => {
370
+ if (json.exports !== undefined) {
371
+ const list = exportTargets(json.exports, subpath);
372
+ return [
373
+ ...new Set((list ?? []).flatMap((target) => exact(inPackage(dir, posix.normalize(target)))))
374
+ ];
375
+ }
376
+ if (subpath === ".") {
377
+ return probe(inPackage(dir, posix.normalize(json.main ?? "index")));
671
378
  }
379
+ return probe(inPackage(dir, subpath.slice(2)));
672
380
  };
673
- }
674
- function checkDeadGlob(value, at) {
675
- if (!isRecord(value)) {
676
- throw new Error(`bivium config: ${at} must be an object`);
677
- }
678
- const file = field(value, "file", isString, `${at}.`, "a path");
679
- const glob = field(value, "glob", isString, `${at}.`, "a glob");
680
- const reason = field(value, "reason", isString, `${at}.`, "a string");
681
- if (!(file && glob && reason)) {
682
- throw new Error(`bivium config: ${at} needs a file, glob and reason`);
683
- }
684
- return { file, glob, reason };
685
- }
686
- function checkKnownUnknown(value, at) {
687
- if (!isRecord(value)) {
688
- throw new Error(`bivium config: ${at} must be an object`);
689
- }
690
- const file = field(value, "file", isString, `${at}.`, "a path");
691
- const reason = field(value, "reason", isString, `${at}.`, "a string");
692
- if (!(file && reason)) {
693
- throw new Error(`bivium config: ${at} needs a file and reason`);
694
- }
695
- return { file, reason };
696
- }
697
- function checkCaptures(name, record) {
698
- for (const [key, globs] of Object.entries(record ?? {})) {
699
- const { wildcards } = captureGlob(key);
700
- for (const value of list(globs, [])) {
701
- const bad = captureReferences(value).find((n) => n < 1 || n > wildcards);
702
- if (bad === undefined)
381
+ const resolveImport = (scope, bare) => {
382
+ const { owning } = scope;
383
+ const imports = owning?.[1].imports;
384
+ const list = owning && imports && mapTargets(imports, bare);
385
+ if (!list)
386
+ return;
387
+ const found = [];
388
+ let pkg;
389
+ for (const target of list) {
390
+ if (target.startsWith("./")) {
391
+ for (const path of exact(inPackage(owning[0], posix.normalize(target)))) {
392
+ if (!found.includes(path))
393
+ found.push(path);
394
+ }
703
395
  continue;
704
- const has = `${wildcards} ${wildcards === 1 ? "wildcard" : "wildcards"}`;
705
- const why = bad < 1 ? "captures count from $1" : `its key has ${has}`;
706
- throw new Error(`bivium config: ${name}["${key}"] refers to $${bad} in ${value}, but ${why}`);
396
+ }
397
+ if (INVALID_IMPORT_TARGET.test(target))
398
+ continue;
399
+ const specifier = target.replace(QUERY, "");
400
+ const resolved = specifier === "" ? undefined : resolveBare(scope, specifier);
401
+ if (resolved === undefined)
402
+ return;
403
+ if ("pkg" in resolved)
404
+ pkg ??= resolved.pkg;
405
+ else {
406
+ for (const file of resolved.files) {
407
+ if (!found.includes(file))
408
+ found.push(file);
409
+ }
410
+ }
707
411
  }
708
- }
709
- }
710
- function checkConfig(value) {
711
- if (!isRecord(value))
712
- throw new Error("bivium config: not an object");
713
- if (!isRecord(value.suites)) {
714
- throw new Error("bivium config: suites must be an object");
715
- }
716
- const unknown = unknownKeys(value);
717
- if (unknown.length === 1) {
718
- throw new Error(`bivium config: unknown key ${unknown[0]}`);
719
- }
720
- if (unknown.length > 1) {
721
- throw new Error(`bivium config: unknown keys:
722
- ${unknown.map((key) => ` ${key}`).join(`
723
- `)}`);
724
- }
725
- const { narrowers, deadGlobs, knownUnknowns } = value;
726
- if (narrowers !== undefined && !Array.isArray(narrowers)) {
727
- throw new Error("bivium config: narrowers must be a list");
728
- }
729
- if (deadGlobs !== undefined && !Array.isArray(deadGlobs)) {
730
- throw new Error("bivium config: deadGlobs must be a list");
731
- }
732
- if (knownUnknowns !== undefined && !Array.isArray(knownUnknowns)) {
733
- throw new Error("bivium config: knownUnknowns must be a list");
734
- }
735
- const suites = {};
736
- for (const [name, suite] of Object.entries(value.suites)) {
737
- suites[name] = checkSuite(name, suite);
738
- }
739
- const globs = "a glob or a list of globs";
740
- const edges = field(value, "edges", isGlobsRecord, "", "a map of globs");
741
- const reads = field(value, "reads", isGlobsRecord, "", "a map of globs");
742
- checkCaptures("edges", edges);
743
- checkCaptures("reads", reads);
744
- return {
745
- suites,
746
- ...optional("narrowers", narrowers?.map((narrower, i) => checkNarrower(narrower, `narrowers[${i}]`))),
747
- ...optional("roots", paths(value, "roots", "")),
748
- ...optional("ignore", field(value, "ignore", isGlobs, "", globs)),
749
- ...optional("alias", field(value, "alias", isStringRecord, "", "a map of paths")),
750
- ...optional("edges", edges),
751
- ...optional("reads", reads),
752
- ...optional("self", field(value, "self", isGlobs, "", globs)),
753
- ...optional("importOnly", field(value, "importOnly", isGlobs, "", globs)),
754
- ...optional("hermetic", field(value, "hermetic", isGlobs, "", globs)),
755
- ...optional("barrels", field(value, "barrels", isGlobs, "", globs)),
756
- ...optional("external", field(value, "external", isStrings, "", "a list of packages")),
757
- ...optional("inert", field(value, "inert", isGlobs, "", globs)),
758
- ...optional("loadedByName", field(value, "loadedByName", isGlobs, "", globs)),
759
- ...optional("extensions", field(value, "extensions", isStrings, "", "a list")),
760
- ...optional("deadGlobs", deadGlobs?.map((entry, i) => checkDeadGlob(entry, `deadGlobs[${i}]`))),
761
- ...optional("knownUnknowns", knownUnknowns?.map((entry, i) => checkKnownUnknown(entry, `knownUnknowns[${i}]`))),
762
- ...optional("base", field(value, "base", isString, "", "a ref")),
763
- ...optional("cache", field(value, "cache", isCache, "", "a directory or a boolean"))
412
+ if (found.length > 0)
413
+ return { files: found };
414
+ return pkg === undefined ? undefined : { pkg };
764
415
  };
765
- }
766
- var CONFIG_FILES = [
767
- "bivium.config.ts",
768
- "bivium.config.mts",
769
- "bivium.config.mjs",
770
- "bivium.config.js",
771
- "bivium.config.json"
772
- ];
773
- async function readConfig(file) {
774
- if (file.endsWith(".json"))
775
- return JSON.parse(readFileSync(file, "utf-8"));
776
- const module = await import(pathToFileURL(file).href);
777
- return isRecord(module) ? module.default : undefined;
778
- }
779
- var CONFIG_PREFIX = /^bivium config: /;
780
- async function loadConfig(root, path) {
781
- const file = path === undefined ? CONFIG_FILES.map((name) => join2(root, name)).find((f) => existsSync2(f)) : resolve(process.cwd(), path);
782
- if (!file || !existsSync2(file)) {
783
- throw new BiviumError2("BV_CONFIG_NOT_FOUND", path ? `bivium: no config found at ${path}` : `bivium: no config found in ${root}: looked for ${CONFIG_FILES.join(", ")} (--config names another file, --cwd another repository)`);
784
- }
785
- const inside = relative(root, file);
786
- const shown = inside.startsWith("..") || isAbsolute2(inside) ? file : inside;
787
- const named = (code, error) => {
788
- const message = error instanceof Error ? error.message : String(error);
789
- return new BiviumError2(code, `bivium config: ${shown}: ${message.replace(CONFIG_PREFIX, "")}`, { cause: error });
416
+ const resolveRelative = (fromDir, bare) => {
417
+ if (bare.startsWith(SVELTEKIT_ASSETS)) {
418
+ const rest = bare.slice(SVELTEKIT_ASSETS.length);
419
+ const found = probe(posix.join(svelteKitRoot(fromDir), "static", rest));
420
+ return found.length > 0 ? { files: found } : undefined;
421
+ }
422
+ const found = probe(posix.join(fromDir, bare).replace(/(.)\/+$/, "$1"));
423
+ return found.length > 0 ? { files: found } : undefined;
424
+ };
425
+ const resolveBare = (scope, bare) => {
426
+ for (const alias of config.alias) {
427
+ const path = aliasPath(alias, bare);
428
+ if (path === undefined)
429
+ continue;
430
+ const found = probe(path);
431
+ if (found.length > 0)
432
+ return { files: found };
433
+ }
434
+ const { ts } = scope;
435
+ const mapped = ts && mapTargets(ts.paths, bare);
436
+ if (mapped) {
437
+ const found = [
438
+ ...new Set(mapped.flatMap((path) => probe(posix.normalize(path))))
439
+ ];
440
+ if (found.length > 0)
441
+ return { files: found };
442
+ }
443
+ if (bare.startsWith("#"))
444
+ return resolveImport(scope, bare);
445
+ const name = packageName(bare);
446
+ const dir = local.get(name);
447
+ if (dir !== undefined) {
448
+ const subpath = `.${bare.slice(name.length)}`;
449
+ const found = resolveLocal(dir, packages.get(dir) ?? {}, subpath);
450
+ return found.length > 0 ? { files: found } : undefined;
451
+ }
452
+ if (ts?.baseUrl !== undefined) {
453
+ const found = probe(posix.join(ts.baseUrl, bare), true);
454
+ if (found.length > 0)
455
+ return { files: found };
456
+ }
457
+ const node = builtin(bare);
458
+ if (node)
459
+ return { pkg: node };
460
+ if (scope.declared.has(name) || config.external.has(name)) {
461
+ return { pkg: name };
462
+ }
463
+ return;
464
+ };
465
+ const dirs = new Map;
466
+ const directoryOf = (from) => {
467
+ const dir = posix.dirname(from);
468
+ let found = dirs.get(dir);
469
+ if (!found) {
470
+ found = { dir, relative: new Map, scope: scopeOf(from) };
471
+ dirs.set(dir, found);
472
+ }
473
+ return found;
474
+ };
475
+ let lastFrom;
476
+ let last;
477
+ return (from, specifier) => {
478
+ if (from !== lastFrom || !last) {
479
+ lastFrom = from;
480
+ last = directoryOf(from);
481
+ }
482
+ const { dir, relative, scope } = last;
483
+ const hash = specifier.startsWith("#") ? "#" : "";
484
+ const isRelative = RELATIVE.test(specifier);
485
+ const memo = isRelative ? relative : scope.resolved;
486
+ if (memo.has(specifier))
487
+ return memo.get(specifier);
488
+ const bare = hash + specifier.slice(hash.length).replace(QUERY, "");
489
+ let resolved;
490
+ if (bare !== "" && bare !== "#") {
491
+ resolved = isRelative ? resolveRelative(dir, bare) : resolveBare(scope, bare);
492
+ }
493
+ memo.set(specifier, resolved);
494
+ return resolved;
790
495
  };
791
- let raw;
792
- try {
793
- raw = await readConfig(file);
794
- } catch (error) {
795
- throw named("BV_CONFIG_UNREADABLE", error);
796
- }
797
- let config;
798
- try {
799
- config = resolveConfig(checkConfig(raw));
800
- } catch (error) {
801
- throw named("BV_CONFIG_INVALID", error);
802
- }
803
- return { config, file: shown };
804
496
  }
805
497
 
806
- // src/git.ts
807
- import { spawn } from "node:child_process";
808
- import { readFile as readFile2 } from "node:fs/promises";
809
- import { join as join3 } from "node:path";
498
+ // src/scan.ts
499
+ import { posix as posix2 } from "node:path";
810
500
 
811
- // src/sorted.ts
812
- function byCodeUnit(a, b) {
813
- if (a === b)
814
- return 0;
815
- return a < b ? -1 : 1;
816
- }
817
- function sorted(values) {
818
- return [...values].sort(byCodeUnit);
501
+ // src/lex.ts
502
+ function createLexed() {
503
+ return {
504
+ imports: [],
505
+ globs: [],
506
+ gotos: [],
507
+ dependsOn: [],
508
+ reads: [],
509
+ lists: [],
510
+ registry: false,
511
+ nonLiteralImport: false,
512
+ nonLiteralGlob: false,
513
+ readsDisk: false
514
+ };
819
515
  }
820
516
 
821
- // src/git.ts
822
- function git(cwd, ...args) {
823
- return new Promise((resolve, reject) => {
824
- const child = spawn("git", args, { cwd });
825
- const chunks = [];
826
- const errors = [];
827
- child.stdout.on("data", (chunk) => chunks.push(chunk));
828
- child.stderr.on("data", (chunk) => errors.push(chunk));
829
- child.on("error", reject);
830
- child.on("close", (status) => {
831
- resolve({
832
- status: status ?? 1,
833
- stdout: Buffer.concat(chunks).toString("utf-8"),
834
- stderr: Buffer.concat(errors).toString("utf-8")
835
- });
836
- });
837
- });
517
+ class LexError extends Error {
838
518
  }
839
- async function gitOrThrow(cwd, ...args) {
840
- const result = await git(cwd, ...args);
841
- if (result.status !== 0) {
842
- const said = result.stderr.trim().split(`
843
- `)[0];
844
- throw new BiviumError2("BV_GIT_FAILED", `bivium: git ${args.join(" ")} failed${said ? `: ${said}` : ""}`);
845
- }
846
- return result.stdout;
519
+ var TS = { jsx: false, tsx: false };
520
+ var JS = { jsx: true, tsx: false };
521
+ var TSX = { jsx: true, tsx: true };
522
+ var JS_FILE = /\.[cm]?jsx?$/;
523
+ function dialectOf(path) {
524
+ if (path.endsWith(".tsx"))
525
+ return TSX;
526
+ if (JS_FILE.test(path))
527
+ return JS;
528
+ return TS;
847
529
  }
848
- function lines(output) {
849
- return output.split(`
850
- `).filter(Boolean);
530
+ var T_START = 0;
531
+ var T_PUNCT = 1;
532
+ var T_OPERAND = 2;
533
+ var T_IDENT = 3;
534
+ var T_DOT = 4;
535
+ var T_CLOSE_PAREN = 5;
536
+ var T_CLOSE_KW = 6;
537
+ var T_CLOSE_BLOCK = 7;
538
+ var T_ARROW = 8;
539
+ var T_SEMI = 9;
540
+ var T_LBRACE = 10;
541
+ var M_PAREN = 0;
542
+ var M_PAREN_KW = 1;
543
+ var M_BRACKET = 2;
544
+ var M_BLOCK = 3;
545
+ var M_EXPR = 4;
546
+ var M_TEMPLATE = 5;
547
+ var DISK = new Set([
548
+ "fs",
549
+ "node:fs",
550
+ "fs/promises",
551
+ "node:fs/promises",
552
+ "child_process",
553
+ "node:child_process"
554
+ ]);
555
+ var VI_CALLS = new Set([
556
+ "mock",
557
+ "doMock",
558
+ "unmock",
559
+ "importActual",
560
+ "importMock"
561
+ ]);
562
+ var CALL_IMPORT = 0;
563
+ var CALL_PROPERTY = 1;
564
+ var CALL_MOCK = 2;
565
+ var CALL_ACTUAL = 3;
566
+ var src = "";
567
+ var end = 0;
568
+ var out = createLexed();
569
+ var dialect = TS;
570
+ var nextAt = -1;
571
+ var nextImport = -1;
572
+ var LS = String.fromCharCode(8232);
573
+ var PS = String.fromCharCode(8233);
574
+ var oddLines = false;
575
+ var templateOpen = false;
576
+ function fail(message, at) {
577
+ throw new LexError(`${message} at ${at}`);
851
578
  }
852
- var INDEX_ENTRY = /^(\S) (\d{6}) ([0-9a-f]+) (\d)\t(.*)$/;
853
- var RAW_ENTRY = /^:(\d{6}) \d{6} ([0-9a-f]+) [0-9a-f]+ ([A-Z])\d*\t(.*)$/;
854
- async function missingHistory(cwd, base) {
855
- const [known, forked, shallow] = await Promise.all([
856
- git(cwd, "rev-parse", "--verify", "--quiet", `${base}^{commit}`),
857
- git(cwd, "merge-base", base, "HEAD"),
858
- git(cwd, "rev-parse", "--is-shallow-repository")
859
- ]);
860
- const fix = shallow.stdout.trim() === "true" ? " The clone is shallow: fetch the history (actions/checkout: `fetch-depth: 0`)." : "";
861
- if (known.status !== 0) {
862
- return new BiviumError2("BV_GIT_NO_BASE", `bivium: no commit ${base} here to diff against: fetch it.${fix}`);
579
+ function openFile(source, sink) {
580
+ src = source;
581
+ out = sink;
582
+ nextAt = -1;
583
+ nextImport = -1;
584
+ oddLines = source.includes("\r") || source.includes(LS) || source.includes(PS);
585
+ }
586
+ function lexRange(start, stop, language = TS) {
587
+ dialect = language;
588
+ end = stop;
589
+ let i = start;
590
+ if (src.charCodeAt(i) === 65279)
591
+ i++;
592
+ if (src.charCodeAt(i) === 35 && src.charCodeAt(i + 1) === 33) {
593
+ i = lineEnd(i);
863
594
  }
864
- if (forked.status !== 0) {
865
- return new BiviumError2("BV_GIT_NO_MERGE_BASE", `bivium: ${base} and HEAD share no commit here, so there's no merge base to diff against.${fix}`);
595
+ code(i, false);
596
+ }
597
+ function lexExpression(start, stop) {
598
+ dialect = TS;
599
+ end = stop;
600
+ return code(start, true);
601
+ }
602
+ function isUnicodeSpace(c) {
603
+ return c === 160 || c === 65279 || c === 5760 || c >= 8192 && c <= 8202 || c === 8232 || c === 8233 || c === 8239 || c === 8287 || c === 12288;
604
+ }
605
+ var IDENT = new Uint8Array(128);
606
+ for (let c = 0;c < 128; c++) {
607
+ const letter = c >= 97 && c <= 122 || c >= 65 && c <= 90 || c === 36 || c === 95;
608
+ if (letter)
609
+ IDENT[c] = 3;
610
+ else if (c >= 48 && c <= 57)
611
+ IDENT[c] = 2;
612
+ }
613
+ function isIdentStart(c) {
614
+ return c < 128 ? ((IDENT[c] ?? 0) & 1) !== 0 : c >= 128 && !isUnicodeSpace(c);
615
+ }
616
+ function isIdentPart(c) {
617
+ return c < 128 ? IDENT[c] !== 0 : c >= 128 && !isUnicodeSpace(c);
618
+ }
619
+ function identEnd(start) {
620
+ let i = start;
621
+ const s = src;
622
+ const n = end;
623
+ while (i < n) {
624
+ const c = s.charCodeAt(i);
625
+ if (c < 128 ? IDENT[c] === 0 : isUnicodeSpace(c))
626
+ break;
627
+ i++;
866
628
  }
867
- return;
629
+ return i;
868
630
  }
869
- function mergeBaseOf(cwd, base) {
870
- let pending;
871
- return () => {
872
- if (pending === undefined) {
873
- pending = gitOrThrow(cwd, "merge-base", base, "HEAD").then((out) => out.trim());
874
- pending.catch(() => {
875
- return;
876
- });
877
- }
878
- return pending;
879
- };
631
+ function isWord(i, word) {
632
+ return i + word.length <= end && src.startsWith(word, i) && !isIdentPart(src.charCodeAt(i + word.length));
880
633
  }
881
- async function readRevision(cwd, base, roots, {
882
- blobs = false,
883
- mergeBase: eager = false
884
- } = {}) {
885
- const mergeBase = mergeBaseOf(cwd, base);
886
- if (eager)
887
- mergeBase();
888
- const diffArgs = ["--no-renames", "--merge-base", base];
889
- const [listing, diff, staged] = await Promise.all([
890
- gitOrThrow(cwd, "ls-files", "-s", "-v", "-o", "--exclude-standard"),
891
- gitOrThrow(cwd, "diff", "--raw", "--no-abbrev", ...diffArgs),
892
- gitOrThrow(cwd, "diff", "--cached", "--name-only", ...diffArgs)
893
- ]).catch(async (error) => {
894
- throw await missingHistory(cwd, base) ?? error;
895
- });
896
- const entries = lines(listing);
897
- const untracked = [];
898
- for (const line of entries) {
899
- if (line.startsWith("? "))
900
- untracked.push(line.slice(2));
634
+ function lineEnd(start) {
635
+ let i = start;
636
+ if (oddLines) {
637
+ while (i < end) {
638
+ const c = src.charCodeAt(i);
639
+ if (c === 10 || c === 13 || c === 8232 || c === 8233)
640
+ return i;
641
+ i++;
642
+ }
643
+ return end;
901
644
  }
902
- const before = new Map;
903
- const diffed = [];
904
- const layout = new Set(untracked);
905
- for (const line of lines(diff)) {
906
- const [, mode, oid, status, path] = RAW_ENTRY.exec(line) ?? [];
907
- if (mode === undefined || oid === undefined || status === undefined || path === undefined) {
908
- throw new Error(`git diff: unexpected line ${line}`);
645
+ const e = src.indexOf(`
646
+ `, i);
647
+ return e === -1 || e > end ? end : e;
648
+ }
649
+ function skipTrivia(start) {
650
+ let i = start;
651
+ while (i < end) {
652
+ const c = src.charCodeAt(i);
653
+ if (c === 32 || c >= 9 && c <= 13 || c >= 128 && isUnicodeSpace(c)) {
654
+ i++;
655
+ } else if (c === 47 && src.charCodeAt(i + 1) === 47) {
656
+ i = lineEnd(i + 2);
657
+ } else if (c === 47 && src.charCodeAt(i + 1) === 42) {
658
+ const e = src.indexOf("*/", i + 2);
659
+ if (e === -1 || e + 2 > end)
660
+ return end;
661
+ i = e + 2;
662
+ } else {
663
+ break;
909
664
  }
910
- diffed.push(path);
911
- if (status === "A" || status === "D")
912
- layout.add(path);
913
- if (status === "A")
914
- before.set(path, undefined);
915
- else if ("MTD".includes(status) && mode !== "160000") {
916
- before.set(path, oid);
665
+ }
666
+ return i;
667
+ }
668
+ function stringEnd(i) {
669
+ const quote = src.charCodeAt(i);
670
+ let j = i + 1;
671
+ while (j < end) {
672
+ const c = src.charCodeAt(j);
673
+ if (c === quote)
674
+ return j + 1;
675
+ if (c === 92) {
676
+ j += src.charCodeAt(j + 1) === 13 && src.charCodeAt(j + 2) === 10 ? 3 : 2;
677
+ continue;
917
678
  }
679
+ if (c === 10 || c === 13)
680
+ return -1;
681
+ j++;
918
682
  }
919
- const reads = new Map;
920
- const readBase = (path) => {
921
- let read = reads.get(path);
922
- if (read === undefined) {
923
- read = readBaseOnce(path);
924
- reads.set(path, read);
683
+ return -1;
684
+ }
685
+ function template(start) {
686
+ let j = start;
687
+ while (j < end) {
688
+ const c = src.charCodeAt(j);
689
+ if (c === 96) {
690
+ templateOpen = false;
691
+ return j + 1;
925
692
  }
926
- return read;
927
- };
928
- const readBaseOnce = (path) => {
929
- if (!before.has(path)) {
930
- if (present.has(path)) {
931
- return readFile2(join3(cwd, path), "utf-8").catch(() => mergeBase().then((commit) => show(cwd, `${commit}:${path}`)));
932
- }
933
- return mergeBase().then((commit) => show(cwd, `${commit}:${path}`));
934
- }
935
- const oid = before.get(path);
936
- return oid === undefined ? Promise.resolve(undefined) : show(cwd, oid);
937
- };
938
- const changed = [...new Set([...diffed, ...untracked])];
939
- const dirty = new Set([...changed, ...lines(staged)]);
940
- const underRoots = (path) => roots.some((root) => inRoot(path, root));
941
- const files = new Set;
942
- const tracked = new Set;
943
- const present = new Set;
944
- const oids = new Map;
945
- for (const line of entries) {
946
- const entry = INDEX_ENTRY.exec(line);
947
- if (!entry) {
948
- if (line.startsWith("? ") && underRoots(line.slice(2))) {
949
- files.add(line.slice(2));
950
- }
693
+ if (c === 92) {
694
+ j += 2;
951
695
  continue;
952
696
  }
953
- const [, tag, mode, oid, stage, path] = entry;
954
- if (tag === undefined || mode === undefined || oid === undefined || stage === undefined || path === undefined) {
955
- throw new Error(`bivium: git: unexpected ls-files line ${line}.`);
697
+ if (c === 36 && src.charCodeAt(j + 1) === 123) {
698
+ templateOpen = true;
699
+ return j + 2;
956
700
  }
957
- tracked.add(path);
958
- if (mode === "160000" || !underRoots(path))
959
- continue;
960
- files.add(path);
961
- if (dirty.has(path) || stage !== "0" || tag !== "H")
962
- continue;
963
- if (mode !== "100644" && mode !== "100755")
964
- continue;
965
- present.add(path);
966
- if (blobs)
967
- oids.set(path, oid);
701
+ j++;
968
702
  }
969
- return {
970
- files: sorted(files),
971
- listed: [...tracked, ...untracked],
972
- changed,
973
- layout,
974
- mergeBase,
975
- readBase,
976
- blobs: oids,
977
- present
978
- };
979
- }
980
- async function show(cwd, object) {
981
- const result = await git(cwd, "show", object);
982
- return result.status === 0 ? result.stdout : undefined;
983
- }
984
- async function defaultBase(cwd) {
985
- const head = await git(cwd, "symbolic-ref", "--short", "refs/remotes/origin/HEAD");
986
- if (head.status === 0 && head.stdout.trim())
987
- return head.stdout.trim();
988
- const refs = ["origin/main", "origin/master", "main", "master"];
989
- const found = await Promise.all(refs.map((ref) => git(cwd, "rev-parse", "--verify", "--quiet", ref)));
990
- const branch = refs[found.findIndex((result) => result.status === 0)];
991
- if (branch)
992
- return branch;
993
- throw new BiviumError2("BV_GIT_NO_BASE", `bivium: no base given and no default branch found (tried origin/HEAD, ${refs.join(", ")}): pass one, as in \`bivium plan origin/main\`, or set base in the config`);
703
+ return fail("unterminated template", j);
994
704
  }
995
-
996
- // src/barrel.ts
997
- var COMMENTS = /\/\/.*$|\/\*[\s\S]*?\*\//gm;
998
- var AS = /\s+as\s+/;
999
- var TYPE_PREFIX = /^type\s+/;
1000
- var NAMED_EXPORT = /export\s+(?:type\s+)?\{([^}]*)\}\s*from\s*["']([^"']+)["']\s*;?/g;
1001
- var STAR_EXPORT = /export\s+(?:type\s+)?\*(?:\s+as\s+([\w$]+))?\s+from\s*["']([^"']+)["']\s*;?/g;
1002
- var BARREL_FILE = /\.[cm]?[jt]sx?$/;
1003
- var ONLY_SEPARATORS = /^[\s;]*$/;
1004
- var STARTS_WITH_EXPORT = /^(?:\s+|\/\/[^\n]*|\/\*[\s\S]*?\*\/)*export\b/;
1005
- function parseBarrel(path, source) {
1006
- return BARREL_FILE.test(path) ? parseReExports(source) : undefined;
705
+ function templatePart(start, stack) {
706
+ const e = template(start);
707
+ if (out.strings && !stack.includes(M_BRACKET)) {
708
+ out.strings.push(src.slice(start, templateOpen ? e - 2 : e - 1));
709
+ }
710
+ return e;
1007
711
  }
1008
- function parseReExports(source) {
1009
- if (!STARTS_WITH_EXPORT.test(source))
1010
- return;
1011
- const code = source.replace(COMMENTS, "");
1012
- const barrel = { names: new Map, stars: [] };
1013
- let rest = code.replace(NAMED_EXPORT, (_, list, from) => {
1014
- for (const part of list.split(",")) {
1015
- const name = part.trim().replace(TYPE_PREFIX, "").split(AS).pop();
1016
- if (name)
1017
- barrel.names.set(name, from);
712
+ function regex(i) {
713
+ let j = i + 1;
714
+ let inClass = false;
715
+ for (;; ) {
716
+ if (j >= end)
717
+ fail("unterminated regex", i);
718
+ const c = src.charCodeAt(j);
719
+ if (c === 92) {
720
+ j += 2;
721
+ continue;
1018
722
  }
1019
- return "";
1020
- });
1021
- rest = rest.replace(STAR_EXPORT, (_, name, from) => {
1022
- if (name)
1023
- barrel.names.set(name, from);
1024
- else
1025
- barrel.stars.push(from);
1026
- return "";
1027
- });
1028
- if (barrel.names.size + barrel.stars.length === 0)
1029
- return;
1030
- return ONLY_SEPARATORS.test(rest) ? barrel : undefined;
723
+ if (c === 10 || c === 13)
724
+ fail("unterminated regex", i);
725
+ if (inClass) {
726
+ if (c === 93)
727
+ inClass = false;
728
+ } else if (c === 47) {
729
+ break;
730
+ } else if (c === 91) {
731
+ inClass = true;
732
+ }
733
+ j++;
734
+ }
735
+ return identEnd(j + 1);
1031
736
  }
1032
-
1033
- // src/resolve.ts
1034
- import { builtinModules } from "node:module";
1035
- import { posix } from "node:path";
1036
-
1037
- // src/syntax.ts
1038
- var QUERY = /[?#].*$/;
1039
- var UNDECLARED_READS = "reads the disk without @depends-on";
1040
- var RELATIVE = /^\.\.?(?:\/|$)/;
1041
- var URL_REF = /^[a-z]+:|^\/\//;
1042
- var LIST_SEPARATOR = /[\s,]+(?![^{]*\})/;
1043
- var DEPENDS_ON = /^\s*(?:\/\/|\/?\*+)\s*@depends-on\s+(.+?)\s*(?:\*\/)?\s*$/gm;
1044
- var READS = /^\s*(?:\/\/|\/?\*+)\s*@reads\s+(.+?)\s*(?:\*\/)?\s*$/gm;
1045
- var LISTS = /^\s*(?:\/\/|\/?\*+)\s*@lists\s+(.+?)\s*(?:\*\/)?\s*$/gm;
1046
- var GLOB_REGISTRY = /^\s*(?:\/\/|\/?\*+)\s*@glob-registry\b/m;
1047
- var AS2 = /\s+as\s+/;
1048
- var TYPE_PREFIX2 = /^type\s+/;
1049
- var NAMED_CLAUSE = /\{([^}]*)\}/;
1050
- var DEFAULT_OR_NAMESPACE = /^\s*[\w$*]/;
1051
- function namedBindings(clause) {
1052
- const named = NAMED_CLAUSE.exec(clause);
1053
- if (!named || DEFAULT_OR_NAMESPACE.test(clause.replace(NAMED_CLAUSE, ""))) {
1054
- return;
737
+ function isOneOf(start, stop, words) {
738
+ const [first] = words;
739
+ if (first === undefined || stop - start !== first.length)
740
+ return false;
741
+ const c = src.charCodeAt(start);
742
+ for (const word of words) {
743
+ if (word.charCodeAt(0) === c && src.startsWith(word, start))
744
+ return true;
1055
745
  }
1056
- return captured(named, 1).split(",").map((part) => (part.trim().replace(TYPE_PREFIX2, "").split(AS2)[0] ?? "").trim()).filter(Boolean);
746
+ return false;
1057
747
  }
1058
- function captured(match, index) {
1059
- const value = match[index];
1060
- if (value === undefined) {
1061
- throw new Error(`bivium: scan: group ${index} of ${match[0]} is unset.`);
748
+ var EXPRESSION_KEYWORDS = [];
749
+ var PAREN_KEYWORDS = [];
750
+ var BLOCK_KEYWORDS = [];
751
+ function byLength(table, words) {
752
+ for (const word of words) {
753
+ table[word.length] = [...table[word.length] ?? [], word];
1062
754
  }
1063
- return value;
1064
755
  }
1065
-
1066
- // src/resolve.ts
1067
- function isRecord2(value) {
1068
- return typeof value === "object" && value !== null && !Array.isArray(value);
756
+ byLength(EXPRESSION_KEYWORDS, [
757
+ ...["in", "do", "new", "case", "else", "void", "throw", "yield"],
758
+ ...["await", "return", "typeof", "delete", "default", "instanceof"]
759
+ ]);
760
+ byLength(PAREN_KEYWORDS, ["if", "for", "with", "while"]);
761
+ byLength(BLOCK_KEYWORDS, ["do", "try", "else", "finally"]);
762
+ function isKeyword(table, start, stop) {
763
+ const words = table[stop - start];
764
+ return words !== undefined && isOneOf(start, stop, words);
1069
765
  }
1070
- function isStringRecord2(value) {
1071
- return isRecord2(value) && Object.values(value).every((item) => typeof item === "string");
766
+ function isExpressionKeyword(start, stop) {
767
+ return isKeyword(EXPRESSION_KEYWORDS, start, stop);
1072
768
  }
1073
- function toPackageJson(value) {
1074
- if (!isRecord2(value))
1075
- return {};
1076
- const json = {};
1077
- if (typeof value.name === "string")
1078
- json.name = value.name;
1079
- if (value.exports !== undefined)
1080
- json.exports = value.exports;
1081
- if (isRecord2(value.imports))
1082
- json.imports = value.imports;
1083
- if (typeof value.main === "string")
1084
- json.main = value.main;
1085
- const { sideEffects } = value;
1086
- if (typeof sideEffects === "boolean" || Array.isArray(sideEffects) && sideEffects.every((glob) => typeof glob === "string")) {
1087
- json.sideEffects = sideEffects;
1088
- }
1089
- for (const field of DEP_FIELDS) {
1090
- const deps = value[field];
1091
- if (isStringRecord2(deps))
1092
- json[field] = deps;
1093
- }
1094
- return json;
769
+ function valueEnded(last, wordStart, wordEnd, wordIsProperty) {
770
+ return last === T_OPERAND || last === T_CLOSE_PAREN || last === T_IDENT && (wordIsProperty || !isExpressionKeyword(wordStart, wordEnd));
1095
771
  }
1096
- var BUILTINS = new Set(builtinModules);
1097
- var RUNTIME_BUILTIN = /^(?:node:|bun(?:$|:))/;
1098
- var JS_EXTENSION = /\.(?:js|jsx|mjs|cjs)$/;
1099
- var TS_SOURCES = {
1100
- ".js": [".ts", ".tsx", ".d.ts"],
1101
- ".jsx": [".tsx", ".ts", ".d.ts"],
1102
- ".mjs": [".mts", ".d.mts"],
1103
- ".cjs": [".cts", ".d.cts"]
1104
- };
1105
- var NODE_PREFIX = /^node:/;
1106
- var INVALID_IMPORT_TARGET = /^[./#]/;
1107
- var SVELTEKIT_ASSETS = "./%sveltekit.assets%/";
1108
- var INDEX = "/index";
1109
- var SVELTE_CONFIGS = ["js", "mjs", "cjs", "ts", "mts"].map((ext) => `svelte.config.${ext}`);
1110
- var DEP_FIELDS = [
1111
- "dependencies",
1112
- "devDependencies",
1113
- "peerDependencies",
1114
- "optionalDependencies"
1115
- ];
1116
- function packageName(specifier) {
1117
- const parts = specifier.split("/");
1118
- return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0] ?? "";
772
+ function isParenKeyword(start, stop) {
773
+ return isKeyword(PAREN_KEYWORDS, start, stop);
1119
774
  }
1120
- function builtin(specifier) {
1121
- if (RUNTIME_BUILTIN.test(specifier)) {
1122
- const name = specifier.replace(NODE_PREFIX, "");
1123
- return specifier.startsWith("bun") ? specifier : `node:${name.split("/")[0]}`;
1124
- }
1125
- const name = specifier.split("/")[0] ?? "";
1126
- return BUILTINS.has(specifier) || BUILTINS.has(name) ? `node:${name}` : undefined;
1127
- }
1128
- function targets(value, out = []) {
1129
- if (typeof value === "string")
1130
- out.push(value);
1131
- else if (Array.isArray(value))
1132
- for (const item of value)
1133
- targets(item, out);
1134
- else if (value && typeof value === "object") {
1135
- for (const item of Object.values(value))
1136
- targets(item, out);
1137
- }
1138
- return out;
1139
- }
1140
- function subpathMap(exports) {
1141
- if (typeof exports === "string" || Array.isArray(exports)) {
1142
- return { ".": exports };
1143
- }
1144
- if (!isRecord2(exports))
1145
- return;
1146
- const bySubpath = Object.keys(exports).some((key) => key.startsWith("."));
1147
- return bySubpath ? exports : { ".": exports };
1148
- }
1149
- function mapTargets(map, subpath) {
1150
- if (subpath in map && !subpath.includes("*"))
1151
- return targets(map[subpath]);
1152
- let best;
1153
- for (const key of Object.keys(map)) {
1154
- const star = key.indexOf("*");
1155
- if (star === -1)
1156
- continue;
1157
- const prefix = key.slice(0, star);
1158
- const suffix = key.slice(star + 1);
1159
- if (subpath.length >= key.length - 1 && subpath.startsWith(prefix) && subpath.endsWith(suffix) && (!best || prefix.length > best.key.indexOf("*") || prefix.length === best.key.indexOf("*") && key.length > best.key.length)) {
1160
- best = {
1161
- key,
1162
- match: subpath.slice(prefix.length, subpath.length - suffix.length)
1163
- };
1164
- }
1165
- }
1166
- if (!best)
1167
- return;
1168
- const { match } = best;
1169
- return targets(map[best.key]).map((target) => target.replaceAll("*", match));
1170
- }
1171
- function exportTargets(exports, subpath) {
1172
- const map = subpathMap(exports);
1173
- return map && mapTargets(map, subpath);
1174
- }
1175
- function byDepth(packages) {
1176
- return [...packages].sort(([a], [b]) => b.length - a.length);
1177
- }
1178
- function owner(packages, file) {
1179
- return byDepth(packages).find(([dir]) => dir === "." || file.startsWith(`${dir}/`));
1180
- }
1181
- function aliasPath([key, target], specifier) {
1182
- if (specifier !== key && !specifier.startsWith(`${key}/`))
1183
- return;
1184
- const rest = specifier.slice(key.length + 1);
1185
- if (target === ".")
1186
- return posix.normalize(rest || ".");
1187
- return posix.normalize(rest ? `${target}/${rest}` : target);
1188
- }
1189
- function createResolver({
1190
- files,
1191
- config,
1192
- packages,
1193
- tsconfigs = new Map
1194
- }) {
1195
- const generated = (path) => config.generated.some(({ pattern }) => pattern.test(path));
1196
- const { extensions } = config;
1197
- const exists = (path) => files.has(path);
1198
- const suffixed = new Map;
1199
- const indexes = new Map;
1200
- const byTail = [];
1201
- const undotted = [];
1202
- for (const [i, ext] of extensions.entries()) {
1203
- const dot = ext.lastIndexOf(".");
1204
- if (dot === -1)
1205
- undotted.push(i);
1206
- else {
1207
- const list = byTail[ext.length - dot];
1208
- if (list)
1209
- list.push(i);
1210
- else
1211
- byTail[ext.length - dot] = [i];
1212
- }
1213
- }
1214
- const addSuffixed = (i, file) => {
1215
- const ext = extensions[i];
1216
- if (ext === undefined) {
1217
- throw new Error(`bivium: resolve: no extension at index ${i}.`);
1218
- }
1219
- if (!file.endsWith(ext))
1220
- return;
1221
- const base = file.slice(0, file.length - ext.length);
1222
- const list = suffixed.get(base);
1223
- if (list)
1224
- list.push([i, file]);
1225
- else {
1226
- const created = [[i, file]];
1227
- suffixed.set(base, created);
1228
- if (base.endsWith(INDEX)) {
1229
- indexes.set(base.slice(0, -INDEX.length), created);
1230
- }
1231
- }
1232
- };
1233
- for (const file of files) {
1234
- const dot = file.lastIndexOf(".");
1235
- if (dot !== -1) {
1236
- for (const i of byTail[file.length - dot] ?? [])
1237
- addSuffixed(i, file);
1238
- }
1239
- for (const i of undotted)
1240
- addSuffixed(i, file);
1241
- }
1242
- for (const list of suffixed.values()) {
1243
- if (list.length > 1)
1244
- list.sort(([a], [b]) => a - b);
1245
- }
1246
- const deepestFirst = byDepth(packages);
1247
- const local = new Map;
1248
- for (const [dir, json] of deepestFirst) {
1249
- if (json.name && !local.has(json.name))
1250
- local.set(json.name, dir);
1251
- }
1252
- const declaredIn = (dir) => {
1253
- const names = new Set;
1254
- for (const [pkgDir, json] of deepestFirst) {
1255
- if (pkgDir !== "." && dir !== pkgDir && !dir.startsWith(`${pkgDir}/`))
1256
- continue;
1257
- for (const field of DEP_FIELDS) {
1258
- for (const name of Object.keys(json[field] ?? {}))
1259
- names.add(name);
1260
- }
1261
- }
1262
- return names;
1263
- };
1264
- const tsSources = (path) => {
1265
- const js = JS_EXTENSION.exec(path);
1266
- if (!js)
1267
- return [];
1268
- const stem = path.slice(0, js.index);
1269
- return (TS_SOURCES[js[0]] ?? []).map((ext) => stem + ext).filter((file) => generated(file) || exists(file));
1270
- };
1271
- const exact = (path) => generated(path) || exists(path) ? [path] : tsSources(path);
1272
- const probe = (base, guess = false) => {
1273
- if (generated(base))
1274
- return [base];
1275
- const found = [];
1276
- if (exists(base))
1277
- found.push(base);
1278
- for (const [, file] of suffixed.get(base) ?? [])
1279
- found.push(file);
1280
- if (found.length === 0)
1281
- found.push(...tsSources(base));
1282
- for (const [, file] of indexes.get(base) ?? [])
1283
- found.push(file);
1284
- if (found.length === 0 && !guess && config.generated.length > 0) {
1285
- for (const ext of extensions) {
1286
- if (generated(base + ext))
1287
- found.push(base + ext);
1288
- }
1289
- for (const ext of extensions) {
1290
- if (generated(`${base}/index${ext}`))
1291
- found.push(`${base}/index${ext}`);
1292
- }
1293
- }
1294
- return found;
1295
- };
1296
- const tsDeepestFirst = [...tsconfigs].sort(([a], [b]) => b.length - a.length);
1297
- const scopes = new Map;
1298
- const scopeOf = (from) => {
1299
- const contains = ([dir]) => dir === "." || from.startsWith(`${dir}/`);
1300
- const pkg = deepestFirst.findIndex(contains);
1301
- const ts = tsDeepestFirst.findIndex(contains);
1302
- const key = `${pkg} ${ts}`;
1303
- let scope = scopes.get(key);
1304
- if (!scope) {
1305
- const owning = pkg === -1 ? undefined : deepestFirst[pkg];
1306
- scope = {
1307
- owning,
1308
- ts: ts === -1 ? undefined : tsDeepestFirst[ts]?.[1],
1309
- declared: declaredIn(owning?.[0] ?? "."),
1310
- resolved: new Map
1311
- };
1312
- scopes.set(key, scope);
1313
- }
1314
- return scope;
1315
- };
1316
- const svelteKitRoot = (dir) => {
1317
- for (let at = dir;; at = posix.dirname(at)) {
1318
- if (at === "." || packages.has(at))
1319
- return at;
1320
- if (SVELTE_CONFIGS.some((name) => exists(`${at}/${name}`)))
1321
- return at;
1322
- }
1323
- };
1324
- const inPackage = (dir, path) => dir === "." ? path : posix.join(dir, path);
1325
- const resolveLocal = (dir, json, subpath) => {
1326
- if (json.exports !== undefined) {
1327
- const list = exportTargets(json.exports, subpath);
1328
- return [
1329
- ...new Set((list ?? []).flatMap((target) => exact(inPackage(dir, posix.normalize(target)))))
1330
- ];
1331
- }
1332
- if (subpath === ".") {
1333
- return probe(inPackage(dir, posix.normalize(json.main ?? "index")));
1334
- }
1335
- return probe(inPackage(dir, subpath.slice(2)));
1336
- };
1337
- const resolveImport = (scope, bare) => {
1338
- const { owning } = scope;
1339
- const imports = owning?.[1].imports;
1340
- const list = owning && imports && mapTargets(imports, bare);
1341
- if (!list)
1342
- return;
1343
- const found = [];
1344
- let pkg;
1345
- for (const target of list) {
1346
- if (target.startsWith("./")) {
1347
- for (const path of exact(inPackage(owning[0], posix.normalize(target)))) {
1348
- if (!found.includes(path))
1349
- found.push(path);
1350
- }
1351
- continue;
1352
- }
1353
- if (INVALID_IMPORT_TARGET.test(target))
1354
- continue;
1355
- const specifier = target.replace(QUERY, "");
1356
- const resolved = specifier === "" ? undefined : resolveBare(scope, specifier);
1357
- if (resolved === undefined)
1358
- return;
1359
- if ("pkg" in resolved)
1360
- pkg ??= resolved.pkg;
1361
- else {
1362
- for (const file of resolved.files) {
1363
- if (!found.includes(file))
1364
- found.push(file);
1365
- }
1366
- }
1367
- }
1368
- if (found.length > 0)
1369
- return { files: found };
1370
- return pkg === undefined ? undefined : { pkg };
1371
- };
1372
- const resolveRelative = (fromDir, bare) => {
1373
- if (bare.startsWith(SVELTEKIT_ASSETS)) {
1374
- const rest = bare.slice(SVELTEKIT_ASSETS.length);
1375
- const found = probe(posix.join(svelteKitRoot(fromDir), "static", rest));
1376
- return found.length > 0 ? { files: found } : undefined;
1377
- }
1378
- const found = probe(posix.join(fromDir, bare));
1379
- return found.length > 0 ? { files: found } : undefined;
1380
- };
1381
- const resolveBare = (scope, bare) => {
1382
- for (const alias of config.alias) {
1383
- const path = aliasPath(alias, bare);
1384
- if (path === undefined)
1385
- continue;
1386
- const found = probe(path);
1387
- if (found.length > 0)
1388
- return { files: found };
1389
- }
1390
- const { ts } = scope;
1391
- const mapped = ts && mapTargets(ts.paths, bare);
1392
- if (mapped) {
1393
- const found = [
1394
- ...new Set(mapped.flatMap((path) => probe(posix.normalize(path))))
1395
- ];
1396
- if (found.length > 0)
1397
- return { files: found };
1398
- }
1399
- if (bare.startsWith("#"))
1400
- return resolveImport(scope, bare);
1401
- const name = packageName(bare);
1402
- const dir = local.get(name);
1403
- if (dir !== undefined) {
1404
- const subpath = `.${bare.slice(name.length)}`;
1405
- const found = resolveLocal(dir, packages.get(dir) ?? {}, subpath);
1406
- return found.length > 0 ? { files: found } : undefined;
1407
- }
1408
- if (ts?.baseUrl !== undefined) {
1409
- const found = probe(posix.join(ts.baseUrl, bare), true);
1410
- if (found.length > 0)
1411
- return { files: found };
1412
- }
1413
- const node = builtin(bare);
1414
- if (node)
1415
- return { pkg: node };
1416
- if (scope.declared.has(name) || config.external.has(name)) {
1417
- return { pkg: name };
1418
- }
1419
- return;
1420
- };
1421
- const dirs = new Map;
1422
- const directoryOf = (from) => {
1423
- const dir = posix.dirname(from);
1424
- let found = dirs.get(dir);
1425
- if (!found) {
1426
- found = { dir, relative: new Map, scope: scopeOf(from) };
1427
- dirs.set(dir, found);
1428
- }
1429
- return found;
1430
- };
1431
- let lastFrom;
1432
- let last;
1433
- return (from, specifier) => {
1434
- if (from !== lastFrom || !last) {
1435
- lastFrom = from;
1436
- last = directoryOf(from);
1437
- }
1438
- const { dir, relative, scope } = last;
1439
- const hash = specifier.startsWith("#") ? "#" : "";
1440
- const isRelative = RELATIVE.test(specifier);
1441
- const memo = isRelative ? relative : scope.resolved;
1442
- if (memo.has(specifier))
1443
- return memo.get(specifier);
1444
- const bare = hash + specifier.slice(hash.length).replace(QUERY, "");
1445
- let resolved;
1446
- if (bare !== "" && bare !== "#") {
1447
- resolved = isRelative ? resolveRelative(dir, bare) : resolveBare(scope, bare);
1448
- }
1449
- memo.set(specifier, resolved);
1450
- return resolved;
1451
- };
1452
- }
1453
-
1454
- // src/scan.ts
1455
- import { posix as posix2 } from "node:path";
1456
-
1457
- // src/lex.ts
1458
- function createLexed() {
1459
- return {
1460
- imports: [],
1461
- globs: [],
1462
- gotos: [],
1463
- dependsOn: [],
1464
- reads: [],
1465
- lists: [],
1466
- registry: false,
1467
- nonLiteralImport: false,
1468
- nonLiteralGlob: false,
1469
- readsDisk: false
1470
- };
1471
- }
1472
-
1473
- class LexError extends Error {
1474
- }
1475
- var TS = { jsx: false, tsx: false };
1476
- var JS = { jsx: true, tsx: false };
1477
- var TSX = { jsx: true, tsx: true };
1478
- var JS_FILE = /\.[cm]?jsx?$/;
1479
- function dialectOf(path) {
1480
- if (path.endsWith(".tsx"))
1481
- return TSX;
1482
- if (JS_FILE.test(path))
1483
- return JS;
1484
- return TS;
1485
- }
1486
- var T_START = 0;
1487
- var T_PUNCT = 1;
1488
- var T_OPERAND = 2;
1489
- var T_IDENT = 3;
1490
- var T_DOT = 4;
1491
- var T_CLOSE_PAREN = 5;
1492
- var T_CLOSE_KW = 6;
1493
- var T_CLOSE_BLOCK = 7;
1494
- var T_ARROW = 8;
1495
- var T_SEMI = 9;
1496
- var T_LBRACE = 10;
1497
- var M_PAREN = 0;
1498
- var M_PAREN_KW = 1;
1499
- var M_BRACKET = 2;
1500
- var M_BLOCK = 3;
1501
- var M_EXPR = 4;
1502
- var M_TEMPLATE = 5;
1503
- var DISK = new Set([
1504
- "fs",
1505
- "node:fs",
1506
- "fs/promises",
1507
- "node:fs/promises",
1508
- "child_process",
1509
- "node:child_process"
1510
- ]);
1511
- var VI_CALLS = new Set([
1512
- "mock",
1513
- "doMock",
1514
- "unmock",
1515
- "importActual",
1516
- "importMock"
1517
- ]);
1518
- var CALL_IMPORT = 0;
1519
- var CALL_PROPERTY = 1;
1520
- var CALL_MOCK = 2;
1521
- var CALL_ACTUAL = 3;
1522
- var src = "";
1523
- var end = 0;
1524
- var out = createLexed();
1525
- var dialect = TS;
1526
- var nextAt = -1;
1527
- var nextImport = -1;
1528
- var LS = String.fromCharCode(8232);
1529
- var PS = String.fromCharCode(8233);
1530
- var oddLines = false;
1531
- var templateOpen = false;
1532
- function fail(message, at) {
1533
- throw new LexError(`${message} at ${at}`);
1534
- }
1535
- function openFile(source, sink) {
1536
- src = source;
1537
- out = sink;
1538
- nextAt = -1;
1539
- nextImport = -1;
1540
- oddLines = source.includes("\r") || source.includes(LS) || source.includes(PS);
1541
- }
1542
- function lexRange(start, stop, language = TS) {
1543
- dialect = language;
1544
- end = stop;
1545
- let i = start;
1546
- if (src.charCodeAt(i) === 65279)
1547
- i++;
1548
- if (src.charCodeAt(i) === 35 && src.charCodeAt(i + 1) === 33) {
1549
- i = lineEnd(i);
1550
- }
1551
- code(i, false);
1552
- }
1553
- function lexExpression(start, stop) {
1554
- dialect = TS;
1555
- end = stop;
1556
- return code(start, true);
1557
- }
1558
- function isUnicodeSpace(c) {
1559
- return c === 160 || c === 65279 || c === 5760 || c >= 8192 && c <= 8202 || c === 8232 || c === 8233 || c === 8239 || c === 8287 || c === 12288;
1560
- }
1561
- var IDENT = new Uint8Array(128);
1562
- for (let c = 0;c < 128; c++) {
1563
- const letter = c >= 97 && c <= 122 || c >= 65 && c <= 90 || c === 36 || c === 95;
1564
- if (letter)
1565
- IDENT[c] = 3;
1566
- else if (c >= 48 && c <= 57)
1567
- IDENT[c] = 2;
1568
- }
1569
- function isIdentStart(c) {
1570
- return c < 128 ? ((IDENT[c] ?? 0) & 1) !== 0 : c >= 128 && !isUnicodeSpace(c);
1571
- }
1572
- function isIdentPart(c) {
1573
- return c < 128 ? IDENT[c] !== 0 : c >= 128 && !isUnicodeSpace(c);
1574
- }
1575
- function identEnd(start) {
1576
- let i = start;
1577
- const s = src;
1578
- const n = end;
1579
- while (i < n) {
1580
- const c = s.charCodeAt(i);
1581
- if (c < 128 ? IDENT[c] === 0 : isUnicodeSpace(c))
1582
- break;
1583
- i++;
1584
- }
1585
- return i;
1586
- }
1587
- function isWord(i, word) {
1588
- return i + word.length <= end && src.startsWith(word, i) && !isIdentPart(src.charCodeAt(i + word.length));
1589
- }
1590
- function lineEnd(start) {
1591
- let i = start;
1592
- if (oddLines) {
1593
- while (i < end) {
1594
- const c = src.charCodeAt(i);
1595
- if (c === 10 || c === 13 || c === 8232 || c === 8233)
1596
- return i;
1597
- i++;
1598
- }
1599
- return end;
1600
- }
1601
- const e = src.indexOf(`
1602
- `, i);
1603
- return e === -1 || e > end ? end : e;
1604
- }
1605
- function skipTrivia(start) {
1606
- let i = start;
1607
- while (i < end) {
1608
- const c = src.charCodeAt(i);
1609
- if (c === 32 || c >= 9 && c <= 13 || c >= 128 && isUnicodeSpace(c)) {
1610
- i++;
1611
- } else if (c === 47 && src.charCodeAt(i + 1) === 47) {
1612
- i = lineEnd(i + 2);
1613
- } else if (c === 47 && src.charCodeAt(i + 1) === 42) {
1614
- const e = src.indexOf("*/", i + 2);
1615
- if (e === -1 || e + 2 > end)
1616
- return end;
1617
- i = e + 2;
1618
- } else {
1619
- break;
1620
- }
1621
- }
1622
- return i;
1623
- }
1624
- function stringEnd(i) {
1625
- const quote = src.charCodeAt(i);
1626
- let j = i + 1;
1627
- while (j < end) {
1628
- const c = src.charCodeAt(j);
1629
- if (c === quote)
1630
- return j + 1;
1631
- if (c === 92) {
1632
- j += src.charCodeAt(j + 1) === 13 && src.charCodeAt(j + 2) === 10 ? 3 : 2;
1633
- continue;
1634
- }
1635
- if (c === 10 || c === 13)
1636
- return -1;
1637
- j++;
1638
- }
1639
- return -1;
1640
- }
1641
- function template(start) {
1642
- let j = start;
1643
- while (j < end) {
1644
- const c = src.charCodeAt(j);
1645
- if (c === 96) {
1646
- templateOpen = false;
1647
- return j + 1;
1648
- }
1649
- if (c === 92) {
1650
- j += 2;
1651
- continue;
1652
- }
1653
- if (c === 36 && src.charCodeAt(j + 1) === 123) {
1654
- templateOpen = true;
1655
- return j + 2;
1656
- }
1657
- j++;
1658
- }
1659
- return fail("unterminated template", j);
1660
- }
1661
- function templatePart(start, stack) {
1662
- const e = template(start);
1663
- if (out.strings && !stack.includes(M_BRACKET)) {
1664
- out.strings.push(src.slice(start, templateOpen ? e - 2 : e - 1));
1665
- }
1666
- return e;
1667
- }
1668
- function regex(i) {
1669
- let j = i + 1;
1670
- let inClass = false;
1671
- for (;; ) {
1672
- if (j >= end)
1673
- fail("unterminated regex", i);
1674
- const c = src.charCodeAt(j);
1675
- if (c === 92) {
1676
- j += 2;
1677
- continue;
1678
- }
1679
- if (c === 10 || c === 13)
1680
- fail("unterminated regex", i);
1681
- if (inClass) {
1682
- if (c === 93)
1683
- inClass = false;
1684
- } else if (c === 47) {
1685
- break;
1686
- } else if (c === 91) {
1687
- inClass = true;
1688
- }
1689
- j++;
1690
- }
1691
- return identEnd(j + 1);
1692
- }
1693
- function isOneOf(start, stop, words) {
1694
- const [first] = words;
1695
- if (first === undefined || stop - start !== first.length)
1696
- return false;
1697
- const c = src.charCodeAt(start);
1698
- for (const word of words) {
1699
- if (word.charCodeAt(0) === c && src.startsWith(word, start))
1700
- return true;
1701
- }
1702
- return false;
1703
- }
1704
- var EXPRESSION_KEYWORDS = [];
1705
- var PAREN_KEYWORDS = [];
1706
- var BLOCK_KEYWORDS = [];
1707
- function byLength(table, words) {
1708
- for (const word of words) {
1709
- table[word.length] = [...table[word.length] ?? [], word];
1710
- }
1711
- }
1712
- byLength(EXPRESSION_KEYWORDS, [
1713
- ...["in", "do", "new", "case", "else", "void", "throw", "yield"],
1714
- ...["await", "return", "typeof", "delete", "default", "instanceof"]
1715
- ]);
1716
- byLength(PAREN_KEYWORDS, ["if", "for", "with", "while"]);
1717
- byLength(BLOCK_KEYWORDS, ["do", "try", "else", "finally"]);
1718
- function isKeyword(table, start, stop) {
1719
- const words = table[stop - start];
1720
- return words !== undefined && isOneOf(start, stop, words);
1721
- }
1722
- function isExpressionKeyword(start, stop) {
1723
- return isKeyword(EXPRESSION_KEYWORDS, start, stop);
1724
- }
1725
- function valueEnded(last, wordStart, wordEnd, wordIsProperty) {
1726
- return last === T_OPERAND || last === T_CLOSE_PAREN || last === T_IDENT && (wordIsProperty || !isExpressionKeyword(wordStart, wordEnd));
1727
- }
1728
- function isParenKeyword(start, stop) {
1729
- return isKeyword(PAREN_KEYWORDS, start, stop);
1730
- }
1731
- function isBlockKeyword(start, stop) {
1732
- return isKeyword(BLOCK_KEYWORDS, start, stop);
775
+ function isBlockKeyword(start, stop) {
776
+ return isKeyword(BLOCK_KEYWORDS, start, stop);
1733
777
  }
1734
778
  function isWordAt(start, stop, word) {
1735
779
  return stop - start === word.length && src.startsWith(word, start);
@@ -2923,7 +1967,7 @@ var leaf = () => ({
2923
1967
  reads: [],
2924
1968
  unknown: []
2925
1969
  });
2926
- var LEADING_DOT_SLASH2 = /^\.\//;
1970
+ var LEADING_DOT_SLASH = /^\.\//;
2927
1971
  var JS_SPECIFIER = /\.[cm]?jsx?$/;
2928
1972
  var DECLARATION = /\.d(?:\.[^/.]+)?\.[cm]?ts$/;
2929
1973
  function addPattern(deps, pattern, kind) {
@@ -2933,6 +1977,19 @@ function addPattern(deps, pattern, kind) {
2933
1977
  deps.patternKinds ??= new Map;
2934
1978
  deps.patternKinds.set(pattern, kind);
2935
1979
  }
1980
+ function addCause(deps, cause) {
1981
+ if (!deps.unknown.includes(cause))
1982
+ deps.unknown.push(cause);
1983
+ }
1984
+ function addPages(deps, pages) {
1985
+ for (const page of pages) {
1986
+ if (!deps.files.has(page)) {
1987
+ deps.pages ??= new Set;
1988
+ deps.pages.add(page);
1989
+ }
1990
+ deps.files.add(page);
1991
+ }
1992
+ }
2936
1993
  var NON_LITERAL_GOTO = "non-literal goto(";
2937
1994
  var HERMETIC_CAUSES = new Set([
2938
1995
  UNDECLARED_READS,
@@ -2948,12 +2005,12 @@ function sideEffectful(owning) {
2948
2005
  return matcher(sideEffects.map((glob) => {
2949
2006
  if (!glob.includes("/"))
2950
2007
  return `**/${glob}`;
2951
- const path = glob.replace(LEADING_DOT_SLASH2, "");
2008
+ const path = glob.replace(LEADING_DOT_SLASH, "");
2952
2009
  return dir === "." ? path : `${dir}/${path}`;
2953
2010
  }));
2954
2011
  }
2955
2012
  function gotoSuite(config, path) {
2956
- return config.suites.find((suite) => suite.urls.length > 0 && suite.roots.some((root) => inRoot(path, root)));
2013
+ return config.suites.find((suite) => suite.urls.length > 0 && suite.roots.some((root) => inRoot2(path, root)));
2957
2014
  }
2958
2015
  function mapUrl(suite, url) {
2959
2016
  for (const { key, targets } of suite.urls) {
@@ -3047,28 +2104,22 @@ function graphFrom(files, extractions, { config, packages, tsconfigs }) {
3047
2104
  (erased ? typed : valued).add(node);
3048
2105
  };
3049
2106
  if (resolved === undefined) {
3050
- const cause = `unresolved "${specifier}"`;
3051
- if (!deps.unknown.includes(cause))
3052
- deps.unknown.push(cause);
2107
+ addCause(deps, `unresolved "${specifier}"`);
3053
2108
  } else if ("pkg" in resolved) {
3054
2109
  add(`pkg:${resolved.pkg}`);
3055
2110
  external.add(`pkg:${resolved.pkg}`);
3056
2111
  } else {
3057
2112
  if (type !== true && !declaration && JS_SPECIFIER.test(specifier.replace(QUERY, "")) && resolved.files.every((file) => DECLARATION.test(file))) {
3058
- const cause = `only declarations for "${specifier}"`;
3059
- if (!deps.unknown.includes(cause))
3060
- deps.unknown.push(cause);
2113
+ addCause(deps, `only declarations for "${specifier}"`);
3061
2114
  }
3062
- for (const file of resolved.files) {
2115
+ const nodes = resolved.files.flatMap((file) => {
3063
2116
  const barrel = names && named.get(file);
3064
- if (!barrel || !names) {
3065
- add(file);
3066
- continue;
3067
- }
3068
- for (const name of names) {
3069
- add(barrel.has(name) ? `${file}#${name}` : file);
3070
- }
3071
- }
2117
+ if (!barrel || !names)
2118
+ return [file];
2119
+ return names.map((name) => barrel.has(name) ? `${file}#${name}` : file);
2120
+ });
2121
+ for (const node of nodes)
2122
+ add(node);
3072
2123
  }
3073
2124
  }
3074
2125
  for (const node of typed) {
@@ -3085,25 +2136,18 @@ function graphFrom(files, extractions, { config, packages, tsconfigs }) {
3085
2136
  if (suite) {
3086
2137
  for (const argument of found.gotos) {
3087
2138
  const url = gotoUrl(argument);
3088
- if (url === undefined) {
3089
- if (found.dependsOn.length === 0) {
3090
- deps.unknown.push(`${NON_LITERAL_GOTO}${argument})`);
3091
- }
3092
- } else if (url !== "about:blank") {
3093
- const mapped = mapUrl(suite, url.replace(QUERY, ""));
3094
- if (mapped === undefined)
3095
- deps.unknown.push(`goto("${url}")`);
3096
- else if (exists.has(mapped[0] ?? "")) {
3097
- for (const page of mapped.filter((file) => exists.has(file))) {
3098
- if (!deps.files.has(page)) {
3099
- deps.pages ??= new Set;
3100
- deps.pages.add(page);
3101
- }
3102
- deps.files.add(page);
3103
- }
3104
- } else
3105
- deps.unknown.push(`missing fixture "${url}"`);
2139
+ if (url === undefined && found.dependsOn.length === 0) {
2140
+ deps.unknown.push(`${NON_LITERAL_GOTO}${argument})`);
3106
2141
  }
2142
+ if (url === undefined || url === "about:blank")
2143
+ continue;
2144
+ const mapped = mapUrl(suite, url.replace(QUERY, ""));
2145
+ if (mapped === undefined)
2146
+ deps.unknown.push(`goto("${url}")`);
2147
+ else if (exists.has(mapped[0] ?? "")) {
2148
+ addPages(deps, mapped.filter((file) => exists.has(file)));
2149
+ } else
2150
+ deps.unknown.push(`missing fixture "${url}"`);
3107
2151
  }
3108
2152
  }
3109
2153
  for (const glob of found.dependsOn) {
@@ -3426,13 +2470,162 @@ function affectedBy(graph, changed, {
3426
2470
  for (const group of active) {
3427
2471
  if (!group.re.test(path))
3428
2472
  continue;
3429
- spend(group, path);
3430
- matched = true;
2473
+ spend(group, path);
2474
+ matched = true;
2475
+ }
2476
+ if (matched)
2477
+ active = active.filter((group) => !spent?.has(group));
2478
+ }
2479
+ return affected;
2480
+ }
2481
+
2482
+ // src/sorted.ts
2483
+ function byCodeUnit(a, b) {
2484
+ if (a === b)
2485
+ return 0;
2486
+ return a < b ? -1 : 1;
2487
+ }
2488
+ function sorted(values) {
2489
+ return [...values].sort(byCodeUnit);
2490
+ }
2491
+
2492
+ // src/terminal.ts
2493
+ var asIs = (text) => text;
2494
+ var PLAIN = {
2495
+ good: asIs,
2496
+ warn: asIs,
2497
+ bad: asIs,
2498
+ dim: asIs,
2499
+ bold: asIs,
2500
+ faint: asIs
2501
+ };
2502
+ function createPaint() {
2503
+ const wrap = (code) => (text) => text === "" ? text : `\x1B[${code}m${text}\x1B[39m`;
2504
+ return {
2505
+ good: wrap(32),
2506
+ warn: wrap(33),
2507
+ bad: wrap(31),
2508
+ dim: wrap(90),
2509
+ bold: (text) => text === "" ? text : `\x1B[1m${text}\x1B[22m`,
2510
+ faint: (text) => text === "" ? text : `\x1B[2m${text}\x1B[22m`
2511
+ };
2512
+ }
2513
+ function wantsColor(forced, terminal, env, agent) {
2514
+ if (forced !== undefined)
2515
+ return forced;
2516
+ if ((env.NO_COLOR ?? "") !== "")
2517
+ return false;
2518
+ const force = env.FORCE_COLOR;
2519
+ if (force !== undefined && force !== "")
2520
+ return force !== "0";
2521
+ return terminal && !agent && !isDumb(env);
2522
+ }
2523
+ var isDumb = (env) => env.TERM === "dumb";
2524
+ var SEPARATOR = " · ";
2525
+ var branch = (index, count) => index === count - 1 ? "└ " : "├ ";
2526
+ var NOTE_INDENT = " ";
2527
+ function closingLine(paint, what, detail) {
2528
+ return `${paint.good("✓")} ${what}${detail === undefined ? "" : paint.dim(`${SEPARATOR}${detail}`)}`;
2529
+ }
2530
+ function failLine(paint, what, detail) {
2531
+ return `${paint.bad("✗")} ${what}${detail === undefined ? "" : paint.dim(`${SEPARATOR}${detail}`)}`;
2532
+ }
2533
+ function truncateWords(text, max) {
2534
+ if ([...text].length <= max)
2535
+ return text;
2536
+ const cut = [...text].slice(0, max - 1).join("");
2537
+ const space = cut.lastIndexOf(" ");
2538
+ return `${(space > max / 2 ? cut.slice(0, space) : cut).replace(/[\s,;:]+$/, "")}…`;
2539
+ }
2540
+ var HASH_TAIL = /[-.][^-./]+\.\w+$/;
2541
+ var WORD_END = /(?<=[-_.])/;
2542
+ var width = (text) => [...text].length;
2543
+ function truncatePath(path, max) {
2544
+ if (width(path) <= max)
2545
+ return path;
2546
+ const parts = path.split("/");
2547
+ const name = parts.pop() ?? path;
2548
+ for (let keep = parts.length - 1;keep >= 0; keep--) {
2549
+ const candidate = `…/${[...parts.slice(parts.length - keep), name].join("/")}`;
2550
+ if (width(candidate) <= max)
2551
+ return candidate;
2552
+ }
2553
+ const prefix = parts.length > 0 ? "…/" : "";
2554
+ const tail = HASH_TAIL.exec(name)?.[0] ?? "";
2555
+ const stem = name.slice(0, name.length - tail.length);
2556
+ const room = max - width(prefix) - width(tail) - 1;
2557
+ if (room < 4)
2558
+ return `${prefix}…${[...name].slice(-(max - width(prefix) - 1)).join("")}`;
2559
+ const words = stem.split(WORD_END);
2560
+ const first = words[0] ?? "";
2561
+ let end = "";
2562
+ for (let i = words.length - 1;i > 0; i--) {
2563
+ const word = words[i] ?? "";
2564
+ if (width(first) + 1 + width(word + end) > room)
2565
+ break;
2566
+ end = word + end;
2567
+ }
2568
+ return end === "" ? `${prefix}${[...stem].slice(0, room).join("")}…${tail}` : `${prefix}${first}…${end}${tail}`;
2569
+ }
2570
+ var ESCAPE = /\x1b\[[0-9;]*m/g;
2571
+ var 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))
2585
+ continue;
2586
+ widths[i] = Math.max(widths[i] ?? 0, cellWidth(cell));
3431
2587
  }
3432
- if (matched)
3433
- active = active.filter((group) => !spent?.has(group));
3434
2588
  }
3435
- return affected;
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
+ });
2600
+ }
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);
2627
+ }
2628
+ };
3436
2629
  }
3437
2630
 
3438
2631
  // src/lockfile.ts
@@ -3613,11 +2806,11 @@ var DEP_FIELDS2 = [
3613
2806
  "peerDependencies",
3614
2807
  "optionalDependencies"
3615
2808
  ];
3616
- function isRecord3(value) {
2809
+ function isRecord2(value) {
3617
2810
  return typeof value === "object" && value !== null && !Array.isArray(value);
3618
2811
  }
3619
- function isStringRecord3(value) {
3620
- return isRecord3(value) && Object.values(value).every((item) => typeof item === "string");
2812
+ function isStringRecord2(value) {
2813
+ return isRecord2(value) && Object.values(value).every((item) => typeof item === "string");
3621
2814
  }
3622
2815
  var STRING_OR_TRAILING_COMMA = /"(?:[^"\\]|\\.)*"|,(\s*[}\]])/g;
3623
2816
  function parseLenient(text) {
@@ -3629,7 +2822,7 @@ function specsOf(value) {
3629
2822
  const deps = value[field];
3630
2823
  if (deps === undefined)
3631
2824
  continue;
3632
- if (!isStringRecord3(deps))
2825
+ if (!isStringRecord2(deps))
3633
2826
  return;
3634
2827
  specs.set(field, new Map(Object.entries(deps)));
3635
2828
  }
@@ -3657,7 +2850,7 @@ function install(packages, name, entry, version, info) {
3657
2850
  "peerDependencies"
3658
2851
  ]) {
3659
2852
  const deps = info?.[field];
3660
- if (isRecord3(deps)) {
2853
+ if (isRecord2(deps)) {
3661
2854
  for (const dep of Object.keys(deps))
3662
2855
  installed.dependencies.add(dep);
3663
2856
  }
@@ -3670,10 +2863,10 @@ function installedName(key) {
3670
2863
  }
3671
2864
  function parseBunLock(text) {
3672
2865
  const value = parseLenient(text);
3673
- if (!isRecord3(value))
2866
+ if (!isRecord2(value))
3674
2867
  return;
3675
2868
  const { packages, workspaces } = value;
3676
- if (!isRecord3(packages) || !isRecord3(workspaces))
2869
+ if (!isRecord2(packages) || !isRecord2(workspaces))
3677
2870
  return;
3678
2871
  const lockfile = {
3679
2872
  packages: new Map,
@@ -3686,10 +2879,10 @@ function parseBunLock(text) {
3686
2879
  const ident = entry[0];
3687
2880
  const at = ident.indexOf("@", 1);
3688
2881
  const version = at === -1 ? "" : ident.slice(at + 1);
3689
- install(lockfile.packages, installedName(key), entry, version, entry.find(isRecord3));
2882
+ install(lockfile.packages, installedName(key), entry, version, entry.find(isRecord2));
3690
2883
  }
3691
2884
  for (const [dir, workspace] of Object.entries(workspaces)) {
3692
- const specs = isRecord3(workspace) ? specsOf(workspace) : undefined;
2885
+ const specs = isRecord2(workspace) ? specsOf(workspace) : undefined;
3693
2886
  if (!specs)
3694
2887
  return;
3695
2888
  lockfile.workspaces.set(dir === "" ? "." : dir, specs);
@@ -3699,7 +2892,7 @@ function parseBunLock(text) {
3699
2892
  var NODE_MODULES = "node_modules/";
3700
2893
  function parsePackageLock(text) {
3701
2894
  const value = JSON.parse(text);
3702
- if (!isRecord3(value) || !isRecord3(value.packages))
2895
+ if (!isRecord2(value) || !isRecord2(value.packages))
3703
2896
  return;
3704
2897
  const { lockfileVersion } = value;
3705
2898
  if (lockfileVersion !== 2 && lockfileVersion !== 3)
@@ -3710,7 +2903,7 @@ function parsePackageLock(text) {
3710
2903
  rest: restOf(value, ["packages", "dependencies", "name", "version"])
3711
2904
  };
3712
2905
  for (const [key, entry] of Object.entries(value.packages)) {
3713
- if (!isRecord3(entry))
2906
+ if (!isRecord2(entry))
3714
2907
  return;
3715
2908
  const at = key.lastIndexOf(NODE_MODULES);
3716
2909
  if (at !== -1 && (at === 0 || key[at - 1] === "/")) {
@@ -3746,18 +2939,18 @@ var PNPM_DEP_FIELDS = [
3746
2939
  ];
3747
2940
  function parsePnpmLock(text) {
3748
2941
  const docs = text.split(YAML_DOCUMENT).filter((doc) => doc.trim() !== "").map(parseYaml);
3749
- const main = docs.findLast((doc) => isRecord3(doc) && typeof doc.lockfileVersion === "string");
3750
- if (!isRecord3(main))
2942
+ const main = docs.findLast((doc) => isRecord2(doc) && typeof doc.lockfileVersion === "string");
2943
+ if (!isRecord2(main))
3751
2944
  return;
3752
2945
  const { lockfileVersion, packages = {}, snapshots = {} } = main;
3753
2946
  if (typeof lockfileVersion !== "string")
3754
2947
  return;
3755
2948
  if (!PNPM_VERSION.test(lockfileVersion))
3756
2949
  return;
3757
- if (!isRecord3(packages) || !isRecord3(snapshots))
2950
+ if (!isRecord2(packages) || !isRecord2(snapshots))
3758
2951
  return;
3759
- const workspaces = isRecord3(main.importers);
3760
- const importers = isRecord3(main.importers) ? main.importers : { ".": main };
2952
+ const workspaces = isRecord2(main.importers);
2953
+ const importers = isRecord2(main.importers) ? main.importers : { ".": main };
3761
2954
  const lockfile = {
3762
2955
  packages: new Map,
3763
2956
  workspaces: new Map,
@@ -3768,18 +2961,18 @@ function parsePnpmLock(text) {
3768
2961
  };
3769
2962
  const restOfImporters = [];
3770
2963
  for (const [dir, importer] of Object.entries(importers)) {
3771
- if (!isRecord3(importer))
2964
+ if (!isRecord2(importer))
3772
2965
  return;
3773
2966
  const specs = new Map;
3774
2967
  for (const field of PNPM_DEP_FIELDS) {
3775
2968
  const deps = importer[field];
3776
2969
  if (deps === undefined)
3777
2970
  continue;
3778
- if (!isRecord3(deps))
2971
+ if (!isRecord2(deps))
3779
2972
  return;
3780
2973
  const declared = new Map;
3781
2974
  for (const [name, dep] of Object.entries(deps)) {
3782
- if (!isRecord3(dep) || typeof dep.specifier !== "string") {
2975
+ if (!isRecord2(dep) || typeof dep.specifier !== "string") {
3783
2976
  return;
3784
2977
  }
3785
2978
  declared.set(name, dep.specifier);
@@ -3801,7 +2994,7 @@ function parsePnpmLock(text) {
3801
2994
  const parsed = pnpmKey(key);
3802
2995
  if (!parsed)
3803
2996
  return;
3804
- const info = isRecord3(entry) ? entry : undefined;
2997
+ const info = isRecord2(entry) ? entry : undefined;
3805
2998
  install(lockfile.packages, parsed.name, [key, entry], parsed.version, info);
3806
2999
  }
3807
3000
  }
@@ -3886,7 +3079,7 @@ function parseManifest(text) {
3886
3079
  return;
3887
3080
  try {
3888
3081
  const value = JSON.parse(text);
3889
- return isRecord3(value) ? value : undefined;
3082
+ return isRecord2(value) ? value : undefined;
3890
3083
  } catch {
3891
3084
  return;
3892
3085
  }
@@ -3939,356 +3132,759 @@ async function readPackageDiff(changed, listed, base, head) {
3939
3132
  }
3940
3133
  }
3941
3134
  }
3942
- if (!lockfiles.includes(file))
3943
- continue;
3944
- if (baseText === undefined || headText === undefined) {
3945
- diff.files.set(file, baseText === undefined ? "added" : "deleted");
3946
- } else if (!(before && after)) {
3947
- diff.files.set(file, "can't parse it");
3948
- } else if (before.rest === after.rest) {
3949
- diff.files.set(file, undefined);
3950
- diff.changes.push(...lockfileChanges(file, before, after));
3951
- } else {
3952
- diff.files.set(file, "a setting other than the packages changed");
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");
3146
+ }
3147
+ }
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;
3159
+ }
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
+ });
3178
+ }
3179
+ }
3180
+ return diff;
3181
+ }
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
+ }
3216
+ }
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);
3240
+ } else {
3241
+ importOnly = true;
3242
+ }
3243
+ }
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
+ });
3266
+ }
3267
+ return result;
3268
+ }
3269
+
3270
+ // src/plan.ts
3271
+ function formatSelection(selection) {
3272
+ return selection.mode === "some" ? selection.files.join(" ") : selection.mode;
3273
+ }
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 };
3281
+ }
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)
3314
+ 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
+ });
3333
+ }
3334
+ }
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);
3352
+ }
3353
+ return new Set([...fine].filter((node) => coarse.has(node)));
3354
+ }
3355
+ function orphanOf(graph, config, suite, file) {
3356
+ if (!suite.roots.some((root) => inRoot2(file, root)))
3357
+ 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
+ })) {
3363
+ return;
3364
+ }
3365
+ const deleted = !graph.has(file);
3366
+ if (deleted && suite.isTest(file))
3367
+ return;
3368
+ if (deleted && config.isImportOnly(file))
3369
+ return;
3370
+ if (suite.isNonInput(file))
3371
+ 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`);
3393
+ }
3394
+ }
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
+ });
3953
3424
  }
3954
3425
  }
3955
- const unread = UNREAD.some((file) => listed.includes(file));
3956
- for (const [file, beforeText, afterText] of manifestTexts) {
3957
- const before = parseManifest(beforeText);
3958
- const after = parseManifest(afterText);
3959
- if (!(before && after) || unread || present.size === 0)
3426
+ const narrowings = new Map;
3427
+ for (const { narrower, result } of narrowed) {
3428
+ const matched = relevant.filter(narrower.match);
3429
+ if (matched.length === 0)
3960
3430
  continue;
3961
- const others = (record) => restOf(record, DEP_FIELDS2);
3962
- const specsBefore = specsOf(before);
3963
- const specsAfter = specsOf(after);
3964
- if (others(before) !== others(after) || !specsBefore || !specsAfter) {
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
+ });
3965
3438
  continue;
3966
3439
  }
3967
- const dir = posix3.dirname(file);
3968
- const declared = specChanges(specsBefore, specsAfter);
3969
- const recorded = [...present.values()].every((lockfile) => {
3970
- const specs = lockfile?.workspaces.get(dir);
3971
- if (!specs)
3972
- return false;
3973
- return [...declared.keys()].every((name) => DEP_FIELDS2.every((field) => specs.get(field)?.get(name) === specsAfter.get(field)?.get(name)));
3974
- });
3975
- if (!recorded)
3976
- continue;
3977
- diff.files.set(file, undefined);
3978
- for (const [name, [from, to]] of declared) {
3979
- diff.declared.add(name);
3980
- diff.changes.push({
3981
- name,
3982
- detail: `${file}: ${describe(`${name} range`, from, to)}`,
3983
- file
3984
- });
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);
3985
3444
  }
3986
3445
  }
3987
- return diff;
3988
- }
3989
- function packageSeeds(graph, config, diff, files) {
3990
- const result = { seeds: new Map, notes: [], reasons: [] };
3991
- const { isLoadedByName } = config;
3992
- const loadedOtherwise = (name) => isLoadedByName === undefined || diff.bins.has(name) || isLoadedByName(name);
3993
- const tested = new Map;
3994
- const reachesTest = (name) => {
3995
- let found = tested.get(name);
3996
- if (found === undefined) {
3997
- const node = `pkg:${name}`;
3998
- found = graph.has(node) && config.suites.some((suite) => reaches(graph, [node], suite.isTest, {
3999
- includeUnknown: false,
4000
- types: suite.types
4001
- }));
4002
- tested.set(name, found);
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" };
3451
+ continue;
4003
3452
  }
4004
- return found;
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
+ }
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
4005
3474
  };
4006
- const changes = diff.changes.filter((change) => files.includes(change.file)).sort((a, b) => byCodeUnit(a.name, b.name));
4007
- const unused = new Map;
4008
- const seen = new Set;
4009
- for (const change of changes) {
4010
- const { name, detail } = change;
4011
- if (seen.has(name))
4012
- continue;
4013
- seen.add(name);
4014
- const closure = new Set([name]);
4015
- const queue = [name];
4016
- for (const queued of queue) {
4017
- for (const dependent of diff.dependents.get(queued) ?? []) {
4018
- if (closure.has(dependent))
4019
- continue;
4020
- closure.add(dependent);
4021
- queue.push(dependent);
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";
3490
+ }
3491
+ function cacheDir(root, cache) {
3492
+ if (cache === false)
3493
+ return;
3494
+ if (typeof cache === "string") {
3495
+ return isAbsolute(cache) ? cache : join(root, cache);
3496
+ }
3497
+ const modules = join(root, "node_modules");
3498
+ return existsSync(modules) ? join(modules, ".cache", "bivium") : join(root, ".bivium", "cache");
3499
+ }
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;
4022
3528
  }
4023
- }
4024
- const through = [];
4025
- let covered = true;
4026
- let importOnly = false;
4027
- for (const user of closure) {
4028
- const node = `pkg:${user}`;
4029
- const imported = graph.has(node);
4030
- if (imported) {
4031
- through.push(user);
4032
- if (!result.seeds.has(node)) {
4033
- result.seeds.set(node, user === name ? detail : `${detail}, which ${user} depends on`);
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);
4034
3533
  }
4035
3534
  }
4036
- const entry = imported || diff.declared.has(user) || !diff.dependents.has(user);
4037
- if (!entry || reachesTest(user) || config.isInert(user))
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
+ }
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));
3570
+ }
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))
4038
3576
  continue;
4039
- if (loadedOtherwise(user)) {
4040
- covered = false;
4041
- const list = unused.get(user) ?? [];
4042
- if (user === name)
4043
- list.unshift(change);
4044
- else
4045
- list.push(change);
4046
- unused.set(user, list);
4047
- } else {
4048
- importOnly = true;
4049
- }
3577
+ try {
3578
+ rows.push(encode(key, decode(row, this.#strings), table));
3579
+ stale--;
3580
+ } catch {}
4050
3581
  }
4051
- if (!covered)
4052
- continue;
4053
- if (through.length === 0) {
4054
- result.notes.push(`${detail}, ${importOnly ? "imported by no test" : "inert"}`);
4055
- continue;
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;
3603
+ });
4056
3604
  }
4057
- const others = through.filter((user) => user !== name);
4058
- const shown = others.slice(0, 3).join(", ");
4059
- const rest = others.length > 3 ? ` and ${others.length - 3} more` : "";
4060
- result.notes.push(others.length === 0 ? detail : `${detail}, through ${shown}${rest}`);
4061
- }
4062
- for (const user of sorted(unused.keys())) {
4063
- const [first, ...more] = unused.get(user) ?? [];
4064
- if (!first)
4065
- continue;
4066
- const own = first.name === user;
4067
- const also = more.length === 0 ? "" : ` (and ${more.length} more ${more.length === 1 ? "package" : "packages"} ${user} depends on)`;
4068
- result.reasons.push({
4069
- package: user,
4070
- file: first.file,
4071
- message: own ? `${first.detail}${also}, and no test imports it` : `${first.detail}, which ${user} depends on${also}, and no test imports ${user}`
4072
- });
4073
3605
  }
4074
- return result;
4075
3606
  }
4076
-
4077
- // src/plan.ts
4078
- function formatSelection(selection) {
4079
- return selection.mode === "some" ? selection.files.join(" ") : selection.mode;
3607
+ function createStrings() {
3608
+ const list = [];
3609
+ const idsByValue = new Map;
3610
+ const id = (value) => {
3611
+ let found = idsByValue.get(value);
3612
+ if (found === undefined) {
3613
+ found = list.length;
3614
+ list.push(value);
3615
+ idsByValue.set(value, found);
3616
+ }
3617
+ return found;
3618
+ };
3619
+ const ids = (values) => values.length === 0 ? 0 : values.map(id);
3620
+ return { list, id, ids };
4080
3621
  }
4081
- function select(affected, tests) {
4082
- const files = tests.filter((file) => affected.has(file));
4083
- if (files.length === 0)
4084
- return { mode: "none" };
4085
- if (files.length === tests.length)
4086
- return { mode: "all" };
4087
- return { mode: "some", files };
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;
4088
3628
  }
4089
- function classify(graph, changed, config, packages, settings) {
4090
- const causes = [];
4091
- const all = config.suites.map((suite) => suite.name);
4092
- const runAll = (cause) => causes.push({ ...cause, suites: all });
4093
- const relevant = [];
4094
- const quiet = [];
4095
- const packageFiles = [];
4096
- const settingFiles = [];
4097
- for (const file of changed) {
4098
- const read = graph.has(file);
4099
- const ignored = config.isIgnored(file);
4100
- if (!read && ignored)
4101
- continue;
4102
- const wired = config.suites.filter((suite) => suite.isWiring(file));
4103
- const diffed = packages?.files.has(file) ?? false;
4104
- if (config.isSelf(file)) {
4105
- runAll({
4106
- kind: "self",
4107
- file,
4108
- message: `${file}: test selector changed`
4109
- });
4110
- continue;
4111
- }
4112
- for (const suite of wired) {
4113
- causes.push({
4114
- kind: "wiring",
4115
- suites: [suite.name],
4116
- file,
4117
- message: `${file}: wires the ${suite.name} suite`
4118
- });
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;
4119
3678
  }
4120
- if (wired.length > 0 && !diffed)
4121
- continue;
4122
- if (diffed) {
4123
- const reason = packages?.files.get(file);
4124
- if (reason === undefined) {
4125
- packageFiles.push(file);
4126
- } else {
4127
- runAll({ kind: "lockfile", file, message: `${file}: ${reason}` });
4128
- }
4129
- } else if (read || config.roots.some((root) => inRoot(file, root))) {
4130
- if (ignored)
4131
- quiet.push(file);
4132
- else
4133
- ((settings?.has(file)) ? settingFiles : relevant).push(file);
4134
- } else {
4135
- runAll({
4136
- kind: "outside",
4137
- file,
4138
- message: `${file}: outside the dependency graph`
4139
- });
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]));
4140
3701
  }
3702
+ extraction.barrel = { names, stars: list(stars) };
4141
3703
  }
4142
- return { relevant, quiet, packageFiles, settingFiles, causes };
3704
+ return extraction;
4143
3705
  }
4144
- function narrowedWalk(graph, seeds, {
4145
- quiet,
4146
- layout,
4147
- types
4148
- }, coarse, narrowings) {
4149
- const matched = new Set(narrowings.flatMap((narrowing) => narrowing.matched));
4150
- const fine = affectedBy(graph, seeds.filter((seed) => !matched.has(seed)), { quiet, layout, types });
4151
- for (const narrowing of narrowings) {
4152
- const walk = affectedBy(graph, [...narrowing.matched, ...narrowing.seeds], {
4153
- opaque: narrowing.narrower.opaque,
4154
- layout,
4155
- types
3706
+
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")
3724
+ });
4156
3725
  });
4157
- for (const node of walk)
4158
- fine.add(node);
4159
- }
4160
- return new Set([...fine].filter((node) => coarse.has(node)));
3726
+ });
4161
3727
  }
4162
- function orphanOf(graph, config, suite, file) {
4163
- if (!suite.roots.some((root) => inRoot(file, root)))
4164
- return;
4165
- const wired = (path) => suite.isTest(path) || suite.isPage(path);
4166
- if (reaches(graph, [file], wired, {
4167
- includeUnknown: false,
4168
- types: suite.types || DECLARATION.test(file)
4169
- })) {
4170
- return;
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}` : ""}`);
4171
3734
  }
4172
- const deleted = !graph.has(file);
4173
- if (deleted && suite.isTest(file))
4174
- return;
4175
- if (deleted && config.isImportOnly(file))
4176
- return;
4177
- if (suite.isNonInput(file))
4178
- return;
4179
- const typed = !suite.types && reaches(graph, [file], suite.isTest, { includeUnknown: false });
4180
- return { typed };
3735
+ return result.stdout;
4181
3736
  }
4182
- function planTests(graph, changed, config, {
4183
- barrelNames = [],
4184
- layout = new Set,
4185
- narrowed = [],
4186
- packages,
4187
- settings
4188
- } = {}) {
4189
- const { relevant, quiet, packageFiles, settingFiles, causes } = classify(graph, changed, config, packages, settings);
4190
- const settingCauses = new Map;
4191
- const settingNotes = [];
4192
- for (const file of settingFiles) {
4193
- const change = settings?.get(file);
4194
- if (!change)
4195
- continue;
4196
- settingNotes.push(change.note);
4197
- for (const seed of change.seeds) {
4198
- if (!settingCauses.has(seed)) {
4199
- settingCauses.set(seed, `governed by ${file}, which changed`);
4200
- }
4201
- }
3737
+ function lines(output) {
3738
+ return output.split(`
3739
+ `).filter(Boolean);
3740
+ }
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}`);
4202
3752
  }
4203
- const bumped = packages && packageFiles.length > 0 ? packageSeeds(graph, config, packages, packageFiles) : { seeds: new Map, notes: [], reasons: [] };
4204
- const all = config.suites.map((suite) => suite.name);
4205
- for (const unused of bumped.reasons) {
4206
- causes.push({ kind: "package", suites: all, ...unused });
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}`);
4207
3755
  }
4208
- const seeds = [
4209
- ...relevant,
4210
- ...settingFiles,
4211
- ...settingCauses.keys(),
4212
- ...barrelNames,
4213
- ...packageFiles,
4214
- ...bumped.seeds.keys()
4215
- ];
4216
- const affected = walksByTypes(graph, seeds, { quiet, layout });
4217
- const nodes = [...graph.keys()];
4218
- const tests = new Map(config.suites.map((suite) => [suite.name, nodes.filter(suite.isTest)]));
4219
- for (const suite of config.suites) {
4220
- for (const file of relevant) {
4221
- const orphan = orphanOf(graph, config, suite, file);
4222
- if (!orphan)
4223
- continue;
4224
- const { typed } = orphan;
4225
- causes.push({
4226
- kind: "orphan",
4227
- suites: [suite.name],
4228
- file,
4229
- 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)" : ""}`
3756
+ return;
3757
+ }
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;
4230
3765
  });
4231
3766
  }
3767
+ return pending;
3768
+ };
3769
+ }
3770
+ async function readRevision(cwd, base, roots, {
3771
+ blobs = false,
3772
+ mergeBase: eager = false
3773
+ } = {}) {
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));
4232
3790
  }
4233
- const narrowings = new Map;
4234
- for (const { narrower, result } of narrowed) {
4235
- const matched = relevant.filter(narrower.match);
4236
- if (matched.length === 0)
4237
- continue;
4238
- if ("all" in result) {
4239
- causes.push({
4240
- kind: "narrower",
4241
- suites: narrower.suites,
4242
- narrower: narrower.name,
4243
- message: `${narrower.name}: ${result.all}`
4244
- });
4245
- continue;
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}`);
4246
3798
  }
4247
- for (const name of narrower.suites) {
4248
- const list = narrowings.get(name) ?? [];
4249
- list.push({ matched, narrower, seeds: result.seeds });
4250
- narrowings.set(name, list);
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);
4251
3806
  }
4252
3807
  }
4253
- const full = new Set(causes.flatMap((cause) => cause.suites));
4254
- const suites = {};
4255
- for (const suite of config.suites) {
4256
- if (full.has(suite.name)) {
4257
- suites[suite.name] = { mode: "all" };
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}`));
3823
+ }
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
+ }
4258
3840
  continue;
4259
3841
  }
4260
- const coarse = affected(suite.types);
4261
- const narrowing = narrowings.get(suite.name);
4262
- suites[suite.name] = select(narrowing ? narrowedWalk(graph, seeds, { quiet, layout, types: suite.types }, coarse, narrowing) : coarse, tests.get(suite.name) ?? []);
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}.`);
3845
+ }
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")
3851
+ continue;
3852
+ if (mode !== "100644" && mode !== "100755")
3853
+ continue;
3854
+ present.add(path);
3855
+ if (blobs)
3856
+ oids.set(path, oid);
4263
3857
  }
4264
3858
  return {
4265
- suites,
4266
- reasons: causes.map((cause) => cause.message),
4267
- causes,
4268
- totals: Object.fromEntries(config.suites.map((suite) => [
4269
- suite.name,
4270
- tests.get(suite.name)?.length ?? 0
4271
- ])),
4272
- full: [...full],
4273
- packages: bumped.notes,
4274
- settings: settingNotes,
4275
- settingCauses,
4276
- seeds,
4277
- quiet,
3859
+ files: sorted(files),
3860
+ listed: [...tracked, ...untracked],
3861
+ changed,
4278
3862
  layout,
4279
- packageCauses: bumped.seeds,
4280
- narrowings
3863
+ mergeBase,
3864
+ readBase,
3865
+ blobs: oids,
3866
+ present
4281
3867
  };
4282
3868
  }
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`);
3883
+ }
4283
3884
 
4284
3885
  // src/settings.ts
4285
3886
  import { posix as posix5 } from "node:path";
4286
3887
 
4287
- // src/text.ts
4288
- function plural(count, one, many = `${one}s`) {
4289
- return `${count} ${count === 1 ? one : many}`;
4290
- }
4291
-
4292
3888
  // src/tsconfig.ts
4293
3889
  import { posix as posix4 } from "node:path";
4294
3890
  var COMMENT2 = /("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g;
@@ -4298,7 +3894,7 @@ var RELATIVE2 = /^\.\.?(?:\/|$)/;
4298
3894
  function parseJsonc(text) {
4299
3895
  return JSON.parse(text.replace(BOM, "").replace(COMMENT2, (_, string) => string ?? " ").replace(TRAILING_COMMA, (_, string) => string ?? ""));
4300
3896
  }
4301
- function isStrings2(value) {
3897
+ function isStrings(value) {
4302
3898
  return Array.isArray(value) && value.every((item) => typeof item === "string");
4303
3899
  }
4304
3900
  function parse2(file, text) {
@@ -4308,24 +3904,24 @@ function parse2(file, text) {
4308
3904
  } catch (error) {
4309
3905
  return { error: error instanceof Error ? error.message : String(error) };
4310
3906
  }
4311
- if (!isRecord2(value))
3907
+ if (!isRecord(value))
4312
3908
  return { error: "not an object" };
4313
3909
  const dir = posix4.dirname(file);
4314
3910
  const { extends: extended } = value;
4315
3911
  const read = {
4316
3912
  extends: typeof extended === "string" ? [extended] : []
4317
3913
  };
4318
- if (isStrings2(extended))
3914
+ if (isStrings(extended))
4319
3915
  read.extends = extended;
4320
3916
  const options = value.compilerOptions;
4321
- if (isRecord2(options)) {
3917
+ if (isRecord(options)) {
4322
3918
  if (typeof options.baseUrl === "string") {
4323
3919
  read.baseUrl = posix4.join(dir, options.baseUrl);
4324
3920
  }
4325
- if (isRecord2(options.paths)) {
3921
+ if (isRecord(options.paths)) {
4326
3922
  const map = {};
4327
3923
  for (const [key, targets] of Object.entries(options.paths)) {
4328
- if (isStrings2(targets))
3924
+ if (isStrings(targets))
4329
3925
  map[key] = targets;
4330
3926
  }
4331
3927
  read.paths = { map, dir };
@@ -4475,7 +4071,7 @@ function parsed(text, jsonc) {
4475
4071
  }
4476
4072
  }
4477
4073
  function changedKeys(before, after) {
4478
- if (!(isRecord2(before) && isRecord2(after)))
4074
+ if (!(isRecord(before) && isRecord(after)))
4479
4075
  return;
4480
4076
  const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
4481
4077
  return [...keys].filter((key) => JSON.stringify(before[key]) !== JSON.stringify(after[key]));
@@ -4540,7 +4136,17 @@ async function readIfFile(path) {
4540
4136
  throw error;
4541
4137
  }
4542
4138
  }
4543
- function collectPackages(rootJson, sources) {
4139
+ async function readSources2(root, files) {
4140
+ const texts = await Promise.all(files.map((file) => readIfFile(join3(root, file))));
4141
+ const sources = new Map;
4142
+ for (const [i, file] of files.entries()) {
4143
+ const text = texts[i];
4144
+ if (text !== undefined)
4145
+ sources.set(file, text);
4146
+ }
4147
+ return sources;
4148
+ }
4149
+ function collectPackages2(rootJson, sources) {
4544
4150
  const packages = new Map;
4545
4151
  const parse = (text) => {
4546
4152
  try {
@@ -4576,14 +4182,14 @@ async function isFile(path) {
4576
4182
  throw error;
4577
4183
  }
4578
4184
  }
4579
- async function extractRevision(root, revision, cache) {
4185
+ async function extractRevision2(root, revision, cache) {
4580
4186
  const extractions = new Map;
4581
4187
  const texts = new Map;
4582
4188
  const missing = new Set;
4583
4189
  const tasks = [];
4584
4190
  let cached = 0;
4585
4191
  const read = async (file) => {
4586
- const text = await readIfFile(join4(root, file));
4192
+ const text = await readIfFile(join3(root, file));
4587
4193
  if (text === undefined)
4588
4194
  missing.add(file);
4589
4195
  return text;
@@ -4612,7 +4218,7 @@ async function extractRevision(root, revision, cache) {
4612
4218
  texts.set(file, source);
4613
4219
  }));
4614
4220
  } else if (!revision.present.has(file)) {
4615
- tasks.push(() => isFile(join4(root, file)).then((found) => {
4221
+ tasks.push(() => isFile(join3(root, file)).then((found) => {
4616
4222
  if (!found)
4617
4223
  missing.add(file);
4618
4224
  }));
@@ -4633,7 +4239,7 @@ async function extractRevision(root, revision, cache) {
4633
4239
  extracted: { cached, read: extractions.size - cached }
4634
4240
  };
4635
4241
  }
4636
- function graphView(graph, config) {
4242
+ function graphView2(graph, config) {
4637
4243
  const nodes = [...graph.keys()];
4638
4244
  return {
4639
4245
  nodes: () => nodes,
@@ -4656,14 +4262,14 @@ async function runNarrowers(root, revision, graph, config, suites, packages, set
4656
4262
  const wanted = config.narrowers.filter((narrower) => relevant.some(narrower.match) && (suites === undefined || narrower.suites.some((name) => suites.includes(name))));
4657
4263
  if (wanted.length === 0)
4658
4264
  return [];
4659
- const view = graphView(graph, config);
4265
+ const view = graphView2(graph, config);
4660
4266
  const base = {
4661
4267
  commit: await revision.mergeBase(),
4662
4268
  read: revision.readBase
4663
4269
  };
4664
4270
  const head = {
4665
4271
  commit: undefined,
4666
- read: (path) => readIfFile(join4(root, path))
4272
+ read: (path) => readIfFile(join3(root, path))
4667
4273
  };
4668
4274
  return Promise.all(wanted.map(async (narrower) => {
4669
4275
  const changed = relevant.filter(narrower.match);
@@ -4681,7 +4287,7 @@ async function runNarrowers(root, revision, graph, config, suites, packages, set
4681
4287
  }
4682
4288
  }));
4683
4289
  }
4684
- async function computePlan(root, base, config, {
4290
+ async function computePlan2(root, base, config, {
4685
4291
  cache: cacheOption = config.cache,
4686
4292
  suites,
4687
4293
  mergeBase = false
@@ -4692,7 +4298,7 @@ async function computePlan(root, base, config, {
4692
4298
  blobs: dir !== undefined,
4693
4299
  mergeBase
4694
4300
  }),
4695
- readFile3(join4(root, "package.json"), "utf-8").catch(() => {
4301
+ readFile3(join3(root, "package.json"), "utf-8").catch(() => {
4696
4302
  return;
4697
4303
  }),
4698
4304
  ExtractionCache.open(dir)
@@ -4707,19 +4313,19 @@ async function computePlan(root, base, config, {
4707
4313
  if (!listed.has(file))
4708
4314
  return;
4709
4315
  }
4710
- return readIfFile(join4(root, file));
4316
+ return readIfFile(join3(root, file));
4711
4317
  };
4712
4318
  const [{ files, extractions, manifests, extracted }, ts, packageDiff] = await Promise.all([
4713
- extractRevision(root, revision, cache),
4319
+ extractRevision2(root, revision, cache),
4714
4320
  readTsconfigs([
4715
4321
  "tsconfig.json",
4716
4322
  ...revision.files.filter((file) => file.endsWith("/tsconfig.json"))
4717
4323
  ], readTsconfig),
4718
- readPackageDiff(revision.changed, revision.listed, revision.readBase, (path) => readIfFile(join4(root, path)))
4324
+ readPackageDiff(revision.changed, revision.listed, revision.readBase, (path) => readIfFile(join3(root, path)))
4719
4325
  ]);
4720
4326
  const { tsconfigs } = ts;
4721
4327
  const basePending = new Map(revision.changed.filter((file) => config.isBarrel(file) && extractions.get(file)?.barrel).map((file) => [file, revision.readBase(file)]));
4722
- const packages = collectPackages(rootJson, manifests);
4328
+ const packages = collectPackages2(rootJson, manifests);
4723
4329
  const graph = graphFrom(files, extractions, {
4724
4330
  config,
4725
4331
  packages,
@@ -4733,7 +4339,7 @@ async function computePlan(root, base, config, {
4733
4339
  packages: packages.keys(),
4734
4340
  accounted: new Set(packageDiff?.files.keys()),
4735
4341
  base: revision.readBase,
4736
- head: (path) => readIfFile(join4(root, path))
4342
+ head: (path) => readIfFile(join3(root, path))
4737
4343
  });
4738
4344
  const moved = await Promise.all([...basePending].map(async ([file, pending]) => {
4739
4345
  const head = graph.get(file)?.barrel;
@@ -4769,18 +4375,18 @@ async function computePlan(root, base, config, {
4769
4375
  extracted
4770
4376
  };
4771
4377
  }
4772
- async function prepare({
4378
+ async function prepare2({
4773
4379
  cwd = process.cwd(),
4774
4380
  base,
4775
4381
  config,
4776
4382
  configFile
4777
4383
  }) {
4778
- const root = resolve2(cwd);
4384
+ const root = resolve(cwd);
4779
4385
  let resolved;
4780
4386
  if (config) {
4781
- resolved = resolveConfig(checkConfig(config));
4387
+ resolved = resolveConfig2(checkConfig2(config));
4782
4388
  } else {
4783
- const loaded = await loadConfig(root, configFile);
4389
+ const loaded = await loadConfig2(root, configFile);
4784
4390
  const isSelf = loaded.config.isSelf;
4785
4391
  resolved = {
4786
4392
  ...loaded.config,
@@ -4795,8 +4401,8 @@ async function prepare({
4795
4401
  };
4796
4402
  }
4797
4403
  async function plan2(options = {}) {
4798
- const { root, base, config } = await prepare(options);
4799
- const computed = await computePlan(root, base, config, {
4404
+ const { root, base, config } = await prepare2(options);
4405
+ const computed = await computePlan2(root, base, config, {
4800
4406
  ...options.cache !== undefined && { cache: options.cache },
4801
4407
  mergeBase: true
4802
4408
  });
@@ -4816,4 +4422,4 @@ async function plan2(options = {}) {
4816
4422
  };
4817
4423
  }
4818
4424
 
4819
- export { version, githubOutputPath, BiviumError2, didYouMean, globToRegExp, defineConfig2, inRoot, sorted, QUERY, UNDECLARED_READS, RELATIVE, aliasPath, createResolver, SCANNED, formatOf, extract, stringsOf, finish, gotoPage, walksByTypes, importersOf, affectedBy, formatSelection, orphanOf, plural, computePlan, prepare, plan2 };
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 };