veoflow 0.5.4 → 0.5.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/veo.mjs CHANGED
@@ -2045,16 +2045,16 @@ function applySelection(source, paths, selected, options2 = {}) {
2045
2045
  `${path} can't be analyzed (${first.notAnalyzable === "over-hard-cap" ? "it is over the 64 MB cap" : first.notAnalyzable === "symlink" ? "it is a symbolic link" : "type declarations are not analyzed"})`,
2046
2046
  { fields: ["paths"] }
2047
2047
  );
2048
- const inside3 = (p) => p === path || p.startsWith(`${path}/`);
2048
+ const inside4 = (p) => p === path || p.startsWith(`${path}/`);
2049
2049
  const written2 = (rule) => {
2050
2050
  const r = rule.replace(/^\/+/, "").replace(/\/+$/, "");
2051
- return rule.startsWith("/") && (kind === "dir" ? inside3(r) : r === path);
2051
+ return rule.startsWith("/") && (kind === "dir" ? inside4(r) : r === path);
2052
2052
  };
2053
2053
  if (selected) {
2054
2054
  rules = { ...rules, exclude: rules.exclude.filter((r) => !written2(r)) };
2055
- if (entry().excludedBy) rules = { ...rules, optIn: [...rules.optIn.filter((p) => !inside3(p)), path] };
2056
- if (options2.keep) rules = { ...rules, kept: [...rules.kept.filter((p) => !inside3(p)), path] };
2057
- for (const o of rules.optIn.filter((p) => p !== path && inside3(p))) {
2055
+ if (entry().excludedBy) rules = { ...rules, optIn: [...rules.optIn.filter((p) => !inside4(p)), path] };
2056
+ if (options2.keep) rules = { ...rules, kept: [...rules.kept.filter((p) => !inside4(p)), path] };
2057
+ for (const o of rules.optIn.filter((p) => p !== path && inside4(p))) {
2058
2058
  const without = { ...rules, optIn: rules.optIn.filter((p) => p !== o) };
2059
2059
  let needed = false;
2060
2060
  try {
@@ -2067,8 +2067,8 @@ function applySelection(source, paths, selected, options2 = {}) {
2067
2067
  } else {
2068
2068
  rules = {
2069
2069
  ...rules,
2070
- optIn: rules.optIn.filter((p) => !inside3(p)),
2071
- kept: rules.kept.filter((p) => !inside3(p))
2070
+ optIn: rules.optIn.filter((p) => !inside4(p)),
2071
+ kept: rules.kept.filter((p) => !inside4(p))
2072
2072
  };
2073
2073
  if (!entry().excludedBy)
2074
2074
  rules = { ...rules, exclude: [...rules.exclude, kind === "dir" ? `/${path}/` : `/${path}`] };
@@ -2129,7 +2129,10 @@ function transaction(db, fn, mode = "IMMEDIATE") {
2129
2129
  db.exec("COMMIT");
2130
2130
  return result2;
2131
2131
  } catch (e) {
2132
- db.exec("ROLLBACK");
2132
+ try {
2133
+ db.exec("ROLLBACK");
2134
+ } catch {
2135
+ }
2133
2136
  throw e;
2134
2137
  }
2135
2138
  }
@@ -2244,6 +2247,14 @@ function processAlive(pid) {
2244
2247
  return e.code === "EPERM";
2245
2248
  }
2246
2249
  }
2250
+ function sortById(rows) {
2251
+ if (!rows.some((r) => SURROGATE.test(r.id)))
2252
+ return rows.sort(
2253
+ (a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0
2254
+ );
2255
+ const bytes = new Map(rows.map((r) => [r, Buffer.from(r.id)]));
2256
+ return rows.sort((a, b) => Buffer.compare(bytes.get(a), bytes.get(b)));
2257
+ }
2247
2258
  function lockIsLive(lock) {
2248
2259
  const pid = Number(lock.pid);
2249
2260
  if (pid === process.pid) return liveOwners.has(String(lock.owner));
@@ -2266,7 +2277,7 @@ function toRunInfo(row) {
2266
2277
  ...row.analysis ? { analysis: JSON.parse(String(row.analysis)) } : {}
2267
2278
  };
2268
2279
  }
2269
- var SCRATCH_RUNS, DEFAULT_RETENTION_GRACE_MS, CoalescedError, StaleCurrentRunError, ProjectLockedError, SCHEMA, CLOSED_HERE, liveOwners, STAGE_NAME, GraphReader, ProjectStore, RunHandle;
2280
+ var SCRATCH_RUNS, DEFAULT_RETENTION_GRACE_MS, CoalescedError, StaleCurrentRunError, ProjectLockedError, SCHEMA, CLOSED_HERE, liveOwners, SURROGATE, STAGE_NAME, GraphReader, ProjectStore, RunHandle;
2270
2281
  var init_project_store = __esm({
2271
2282
  "packages/store/src/project-store.ts"() {
2272
2283
  "use strict";
@@ -2371,6 +2382,7 @@ CREATE TABLE IF NOT EXISTS lock (
2371
2382
  `;
2372
2383
  CLOSED_HERE = "SELECT from_run, hash FROM facts WHERE id = :id AND +to_run = :run";
2373
2384
  liveOwners = /* @__PURE__ */ new Set();
2385
+ SURROGATE = /[\uD800-\uDFFF]/;
2374
2386
  STAGE_NAME = /^[a-z0-9][a-z0-9-]*$/;
2375
2387
  GraphReader = class _GraphReader {
2376
2388
  /**
@@ -2417,8 +2429,9 @@ CREATE TABLE IF NOT EXISTS lock (
2417
2429
  return this.#db.prepare(sql).all({ stage, ...this.pin }).map((r) => r.scope);
2418
2430
  }
2419
2431
  rows(where, params) {
2420
- const sql = `SELECT payload, rev FROM facts WHERE ${this.visible} AND ${where} ORDER BY id`;
2421
- return this.#db.prepare(sql).all({ ...params, ...this.pin }).map((r) => {
2432
+ const sql = `SELECT id, payload, rev FROM facts WHERE ${this.visible} AND ${where}`;
2433
+ const found = sortById(this.#db.prepare(sql).all({ ...params, ...this.pin }));
2434
+ return found.map((r) => {
2422
2435
  const fact = JSON.parse(r.payload);
2423
2436
  if ("evidence" in fact && fact.evidence && !fact.evidence.commit) fact.evidence.commit = String(r.rev);
2424
2437
  return fact;
@@ -2494,10 +2507,24 @@ CREATE TABLE IF NOT EXISTS lock (
2494
2507
  }
2495
2508
  return out;
2496
2509
  }
2497
- /** The stages that wrote the visible facts, in name order. */
2510
+ /**
2511
+ * The stages that wrote the visible facts, in name order. Asked on almost
2512
+ * every read, so it never reads every fact: the stage names come from
2513
+ * stepping through the stage index (one seek per stage), and each is kept
2514
+ * if one of its facts is visible here.
2515
+ */
2498
2516
  writtenStages() {
2499
- const rows = this.#db.prepare(`SELECT DISTINCT stage FROM facts WHERE ${this.visible} ORDER BY stage`).all(this.pin);
2500
- return rows.map((r) => r.stage);
2517
+ const names = this.#db.prepare(
2518
+ `WITH RECURSIVE s(stage) AS (
2519
+ SELECT MIN(stage) FROM facts INDEXED BY facts_by_scope
2520
+ UNION ALL
2521
+ SELECT (SELECT MIN(stage) FROM facts INDEXED BY facts_by_scope WHERE stage > s.stage) FROM s WHERE s.stage IS NOT NULL
2522
+ ) SELECT stage FROM s WHERE stage IS NOT NULL ORDER BY stage`
2523
+ ).all();
2524
+ const visible = this.#db.prepare(
2525
+ `SELECT 1 FROM facts INDEXED BY facts_by_scope WHERE stage = :stage AND ${this.visible} LIMIT 1`
2526
+ );
2527
+ return names.map((r) => r.stage).filter((stage) => visible.get({ stage, ...this.pin }) !== void 0);
2501
2528
  }
2502
2529
  /** Every visible fact, ordered by id (for diffs and exports). */
2503
2530
  all() {
@@ -2594,14 +2621,14 @@ CREATE TABLE IF NOT EXISTS lock (
2594
2621
  SELECT a.id, a.type, a.file, a.src, 'removed' AS change
2595
2622
  FROM a LEFT JOIN b ON b.id = a.id WHERE b.id IS NULL`
2596
2623
  ).all({ ...pinParams(pa, "a_"), ...pinParams(pb, "b_") });
2597
- const cmp9 = (x, y) => x < y ? -1 : x > y ? 1 : 0;
2624
+ const cmp11 = (x, y) => x < y ? -1 : x > y ? 1 : 0;
2598
2625
  return rows.map((r) => ({
2599
2626
  id: r.id,
2600
2627
  type: r.type,
2601
2628
  change: r.change,
2602
2629
  file: r.file,
2603
2630
  source: changeSource(r.id, r.file, r.src)
2604
- })).sort((x, y) => cmp9(x.file ?? "", y.file ?? "") || cmp9(x.type, y.type) || cmp9(x.id, y.id));
2631
+ })).sort((x, y) => cmp11(x.file ?? "", y.file ?? "") || cmp11(x.type, y.type) || cmp11(x.id, y.id));
2605
2632
  }
2606
2633
  /** How many facts of each type a committed run's graph holds. */
2607
2634
  factCounts(run2) {
@@ -4041,6 +4068,11 @@ function sleep(ms) {
4041
4068
  function message(e) {
4042
4069
  return e instanceof Error ? e.message : String(e);
4043
4070
  }
4071
+ function failureMessage(e) {
4072
+ const text = message(e);
4073
+ const full = e.errcode === 13 || /database or disk is full/i.test(text);
4074
+ return full ? `the disk holding veoflow's data is full: ${text}` : text;
4075
+ }
4044
4076
  function badRequest(request) {
4045
4077
  const names = request.stages.map((s) => s.name);
4046
4078
  for (const name of [...names, ...request.retire ?? []])
@@ -4491,15 +4523,16 @@ async function runNow(request) {
4491
4523
  stopProgress();
4492
4524
  const code = e.code;
4493
4525
  const errorCode = typeof code === "string" ? code : void 0;
4526
+ const error62 = failureMessage(e);
4494
4527
  try {
4495
- run2.fail(message(e), current ?? "commit", errorCode);
4528
+ run2.fail(error62, current ?? "commit", errorCode);
4496
4529
  } finally {
4497
4530
  emit({
4498
4531
  type: "run.failed",
4499
4532
  projectId,
4500
4533
  runId: run2.runId,
4501
4534
  stage: current,
4502
- error: message(e),
4535
+ error: error62,
4503
4536
  ...errorCode ? { code: errorCode } : {}
4504
4537
  });
4505
4538
  }
@@ -4921,9 +4954,9 @@ function runTemplateLink(ctx) {
4921
4954
  if (ownerRoot) {
4922
4955
  const abs = join9(ownerRoot.root, ...owner.path.split("/").slice(0, -1), ...d.specifier.split("/"));
4923
4956
  for (const r of roots) {
4924
- const inside3 = relative2(r.root, abs);
4925
- if (inside3 && !inside3.startsWith("..") && !inside3.startsWith(sep5) && !/^[a-zA-Z]:/.test(inside3)) {
4926
- const inRel = inside3.split(sep5).join("/");
4957
+ const inside4 = relative2(r.root, abs);
4958
+ if (inside4 && !inside4.startsWith("..") && !inside4.startsWith(sep5) && !/^[a-zA-Z]:/.test(inside4)) {
4959
+ const inRel = inside4.split(sep5).join("/");
4927
4960
  const file2 = fileById.get(ids.file(r.source, inRel));
4928
4961
  if (file2)
4929
4962
  return file2.language === "angular-template" ? { kind: "file", file: file2 } : { kind: "not-analyzed" };
@@ -5173,7 +5206,7 @@ function childRepositories(root) {
5173
5206
  other: entries.filter((d) => !isRepo(d)).map((d) => d.isDirectory() ? `${d.name}/` : d.name)
5174
5207
  };
5175
5208
  }
5176
- var HISTORY_CAP, HISTORY_MAX, DIFF_ITEMS_MAX, DIFF_FILES_MAX, scratch, UNNAMED, CODE_HEAD, CODE_BEFORE, GROUP_BY, SEARCH_LIMIT, SEARCH_MAX, AGGREGATE_MAX, OUTLINE_MAX, sleep2, MB, R1_STAGES, MAX_FILE_MB_CAP, normalizePath2, slug2, LICENSE_FINDINGS, Engine;
5209
+ var HISTORY_CAP, HISTORY_MAX, DIFF_ITEMS_MAX, DIFF_FILES_MAX, scratch, UNNAMED, CODE_HEAD, CODE_BEFORE, GROUP_BY, SEARCH_LIMIT, SEARCH_MAX, AGGREGATE_MAX, OUTLINE_MAX, sleep2, MB, MEMO_MAX, R1_STAGES, MAX_FILE_MB_CAP, normalizePath2, slug2, LICENSE_FINDINGS, Engine;
5177
5210
  var init_engine = __esm({
5178
5211
  "packages/query/src/engine.ts"() {
5179
5212
  "use strict";
@@ -5203,6 +5236,7 @@ var init_engine = __esm({
5203
5236
  OUTLINE_MAX = 500;
5204
5237
  sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
5205
5238
  MB = 1024 * 1024;
5239
+ MEMO_MAX = 32;
5206
5240
  R1_STAGES = [stage1.name, templateLink.name];
5207
5241
  MAX_FILE_MB_CAP = 64;
5208
5242
  normalizePath2 = (p) => p.replace(/\\/g, "/").replace(/^\.?\/+|\/+$/g, "");
@@ -5210,9 +5244,12 @@ var init_engine = __esm({
5210
5244
  LICENSE_FINDINGS = /* @__PURE__ */ new Set(["license", "entitlement", "frozen"]);
5211
5245
  Engine = class {
5212
5246
  afterCommit;
5247
+ afterSummaries;
5213
5248
  catalog;
5214
5249
  /** Run events from every project (run.started, stage.completed, ...). */
5215
5250
  events = new EventEmitter();
5251
+ /** Whole-project reads already made, by project, run and key (#386); the oldest goes first. */
5252
+ memos = /* @__PURE__ */ new Map();
5216
5253
  /** Each project's run in progress, as far as its events say (#299). */
5217
5254
  progress = /* @__PURE__ */ new Map();
5218
5255
  license;
@@ -5247,6 +5284,7 @@ var init_engine = __esm({
5247
5284
  this.license = options2.license ?? {};
5248
5285
  this.runner = options2.runner;
5249
5286
  this.afterCommit = options2.afterCommit;
5287
+ this.afterSummaries = options2.afterSummaries;
5250
5288
  if (options2.runner && options2.repository)
5251
5289
  throw new Error(
5252
5290
  "a runner's run processes use the SQLite backend: give a runner or a repository, not both"
@@ -5755,6 +5793,7 @@ var init_engine = __esm({
5755
5793
  entry.runId = e.runId;
5756
5794
  onStarted?.(e.runId);
5757
5795
  }
5796
+ if (e.type === "run.committed") entry.committedAt = Date.now();
5758
5797
  this.events.emit("event", e);
5759
5798
  }
5760
5799
  }).then((info) => {
@@ -5764,6 +5803,14 @@ var init_engine = __esm({
5764
5803
  this.afterCommit(this, project2.id, info.runId);
5765
5804
  } catch (e) {
5766
5805
  process.stderr.write(`veoflow: after the run: ${e.message}
5806
+ `);
5807
+ }
5808
+ this.events.emit("summarized", { projectId: project2.id, runId: info.runId });
5809
+ if (this.afterSummaries && info.kind === "history")
5810
+ try {
5811
+ this.afterSummaries(this, project2.id, info.runId);
5812
+ } catch (e) {
5813
+ process.stderr.write(`veoflow: after the run: ${e.message}
5767
5814
  `);
5768
5815
  }
5769
5816
  try {
@@ -5802,6 +5849,9 @@ var init_engine = __esm({
5802
5849
  };
5803
5850
  let started = null;
5804
5851
  let cancelling = false;
5852
+ let counted = () => {
5853
+ };
5854
+ const summarized = new Promise((r) => counted = r);
5805
5855
  const done = new Promise((resolve9, reject) => {
5806
5856
  let settled = false;
5807
5857
  child.on("message", (m) => {
@@ -5811,7 +5861,10 @@ var init_engine = __esm({
5811
5861
  entry.runId = m.event.runId;
5812
5862
  onStarted?.(m.event.runId);
5813
5863
  }
5864
+ if (m.event.type === "run.committed") entry.committedAt = Date.now();
5814
5865
  this.events.emit("event", m.event);
5866
+ } else if (m.type === "summarized") {
5867
+ counted();
5815
5868
  } else if (m.type === "done") {
5816
5869
  settled = true;
5817
5870
  resolve9(m.run);
@@ -5857,7 +5910,9 @@ var init_engine = __esm({
5857
5910
  child.kill();
5858
5911
  },
5859
5912
  done: done.catch(() => void 0),
5860
- process: child
5913
+ process: child,
5914
+ // However the process ends, nothing waits on its counts after.
5915
+ summarized: Promise.race([summarized, done.catch(() => void 0)])
5861
5916
  };
5862
5917
  const runs = this.inflight.get(project2.id) ?? /* @__PURE__ */ new Set();
5863
5918
  this.inflight.set(project2.id, runs.add(entry));
@@ -5867,7 +5922,9 @@ var init_engine = __esm({
5867
5922
  /** Serve one run request in a run process (`veoflow __run`, #129). */
5868
5923
  async serveRunRequest(request, send) {
5869
5924
  const listener = (event) => send({ type: "event", event });
5925
+ const summarized = () => send({ type: "summarized" });
5870
5926
  this.events.on("event", listener);
5927
+ this.events.on("summarized", summarized);
5871
5928
  try {
5872
5929
  const project2 = this.resolveProject({ project: request.project });
5873
5930
  const run2 = await this.runProject(project2, void 0, request.retire, request.options);
@@ -5877,6 +5934,7 @@ var init_engine = __esm({
5877
5934
  send({ type: "error", error: err });
5878
5935
  } finally {
5879
5936
  this.events.off("event", listener);
5937
+ this.events.off("summarized", summarized);
5880
5938
  }
5881
5939
  }
5882
5940
  /**
@@ -6531,6 +6589,26 @@ var init_engine = __esm({
6531
6589
  runInProgress(project2) {
6532
6590
  return (this.inflight.get(project2)?.size ?? 0) > 0;
6533
6591
  }
6592
+ /**
6593
+ * Wait while a run of the project that has committed is still finishing in
6594
+ * its process (#372): counting its findings and their impact, kept with the
6595
+ * run (D75). A read that needs those counts waits for them rather than
6596
+ * counting them again, which would hold this process for as long. A run
6597
+ * that hasn't committed is never waited for, and one is waited for at most
6598
+ * `limitMs` after it committed, however many reads wait. `all` waits for
6599
+ * the work after the summaries too (the connected grouping, #374).
6600
+ */
6601
+ async finishing(project2, limitMs = 6e4, all2 = false) {
6602
+ const now2 = Date.now();
6603
+ const waits = [...this.inflight.get(project2) ?? []].filter((r) => r.committedAt !== void 0 && r.committedAt + limitMs > now2).map((r) => {
6604
+ let timer;
6605
+ return Promise.race([
6606
+ all2 ? r.done : r.summarized ?? r.done,
6607
+ new Promise((done) => timer = setTimeout(done, r.committedAt + limitMs - now2))
6608
+ ]).finally(() => clearTimeout(timer));
6609
+ });
6610
+ await Promise.all(waits);
6611
+ }
6534
6612
  /** What a run read of each source (planner): its offers, what it left out, its notices (#330). */
6535
6613
  runSources(project2, run2) {
6536
6614
  if (run2 === null) return [];
@@ -6574,6 +6652,28 @@ var init_engine = __esm({
6574
6652
  setRunSummary(project2, run2, key, value) {
6575
6653
  this.handle(this.resolveProject({ project: project2 })).store.setRunSummary(run2, key, value);
6576
6654
  }
6655
+ /**
6656
+ * A read's result kept while this engine lives (#386), for whole-project
6657
+ * reads that cost seconds on a large project and can't change until the
6658
+ * next run: the same project (by id and when it was made), run and key get
6659
+ * the same value back, so callers must not change what they get. At most
6660
+ * MEMO_MAX results are kept, the least recently used dropped first; a run
6661
+ * that isn't committed yet (0) is never kept.
6662
+ */
6663
+ memo(project2, run2, key, compute) {
6664
+ if (run2 === 0) return compute();
6665
+ const k = `${project2.id}\0${project2.createdAt}\0${run2}\0${key}`;
6666
+ if (this.memos.has(k)) {
6667
+ const hit = this.memos.get(k);
6668
+ this.memos.delete(k);
6669
+ this.memos.set(k, hit);
6670
+ return hit;
6671
+ }
6672
+ const value = compute();
6673
+ if (this.memos.size >= MEMO_MAX) this.memos.delete(this.memos.keys().next().value);
6674
+ this.memos.set(k, value);
6675
+ return value;
6676
+ }
6577
6677
  readAllStages(args, cwd) {
6578
6678
  const project2 = this.resolveProject(args, cwd);
6579
6679
  const reader = this.pinnedReader(project2, args.run);
@@ -6950,10 +7050,23 @@ var init_engine = __esm({
6950
7050
  fields: ["filters"]
6951
7051
  });
6952
7052
  const limit = checkLimit(args.limit, AGGREGATE_MAX, AGGREGATE_MAX);
7053
+ const pending = args.filters?.ownCode ? this.pendingLibraries(project2.id, args.run ?? this.handle(project2).store.currentRun()) : /* @__PURE__ */ new Map();
7054
+ const offers = JSON.stringify([...pending].map(([s, paths]) => [s, [...paths].sort()]).sort());
7055
+ const key = `aggregate\0${JSON.stringify([args.label, args.groupBy, args.filters ?? null, limit, args.source ?? null, offers])}`;
7056
+ const counted = this.memo(
7057
+ project2,
7058
+ reader.run,
7059
+ key,
7060
+ () => this.aggregateCounts(project2, reader, args, limit, pending)
7061
+ );
7062
+ return { ...this.meta(project2, reader), label: args.label, groupBy: args.groupBy, ...counted };
7063
+ }
7064
+ /** `aggregate`'s counting, apart from the read's meta (#386). */
7065
+ aggregateCounts(project2, reader, args, limit, pending) {
7066
+ const open3 = args.filters?.open;
6953
7067
  const prefix = args.filters?.path;
6954
7068
  const files = reader.facts("File");
6955
7069
  const pathOf9 = new Map(files.map((f) => [f.id, f.path]));
6956
- const pending = args.filters?.ownCode ? this.pendingLibraries(project2.id, args.run ?? this.handle(project2).store.currentRun()) : /* @__PURE__ */ new Map();
6957
7070
  const foreign = new Set(
6958
7071
  args.filters?.ownCode ? files.filter((f) => f.origin || inPendingLibrary(f, pending)).map((f) => f.id) : []
6959
7072
  );
@@ -7004,9 +7117,6 @@ var init_engine = __esm({
7004
7117
  let total = 0;
7005
7118
  for (const [, n2] of sorted) total += n2;
7006
7119
  return {
7007
- ...this.meta(project2, reader),
7008
- label: args.label,
7009
- groupBy: args.groupBy,
7010
7120
  total,
7011
7121
  groupCount: sorted.length,
7012
7122
  truncated: sorted.length > limit,
@@ -7071,16 +7181,27 @@ var init_engine = __esm({
7071
7181
  const reader = this.reader(project2, args.run);
7072
7182
  if (args.file && reader.fact(args.file)?.type !== "File")
7073
7183
  throw new VeoError("not-found", `no file ${args.file}`, { kind: "file", id: args.file });
7074
- const everywhere = args.file ? visibleSites(reader.inFile(args.file)) : visibleSites(reader.facts("UnresolvedCallSite"), reader);
7075
- const all2 = args.source ? everywhere.filter((s) => s.file.startsWith(`${args.source}:`)) : everywhere;
7076
- const listed = args.includeAll ? all2 : all2.filter(isOpenQuestion);
7077
- if (!paged) return { ...this.meta(project2, reader), sites: withProvenance(reader, listed) };
7184
+ const list = () => {
7185
+ const everywhere = args.file ? visibleSites(reader.inFile(args.file)) : visibleSites(reader.facts("UnresolvedCallSite"), reader);
7186
+ const all2 = args.source ? everywhere.filter((s) => s.file.startsWith(`${args.source}:`)) : everywhere;
7187
+ return args.includeAll ? all2 : all2.filter(isOpenQuestion);
7188
+ };
7189
+ if (!paged) return { ...this.meta(project2, reader), sites: withProvenance(reader, list()) };
7190
+ const ids2 = args.file ? null : this.memo(
7191
+ project2,
7192
+ reader.run,
7193
+ `unresolved\0${args.source ?? ""}\0${args.includeAll ? 1 : 0}`,
7194
+ () => list().map((s) => s.id)
7195
+ );
7196
+ const byId = (some) => some.map((id) => reader.fact(id));
7197
+ const ofFile = ids2 ? null : list();
7078
7198
  const offset = args.offset ?? 0;
7079
- const page = listed.slice(offset, args.limit === void 0 ? void 0 : offset + args.limit);
7199
+ const end2 = args.limit === void 0 ? void 0 : offset + args.limit;
7200
+ const page = ids2 ? byId(ids2.slice(offset, end2)) : ofFile.slice(offset, end2);
7080
7201
  return {
7081
7202
  ...this.meta(project2, reader),
7082
7203
  sites: withProvenance(reader, page),
7083
- total: listed.length,
7204
+ total: ids2 ? ids2.length : ofFile.length,
7084
7205
  offset
7085
7206
  };
7086
7207
  }
@@ -7111,6 +7232,18 @@ var init_engine = __esm({
7111
7232
  });
7112
7233
 
7113
7234
  // packages/query/src/view.ts
7235
+ function hideReveal(reveal, file2) {
7236
+ const gone = /* @__PURE__ */ new Set([file2]);
7237
+ for (let grew = true; grew; ) {
7238
+ grew = false;
7239
+ for (const r of reveal)
7240
+ if (!gone.has(r.file) && gone.has(r.from)) {
7241
+ gone.add(r.file);
7242
+ grew = true;
7243
+ }
7244
+ }
7245
+ return reveal.filter((r) => !gone.has(r.file));
7246
+ }
7114
7247
  var INITIAL_VIEW, str, oneOf, all, none, COMMANDS, ACTIONS;
7115
7248
  var init_view = __esm({
7116
7249
  "packages/query/src/view.ts"() {
@@ -7134,7 +7267,10 @@ var init_view = __esm({
7134
7267
  compare: null,
7135
7268
  only: null,
7136
7269
  area: null,
7137
- reach: null
7270
+ reach: null,
7271
+ grouping: "declared",
7272
+ differences: false,
7273
+ reveal: []
7138
7274
  };
7139
7275
  str = (field, optional2 = false) => (a) => optional2 && a[field] === void 0 || typeof a[field] === "string" && a[field].length > 0 ? [] : [field];
7140
7276
  oneOf = (field, values) => (a) => values.includes(a[field]) ? [] : [field];
@@ -7171,7 +7307,9 @@ var init_view = __esm({
7171
7307
  file: a.file,
7172
7308
  selection: null,
7173
7309
  fileLevel: s.tab === "imports",
7174
- pick: s.tab === "imports" ? null : s.pick
7310
+ pick: s.tab === "imports" ? null : s.pick,
7311
+ // What was revealed belongs to the file it was revealed on (#378), at its level (as openImportsFile).
7312
+ reveal: a.file === s.file && (s.tab !== "imports" || s.fileLevel) ? s.reveal : []
7175
7313
  })
7176
7314
  },
7177
7315
  select: {
@@ -7182,6 +7320,8 @@ var init_view = __esm({
7182
7320
  ...s,
7183
7321
  file: a.file ?? s.file,
7184
7322
  selection: { kind: a.kind, id: a.id },
7323
+ // What was revealed belongs to the file it was revealed on (#378).
7324
+ reveal: (a.file ?? s.file) === s.file ? s.reveal : [],
7185
7325
  panel: "evidence",
7186
7326
  // Functions, calls and call sites are the File tab's.
7187
7327
  tab: "file",
@@ -7211,9 +7351,27 @@ var init_view = __esm({
7211
7351
  a.tab === "reach" && !s.reach ? s : (
7212
7352
  // From the File tab with a file open, Imports opens at that file: its imports
7213
7353
  // and cross-file calls, in its own group (#289), never a group left from before.
7214
- a.tab === "imports" && s.tab === "file" && s.file ? { ...s, tab: "imports", fileLevel: true, group: null, pick: null, only: null, expand: [] } : (
7354
+ a.tab === "imports" && s.tab === "file" && s.file ? {
7355
+ ...s,
7356
+ tab: "imports",
7357
+ fileLevel: true,
7358
+ group: null,
7359
+ pick: null,
7360
+ only: null,
7361
+ expand: [],
7362
+ reveal: []
7363
+ } : (
7215
7364
  // Imports again while on it: a fresh start, at the project map.
7216
- a.tab === "imports" && s.tab === "imports" ? { ...s, fileLevel: false, group: null, pick: null, only: null, expand: [], area: null } : { ...s, tab: a.tab }
7365
+ a.tab === "imports" && s.tab === "imports" ? {
7366
+ ...s,
7367
+ fileLevel: false,
7368
+ group: null,
7369
+ pick: null,
7370
+ only: null,
7371
+ expand: [],
7372
+ area: null,
7373
+ reveal: []
7374
+ } : { ...s, tab: a.tab }
7217
7375
  )
7218
7376
  )
7219
7377
  )
@@ -7257,7 +7415,9 @@ var init_view = __esm({
7257
7415
  // The project map (no group) is the whole map again; a group keeps the area it was opened from.
7258
7416
  area: a.group ? s.area : null,
7259
7417
  // A folder opened with it, in one step (#290: the outline, from a file's level).
7260
- expand: a.folder && !kept.includes(a.folder) ? [...kept, a.folder].sort() : kept
7418
+ expand: a.folder && !kept.includes(a.folder) ? [...kept, a.folder].sort() : kept,
7419
+ // What was revealed belonged to the file level left behind (#378, #390).
7420
+ reveal: []
7261
7421
  };
7262
7422
  }
7263
7423
  },
@@ -7273,7 +7433,9 @@ var init_view = __esm({
7273
7433
  group: null,
7274
7434
  pick: null,
7275
7435
  fileLevel: false,
7276
- area: a.area ?? null
7436
+ area: a.area ?? null,
7437
+ // What was revealed belonged to the file level left behind (#378, #390).
7438
+ reveal: []
7277
7439
  })
7278
7440
  },
7279
7441
  openImportsFile: {
@@ -7288,12 +7450,32 @@ var init_view = __esm({
7288
7450
  file: a.file,
7289
7451
  group: a.group ?? s.group,
7290
7452
  fileLevel: true,
7453
+ // What was revealed belongs to the file it was revealed on (#378).
7454
+ reveal: a.file === s.file && s.fileLevel ? s.reveal : [],
7291
7455
  // A finding opens with its import picked (its code and Explain in Details).
7292
7456
  pick: a.pick ?? null,
7293
7457
  panel: a.pick ? "evidence" : s.panel,
7294
7458
  selection: null
7295
7459
  })
7296
7460
  },
7461
+ revealFile: {
7462
+ description: "On a file's Imports level, show another file's imports and calls in place (or hide them again, with what was revealed from it)",
7463
+ control: { kind: "canvas", testId: "reveal-file" },
7464
+ check: all(str("file"), str("from", true)),
7465
+ apply: (s, a) => s.reveal.some((r) => r.file === a.file) ? { ...s, reveal: hideReveal(s.reveal, a.file) } : (
7466
+ // Only at a file's Imports level, and never the open file itself.
7467
+ a.file === s.file || !s.file || s.tab !== "imports" || !s.fileLevel ? s : {
7468
+ ...s,
7469
+ reveal: [...s.reveal, { file: a.file, from: a.from ?? s.file }]
7470
+ }
7471
+ )
7472
+ },
7473
+ resetReveal: {
7474
+ description: "On a file's Imports level, hide every file revealed in place: the open file's own imports and calls only",
7475
+ control: { kind: "button", testId: "reset-reveal" },
7476
+ check: none,
7477
+ apply: (s) => ({ ...s, reveal: [] })
7478
+ },
7297
7479
  toggleFolder: {
7298
7480
  description: "Open or close a folder in a large group on the Imports tab",
7299
7481
  control: { kind: "canvas", testId: "toggle-folder" },
@@ -7360,6 +7542,28 @@ var init_view = __esm({
7360
7542
  check: str("id", true),
7361
7543
  apply: (s, a) => ({ ...s, only: a.id ?? null })
7362
7544
  },
7545
+ setGrouping: {
7546
+ description: "Group the project map by its packages and folders (declared), or by how its files connect (connected)",
7547
+ control: { kind: "select", testId: "set-grouping" },
7548
+ check: oneOf("grouping", ["declared", "connected"]),
7549
+ // Group ids differ between groupings: back to the map, nothing picked.
7550
+ apply: (s, a) => a.grouping === s.grouping ? s : {
7551
+ ...s,
7552
+ grouping: a.grouping,
7553
+ differences: a.grouping === "connected" && s.differences,
7554
+ group: null,
7555
+ pick: null,
7556
+ area: null,
7557
+ expand: [],
7558
+ only: null
7559
+ }
7560
+ },
7561
+ toggleDifferences: {
7562
+ description: "Mark, on the map grouped by how files connect, the declared groups it splits or merges",
7563
+ control: { kind: "toggle", testId: "toggle-differences" },
7564
+ check: none,
7565
+ apply: (s) => ({ ...s, differences: !s.differences })
7566
+ },
7363
7567
  togglePending: {
7364
7568
  description: "Show or hide imports waiting for another source (pending)",
7365
7569
  control: { kind: "toggle", testId: "toggle-pending" },
@@ -7647,6 +7851,845 @@ var init_builtins = __esm({
7647
7851
  }
7648
7852
  });
7649
7853
 
7854
+ // packages/stage2/src/cluster.ts
7855
+ import { posix as posix2 } from "node:path";
7856
+ function rollUp(out, groupOf, input2, fnFile) {
7857
+ const byId = new Map(out.map((g) => [g.id, g]));
7858
+ const roll = /* @__PURE__ */ new Map();
7859
+ const rollOf = (from, to) => {
7860
+ const key = `${from}\0${to}`;
7861
+ let r = roll.get(key);
7862
+ if (!r) roll.set(key, r = { imports: [], calls: [], references: [] });
7863
+ return r;
7864
+ };
7865
+ for (const e of input2.imports) {
7866
+ const from = groupOf.get(e.from);
7867
+ if (!from) continue;
7868
+ if (e.to.startsWith("package|")) {
7869
+ const g = byId.get(from);
7870
+ if (!g.externalPackages.includes(e.to)) g.externalPackages.push(e.to);
7871
+ continue;
7872
+ }
7873
+ const to = groupOf.get(e.to);
7874
+ if (to && to !== from) rollOf(from, to).imports.push(e);
7875
+ }
7876
+ for (const c of input2.calls) {
7877
+ const fromFile = fnFile.get(c.from);
7878
+ const toFile = fnFile.get(c.to);
7879
+ const from = fromFile ? groupOf.get(fromFile) : void 0;
7880
+ const to = toFile ? groupOf.get(toFile) : void 0;
7881
+ if (from && to && from !== to) rollOf(from, to).calls.push(c);
7882
+ }
7883
+ for (const c of input2.references ?? []) {
7884
+ const fromFile = fnFile.get(c.from);
7885
+ const toFile = fnFile.get(c.to);
7886
+ const from = fromFile ? groupOf.get(fromFile) : void 0;
7887
+ const to = toFile ? groupOf.get(toFile) : void 0;
7888
+ if (from && to && from !== to) rollOf(from, to).references.push(c);
7889
+ }
7890
+ for (const g of out) g.externalPackages.sort(cmp);
7891
+ const carries = /* @__PURE__ */ new Map();
7892
+ for (const s of input2.symbols ?? []) {
7893
+ const key = s.id.slice("IMPORTS_SYMBOL|".length, s.id.lastIndexOf("|"));
7894
+ const u = s.uses;
7895
+ const yes = u === null || u.calls + u.jsx + u.extends > 0;
7896
+ carries.set(key, (carries.get(key) ?? false) || yes);
7897
+ }
7898
+ const carrying = (e) => carries.get(e.id.slice("IMPORTS|".length)) ?? true;
7899
+ return [...roll].map(([key, r]) => {
7900
+ const [from, to] = key.split("\0");
7901
+ const first = (xs) => [...xs].sort((a, b) => cmp(a.id, b.id))[0];
7902
+ const evidence = (first(r.imports) ?? first(r.calls) ?? first(r.references)).evidence;
7903
+ return {
7904
+ type: "DEPENDS_ON",
7905
+ id: ids.dependsOn(from, to),
7906
+ from,
7907
+ to,
7908
+ imports: r.imports.length,
7909
+ calls: r.calls.length,
7910
+ ...r.references.length ? { references: r.references.length } : {},
7911
+ carrying: r.imports.filter(carrying).length,
7912
+ evidence
7913
+ };
7914
+ }).sort((a, b) => cmp(a.id, b.id));
7915
+ }
7916
+ function ancestors(dir) {
7917
+ if (!dir) return [""];
7918
+ const parts = dir.split("/");
7919
+ return ["", ...parts.map((_, i) => parts.slice(0, i + 1).join("/"))];
7920
+ }
7921
+ function nameCluster(list) {
7922
+ const dirs = list.map((f) => {
7923
+ const d = posix2.dirname(f.path);
7924
+ return d === "." ? "" : d;
7925
+ });
7926
+ const counts = /* @__PURE__ */ new Map();
7927
+ for (const d of dirs) for (const a of ancestors(d)) counts.set(a, (counts.get(a) ?? 0) + 1);
7928
+ const root = [...counts].filter(([, n2]) => n2 === list.length).sort((x, y) => y[0].length - x[0].length)[0][0];
7929
+ const need = Math.ceil(list.length * 0.75);
7930
+ const main2 = [...counts].filter(([dir, n2]) => n2 >= need && inside2(`${dir}/x`, root)).sort((x, y) => y[0].length - x[0].length || y[1] - x[1] || cmp(x[0], y[0]))[0][0];
7931
+ const outside = list.length - counts.get(main2);
7932
+ const roles = /* @__PURE__ */ new Map();
7933
+ for (const f of list) {
7934
+ const parts = posix2.basename(f.path).split(".");
7935
+ if (parts.length >= 3)
7936
+ roles.set(parts[parts.length - 2], (roles.get(parts[parts.length - 2]) ?? 0) + 1);
7937
+ }
7938
+ const [role, shared] = [...roles].sort((x, y) => y[1] - x[1] || cmp(x[0], y[0]))[0] ?? ["", 0];
7939
+ const base2 = `${main2 || "(root)"}${list.length > 1 && shared >= Math.ceil(list.length * 0.6) ? ` \xB7 ${role} files` : ""}`;
7940
+ const name = outside > 0 ? `${base2} (+${outside} elsewhere in ${root || "the repository"})` : base2;
7941
+ return { name, root, main: main2, files: list };
7942
+ }
7943
+ function disambiguate() {
7944
+ const seen = /* @__PURE__ */ new Set();
7945
+ return (c) => {
7946
+ const key = c.main || "(root)";
7947
+ const taken = seen.has(key);
7948
+ seen.add(key);
7949
+ if (!taken) return { key, name: c.name, root: c.root, files: c.files };
7950
+ const first = [...c.files].map((f) => f.path).sort(cmp).find((p) => inside2(p, c.main));
7951
+ const within = c.main ? first.slice(c.main.length + 1) : first;
7952
+ const counts = /* @__PURE__ */ new Map();
7953
+ for (const f of c.files) {
7954
+ if (!inside2(f.path, c.main)) continue;
7955
+ const rel = posix2.dirname(c.main ? f.path.slice(c.main.length + 1) : f.path);
7956
+ if (rel === ".") continue;
7957
+ const parts = rel.split("/");
7958
+ for (let i = 1; i <= parts.length; i++) {
7959
+ const d = parts.slice(0, i).join("/");
7960
+ counts.set(d, (counts.get(d) ?? 0) + 1);
7961
+ }
7962
+ }
7963
+ const [folder, n2] = [...counts].sort(
7964
+ (a, b) => b[1] - a[1] || b[0].split("/").length - a[0].split("/").length || cmp(a[0], b[0])
7965
+ )[0] ?? ["", 0];
7966
+ const name = n2 >= 2 ? `${c.name} \xB7 mostly ${folder} (${n2} of ${c.files.length})` : `${c.name} (${within})`;
7967
+ return { key: `${key} (${within})`, name, root: c.root, files: c.files };
7968
+ };
7969
+ }
7970
+ function louvain(n2, edges) {
7971
+ let assignment = Array.from({ length: n2 }, (_, i) => i);
7972
+ let nodes = n2;
7973
+ let graph = edges;
7974
+ for (let level = 0; level < 10; level++) {
7975
+ const { community, moved } = localMoves(nodes, graph);
7976
+ if (!moved) break;
7977
+ const renumber2 = /* @__PURE__ */ new Map();
7978
+ for (let i = 0; i < nodes; i++)
7979
+ if (!renumber2.has(community[i])) renumber2.set(community[i], renumber2.size);
7980
+ assignment = assignment.map((c) => renumber2.get(community[c]));
7981
+ const agg = /* @__PURE__ */ new Map();
7982
+ for (const e of graph) {
7983
+ const a = renumber2.get(community[e.a]);
7984
+ const b = renumber2.get(community[e.b]);
7985
+ const key = a < b ? `${a} ${b}` : `${b} ${a}`;
7986
+ agg.set(key, (agg.get(key) ?? 0) + e.w);
7987
+ }
7988
+ nodes = renumber2.size;
7989
+ graph = [...agg].map(([k, w]) => {
7990
+ const [a, b] = k.split(" ").map(Number);
7991
+ return { a, b, w };
7992
+ });
7993
+ }
7994
+ const refined = localMoves(n2, edges, assignment).community;
7995
+ const renumber = /* @__PURE__ */ new Map();
7996
+ return refined.map((c) => {
7997
+ if (!renumber.has(c)) renumber.set(c, renumber.size);
7998
+ return renumber.get(c);
7999
+ });
8000
+ }
8001
+ function localMoves(n2, edges, initial) {
8002
+ const adj = Array.from({ length: n2 }, () => /* @__PURE__ */ new Map());
8003
+ const selfLoop = new Array(n2).fill(0);
8004
+ let total = 0;
8005
+ for (const e of edges) {
8006
+ if (e.a === e.b) selfLoop[e.a] += e.w;
8007
+ else {
8008
+ adj[e.a].set(e.b, (adj[e.a].get(e.b) ?? 0) + e.w);
8009
+ adj[e.b].set(e.a, (adj[e.b].get(e.a) ?? 0) + e.w);
8010
+ }
8011
+ total += e.w;
8012
+ }
8013
+ const community = initial ? [...initial] : Array.from({ length: n2 }, (_, i) => i);
8014
+ if (total === 0) return { community, moved: false };
8015
+ const m2 = 2 * total;
8016
+ const degree = adj.map((m, i) => [...m.values()].reduce((s, w) => s + w, 0) + 2 * selfLoop[i]);
8017
+ let size = n2;
8018
+ for (const c of community) if (c + 1 > size) size = c + 1;
8019
+ const communityDegree = new Array(size).fill(0);
8020
+ for (let i = 0; i < n2; i++) communityDegree[community[i]] += degree[i];
8021
+ let moved = false;
8022
+ for (let pass = 0; pass < 50; pass++) {
8023
+ let changed = false;
8024
+ for (let i = 0; i < n2; i++) {
8025
+ const own2 = community[i];
8026
+ const links = /* @__PURE__ */ new Map();
8027
+ for (const [j, w] of adj[i]) links.set(community[j], (links.get(community[j]) ?? 0) + w);
8028
+ communityDegree[own2] -= degree[i];
8029
+ const gain = (c) => (links.get(c) ?? 0) - communityDegree[c] * degree[i] / m2;
8030
+ let best = own2;
8031
+ let bestGain = gain(own2);
8032
+ for (const c of [...links.keys()].sort((x, y) => x - y)) {
8033
+ const g = gain(c);
8034
+ if (g > bestGain + 1e-12 || Math.abs(g - bestGain) <= 1e-12 && c < best) {
8035
+ best = c;
8036
+ bestGain = g;
8037
+ }
8038
+ }
8039
+ communityDegree[best] += degree[i];
8040
+ if (best !== own2) {
8041
+ community[i] = best;
8042
+ changed = true;
8043
+ moved = true;
8044
+ }
8045
+ }
8046
+ if (!changed) break;
8047
+ }
8048
+ return { community, moved };
8049
+ }
8050
+ var cmp, inside2, byKey;
8051
+ var init_cluster = __esm({
8052
+ "packages/stage2/src/cluster.ts"() {
8053
+ "use strict";
8054
+ init_src();
8055
+ cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
8056
+ inside2 = (path, dir) => dir === "" || path.startsWith(`${dir}/`);
8057
+ byKey = (a, b) => cmp(a.main, b.main) || b.files.length - a.files.length || cmp(a.files[0].path, b.files[0].path);
8058
+ }
8059
+ });
8060
+
8061
+ // packages/query-imports/src/connected.ts
8062
+ import { posix as posix3 } from "node:path";
8063
+ function boundariesOf(declared2, byId) {
8064
+ const out = /* @__PURE__ */ new Map();
8065
+ for (const g of [...declared2].sort((a, b) => cmp2(a.id, b.id))) {
8066
+ const b = g.boundary ?? {
8067
+ kind: g.kind === "cluster" ? "folder" : g.kind,
8068
+ name: g.kind === "cluster" ? g.root || g.name : g.name,
8069
+ root: g.root
8070
+ };
8071
+ const key = `${g.source}\0${b.root}`;
8072
+ let entry = out.get(key);
8073
+ if (!entry)
8074
+ out.set(
8075
+ key,
8076
+ entry = {
8077
+ key,
8078
+ kind: b.kind,
8079
+ name: b.name,
8080
+ root: b.root,
8081
+ source: g.source,
8082
+ files: [],
8083
+ declared: []
8084
+ }
8085
+ );
8086
+ entry.declared.push(g);
8087
+ for (const f of g.files) {
8088
+ const file2 = byId.get(f);
8089
+ if (file2) entry.files.push(file2);
8090
+ }
8091
+ }
8092
+ for (const b of out.values()) b.files.sort((x, y) => cmp2(x.path, y.path));
8093
+ return [...out.values()].sort((a, b) => cmp2(a.source, b.source) || cmp2(a.root, b.root));
8094
+ }
8095
+ function declaredWhy(g) {
8096
+ if (g.kind === "repository") return `Declared: the repository ${g.name}`;
8097
+ if (g.kind === "workspace-package")
8098
+ return `Declared: the workspace package ${g.name} (${g.root || "its root"})`;
8099
+ if (g.boundary?.split === "folders") return `Declared: the folder ${g.root}`;
8100
+ if (g.boundary)
8101
+ return `Declared: part of ${g.boundary.kind === "folder" ? `the folder ${g.boundary.name}` : g.boundary.name}, split by how its files connect`;
8102
+ return `Declared: a cluster of ${g.root || "the repository"}, split by how its files connect`;
8103
+ }
8104
+ function connectedGrouping(input2) {
8105
+ const byId = new Map(input2.files.map((f) => [f.id, f]));
8106
+ const fileOf = (fn) => input2.fnFile.get(fn);
8107
+ const user = (id) => {
8108
+ const f = byId.get(id);
8109
+ return !!f && input2.own(f) && !isTestPath(f.path);
8110
+ };
8111
+ const links = /* @__PURE__ */ new Map();
8112
+ const callsInto = /* @__PURE__ */ new Map();
8113
+ const add2 = (m, from, to, n2 = 1) => {
8114
+ let row = m.get(from);
8115
+ if (!row) m.set(from, row = /* @__PURE__ */ new Map());
8116
+ row.set(to, (row.get(to) ?? 0) + n2);
8117
+ };
8118
+ const pairs = /* @__PURE__ */ new Set();
8119
+ const path = (from, to, key) => {
8120
+ if (!from || !to || from === to || !byId.has(from) || !byId.has(to)) return;
8121
+ if (pairs.has(key)) return;
8122
+ pairs.add(key);
8123
+ add2(links, from, to);
8124
+ add2(callsInto, from, to);
8125
+ };
8126
+ for (const c of input2.calls) path(fileOf(c.from), fileOf(c.to), `${c.from}\0${c.to}`);
8127
+ for (const r of input2.references)
8128
+ if (r.exit === void 0) path(fileOf(r.from), fileOf(r.to), `${r.from}\0${r.to}`);
8129
+ const told = /* @__PURE__ */ new Map();
8130
+ for (const s of input2.symbols) {
8131
+ const key = s.id.slice("IMPORTS_SYMBOL|".length, s.id.lastIndexOf("|"));
8132
+ told.set(key, (told.get(key) ?? true) && s.uses !== null);
8133
+ }
8134
+ for (const e of input2.imports) {
8135
+ if (e.to.startsWith("package|") || e.from === e.to || !byId.has(e.from) || !byId.has(e.to)) continue;
8136
+ if (told.get(e.id.slice("IMPORTS|".length)) ?? false) continue;
8137
+ add2(links, e.from, e.to);
8138
+ }
8139
+ const uses = /* @__PURE__ */ new Map();
8140
+ const users = /* @__PURE__ */ new Map();
8141
+ for (const [from, row] of links) {
8142
+ if (!user(from)) continue;
8143
+ for (const to of row.keys()) {
8144
+ (uses.get(from) ?? uses.set(from, /* @__PURE__ */ new Set()).get(from)).add(to);
8145
+ (users.get(to) ?? users.set(to, /* @__PURE__ */ new Set()).get(to)).add(from);
8146
+ }
8147
+ }
8148
+ const linkCount = (a, b) => user(a) ? links.get(a)?.get(b) ?? 0 : 0;
8149
+ const boundaries = boundariesOf(input2.declared, byId);
8150
+ const boundaryOf = /* @__PURE__ */ new Map();
8151
+ for (const b of boundaries) for (const f of b.files) boundaryOf.set(f.id, b);
8152
+ const shared = /* @__PURE__ */ new Set();
8153
+ const sharedOf = /* @__PURE__ */ new Map();
8154
+ for (const b of boundaries) {
8155
+ const members2 = b.files.filter((f) => user(f.id));
8156
+ const inB = new Set(b.files.map((f) => f.id));
8157
+ const n2 = members2.length - 1;
8158
+ const need = Math.max(SHARED_MIN_USERS, SHARED_SQRT_FACTOR * Math.sqrt(Math.max(n2, 0)));
8159
+ const qualifies = (group) => {
8160
+ const by = /* @__PURE__ */ new Set();
8161
+ const used = /* @__PURE__ */ new Set();
8162
+ for (const f of group) {
8163
+ for (const u of users.get(f) ?? []) if (inB.has(u) && !group.has(u)) by.add(u);
8164
+ for (const t of uses.get(f) ?? []) if (inB.has(t) && !group.has(t)) used.add(t);
8165
+ }
8166
+ return by.size >= need && used.size <= by.size * SHARED_MAX_USES;
8167
+ };
8168
+ const layer = /* @__PURE__ */ new Set();
8169
+ for (const f of members2) if (qualifies(/* @__PURE__ */ new Set([f.id]))) layer.add(f.id);
8170
+ if (layer.size) {
8171
+ const list = [...layer].sort((x, y) => cmp2(byId.get(x).path, byId.get(y).path));
8172
+ sharedOf.set(b.key, list);
8173
+ for (const f of list) shared.add(f);
8174
+ }
8175
+ }
8176
+ const counted = (id) => user(id) && !shared.has(id);
8177
+ const memo2 = (m) => {
8178
+ const cache = /* @__PURE__ */ new Map();
8179
+ return (id) => {
8180
+ let list = cache.get(id);
8181
+ if (!list) cache.set(id, list = [...m.get(id) ?? []].filter((x) => !shared.has(x)).sort(cmp2));
8182
+ return list;
8183
+ };
8184
+ };
8185
+ const usersOf = memo2(users);
8186
+ const usersN = (t) => usersOf(t).length;
8187
+ const usesOf2 = memo2(uses);
8188
+ const similarity = (files) => {
8189
+ const index = new Map(files.map((f, i) => [f, i]));
8190
+ const direct = /* @__PURE__ */ new Map();
8191
+ const usage = /* @__PURE__ */ new Map();
8192
+ const dependence = /* @__PURE__ */ new Map();
8193
+ const bump = (m, a, b, w) => {
8194
+ if (a === b) return;
8195
+ const key = a < b ? `${a} ${b}` : `${b} ${a}`;
8196
+ m.set(key, (m.get(key) ?? 0) + w);
8197
+ };
8198
+ for (const a of files)
8199
+ for (const t of usesOf2(a)) {
8200
+ const j = index.get(t);
8201
+ if (j !== void 0) bump(direct, index.get(a), j, linkCount(a, t) * discount(usersN(t)));
8202
+ }
8203
+ const usersSeen = /* @__PURE__ */ new Set();
8204
+ for (const f of files) for (const u of usersOf(f)) usersSeen.add(u);
8205
+ for (const u of [...usersSeen].sort(cmp2)) {
8206
+ const used = usesOf2(u).filter((t) => index.has(t));
8207
+ if (used.length < 2 || usesOf2(u).length > COMMON_MAX) continue;
8208
+ const w = discount(usesOf2(u).length);
8209
+ for (let x = 0; x < used.length; x++)
8210
+ for (let y = x + 1; y < used.length; y++) bump(usage, index.get(used[x]), index.get(used[y]), w);
8211
+ }
8212
+ const targets = /* @__PURE__ */ new Map();
8213
+ for (const f of files)
8214
+ if (counted(f))
8215
+ for (const t of usesOf2(f)) {
8216
+ const list = targets.get(t) ?? [];
8217
+ list.push(index.get(f));
8218
+ targets.set(t, list);
8219
+ }
8220
+ for (const [t, list] of [...targets].sort((a, b) => cmp2(a[0], b[0]))) {
8221
+ if (list.length < 2 || usersN(t) > COMMON_MAX) continue;
8222
+ const w = discount(usersN(t));
8223
+ for (let x = 0; x < list.length; x++)
8224
+ for (let y = x + 1; y < list.length; y++) bump(dependence, list[x], list[y], w);
8225
+ }
8226
+ const total = /* @__PURE__ */ new Map();
8227
+ for (const [k, w] of direct) total.set(k, (total.get(k) ?? 0) + w);
8228
+ for (const [k, w] of usage) total.set(k, (total.get(k) ?? 0) + w * CO_WEIGHT);
8229
+ for (const [k, w] of dependence) total.set(k, (total.get(k) ?? 0) + w * CO_WEIGHT);
8230
+ const pairKey = (a, b) => {
8231
+ const x = index.get(a);
8232
+ const y = index.get(b);
8233
+ return x < y ? `${x} ${y}` : `${y} ${x}`;
8234
+ };
8235
+ const adjacency = (m) => {
8236
+ const adj = files.map(() => /* @__PURE__ */ new Map());
8237
+ for (const [k, w] of m) {
8238
+ const [a, b] = k.split(" ").map(Number);
8239
+ adj[a].set(b, w);
8240
+ adj[b].set(a, w);
8241
+ }
8242
+ return adj;
8243
+ };
8244
+ return {
8245
+ edges: [...total].map(([k, w]) => {
8246
+ const [a, b] = k.split(" ").map(Number);
8247
+ return { a, b, w };
8248
+ }),
8249
+ /** By file index: its similarity to each other file, and its direct links. */
8250
+ near: adjacency(total),
8251
+ index,
8252
+ linked: adjacency(direct),
8253
+ usage: (a, b) => (usage.get(pairKey(a, b)) ?? 0) > 0,
8254
+ dependence: (a, b) => (dependence.get(pairKey(a, b)) ?? 0) > 0
8255
+ };
8256
+ };
8257
+ const modules = [];
8258
+ const pathOfId = (id) => byId.get(id).path;
8259
+ const byPath = (a, b) => cmp2(pathOfId(a), pathOfId(b));
8260
+ const folders = (root, parts) => {
8261
+ const counts = /* @__PURE__ */ new Map();
8262
+ const top = (path2) => {
8263
+ const rel = root ? path2.slice(root.length + 1) : path2;
8264
+ const at = rel.indexOf("/");
8265
+ return at < 0 ? root : root ? `${root}/${rel.slice(0, at)}` : rel.slice(0, at);
8266
+ };
8267
+ const own2 = /* @__PURE__ */ new Map();
8268
+ const note = (file2, part) => {
8269
+ for (let d = dirOf(pathOfId(file2)); inside3(d, root) && d !== root; d = dirOf(d)) {
8270
+ const m = counts.get(d) ?? /* @__PURE__ */ new Map();
8271
+ m.set(part, (m.get(part) ?? 0) + 1);
8272
+ counts.set(d, m);
8273
+ }
8274
+ };
8275
+ parts.forEach((p, i) => p.forEach((f) => note(f, i)));
8276
+ return {
8277
+ place(file2) {
8278
+ const path2 = pathOfId(file2);
8279
+ for (let d = dirOf(path2); inside3(d, root) && d !== root; d = dirOf(d)) {
8280
+ const m = counts.get(d);
8281
+ if (!m) continue;
8282
+ const [best] = [...m].sort((x, y) => y[1] - x[1] || x[0] - y[0])[0];
8283
+ parts[best].push(file2);
8284
+ note(file2, best);
8285
+ return best;
8286
+ }
8287
+ const key = top(path2);
8288
+ if (key === root && parts.some((p) => p.length)) {
8289
+ let largest = 0;
8290
+ parts.forEach((p, i) => {
8291
+ if (p.length > parts[largest].length) largest = i;
8292
+ });
8293
+ parts[largest].push(file2);
8294
+ note(file2, largest);
8295
+ return largest;
8296
+ }
8297
+ let part = own2.get(key);
8298
+ if (part === void 0) {
8299
+ own2.set(key, part = parts.length);
8300
+ parts.push([]);
8301
+ }
8302
+ parts[part].push(file2);
8303
+ note(file2, part);
8304
+ return part;
8305
+ },
8306
+ note
8307
+ };
8308
+ };
8309
+ for (const b of boundaries) {
8310
+ const nodes = b.files.map((f) => f.id).filter(counted);
8311
+ const rest = b.files.map((f) => f.id).filter((f) => !counted(f) && !shared.has(f));
8312
+ const sim = similarity(nodes);
8313
+ const community = nodes.length ? louvain(nodes.length, sim.edges) : [];
8314
+ const groupsOf = /* @__PURE__ */ new Map();
8315
+ community.forEach((c, i) => {
8316
+ const list = groupsOf.get(c);
8317
+ if (list) list.push(i);
8318
+ else groupsOf.set(c, [i]);
8319
+ });
8320
+ const within = /* @__PURE__ */ new Map();
8321
+ const across = /* @__PURE__ */ new Map();
8322
+ for (const e of sim.edges) {
8323
+ const ca = community[e.a];
8324
+ const cb = community[e.b];
8325
+ if (ca === cb) within.set(ca, (within.get(ca) ?? 0) + e.w);
8326
+ else {
8327
+ across.set(ca, (across.get(ca) ?? 0) + e.w);
8328
+ across.set(cb, (across.get(cb) ?? 0) + e.w);
8329
+ }
8330
+ }
8331
+ const ownCount = b.files.filter((f) => user(f.id)).length;
8332
+ const minJoined = Math.max(PART_MIN_FILES, Math.floor(Math.log2(Math.max(ownCount, 1))));
8333
+ const joinedIn = (c, members2) => {
8334
+ const seen = /* @__PURE__ */ new Set();
8335
+ let largest = 0;
8336
+ for (const start of members2) {
8337
+ if (seen.has(start)) continue;
8338
+ let size = 0;
8339
+ const stack = [start];
8340
+ seen.add(start);
8341
+ while (stack.length) {
8342
+ const i = stack.pop();
8343
+ size++;
8344
+ for (const j of sim.linked[i].keys())
8345
+ if (!seen.has(j) && community[j] === c) {
8346
+ seen.add(j);
8347
+ stack.push(j);
8348
+ }
8349
+ }
8350
+ largest = Math.max(largest, size);
8351
+ }
8352
+ return largest;
8353
+ };
8354
+ const kept = [];
8355
+ const loose = [];
8356
+ for (const [c, members2] of [...groupsOf].sort((x, y) => x[1][0] - y[1][0])) {
8357
+ if (joinedIn(c, members2) >= minJoined && (within.get(c) ?? 0) >= (across.get(c) ?? 0))
8358
+ kept.push(members2);
8359
+ else loose.push(...members2);
8360
+ }
8361
+ let parts;
8362
+ let prior;
8363
+ if (kept.length < 2) {
8364
+ parts = [[...nodes]];
8365
+ prior = folders(b.root, parts);
8366
+ for (const f of rest) {
8367
+ parts[0].push(f);
8368
+ prior.note(f, 0);
8369
+ }
8370
+ rest.length = 0;
8371
+ } else {
8372
+ const partOf = /* @__PURE__ */ new Map();
8373
+ kept.forEach((p, i) => p.forEach((n2) => partOf.set(n2, i)));
8374
+ parts = kept.map((p) => p.map((i) => nodes[i]));
8375
+ prior = folders(b.root, parts);
8376
+ for (const i of loose.sort((x, y) => x - y)) {
8377
+ const toPart = /* @__PURE__ */ new Map();
8378
+ for (const [j, w] of sim.near[i]) {
8379
+ const p = partOf.get(j);
8380
+ if (p !== void 0) toPart.set(p, (toPart.get(p) ?? 0) + w);
8381
+ }
8382
+ let best = -1;
8383
+ let bestW = 0;
8384
+ for (const [p, w] of [...toPart].sort((x, y) => x[0] - y[0]))
8385
+ if (w > bestW + 1e-12) [best, bestW] = [p, w];
8386
+ if (best >= 0) {
8387
+ parts[best].push(nodes[i]);
8388
+ prior.note(nodes[i], best);
8389
+ partOf.set(i, best);
8390
+ } else partOf.set(i, prior.place(nodes[i]));
8391
+ }
8392
+ }
8393
+ const partOfFile = /* @__PURE__ */ new Map();
8394
+ parts.forEach((p, i) => p.forEach((f) => partOfFile.set(f, i)));
8395
+ for (const f of rest.sort(byPath)) {
8396
+ let best = -1;
8397
+ let most = 0;
8398
+ if (byId.get(f) && isTestPath(pathOfId(f)) && input2.own(byId.get(f))) {
8399
+ const toPart = /* @__PURE__ */ new Map();
8400
+ for (const [g, n2] of callsInto.get(f) ?? []) {
8401
+ const p = partOfFile.get(g);
8402
+ if (p !== void 0) toPart.set(p, (toPart.get(p) ?? 0) + n2);
8403
+ }
8404
+ for (const [p, n2] of [...toPart].sort((x, y) => x[0] - y[0])) if (n2 > most) [best, most] = [p, n2];
8405
+ }
8406
+ if (best >= 0) {
8407
+ parts[best].push(f);
8408
+ prior.note(f, best);
8409
+ } else prior.place(f);
8410
+ }
8411
+ for (const p of parts) {
8412
+ if (!p.length) continue;
8413
+ const files = [...p].sort(byPath);
8414
+ const placed = /* @__PURE__ */ new Map();
8415
+ const here = new Set(files);
8416
+ const linkedHere = /* @__PURE__ */ new Set();
8417
+ for (const f of files)
8418
+ for (const g of links.get(f)?.keys() ?? [])
8419
+ if (g !== f && here.has(g)) {
8420
+ linkedHere.add(f);
8421
+ if (user(f)) linkedHere.add(g);
8422
+ }
8423
+ for (const f of files) {
8424
+ const i = sim.index.get(f);
8425
+ const near = i === void 0 ? [] : [...sim.near[i].keys()].map((j) => nodes[j]).filter((g) => here.has(g));
8426
+ if (linkedHere.has(f)) placed.set(f, "joined");
8427
+ else if (near.some((g) => sim.usage(f, g))) placed.set(f, "used");
8428
+ else if (near.some((g) => sim.dependence(f, g))) placed.set(f, "using");
8429
+ else placed.set(f, "folder");
8430
+ }
8431
+ modules.push({ boundary: b, files, placed });
8432
+ }
8433
+ }
8434
+ const moduleOf = /* @__PURE__ */ new Map();
8435
+ modules.forEach((m, i) => {
8436
+ for (const f of m.files) moduleOf.set(f, i);
8437
+ });
8438
+ const between = /* @__PURE__ */ new Map();
8439
+ const outOf = new Array(modules.length).fill(0);
8440
+ for (const [from, row] of callsInto) {
8441
+ if (!counted(from)) continue;
8442
+ const a = moduleOf.get(from);
8443
+ if (a === void 0) continue;
8444
+ for (const [to, n2] of row) {
8445
+ const b = moduleOf.get(to);
8446
+ if (b === void 0 || b === a || shared.has(to)) continue;
8447
+ outOf[a] = outOf[a] + n2;
8448
+ between.set(`${a} ${b}`, (between.get(`${a} ${b}`) ?? 0) + n2);
8449
+ }
8450
+ }
8451
+ const parent = modules.map((_, i) => i);
8452
+ const find2 = (i) => parent[i] === i ? i : parent[i] = find2(parent[i]);
8453
+ const mutual = /* @__PURE__ */ new Map();
8454
+ for (let a = 0; a < modules.length; a++)
8455
+ for (let b = a + 1; b < modules.length; b++) {
8456
+ if (modules[a].boundary === modules[b].boundary) continue;
8457
+ if (modules[a].boundary.source !== modules[b].boundary.source) continue;
8458
+ const ab = between.get(`${a} ${b}`) ?? 0;
8459
+ const ba = between.get(`${b} ${a}`) ?? 0;
8460
+ if (Math.min(ab, ba) >= MERGE_MIN_CALLS && Math.min(ab, ba) >= Math.max(ab, ba) * MERGE_BALANCE && ab + ba >= Math.min(outOf[a], outOf[b]) * MERGE_SHARE) {
8461
+ mutual.set(`${a} ${b}`, [ab, ba]);
8462
+ parent[find2(b)] = find2(a);
8463
+ }
8464
+ }
8465
+ const sets = /* @__PURE__ */ new Map();
8466
+ modules.forEach((_, i) => {
8467
+ const r = find2(i);
8468
+ const list = sets.get(r);
8469
+ if (list) list.push(i);
8470
+ else sets.set(r, [i]);
8471
+ });
8472
+ const whole = (m) => m.files.length === m.boundary.files.length - (sharedOf.get(m.boundary.key)?.length ?? 0);
8473
+ const declaredSame = (files) => {
8474
+ const set2 = new Set(files);
8475
+ return input2.declared.find((g) => g.files.length === set2.size && g.files.every((f) => set2.has(f)));
8476
+ };
8477
+ const out = [];
8478
+ const reasons = [
8479
+ ["joined", "joined by calls"],
8480
+ ["used", "used by the same files"],
8481
+ ["using", "using the same files"],
8482
+ ["folder", "placed by its folder"]
8483
+ ];
8484
+ const describe4 = (m) => {
8485
+ const counts = reasons.map(([r, words]) => [[...m.placed.values()].filter((p) => p === r).length, words]).filter(([n3]) => n3 > 0);
8486
+ const n2 = m.files.length;
8487
+ const files = `${n2} file${n2 === 1 ? "" : "s"}`;
8488
+ const head = counts.length === 1 ? `${files} ${counts[0][1].replace("its folder", n2 === 1 ? "its folder" : "their folder")}` : `${files}, ${counts.map(
8489
+ ([k, words], i) => `${i === counts.length - 1 ? "and " : ""}${k} ${words.replace("its folder", k === 1 ? "its folder" : "their folder")}`
8490
+ ).join(counts.length > 2 ? ", " : " ")}`;
8491
+ return `Connected: ${head}${whole(m) ? `: all of ${m.boundary.name}` : `, part of ${m.boundary.name}`}`;
8492
+ };
8493
+ const singles = [];
8494
+ for (const [, members2] of [...sets].sort((a, b) => a[0] - b[0])) {
8495
+ if (members2.length === 1) {
8496
+ const m = modules[members2[0]];
8497
+ singles.push({ m, c: nameCluster(m.files.map((f) => byId.get(f))) });
8498
+ continue;
8499
+ }
8500
+ const ms = members2.map((i) => modules[i]);
8501
+ const files = ms.flatMap((m) => m.files).sort(byPath);
8502
+ const keyOf2 = (m) => whole(m) ? m.boundary.root : nameCluster(m.files.map((f) => byId.get(f))).main;
8503
+ const nameOf = (m) => whole(m) ? m.boundary.name : nameCluster(m.files.map((f) => byId.get(f))).name;
8504
+ const order = [...ms].sort((x, y) => cmp2(keyOf2(x), keyOf2(y)));
8505
+ const names = order.map(nameOf);
8506
+ let why = `Connected: ${names.slice(0, -1).join(", ")} and ${names[names.length - 1]} call into each other`;
8507
+ if (members2.length === 2) {
8508
+ const [ab, ba] = mutual.get(`${members2[0]} ${members2[1]}`) ?? [0, 0];
8509
+ why += ab === ba ? ` (${ab} calls each way)` : ` (${Math.max(ab, ba)} calls one way, ${Math.min(ab, ba)} the other)`;
8510
+ }
8511
+ out.push({
8512
+ type: "Group",
8513
+ id: `group|${ms[0].boundary.source}|module:${order.map(keyOf2).join("+")}`,
8514
+ name: names.join(" + "),
8515
+ kind: "module",
8516
+ source: ms[0].boundary.source,
8517
+ root: nameCluster(files.map((f) => byId.get(f))).root,
8518
+ files,
8519
+ externalPackages: [],
8520
+ why
8521
+ });
8522
+ }
8523
+ const mainCount = /* @__PURE__ */ new Map();
8524
+ for (const { m, c } of singles)
8525
+ if (!declaredSame(m.files))
8526
+ mainCount.set(
8527
+ `${m.boundary.source}\0${c.main}`,
8528
+ (mainCount.get(`${m.boundary.source}\0${c.main}`) ?? 0) + 1
8529
+ );
8530
+ const bySource = /* @__PURE__ */ new Map();
8531
+ for (const s of singles) {
8532
+ const list = bySource.get(s.m.boundary.source);
8533
+ if (list) list.push(s);
8534
+ else bySource.set(s.m.boundary.source, [s]);
8535
+ }
8536
+ for (const [source, list] of [...bySource].sort((a, b) => cmp2(a[0], b[0]))) {
8537
+ const named = disambiguate();
8538
+ const sorted = [...list].sort(
8539
+ (x, y) => cmp2(x.c.main, y.c.main) || y.c.files.length - x.c.files.length || cmp2(x.c.files[0].path, y.c.files[0].path)
8540
+ );
8541
+ for (const { m, c } of sorted) {
8542
+ const same = declaredSame(m.files);
8543
+ if (same) {
8544
+ out.push({
8545
+ type: "Group",
8546
+ id: same.id,
8547
+ name: same.name,
8548
+ kind: "module",
8549
+ source,
8550
+ root: same.root,
8551
+ files: m.files,
8552
+ externalPackages: [],
8553
+ why: describe4(m)
8554
+ });
8555
+ continue;
8556
+ }
8557
+ const d = named(c);
8558
+ let name = d.name;
8559
+ if ((mainCount.get(`${source}\0${c.main}`) ?? 0) > 1) {
8560
+ const prefix = sharedPrefix(c.files.map((f) => posix3.basename(f.path)));
8561
+ if (prefix) name = `${c.main || "(root)"} \xB7 ${prefix}* files`;
8562
+ }
8563
+ out.push({
8564
+ type: "Group",
8565
+ id: ids.cluster(source, d.key).replace("|cluster:", "|module:"),
8566
+ name,
8567
+ kind: "module",
8568
+ source,
8569
+ root: d.root,
8570
+ files: m.files,
8571
+ externalPackages: [],
8572
+ why: describe4(m)
8573
+ });
8574
+ }
8575
+ }
8576
+ const groupOf = /* @__PURE__ */ new Map();
8577
+ for (const g of out) for (const f of g.files) groupOf.set(f, g.id);
8578
+ for (const b of boundaries) {
8579
+ const layer = sharedOf.get(b.key);
8580
+ if (!layer) continue;
8581
+ const by = /* @__PURE__ */ new Set();
8582
+ for (const f of layer) for (const u of users.get(f) ?? []) if (!shared.has(u)) by.add(u);
8583
+ const groupsUsing = new Set([...by].map((u) => groupOf.get(u)).filter(Boolean));
8584
+ const files = layer.map((f) => byId.get(f));
8585
+ out.push({
8586
+ type: "Group",
8587
+ id: `group|${b.source}|shared:${b.root}`,
8588
+ name: `${b.name} \xB7 shared layer`,
8589
+ kind: "shared",
8590
+ source: b.source,
8591
+ root: nameCluster(files).root,
8592
+ files: layer,
8593
+ externalPackages: [],
8594
+ why: `Shared layer of ${b.name}: used by ${by.size} file${by.size === 1 ? "" : "s"} in ${groupsUsing.size} group${groupsUsing.size === 1 ? "" : "s"}`
8595
+ });
8596
+ for (const f of layer) groupOf.set(f, `group|${b.source}|shared:${b.root}`);
8597
+ }
8598
+ const taken = /* @__PURE__ */ new Set();
8599
+ for (const g of out) {
8600
+ if (taken.has(g.id)) g.id = `${g.id} (${byId.get(g.files[0]).path})`;
8601
+ taken.add(g.id);
8602
+ }
8603
+ out.sort((a, b) => cmp2(a.id, b.id));
8604
+ groupOf.clear();
8605
+ for (const g of out) for (const f of g.files) groupOf.set(f, g.id);
8606
+ const dependsOn = rollUp(out, groupOf, input2, input2.fnFile);
8607
+ for (const g of out) g.externalPackages.sort(cmp2);
8608
+ return { groups: out, dependsOn, differences: differencesOf(input2.declared, out) };
8609
+ }
8610
+ function sharedPrefix(names) {
8611
+ const counts = /* @__PURE__ */ new Map();
8612
+ for (const n3 of names) {
8613
+ const m = /^(.+?[-_.])/.exec(n3);
8614
+ if (m) counts.set(m[1], (counts.get(m[1]) ?? 0) + 1);
8615
+ }
8616
+ const [best, n2] = [...counts].sort((a, b) => b[1] - a[1] || cmp2(a[0], b[0]))[0] ?? ["", 0];
8617
+ return n2 >= Math.ceil(names.length * 0.6) && best ? best : null;
8618
+ }
8619
+ function differencesOf(declared2, connected) {
8620
+ const node2 = (side, id) => `${side}\0${id}`;
8621
+ const parent = /* @__PURE__ */ new Map();
8622
+ const find2 = (x) => {
8623
+ const p = parent.get(x) ?? x;
8624
+ if (p === x) return x;
8625
+ const r = find2(p);
8626
+ parent.set(x, r);
8627
+ return r;
8628
+ };
8629
+ const union2 = (a, b) => {
8630
+ const ra = find2(a);
8631
+ const rb = find2(b);
8632
+ if (ra !== rb) parent.set(rb, ra);
8633
+ };
8634
+ const declaredOf = /* @__PURE__ */ new Map();
8635
+ for (const g of declared2) for (const f of g.files) declaredOf.set(f, g.id);
8636
+ const counts = /* @__PURE__ */ new Map();
8637
+ for (const g of connected)
8638
+ for (const f of g.files) {
8639
+ const d = declaredOf.get(f);
8640
+ if (!d) continue;
8641
+ union2(node2("d", d), node2("c", g.id));
8642
+ const key = `${d}\0${g.id}`;
8643
+ counts.set(key, (counts.get(key) ?? 0) + 1);
8644
+ }
8645
+ const named = /* @__PURE__ */ new Map();
8646
+ for (const g of declared2) named.set(node2("d", g.id), { id: g.id, name: g.name });
8647
+ for (const g of connected) named.set(node2("c", g.id), { id: g.id, name: g.name });
8648
+ const sets = /* @__PURE__ */ new Map();
8649
+ for (const [key, g] of named) {
8650
+ const r = find2(key);
8651
+ const s = sets.get(r) ?? { declared: [], connected: [] };
8652
+ (key.startsWith("d\0") ? s.declared : s.connected).push(g);
8653
+ sets.set(r, s);
8654
+ }
8655
+ const byName = (a, b) => cmp2(a.name, b.name) || cmp2(a.id, b.id);
8656
+ return [...sets.values()].filter((s) => s.declared.length > 1 || s.connected.length > 1).map((s) => {
8657
+ const ids2 = new Set(s.connected.map((g) => g.id));
8658
+ return {
8659
+ declared: s.declared.sort(byName),
8660
+ connected: s.connected.sort(byName),
8661
+ files: [...counts].map(([key, count2]) => {
8662
+ const [d, c] = key.split("\0");
8663
+ return { declared: d, connected: c, count: count2 };
8664
+ }).filter((x) => ids2.has(x.connected)).sort((a, b) => cmp2(a.connected, b.connected) || cmp2(a.declared, b.declared))
8665
+ };
8666
+ }).sort((a, b) => cmp2(a.declared[0]?.id ?? "", b.declared[0]?.id ?? ""));
8667
+ }
8668
+ var SHARED_MIN_USERS, SHARED_SQRT_FACTOR, SHARED_MAX_USES, PART_MIN_FILES, MERGE_MIN_CALLS, MERGE_BALANCE, MERGE_SHARE, COMMON_MAX, CO_WEIGHT, cmp2, dirOf, inside3, discount;
8669
+ var init_connected = __esm({
8670
+ "packages/query-imports/src/connected.ts"() {
8671
+ "use strict";
8672
+ init_src();
8673
+ init_cluster();
8674
+ SHARED_MIN_USERS = 5;
8675
+ SHARED_SQRT_FACTOR = 2;
8676
+ SHARED_MAX_USES = 1 / 4;
8677
+ PART_MIN_FILES = 3;
8678
+ MERGE_MIN_CALLS = 2;
8679
+ MERGE_BALANCE = 1 / 3;
8680
+ MERGE_SHARE = 1 / 4;
8681
+ COMMON_MAX = 200;
8682
+ CO_WEIGHT = 0.5;
8683
+ cmp2 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
8684
+ dirOf = (path) => {
8685
+ const d = posix3.dirname(path);
8686
+ return d === "." ? "" : d;
8687
+ };
8688
+ inside3 = (path, dir) => dir === "" || path.startsWith(`${dir}/`);
8689
+ discount = (n2) => 1 / Math.log2(1 + Math.max(n2, 1));
8690
+ }
8691
+ });
8692
+
7650
8693
  // packages/query-imports/src/impact.ts
7651
8694
  function findingImpacts(reader, rows, own2, all2 = rows) {
7652
8695
  const into = /* @__PURE__ */ new Map();
@@ -7743,6 +8786,64 @@ var init_impact = __esm({
7743
8786
  }
7744
8787
  });
7745
8788
 
8789
+ // packages/query-imports/src/once.ts
8790
+ function onceReader(reader) {
8791
+ const byType = /* @__PURE__ */ new Map();
8792
+ const byFile = /* @__PURE__ */ new Map();
8793
+ const ofType = (type) => {
8794
+ let list = byType.get(type);
8795
+ if (!list) byType.set(type, list = reader.facts(type));
8796
+ return list;
8797
+ };
8798
+ const inFileOf = (type, file2) => {
8799
+ let index = byFile.get(type);
8800
+ if (!index) {
8801
+ index = /* @__PURE__ */ new Map();
8802
+ for (const f of ofType(type)) {
8803
+ const at = "file" in f && typeof f.file === "string" ? f.file : void 0;
8804
+ if (at === void 0) continue;
8805
+ const list = index.get(at);
8806
+ if (list) list.push(f);
8807
+ else index.set(at, [f]);
8808
+ }
8809
+ byFile.set(type, index);
8810
+ }
8811
+ return index.get(file2) ?? [];
8812
+ };
8813
+ const FILED = /* @__PURE__ */ new Set([
8814
+ "Function",
8815
+ "UnresolvedCallSite",
8816
+ "SiteResolution",
8817
+ "UnresolvedImport"
8818
+ ]);
8819
+ const KEPT = /* @__PURE__ */ new Set([...FILED, "File", "Group", "REFERENCES", "CALLS_CROSS_FILE"]);
8820
+ return {
8821
+ run: reader.run,
8822
+ ...reader.stages ? { stages: reader.stages } : {},
8823
+ ...reader.base !== void 0 ? { base: reader.base } : {},
8824
+ withStages: (stages) => reader.withStages(stages),
8825
+ fact: (id) => reader.fact(id),
8826
+ // As the store: a file given (not empty) reads that file's.
8827
+ facts: ((type, file2) => !KEPT.has(type) ? reader.facts(type, file2) : !file2 ? ofType(type) : FILED.has(type) ? inFileOf(type, file2) : reader.facts(type, file2)),
8828
+ factsTo: (type, dst) => reader.factsTo(type, dst),
8829
+ inFile: (file2) => reader.inFile(file2),
8830
+ callsFrom: (fn) => reader.callsFrom(fn),
8831
+ callsTo: (fn) => reader.callsTo(fn),
8832
+ countByFile: (type) => reader.countByFile(type),
8833
+ callCounts: (end2, ids2) => reader.callCounts(end2, ids2),
8834
+ count: (type) => reader.count(type),
8835
+ provenance: (ids2) => reader.provenance(ids2),
8836
+ writtenStages: () => reader.writtenStages(),
8837
+ scopesOf: (stage) => reader.scopesOf(stage),
8838
+ all: () => reader.all()
8839
+ };
8840
+ }
8841
+ var init_once = __esm({
8842
+ "packages/query-imports/src/once.ts"() {
8843
+ "use strict";
8844
+ }
8845
+ });
8846
+
7746
8847
  // packages/query-imports/src/symbols.ts
7747
8848
  function describeName(reader, e) {
7748
8849
  let target2 = null;
@@ -7879,7 +8980,7 @@ function listReferences(engine, args, cwd) {
7879
8980
  edges = edges.filter((e) => inFile.has(e.to));
7880
8981
  }
7881
8982
  }
7882
- edges.sort((a, b) => byPosition(a, b) || cmp(a.id, b.id));
8983
+ edges.sort((a, b) => byPosition(a, b) || cmp3(a.id, b.id));
7883
8984
  const references = edges.slice(0, limit).map((e) => ({
7884
8985
  id: e.id,
7885
8986
  from: endOf(reader, e.from),
@@ -7895,17 +8996,17 @@ function listReferences(engine, args, cwd) {
7895
8996
  }));
7896
8997
  return { ...meta3, direction, total: edges.length, truncated: edges.length > limit, references };
7897
8998
  }
7898
- var SYMBOL_IMPORTS_MAX, REFERENCES_MAX, cmp, pathOf, unusedName, byPosition;
8999
+ var SYMBOL_IMPORTS_MAX, REFERENCES_MAX, cmp3, pathOf, unusedName, byPosition;
7899
9000
  var init_symbols = __esm({
7900
9001
  "packages/query-imports/src/symbols.ts"() {
7901
9002
  "use strict";
7902
9003
  init_src();
7903
9004
  SYMBOL_IMPORTS_MAX = 500;
7904
9005
  REFERENCES_MAX = 500;
7905
- cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
9006
+ cmp3 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
7906
9007
  pathOf = (fileId) => fileId.slice(fileId.indexOf(":") + 1);
7907
9008
  unusedName = (e) => e.uses !== null && Object.values(e.uses).every((v) => v === 0);
7908
- byPosition = (a, b) => cmp(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset || cmp(a.local ?? "", b.local ?? "");
9009
+ byPosition = (a, b) => cmp3(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset || cmp3(a.local ?? "", b.local ?? "");
7909
9010
  }
7910
9011
  });
7911
9012
 
@@ -7978,8 +9079,8 @@ function projectTotals(engine, args, cwd) {
7978
9079
  const withinFiles = sum(reader.countByFile("CALLS"));
7979
9080
  const acrossFiles = sum(reader.countByFile("CALLS_CROSS_FILE"));
7980
9081
  const run2 = args.run ?? meta3.committedRun;
7981
- const summary2 = args.own && args.source === void 0 && run2 !== null ? keptFindingSummary(engine, meta3.project, run2) : void 0;
7982
- const kept = summary2?.completenessPending === pendingKey(pending) ? summary2.completeness : void 0;
9082
+ const summary2 = args.source === void 0 && run2 !== null ? keptFindingSummary(engine, meta3.project, run2) : void 0;
9083
+ const kept = summary2?.completenessPending === pendingKey(pending) ? args.own ? summary2.completeness : summary2.completenessAll : void 0;
7983
9084
  const completeness = kept ?? completenessOf(reader, inScope, withinFiles, acrossFiles);
7984
9085
  return {
7985
9086
  ...meta3,
@@ -7995,9 +9096,9 @@ function projectTotals(engine, args, cwd) {
7995
9096
  completeness
7996
9097
  };
7997
9098
  }
7998
- function completenessOf(reader, inScope, withinFiles, acrossFiles) {
9099
+ function completenessOf(reader, inScope, withinFiles, acrossFiles, file2) {
7999
9100
  const resolutions = new Map(
8000
- reader.facts("SiteResolution").filter((r) => inScope(r.file)).map((r) => [r.site, r])
9101
+ reader.facts("SiteResolution", file2).filter((r) => inScope(r.file)).map((r) => [r.site, r])
8001
9102
  );
8002
9103
  let external = 0;
8003
9104
  const candidates = { one: 0, several: 0 };
@@ -8009,7 +9110,8 @@ function completenessOf(reader, inScope, withinFiles, acrossFiles) {
8009
9110
  else exits2.named++;
8010
9111
  if (x.byType) exits2.byType++;
8011
9112
  };
8012
- for (const site of visibleSites(reader.facts("UnresolvedCallSite"), reader)) {
9113
+ const sites = file2 ? visibleSites([...reader.facts("UnresolvedCallSite", file2), ...reader.facts("CALLS_CROSS_FILE", file2)]) : visibleSites(reader.facts("UnresolvedCallSite"), reader);
9114
+ for (const site of sites) {
8013
9115
  if (!inScope(site.file)) continue;
8014
9116
  const r = resolutions.get(site.id);
8015
9117
  if (r?.status === "linked" || !r && (site.status === "linked" || site.status === "runtime-confirmed"))
@@ -8029,7 +9131,7 @@ function completenessOf(reader, inScope, withinFiles, acrossFiles) {
8029
9131
  open3.set(reason, (open3.get(reason) ?? 0) + 1);
8030
9132
  }
8031
9133
  const references = { functions: 0, packages: 0 };
8032
- for (const e of reader.facts("REFERENCES")) {
9134
+ for (const e of reader.facts("REFERENCES", file2)) {
8033
9135
  if (!inScope(e.evidence.file)) continue;
8034
9136
  if (e.exit) {
8035
9137
  references.packages++;
@@ -8044,7 +9146,7 @@ function completenessOf(reader, inScope, withinFiles, acrossFiles) {
8044
9146
  external,
8045
9147
  candidates,
8046
9148
  open: openTotal,
8047
- openByReason: [...open3].map(([reason, sites]) => ({ reason, sites })).sort((a, b) => b.sites - a.sites || (a.reason < b.reason ? -1 : 1)),
9149
+ openByReason: [...open3].map(([reason, sites2]) => ({ reason, sites: sites2 })).sort((a, b) => b.sites - a.sites || (a.reason < b.reason ? -1 : 1)),
8048
9150
  references,
8049
9151
  exits: exits2
8050
9152
  };
@@ -8061,7 +9163,7 @@ var init_totals = __esm({
8061
9163
  });
8062
9164
 
8063
9165
  // packages/query-imports/src/reads.ts
8064
- function cmp2(a, b) {
9166
+ function cmp4(a, b) {
8065
9167
  return a < b ? -1 : a > b ? 1 : 0;
8066
9168
  }
8067
9169
  function nonNegative2(offset) {
@@ -8094,16 +9196,100 @@ function fileFact(reader, id) {
8094
9196
  if (!f || f.type !== "File") throw new VeoError("not-found", `no file ${id}`, { kind: "file", id });
8095
9197
  return f;
8096
9198
  }
9199
+ function groupingOf(grouping) {
9200
+ if (grouping === void 0) return "declared";
9201
+ if (!GROUPINGS.includes(grouping))
9202
+ throw new VeoError("invalid-arguments", `grouping must be one of ${GROUPINGS.join(", ")}`, {
9203
+ fields: ["grouping"]
9204
+ });
9205
+ return grouping;
9206
+ }
9207
+ function deriveConnected(reader, pending) {
9208
+ return connectedGrouping({
9209
+ files: reader.facts("File"),
9210
+ declared: reader.facts("Group"),
9211
+ fnFile: new Map(reader.facts("Function").map((f) => [f.id, f.file])),
9212
+ imports: reader.facts("IMPORTS"),
9213
+ calls: reader.facts("CALLS_CROSS_FILE"),
9214
+ references: reader.facts("REFERENCES"),
9215
+ symbols: reader.facts("IMPORTS_SYMBOL"),
9216
+ own: (f) => f.origin === void 0 && !inPendingLibrary(f, pending)
9217
+ });
9218
+ }
9219
+ function connectedCounts(groups2, kept) {
9220
+ const groupOf = groupIndex([...groups2]);
9221
+ const counts = /* @__PURE__ */ new Map();
9222
+ for (const k of Object.values(kept)) {
9223
+ const g = groupOf.get(k.file)?.id;
9224
+ if (!g) continue;
9225
+ const c = counts.get(g) ?? zero();
9226
+ tally(c, k.kind);
9227
+ counts.set(g, c);
9228
+ }
9229
+ return counts;
9230
+ }
9231
+ function keepConnectedGrouping(engine, project2, run2) {
9232
+ const { reader, stage2: stage22 } = open(engine, { project: project2, run: run2 });
9233
+ if (!stage22) return;
9234
+ const pending = engine.pendingLibraries(project2, run2);
9235
+ const key = pendingKey(pending);
9236
+ const derived2 = deriveConnected(reader, pending);
9237
+ const impacts = keptImpacts(engine, project2, run2, key);
9238
+ const kept = {
9239
+ pending: key,
9240
+ made: engine.veoflow,
9241
+ ...derived2,
9242
+ ...impacts ? { findings: Object.fromEntries(connectedCounts(derived2.groups, impacts)) } : {}
9243
+ };
9244
+ engine.setRunSummary(project2, run2, CONNECTED_SUMMARY, kept);
9245
+ }
9246
+ function groupsView(engine, meta3, reader, run2, grouping) {
9247
+ const declared2 = reader.facts("Group");
9248
+ if (grouping === "declared")
9249
+ return {
9250
+ groups: declared2,
9251
+ dependsOn: reader.facts("DEPENDS_ON"),
9252
+ why: new Map(declared2.map((g) => [g.id, declaredWhy(g)]))
9253
+ };
9254
+ const pending = engine.pendingLibraries(meta3.project, run2);
9255
+ const made = engine.resolveProject({ project: meta3.project }).createdAt;
9256
+ const key = run2 === null ? null : `${meta3.project}\0${made}\0${run2}\0${pendingKey(pending)}`;
9257
+ let cache = connectedCache.get(engine);
9258
+ if (!cache) connectedCache.set(engine, cache = /* @__PURE__ */ new Map());
9259
+ const hit = key === null ? void 0 : cache.get(key);
9260
+ if (hit) return hit;
9261
+ const kept = run2 === null ? void 0 : engine.runSummary(meta3.project, run2, CONNECTED_SUMMARY);
9262
+ const usable = kept && kept.pending === pendingKey(pending) && (engine.veoflow === null || kept.made === engine.veoflow) ? kept : void 0;
9263
+ const derived2 = usable ?? deriveConnected(reader, pending);
9264
+ if (!usable && run2 !== null && declared2.length > 0)
9265
+ try {
9266
+ const keep = { pending: pendingKey(pending), made: engine.veoflow, ...derived2 };
9267
+ engine.setRunSummary(meta3.project, run2, CONNECTED_SUMMARY, keep);
9268
+ } catch {
9269
+ }
9270
+ const view = {
9271
+ groups: derived2.groups,
9272
+ dependsOn: derived2.dependsOn,
9273
+ why: new Map(derived2.groups.map((g) => [g.id, g.why])),
9274
+ differences: derived2.differences,
9275
+ ...usable?.findings ? { findings: new Map(Object.entries(usable.findings)) } : {}
9276
+ };
9277
+ if (key !== null) {
9278
+ if (cache.size >= CACHED_GROUPINGS) cache.delete(cache.keys().next().value);
9279
+ cache.set(key, view);
9280
+ }
9281
+ return view;
9282
+ }
8097
9283
  function groupIndex(groups2) {
8098
9284
  const byFile = /* @__PURE__ */ new Map();
8099
9285
  for (const g of groups2) for (const f of g.files) if (!byFile.has(f)) byFile.set(f, g);
8100
9286
  return byFile;
8101
9287
  }
8102
- function findingsIn(reader, groupOf, files) {
9288
+ function findingsIn(reader, groupOf, files, plain2 = false) {
8103
9289
  const each = (type) => files === null ? reader.facts(type) : files.flatMap((f) => reader.facts(type, f));
8104
9290
  const rows = [];
8105
9291
  const row = (fact, kind, text, reason, candidates, exhaustive) => {
8106
- const builtins = kind === "open-call" && UNTYPED_REASONS.has(reason) ? builtinsNamed(text) : [];
9292
+ const builtins = !plain2 && kind === "open-call" && UNTYPED_REASONS.has(reason) ? builtinsNamed(text) : [];
8107
9293
  rows.push({
8108
9294
  id: fact.id,
8109
9295
  kind,
@@ -8149,13 +9335,14 @@ function tally(counts, kind) {
8149
9335
  else if (kind === "pending") counts.pending++;
8150
9336
  else counts.openCalls++;
8151
9337
  }
8152
- function summary(g, functions, findings) {
9338
+ function summary(g, functions, findings, why) {
8153
9339
  let fns = 0;
8154
9340
  for (const f of g.files) fns += functions.get(f) ?? 0;
8155
9341
  return {
8156
9342
  id: g.id,
8157
9343
  name: g.name,
8158
9344
  kind: g.kind,
9345
+ why: why.get(g.id) ?? "",
8159
9346
  source: g.source,
8160
9347
  root: g.root,
8161
9348
  files: g.files.length,
@@ -8167,21 +9354,41 @@ function summary(g, functions, findings) {
8167
9354
  function listGroups(engine, args, cwd) {
8168
9355
  const limit = positiveLimit(args.limit, GROUPS_MAX, GROUPS_MAX);
8169
9356
  const offset = nonNegative2(args.offset);
9357
+ const grouping = groupingOf(args.grouping);
8170
9358
  const { meta: meta3, reader, stage2: stage22 } = open(engine, args, cwd);
8171
9359
  const inScope = (source) => args.source === void 0 || source === args.source;
8172
- const groups2 = reader.facts("Group").filter((g) => inScope(g.source)).sort((a, b) => cmp2(a.id, b.id));
9360
+ const run2 = args.run ?? meta3.committedRun;
9361
+ const view = groupsView(engine, meta3, reader, run2, grouping);
9362
+ const groups2 = view.groups.filter((g) => inScope(g.source)).sort((a, b) => cmp4(a.id, b.id));
8173
9363
  const groupOf = groupIndex(groups2);
8174
9364
  const findings = /* @__PURE__ */ new Map();
8175
9365
  let brokenImports2 = 0;
8176
9366
  let openCalls = 0;
8177
9367
  const files = reader.facts("File").filter((f) => inScope(f.source));
8178
- const run2 = args.run ?? meta3.committedRun;
8179
9368
  const pending = engine.pendingLibraries(meta3.project, run2);
8180
9369
  const ownFiles = new Set(files.filter(ownCodeTest(pending)).map((f) => f.id));
8181
9370
  let ownFindings;
8182
9371
  const kept = run2 === null ? void 0 : keptFindingSummary(engine, meta3.project, run2);
8183
9372
  if (kept) {
8184
- for (const g of groups2) if (kept.groups[g.id]) findings.set(g.id, kept.groups[g.id]);
9373
+ if (grouping === "declared") {
9374
+ for (const g of groups2) if (kept.groups[g.id]) findings.set(g.id, kept.groups[g.id]);
9375
+ } else {
9376
+ view.findings ??= (() => {
9377
+ const keptRows = run2 === null ? void 0 : keptImpacts(engine, meta3.project, run2, pendingKey(pending));
9378
+ if (keptRows) return connectedCounts(view.groups, keptRows);
9379
+ const all2 = groupIndex(view.groups);
9380
+ const counts = /* @__PURE__ */ new Map();
9381
+ for (const f of findingsIn(reader, all2, null, true)) {
9382
+ const g = all2.get(f.file)?.id;
9383
+ if (!g) continue;
9384
+ const c = counts.get(g) ?? zero();
9385
+ tally(c, f.kind);
9386
+ counts.set(g, c);
9387
+ }
9388
+ return counts;
9389
+ })();
9390
+ for (const g of groups2) if (view.findings.has(g.id)) findings.set(g.id, view.findings.get(g.id));
9391
+ }
8185
9392
  for (const [source, c] of Object.entries(kept.sources))
8186
9393
  if (inScope(source)) {
8187
9394
  brokenImports2 += c.broken;
@@ -8198,7 +9405,7 @@ function listGroups(engine, args, cwd) {
8198
9405
  }
8199
9406
  } else {
8200
9407
  ownFindings = { brokenImports: 0, openCalls: 0 };
8201
- for (const f of findingsIn(reader, groupOf, null)) {
9408
+ for (const f of findingsIn(reader, groupOf, null, true)) {
8202
9409
  if (!inScope(sourceOf2(f.file))) continue;
8203
9410
  if (f.kind === "broken") brokenImports2++;
8204
9411
  if (f.kind === "open-call") openCalls++;
@@ -8224,11 +9431,12 @@ function listGroups(engine, args, cwd) {
8224
9431
  for (const g of groups2) for (const p of g.externalPackages) importers.set(p, (importers.get(p) ?? 0) + 1);
8225
9432
  const packages = [...importers.keys()].map((id) => reader.fact(id)).filter((p) => p?.type === "ExternalPackage");
8226
9433
  packages.sort(
8227
- (a, b) => importers.get(b.id) - importers.get(a.id) || cmp2(a.name, b.name) || cmp2(a.id, b.id)
9434
+ (a, b) => importers.get(b.id) - importers.get(a.id) || cmp4(a.name, b.name) || cmp4(a.id, b.id)
8228
9435
  );
8229
9436
  return {
8230
9437
  ...meta3,
8231
9438
  stage2: stage22,
9439
+ grouping,
8232
9440
  stats: {
8233
9441
  files: files.length,
8234
9442
  functions: fnCount,
@@ -8245,8 +9453,8 @@ function listGroups(engine, args, cwd) {
8245
9453
  total: groups2.length,
8246
9454
  offset,
8247
9455
  truncated: groups2.length > offset + limit,
8248
- groups: shown.map((g) => summary(g, functions, findings)),
8249
- dependsOn: reader.facts("DEPENDS_ON").filter((d) => ids2.has(d.from) && ids2.has(d.to)).sort((a, b) => cmp2(a.id, b.id)).map(({ id, from, to, imports, calls, references, carrying, evidence }) => ({
9456
+ groups: shown.map((g) => summary(g, functions, findings, view.why)),
9457
+ dependsOn: view.dependsOn.filter((d) => ids2.has(d.from) && ids2.has(d.to)).sort((a, b) => cmp4(a.id, b.id)).map(({ id, from, to, imports, calls, references, carrying, evidence }) => ({
8250
9458
  id,
8251
9459
  from,
8252
9460
  to,
@@ -8259,9 +9467,14 @@ function listGroups(engine, args, cwd) {
8259
9467
  externalPackages: {
8260
9468
  total: packages.length,
8261
9469
  top: packages.slice(0, TOP_PACKAGES).map((p) => ({ id: p.id, name: p.name, ecosystem: p.ecosystem, groups: importers.get(p.id) }))
8262
- }
9470
+ },
9471
+ ...view.differences ? { differences: inScopeDifferences(view, groups2) } : {}
8263
9472
  };
8264
9473
  }
9474
+ function inScopeDifferences(view, groups2) {
9475
+ const ids2 = new Set(groups2.map((g) => g.id));
9476
+ return view.differences.filter((d) => d.connected.some((g) => ids2.has(g.id)));
9477
+ }
8265
9478
  function parentOf2(path) {
8266
9479
  const i = path.lastIndexOf("/");
8267
9480
  return i < 0 ? "" : path.slice(0, i);
@@ -8289,14 +9502,14 @@ function collapsedFolders(root, paths, expand, over) {
8289
9502
  return e ? e.files + e.folders.size : 0;
8290
9503
  };
8291
9504
  let visible = size(root);
8292
- const queue = [...children.get(root)?.folders ?? []].sort(cmp2);
9505
+ const queue = [...children.get(root)?.folders ?? []].sort(cmp4);
8293
9506
  while (queue.length) {
8294
9507
  const dir = queue.shift();
8295
9508
  const grows = size(dir) - 1;
8296
9509
  const asked = [...expand].some((x) => x === dir || x.startsWith(`${dir}/`));
8297
9510
  if (asked || visible === 1 || visible + grows <= over) {
8298
9511
  visible += grows;
8299
- queue.push(...[...children.get(dir)?.folders ?? []].sort(cmp2));
9512
+ queue.push(...[...children.get(dir)?.folders ?? []].sort(cmp4));
8300
9513
  } else collapsed.add(dir);
8301
9514
  }
8302
9515
  return collapsed;
@@ -8304,15 +9517,16 @@ function collapsedFolders(root, paths, expand, over) {
8304
9517
  function getGroup(engine, args, cwd) {
8305
9518
  if (typeof args.group !== "string" || !args.group)
8306
9519
  throw new VeoError("invalid-arguments", "group is required", { fields: ["group"] });
9520
+ const grouping = groupingOf(args.grouping);
8307
9521
  const { meta: meta3, reader, stage2: stage22 } = open(engine, args, cwd);
8308
- const group = reader.fact(args.group);
8309
- if (!group || group.type !== "Group")
8310
- throw new VeoError("not-found", `no group ${args.group}`, { kind: "group", id: args.group });
8311
- const groups2 = reader.facts("Group");
9522
+ const view = groupsView(engine, meta3, reader, args.run ?? meta3.committedRun, grouping);
9523
+ const group = view.groups.find((g) => g.id === args.group);
9524
+ if (!group) throw new VeoError("not-found", `no group ${args.group}`, { kind: "group", id: args.group });
9525
+ const groups2 = view.groups;
8312
9526
  const groupOf = groupIndex(groups2);
8313
9527
  const members2 = new Set(group.files);
8314
- const files = group.files.map((id) => reader.fact(id)).filter((f) => f?.type === "File").sort((a, b) => cmp2(a.path, b.path));
8315
- const root = group.kind === "cluster" ? "" : group.root;
9528
+ const files = group.files.map((id) => reader.fact(id)).filter((f) => f?.type === "File").sort((a, b) => cmp4(a.path, b.path));
9529
+ const root = group.kind === "repository" || group.kind === "workspace-package" ? group.root : "";
8316
9530
  const collapsed = collapsedFolders(
8317
9531
  root,
8318
9532
  files.map((f) => f.path),
@@ -8360,7 +9574,7 @@ function getGroup(engine, args, cwd) {
8360
9574
  findings: counts.get(f.id) ?? zero()
8361
9575
  })),
8362
9576
  ...folders.values()
8363
- ].sort((a, b) => cmp2(a.path, b.path) || cmp2(a.kind, b.kind));
9577
+ ].sort((a, b) => cmp4(a.path, b.path) || cmp4(a.kind, b.kind));
8364
9578
  const edges = /* @__PURE__ */ new Map();
8365
9579
  const stubs = /* @__PURE__ */ new Map();
8366
9580
  const add2 = (map2, from, to, evidence) => {
@@ -8454,8 +9668,8 @@ function getGroup(engine, args, cwd) {
8454
9668
  }
8455
9669
  }
8456
9670
  const packages = stubs.get("stub|packages");
8457
- packages?.packages.sort(cmp2);
8458
- const sorted = (m) => [...m.values()].filter((e) => kept.has(e.to) || stubs.has(e.to)).sort((a, b) => cmp2(a.id, b.id));
9671
+ packages?.packages.sort(cmp4);
9672
+ const sorted = (m) => [...m.values()].filter((e) => kept.has(e.to) || stubs.has(e.to)).sort((a, b) => cmp4(a.id, b.id));
8459
9673
  const functions = reader.countByFile("Function");
8460
9674
  const findings = /* @__PURE__ */ new Map();
8461
9675
  for (const c of counts.values()) {
@@ -8469,24 +9683,28 @@ function getGroup(engine, args, cwd) {
8469
9683
  return {
8470
9684
  ...meta3,
8471
9685
  stage2: stage22,
8472
- group: summary(group, functions, findings),
9686
+ grouping,
9687
+ group: summary(group, functions, findings, view.why),
8473
9688
  collapsed: collapsed.size > 0,
8474
9689
  total: nodes.length,
8475
9690
  truncated: nodes.length > GROUP_NODES_MAX,
8476
9691
  nodes: shown,
8477
9692
  imports: sorted(edges),
8478
- stubs: [...stubs.values()].sort((a, b) => cmp2(a.id, b.id)),
9693
+ stubs: [...stubs.values()].sort((a, b) => cmp4(a.id, b.id)),
8479
9694
  stubEdges: sorted(stubEdges),
8480
- calls: [...callEdges.values()].filter((e) => kept.has(e.to)).sort((a, b) => cmp2(a.id, b.id)),
8481
- callStubEdges: [...callStubs.values()].sort((a, b) => cmp2(a.id, b.id))
9695
+ calls: [...callEdges.values()].filter((e) => kept.has(e.to)).sort((a, b) => cmp4(a.id, b.id)),
9696
+ callStubEdges: [...callStubs.values()].sort((a, b) => cmp4(a.id, b.id))
8482
9697
  };
8483
9698
  }
8484
9699
  function resolveImports(engine, args, cwd) {
8485
9700
  if (typeof args.file !== "string" || !args.file)
8486
9701
  throw new VeoError("invalid-arguments", "file is required", { fields: ["file"] });
9702
+ const grouping = groupingOf(args.grouping);
8487
9703
  const { meta: meta3, reader, stage2: stage22 } = open(engine, args, cwd);
8488
9704
  const file2 = fileFact(reader, args.file);
8489
- const groupOf = groupIndex(reader.facts("Group"));
9705
+ const groupOf = groupIndex(
9706
+ groupsView(engine, meta3, reader, args.run ?? meta3.committedRun, grouping).groups
9707
+ );
8490
9708
  const ref = (id) => ({ id, path: pathOf2(id), group: groupOf.get(id)?.id ?? null });
8491
9709
  const imports = [
8492
9710
  ...reader.facts("IMPORTS", file2.id).map((e) => {
@@ -8570,21 +9788,22 @@ function listFindings(engine, args, cwd) {
8570
9788
  if (args.own !== void 0 && typeof args.own !== "boolean")
8571
9789
  throw new VeoError("invalid-arguments", "own must be true or false", { fields: ["own"] });
8572
9790
  const limit = positiveLimit(args.limit, 100, FINDINGS_MAX);
9791
+ const grouping = groupingOf(args.grouping);
8573
9792
  const { meta: meta3, reader, stage2: stage22 } = open(engine, args, cwd);
8574
9793
  const run2 = args.run ?? meta3.committedRun;
8575
9794
  const pending = engine.pendingLibraries(meta3.project, run2);
8576
9795
  const ownFiles = args.own ? new Set(
8577
9796
  reader.facts("File").filter(ownCodeTest(pending)).map((f) => f.id)
8578
9797
  ) : null;
8579
- const groups2 = reader.facts("Group");
9798
+ const view = groupsView(engine, meta3, reader, run2, grouping);
9799
+ const groups2 = view.groups;
8580
9800
  const groupOf = groupIndex(groups2);
8581
9801
  let inScope = () => true;
8582
9802
  let files = null;
8583
9803
  if (args.source !== void 0) inScope = (f) => sourceOf2(f.file) === args.source;
8584
9804
  else if (args.group !== void 0) {
8585
- const g = reader.fact(args.group);
8586
- if (!g || g.type !== "Group")
8587
- throw new VeoError("not-found", `no group ${args.group}`, { kind: "group", id: args.group });
9805
+ const g = groups2.find((x) => x.id === args.group);
9806
+ if (!g) throw new VeoError("not-found", `no group ${args.group}`, { kind: "group", id: args.group });
8588
9807
  files = g.files;
8589
9808
  } else if (args.file !== void 0) files = [fileFact(reader, args.file).id];
8590
9809
  const kinds = new Set(args.kind?.length ? args.kind : ["broken", "not-analyzed", "open-call"]);
@@ -8634,7 +9853,7 @@ function listFindings(engine, args, cwd) {
8634
9853
  if (kinds.has(k.kind)) order.push([id, k]);
8635
9854
  }
8636
9855
  order.sort(
8637
- ([ia, a], [ib, b]) => Number(!!a.last) - Number(!!b.last) || b.opens - a.opens || cmp2(a.file, b.file) || a.offset - b.offset || cmp2(ia, ib)
9856
+ ([ia, a], [ib, b]) => Number(!!a.last) - Number(!!b.last) || b.opens - a.opens || cmp4(a.file, b.file) || a.offset - b.offset || cmp4(ia, ib)
8638
9857
  );
8639
9858
  const page = order.slice(offset, offset + limit);
8640
9859
  const wanted2 = new Set(page.map(([id]) => id));
@@ -8660,7 +9879,7 @@ function listFindings(engine, args, cwd) {
8660
9879
  if (kinds.has(f.kind)) rows2.push(f);
8661
9880
  }
8662
9881
  const all2 = withImpact(rows2).sort(
8663
- (a, b) => Number(listedLast(a)) - Number(listedLast(b)) || (b.impact?.opens ?? 0) - (a.impact?.opens ?? 0) || byEvidence(a, b) || cmp2(a.id, b.id)
9882
+ (a, b) => Number(listedLast(a)) - Number(listedLast(b)) || (b.impact?.opens ?? 0) - (a.impact?.opens ?? 0) || byEvidence(a, b) || cmp4(a.id, b.id)
8664
9883
  );
8665
9884
  return {
8666
9885
  ...meta3,
@@ -8673,9 +9892,9 @@ function listFindings(engine, args, cwd) {
8673
9892
  };
8674
9893
  }
8675
9894
  const kept = run2 === null || args.source !== void 0 || args.file !== void 0 ? void 0 : keptFindingSummary(engine, meta3.project, run2);
8676
- const keptCounts = !kept ? void 0 : ownFiles ? args.group === void 0 ? ownCounts(kept, pending) : void 0 : args.group === void 0 ? kept.counts : kept.groups[args.group] ?? zero();
9895
+ const keptCounts = !kept ? void 0 : ownFiles ? args.group === void 0 ? ownCounts(kept, pending) : void 0 : args.group === void 0 ? kept.counts : grouping === "declared" ? kept.groups[args.group] ?? zero() : void 0;
8677
9896
  if (keptCounts) {
8678
- const order = (files ?? reader.facts("File").map((f) => f.id)).filter((f) => !ownFiles || ownFiles.has(f)).sort(cmp2);
9897
+ const order = (files ?? reader.facts("File").map((f) => f.id)).filter((f) => !ownFiles || ownFiles.has(f)).sort(cmp4);
8679
9898
  const total = [...kinds].reduce((n2, k) => n2 + keptCounts[KIND_COUNT[k]], 0);
8680
9899
  const page = [];
8681
9900
  let skipped = 0;
@@ -8755,7 +9974,7 @@ function siteLinks(engine, args, cwd) {
8755
9974
  return { ...meta3, stage2: stage22, links };
8756
9975
  }
8757
9976
  function summarizeFindings(engine, project2, run2) {
8758
- const { reader } = open(engine, { project: project2, run: run2 });
9977
+ const reader = onceReader(open(engine, { project: project2, run: run2 }).reader);
8759
9978
  const files = reader.facts("File");
8760
9979
  const summary2 = {
8761
9980
  counts: zero(),
@@ -8804,13 +10023,16 @@ function summarizeFindings(engine, project2, run2) {
8804
10023
  };
8805
10024
  engine.setRunSummary(project2, run2, IMPACT_SUMMARY, { pending: pendingNow, items });
8806
10025
  if (reader.count("Group") > 0) {
8807
- const count2 = (byFile) => [...byFile].reduce((n2, [f, c]) => n2 + (inOwn.has(f) ? c : 0), 0);
10026
+ const within = reader.countByFile("CALLS");
10027
+ const across = reader.countByFile("CALLS_CROSS_FILE");
10028
+ const count2 = (byFile, own3) => [...byFile].reduce((n2, [f, c]) => n2 + (!own3 || inOwn.has(f) ? c : 0), 0);
8808
10029
  summary2.completeness = completenessOf(
8809
10030
  reader,
8810
10031
  (file2) => inOwn.has(file2),
8811
- count2(reader.countByFile("CALLS")),
8812
- count2(reader.countByFile("CALLS_CROSS_FILE"))
10032
+ count2(within, true),
10033
+ count2(across, true)
8813
10034
  );
10035
+ summary2.completenessAll = completenessOf(reader, () => true, count2(within, false), count2(across, false));
8814
10036
  summary2.completenessPending = pendingNow;
8815
10037
  }
8816
10038
  engine.setRunSummary(project2, run2, FINDINGS_SUMMARY, summary2);
@@ -8838,13 +10060,15 @@ function ownCounts(summary2, pending) {
8838
10060
  const own2 = ownBySource(summary2, pending);
8839
10061
  return own2 ? Object.values(own2).reduce(add, zero()) : void 0;
8840
10062
  }
8841
- var STAGE2, GROUPS_MAX, GROUP_NODES_MAX, GROUP_COLLAPSE_OVER, IMPORTS_MAX, FINDINGS_MAX, TOP_PACKAGES, pathOf2, sourceOf2, byEvidence, FINDING_KINDS, UNTYPED_REASONS, listedLast, KIND_COUNT, zero, add, FINDINGS_SUMMARY, IMPACT_SUMMARY;
10063
+ var STAGE2, GROUPS_MAX, GROUP_NODES_MAX, GROUP_COLLAPSE_OVER, IMPORTS_MAX, FINDINGS_MAX, TOP_PACKAGES, pathOf2, sourceOf2, byEvidence, GROUPINGS, CONNECTED_SUMMARY, connectedCache, CACHED_GROUPINGS, FINDING_KINDS, UNTYPED_REASONS, listedLast, KIND_COUNT, zero, add, FINDINGS_SUMMARY, IMPACT_SUMMARY;
8842
10064
  var init_reads = __esm({
8843
10065
  "packages/query-imports/src/reads.ts"() {
8844
10066
  "use strict";
8845
10067
  init_src();
8846
10068
  init_builtins();
10069
+ init_connected();
8847
10070
  init_impact();
10071
+ init_once();
8848
10072
  init_symbols();
8849
10073
  init_totals();
8850
10074
  STAGE2 = "stage2";
@@ -8856,7 +10080,11 @@ var init_reads = __esm({
8856
10080
  TOP_PACKAGES = 20;
8857
10081
  pathOf2 = (fileId) => fileId.slice(fileId.indexOf(":") + 1);
8858
10082
  sourceOf2 = (fileId) => fileId.slice(0, fileId.indexOf(":"));
8859
- byEvidence = (a, b) => cmp2(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset || cmp2(a.id, b.id);
10083
+ byEvidence = (a, b) => cmp4(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset || cmp4(a.id, b.id);
10084
+ GROUPINGS = ["declared", "connected"];
10085
+ CONNECTED_SUMMARY = "connected/v1";
10086
+ connectedCache = /* @__PURE__ */ new WeakMap();
10087
+ CACHED_GROUPINGS = 8;
8860
10088
  FINDING_KINDS = ["broken", "not-analyzed", "pending", "open-call"];
8861
10089
  UNTYPED_REASONS = /* @__PURE__ */ new Set(["dynamic-dispatch", "untyped"]);
8862
10090
  listedLast = (f) => f.mayBe?.projectFunctions === 0;
@@ -8873,7 +10101,7 @@ var init_reads = __esm({
8873
10101
  pending: a.pending + b.pending,
8874
10102
  openCalls: a.openCalls + b.openCalls
8875
10103
  });
8876
- FINDINGS_SUMMARY = "findings/v7";
10104
+ FINDINGS_SUMMARY = "findings/v8";
8877
10105
  IMPACT_SUMMARY = "impact/v3";
8878
10106
  }
8879
10107
  });
@@ -9212,7 +10440,7 @@ function explain(engine, args, cwd) {
9212
10440
  items.sort(
9213
10441
  (a, b) => (
9214
10442
  // Every item on a line has evidence (it was matched by it).
9215
- a.evidence.span.start.offset - b.evidence.span.start.offset || cmp3(a.kind, b.kind) || cmp3(a.id, b.id)
10443
+ a.evidence.span.start.offset - b.evidence.span.start.offset || cmp5(a.kind, b.kind) || cmp5(a.id, b.id)
9216
10444
  )
9217
10445
  );
9218
10446
  return {
@@ -9224,7 +10452,7 @@ function explain(engine, args, cwd) {
9224
10452
  ...file2.status !== "analyzed" ? { file: { status: file2.status, ...file2.reason ? { reason: file2.reason } : {} } } : {}
9225
10453
  };
9226
10454
  }
9227
- var EXPLAIN_MAX, pathOf3, cmp3, IMPORT_REASONS, SITE_REASONS, STATUS_WORDS, base, IMPORT_FIXES, CALL_FIXES, RESOLUTION_WORDS;
10455
+ var EXPLAIN_MAX, pathOf3, cmp5, IMPORT_REASONS, SITE_REASONS, STATUS_WORDS, base, IMPORT_FIXES, CALL_FIXES, RESOLUTION_WORDS;
9228
10456
  var init_explain = __esm({
9229
10457
  "packages/query-imports/src/explain.ts"() {
9230
10458
  "use strict";
@@ -9232,7 +10460,7 @@ var init_explain = __esm({
9232
10460
  init_builtins();
9233
10461
  EXPLAIN_MAX = 50;
9234
10462
  pathOf3 = (fileId) => fileId.slice(fileId.indexOf(":") + 1);
9235
- cmp3 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
10463
+ cmp5 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
9236
10464
  IMPORT_REASONS = {
9237
10465
  "file-not-found": "no file matches it",
9238
10466
  "not-exported": "the package's exports don't include that path",
@@ -9362,7 +10590,7 @@ function reach(engine, args, cwd) {
9362
10590
  const exits2 = [];
9363
10591
  let work = 0;
9364
10592
  let truncated = null;
9365
- let frontier = roots.map((f) => f.id).sort(cmp4);
10593
+ let frontier = roots.map((f) => f.id).sort(cmp6);
9366
10594
  if (frontier.length > budget.functions) {
9367
10595
  frontier = frontier.slice(0, budget.functions);
9368
10596
  truncated = { reason: "functions", depth: 0 };
@@ -9399,19 +10627,19 @@ function reach(engine, args, cwd) {
9399
10627
  if (!edges.has(key)) edges.set(key, e);
9400
10628
  }
9401
10629
  }
9402
- frontier = [...next].sort(cmp4);
10630
+ frontier = [...next].sort(cmp6);
9403
10631
  }
9404
- const functions = [...depthOf2.entries()].map(([id, depth]) => g.describe(id, depth)).sort((a, b) => a.depth - b.depth || cmp4(a.id, b.id));
10632
+ const functions = [...depthOf2.entries()].map(([id, depth]) => g.describe(id, depth)).sort((a, b) => a.depth - b.depth || cmp6(a.id, b.id));
9405
10633
  const reached = functions.filter((f) => f.depth > 0);
9406
10634
  const starts = direction === "backward" ? functions.flatMap((f) => {
9407
10635
  const c = reader.fact(`start|${f.id}`);
9408
10636
  return c?.type === "StartCandidate" ? [{ function: f.id, bases: [...new Set(c.bases.map((b) => b.kind))] }] : [];
9409
10637
  }) : [];
9410
10638
  const edgeList = [...edges.values()].sort(
9411
- (a, b) => byEvidence2(a, b) || cmp4(a.from, b.from) || cmp4(a.to, b.to) || cmp4(a.kind, b.kind)
10639
+ (a, b) => byEvidence2(a, b) || cmp6(a.from, b.from) || cmp6(a.to, b.to) || cmp6(a.kind, b.kind)
9412
10640
  );
9413
- gaps.sort((a, b) => byEvidence2(a, b) || cmp4(a.site, b.site));
9414
- exits2.sort((a, b) => byEvidence2(a, b) || cmp4(a.id, b.id));
10641
+ gaps.sort((a, b) => byEvidence2(a, b) || cmp6(a.site, b.site));
10642
+ exits2.sort((a, b) => byEvidence2(a, b) || cmp6(a.id, b.id));
9415
10643
  return {
9416
10644
  ...meta3,
9417
10645
  root: args.function !== void 0 ? { function: args.function } : { file: args.file },
@@ -9665,7 +10893,7 @@ function graphOf(reader, candidates) {
9665
10893
  };
9666
10894
  return { forward, backward, describe: describe4 };
9667
10895
  }
9668
- var callStage, REACH_DEPTH, REACH_FUNCTIONS, REACH_WORK, cmp4, pathOf4, byEvidence2, candidateIndexes;
10896
+ var callStage, REACH_DEPTH, REACH_FUNCTIONS, REACH_WORK, cmp6, pathOf4, byEvidence2, candidateIndexes;
9669
10897
  var init_reach = __esm({
9670
10898
  "packages/query-imports/src/reach.ts"() {
9671
10899
  "use strict";
@@ -9675,9 +10903,9 @@ var init_reach = __esm({
9675
10903
  REACH_DEPTH = { default: 8, max: 64 };
9676
10904
  REACH_FUNCTIONS = { default: 500, max: 5e3 };
9677
10905
  REACH_WORK = { default: 5e4, max: 5e5 };
9678
- cmp4 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
10906
+ cmp6 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
9679
10907
  pathOf4 = (fileId) => fileId.slice(fileId.indexOf(":") + 1);
9680
- byEvidence2 = (a, b) => cmp4(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset;
10908
+ byEvidence2 = (a, b) => cmp6(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset;
9681
10909
  candidateIndexes = /* @__PURE__ */ new WeakMap();
9682
10910
  }
9683
10911
  });
@@ -9710,53 +10938,60 @@ function listExits(engine, args, cwd) {
9710
10938
  if (!g) groups2.set(key, g = { exit: x, calls: [], references: 0 });
9711
10939
  return g;
9712
10940
  };
9713
- const sites = new Map(
9714
- (args.file !== void 0 ? reader.facts("UnresolvedCallSite", args.file) : reader.facts("UnresolvedCallSite")).map((s) => [s.id, s])
9715
- );
9716
- const resolutions = args.file !== void 0 ? reader.facts("SiteResolution", args.file) : reader.facts("SiteResolution");
9717
- for (const r of resolutions) {
9718
- if (!r.exit || !wanted2(r.file, r.exit)) continue;
9719
- const s = sites.get(r.site);
9720
- if (!s) continue;
9721
- at(r.exit).calls.push({
9722
- evidence: r.evidence,
9723
- make: () => ({
9724
- id: r.id,
9725
- kind: "call",
9726
- path: pathOf5(r.file),
9727
- line: r.evidence.span.start.line,
9728
- function: fnEnd(reader, s.enclosingFn),
9729
- expression: s.expression,
9730
- ...r.exit.literals?.length ? { literals: r.exit.literals } : {},
9731
- ...r.exit.reason ? { reason: r.exit.reason } : {},
9732
- evidence: r.evidence
9733
- })
9734
- });
9735
- }
9736
- const references = args.file !== void 0 ? reader.facts("REFERENCES", args.file) : reader.facts("REFERENCES");
9737
- for (const e of references) {
9738
- if (!e.exit || !wanted2(e.evidence.file, e.exit)) continue;
9739
- const g = at(e.exit);
9740
- g.references++;
9741
- g.calls.push({
9742
- evidence: e.evidence,
9743
- make: () => ({
9744
- id: e.id,
9745
- kind: "reference",
9746
- path: pathOf5(e.evidence.file),
9747
- line: e.evidence.span.start.line,
9748
- function: fnEnd(reader, e.from),
9749
- expression: [e.exit.name, e.exit.member].filter(Boolean).join("."),
9750
- evidence: e.evidence
9751
- })
9752
- });
9753
- }
10941
+ const grouped = () => {
10942
+ const sites = new Map(
10943
+ (args.file !== void 0 ? reader.facts("UnresolvedCallSite", args.file) : reader.facts("UnresolvedCallSite")).map((s) => [s.id, s])
10944
+ );
10945
+ const resolutions = args.file !== void 0 ? reader.facts("SiteResolution", args.file) : reader.facts("SiteResolution");
10946
+ for (const r of resolutions) {
10947
+ if (!r.exit || !wanted2(r.file, r.exit)) continue;
10948
+ const s = sites.get(r.site);
10949
+ if (!s) continue;
10950
+ at(r.exit).calls.push({
10951
+ evidence: r.evidence,
10952
+ make: (rd) => ({
10953
+ id: r.id,
10954
+ kind: "call",
10955
+ path: pathOf5(r.file),
10956
+ line: r.evidence.span.start.line,
10957
+ function: fnEnd(rd, s.enclosingFn),
10958
+ expression: s.expression,
10959
+ ...r.exit.literals?.length ? { literals: r.exit.literals } : {},
10960
+ ...r.exit.reason ? { reason: r.exit.reason } : {},
10961
+ evidence: r.evidence
10962
+ })
10963
+ });
10964
+ }
10965
+ const references = args.file !== void 0 ? reader.facts("REFERENCES", args.file) : reader.facts("REFERENCES");
10966
+ for (const e of references) {
10967
+ if (!e.exit || !wanted2(e.evidence.file, e.exit)) continue;
10968
+ const g = at(e.exit);
10969
+ g.references++;
10970
+ g.calls.push({
10971
+ evidence: e.evidence,
10972
+ make: (rd) => ({
10973
+ id: e.id,
10974
+ kind: "reference",
10975
+ path: pathOf5(e.evidence.file),
10976
+ line: e.evidence.span.start.line,
10977
+ function: fnEnd(rd, e.from),
10978
+ expression: [e.exit.name, e.exit.member].filter(Boolean).join("."),
10979
+ evidence: e.evidence
10980
+ })
10981
+ });
10982
+ }
10983
+ for (const g of groups2.values()) g.calls.sort(byPosition2);
10984
+ return [...groups2.entries()].sort(([ka, a], [kb, b]) => b.calls.length - a.calls.length || cmp7(ka, kb));
10985
+ };
9754
10986
  const pkgName = (id) => {
9755
10987
  const p = reader.fact(id);
9756
10988
  return p?.type === "ExternalPackage" ? p.name : id;
9757
10989
  };
9758
- const all2 = [...groups2.entries()].sort(
9759
- ([ka, a], [kb, b]) => b.calls.length - a.calls.length || cmp5(ka, kb)
10990
+ const all2 = args.file !== void 0 || meta3.committedRun === null ? grouped() : engine.memo(
10991
+ engine.resolveProject({ project: meta3.project }),
10992
+ reader.run,
10993
+ `exits\0${JSON.stringify([args.package ?? null, args.name ?? null, args.member ?? null, args.source ?? null])}`,
10994
+ grouped
9760
10995
  );
9761
10996
  let calls = 0;
9762
10997
  let refs = 0;
@@ -9779,7 +11014,7 @@ function listExits(engine, args, cwd) {
9779
11014
  instance: !!g.exit.instance,
9780
11015
  calls: g.calls.length - g.references,
9781
11016
  references: g.references,
9782
- sites: g.calls.sort(byPosition2).slice(0, perGroup).map((c) => c.make())
11017
+ sites: g.calls.slice(0, perGroup).map((c) => c.make(reader))
9783
11018
  }))
9784
11019
  };
9785
11020
  }
@@ -9841,7 +11076,7 @@ function listStartCandidates(engine, args, cwd) {
9841
11076
  }))
9842
11077
  };
9843
11078
  }).sort(
9844
- (a, b) => cmp5(a.group?.name ?? "", b.group?.name ?? "") || cmp5(a.function.path, b.function.path) || a.function.line - b.function.line || cmp5(a.function.id, b.function.id)
11079
+ (a, b) => cmp7(a.group?.name ?? "", b.group?.name ?? "") || cmp7(a.function.path, b.function.path) || a.function.line - b.function.line || cmp7(a.function.id, b.function.id)
9845
11080
  );
9846
11081
  return {
9847
11082
  ...meta3,
@@ -9849,11 +11084,11 @@ function listStartCandidates(engine, args, cwd) {
9849
11084
  offset,
9850
11085
  truncated: offset + limit < rows.length,
9851
11086
  byBasis,
9852
- byGroup: [...counts.values()].sort((a, b) => b.count - a.count || cmp5(a.name, b.name)),
11087
+ byGroup: [...counts.values()].sort((a, b) => b.count - a.count || cmp7(a.name, b.name)),
9853
11088
  candidates: rows.slice(offset, offset + limit)
9854
11089
  };
9855
11090
  }
9856
- var EXITS_MAX, EXIT_SITES_MAX, START_CANDIDATES_MAX, cmp5, pathOf5, sourceOf3, exitKey, byPosition2;
11091
+ var EXITS_MAX, EXIT_SITES_MAX, START_CANDIDATES_MAX, cmp7, pathOf5, sourceOf3, exitKey, byPosition2;
9857
11092
  var init_exits = __esm({
9858
11093
  "packages/query-imports/src/exits.ts"() {
9859
11094
  "use strict";
@@ -9862,11 +11097,11 @@ var init_exits = __esm({
9862
11097
  EXITS_MAX = 500;
9863
11098
  EXIT_SITES_MAX = 100;
9864
11099
  START_CANDIDATES_MAX = 500;
9865
- cmp5 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
11100
+ cmp7 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
9866
11101
  pathOf5 = (fileId) => fileId.slice(fileId.indexOf(":") + 1);
9867
11102
  sourceOf3 = (fileId) => fileId.slice(0, fileId.indexOf(":"));
9868
11103
  exitKey = (x) => `${x.package ?? "runtime"}|${x.name ?? ""}|${x.member ?? ""}|${x.instance ? 1 : 0}`;
9869
- byPosition2 = (a, b) => cmp5(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset;
11104
+ byPosition2 = (a, b) => cmp7(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset;
9870
11105
  }
9871
11106
  });
9872
11107
 
@@ -10112,7 +11347,8 @@ function outcomes(reader, file2) {
10112
11347
  reader,
10113
11348
  (f) => f === file2,
10114
11349
  reader.facts("CALLS", file2).length,
10115
- reader.facts("CALLS_CROSS_FILE", file2).length
11350
+ reader.facts("CALLS_CROSS_FILE", file2).length,
11351
+ file2
10116
11352
  );
10117
11353
  return {
10118
11354
  sites: c.sites,
@@ -10338,9 +11574,9 @@ function tallies(engine, s) {
10338
11574
  for (const g of reader.facts("Group")) for (const f of g.files) if (!groupOf.has(f)) groupOf.set(f, g);
10339
11575
  const own2 = ownCodeTest(engine.pendingLibraries(s.meta.project, s.run));
10340
11576
  for (const t of out.values()) {
10341
- t.row.ids.sort(cmp6);
10342
- t.row.versions.sort(cmp6);
10343
- t.row.sources.sort(cmp6);
11577
+ t.row.ids.sort(cmp8);
11578
+ t.row.versions.sort(cmp8);
11579
+ t.row.sources.sort(cmp8);
10344
11580
  t.row.files = t.importers.size;
10345
11581
  const groups2 = /* @__PURE__ */ new Set();
10346
11582
  for (const id of t.importers.keys()) {
@@ -10358,7 +11594,13 @@ function listLibraries(engine, args, cwd) {
10358
11594
  const limit = positive(args.limit, LIBRARIES_MAX, LIBRARIES_MAX, "limit");
10359
11595
  const offset = nonNegative(args.offset);
10360
11596
  const s = scope(engine, args, cwd);
10361
- const packages = [...tallies(engine, s).values()].map((t) => t.row).sort(byUse);
11597
+ const tallied = s.run === null ? tallies(engine, s) : engine.memo(
11598
+ engine.resolveProject({ project: s.meta.project }),
11599
+ s.run,
11600
+ `libraries\0${args.source ?? ""}\0${pendingKey(engine.pendingLibraries(s.meta.project, s.run))}`,
11601
+ () => tallies(engine, s)
11602
+ );
11603
+ const packages = [...tallied.values()].map((t) => t.row).sort(byUse);
10362
11604
  const kept = new Map(
10363
11605
  engine.listSources({ project: s.meta.project }).sources.map((x) => [x.id, x.kept ?? []])
10364
11606
  );
@@ -10380,8 +11622,8 @@ function listLibraries(engine, args, cwd) {
10380
11622
  for (const d of src.defaultExcluded ?? [])
10381
11623
  if (d.origin === "library") leftOut.push({ source: src.sourceId, path: d.path, files: d.files });
10382
11624
  }
10383
- copied.sort((a, b) => cmp6(a.source, b.source) || cmp6(a.path, b.path));
10384
- leftOut.sort((a, b) => cmp6(a.source, b.source) || cmp6(a.path, b.path));
11625
+ copied.sort((a, b) => cmp8(a.source, b.source) || cmp8(a.path, b.path));
11626
+ leftOut.sort((a, b) => cmp8(a.source, b.source) || cmp8(a.path, b.path));
10385
11627
  return {
10386
11628
  ...s.meta,
10387
11629
  stage2: s.stage2,
@@ -10422,11 +11664,11 @@ function getLibrary(engine, args, cwd) {
10422
11664
  path: pathOf6(id),
10423
11665
  source: sourceOf4(id),
10424
11666
  group: g ? { id: g.id, name: g.name } : null,
10425
- forms: [...forms].sort(cmp6),
11667
+ forms: [...forms].sort(cmp8),
10426
11668
  own: f?.type === "File" ? own2(f) : false
10427
11669
  };
10428
- }).sort((a, b) => Number(b.own) - Number(a.own) || cmp6(a.source, b.source) || cmp6(a.path, b.path));
10429
- const members2 = [...t.exits.entries()].sort(([ka, a], [kb, b]) => b.calls + b.references - (a.calls + a.references) || cmp6(ka, kb)).map(([, m]) => ({
11670
+ }).sort((a, b) => Number(b.own) - Number(a.own) || cmp8(a.source, b.source) || cmp8(a.path, b.path));
11671
+ const members2 = [...t.exits.entries()].sort(([ka, a], [kb, b]) => b.calls + b.references - (a.calls + a.references) || cmp8(ka, kb)).map(([, m]) => ({
10430
11672
  name: m.exit.name,
10431
11673
  member: m.exit.member,
10432
11674
  instance: !!m.exit.instance,
@@ -10443,21 +11685,22 @@ function getLibrary(engine, args, cwd) {
10443
11685
  membersTruncated: members2.length > LIBRARY_MEMBERS_MAX
10444
11686
  };
10445
11687
  }
10446
- var LIBRARIES_MAX, LIBRARY_IMPORTERS_MAX, LIBRARY_MEMBERS_MAX, STAGE22, cmp6, sourceOf4, pathOf6, keyOf, byUse;
11688
+ var LIBRARIES_MAX, LIBRARY_IMPORTERS_MAX, LIBRARY_MEMBERS_MAX, STAGE22, cmp8, sourceOf4, pathOf6, keyOf, byUse;
10447
11689
  var init_libraries2 = __esm({
10448
11690
  "packages/query-imports/src/libraries.ts"() {
10449
11691
  "use strict";
10450
11692
  init_src();
11693
+ init_reads();
10451
11694
  init_symbols();
10452
11695
  LIBRARIES_MAX = 1e3;
10453
11696
  LIBRARY_IMPORTERS_MAX = 1e3;
10454
11697
  LIBRARY_MEMBERS_MAX = 500;
10455
11698
  STAGE22 = "stage2";
10456
- cmp6 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
11699
+ cmp8 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
10457
11700
  sourceOf4 = (fileId) => fileId.slice(0, fileId.indexOf(":"));
10458
11701
  pathOf6 = (fileId) => fileId.slice(fileId.indexOf(":") + 1);
10459
11702
  keyOf = (p) => `${p.ecosystem}:${p.name}`;
10460
- byUse = (a, b) => b.files - a.files || b.calls + b.references - (a.calls + a.references) || cmp6(a.name, b.name) || cmp6(a.ecosystem, b.ecosystem);
11703
+ byUse = (a, b) => b.files - a.files || b.calls + b.references - (a.calls + a.references) || cmp8(a.name, b.name) || cmp8(a.ecosystem, b.ecosystem);
10461
11704
  }
10462
11705
  });
10463
11706
 
@@ -10486,13 +11729,15 @@ function crossFileCalls(engine, args, cwd) {
10486
11729
  const offset = args.offset ?? 0;
10487
11730
  if (!Number.isInteger(offset) || offset < 0)
10488
11731
  throw new VeoError("invalid-arguments", "offset must be 0 or more", { fields: ["offset"] });
11732
+ const grouping = groupingOf(args.grouping);
10489
11733
  const { meta: meta3, reader } = engine.readAllStages(args, cwd);
10490
11734
  const end2 = ender(engine, meta3.project, reader);
10491
11735
  let edges;
10492
11736
  let pair;
10493
11737
  if (args.from !== void 0) {
10494
11738
  const list = (v) => Array.isArray(v) ? v : [v];
10495
- const p = pairOf(reader, end2, list(args.from), list(args.to));
11739
+ const groups2 = groupsView(engine, meta3, reader, args.run ?? meta3.committedRun, grouping).groups;
11740
+ const p = pairOf(reader, end2, list(args.from), list(args.to), groups2);
10496
11741
  edges = p.edges;
10497
11742
  pair = p.pair;
10498
11743
  } else if (args.function !== void 0) {
@@ -10519,7 +11764,7 @@ function crossFileCalls(engine, args, cwd) {
10519
11764
  })();
10520
11765
  }
10521
11766
  edges.sort(
10522
- (a, b) => cmp7(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset || cmp7(a.id, b.id)
11767
+ (a, b) => cmp9(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset || cmp9(a.id, b.id)
10523
11768
  );
10524
11769
  const shown = edges.slice(offset, offset + limit);
10525
11770
  const provenance = reader.provenance(shown.map((e) => e.id));
@@ -10538,7 +11783,8 @@ function crossFileCalls(engine, args, cwd) {
10538
11783
  ...pair ? { pair } : {}
10539
11784
  };
10540
11785
  }
10541
- function pairOf(reader, end2, from, to) {
11786
+ function pairOf(reader, end2, from, to, groups2) {
11787
+ const groupById = new Map(groups2.map((g) => [g.id, g]));
10542
11788
  const side = (ids2, field) => {
10543
11789
  const files = /* @__PURE__ */ new Set();
10544
11790
  const kinds = /* @__PURE__ */ new Set();
@@ -10546,18 +11792,18 @@ function pairOf(reader, end2, from, to) {
10546
11792
  for (const id of ids2) {
10547
11793
  if (id.startsWith("folder|")) {
10548
11794
  const rest = id.slice("folder|".length);
10549
- let g;
11795
+ let g2;
10550
11796
  let path = "";
10551
11797
  for (let at = rest.indexOf("|"); at !== -1; at = rest.indexOf("|", at + 1)) {
10552
- const f2 = reader.fact(rest.slice(0, at));
10553
- if (f2?.type === "Group") {
10554
- g = f2;
11798
+ const f2 = groupById.get(rest.slice(0, at));
11799
+ if (f2) {
11800
+ g2 = f2;
10555
11801
  path = rest.slice(at + 1);
10556
11802
  }
10557
11803
  }
10558
- if (!g || !path) throw bad(field);
11804
+ if (!g2 || !path) throw bad(field);
10559
11805
  let found = 0;
10560
- for (const fileId of g.files) {
11806
+ for (const fileId of g2.files) {
10561
11807
  const f2 = reader.fact(fileId);
10562
11808
  if (f2?.type === "File" && f2.path.startsWith(`${path}/`)) {
10563
11809
  files.add(fileId);
@@ -10574,21 +11820,22 @@ function pairOf(reader, end2, from, to) {
10574
11820
  const at = rest.indexOf("|");
10575
11821
  const source = at < 0 ? rest : rest.slice(0, at);
10576
11822
  const path = at < 0 ? "" : rest.slice(at + 1);
10577
- const inside3 = (root) => path === "" || root === path || root.startsWith(`${path}/`);
10578
- const members2 = allGroups().filter(
10579
- (g) => g.source !== source ? false : id.startsWith("area|") ? inside3(g.root) : g.kind === "cluster" && g.files.length === 1 && g.root === path
11823
+ const inside4 = (root) => path === "" || root === path || root.startsWith(`${path}/`);
11824
+ const members2 = groups2.filter(
11825
+ (g2) => g2.source !== source ? false : id.startsWith("area|") ? inside4(g2.root) : (g2.kind === "cluster" || g2.kind === "module") && g2.files.length === 1 && g2.root === path
10580
11826
  );
10581
11827
  if (members2.length === 0) throw bad(field);
10582
- for (const g of members2) for (const f2 of g.files) files.add(f2);
11828
+ for (const g2 of members2) for (const f2 of g2.files) files.add(f2);
10583
11829
  kinds.add("group");
10584
11830
  names.push(id.startsWith("area|") ? `${path || source}/` : `${path || "(top)"}/ single files`);
10585
11831
  continue;
10586
11832
  }
10587
- const f = reader.fact(id);
10588
- if (f?.type === "Group") {
10589
- for (const x of f.files) files.add(x);
11833
+ const g = groupById.get(id);
11834
+ const f = g ? void 0 : reader.fact(id);
11835
+ if (g) {
11836
+ for (const x of g.files) files.add(x);
10590
11837
  kinds.add("group");
10591
- names.push(f.name);
11838
+ names.push(g.name);
10592
11839
  } else if (f?.type === "File") {
10593
11840
  files.add(f.id);
10594
11841
  kinds.add("file");
@@ -10599,8 +11846,6 @@ function pairOf(reader, end2, from, to) {
10599
11846
  const name = names.length <= 3 ? names.join(", ") : `${names.slice(0, 2).join(", ")} and ${names.length - 2} more`;
10600
11847
  return { files, kinds, name, id: ids2.length === 1 ? ids2[0] : ids2.join(",") };
10601
11848
  };
10602
- let groupsRead;
10603
- const allGroups = () => groupsRead ??= reader.facts("Group");
10604
11849
  const bad = (field) => new VeoError("invalid-arguments", `${field} must be groups, files or a group's folders`, {
10605
11850
  fields: [field]
10606
11851
  });
@@ -10616,10 +11861,10 @@ function pairOf(reader, end2, from, to) {
10616
11861
  const bs = b.files;
10617
11862
  const edges = as.flatMap((f) => reader.facts("CALLS_CROSS_FILE", f)).filter((e) => bs.has(fileOfFn(e.to)));
10618
11863
  const references = as.flatMap((f) => reader.facts("REFERENCES", f)).filter((r) => !r.exit && bs.has(fileOfFn(r.to))).sort(
10619
- (x, y) => cmp7(x.evidence.file, y.evidence.file) || x.evidence.span.start.offset - y.evidence.span.start.offset
11864
+ (x, y) => cmp9(x.evidence.file, y.evidence.file) || x.evidence.span.start.offset - y.evidence.span.start.offset
10620
11865
  );
10621
11866
  const imports = as.flatMap((f) => reader.facts("IMPORTS", f)).filter((e) => bs.has(e.to)).sort(
10622
- (x, y) => cmp7(x.evidence.file, y.evidence.file) || x.evidence.span.start.offset - y.evidence.span.start.offset
11867
+ (x, y) => cmp9(x.evidence.file, y.evidence.file) || x.evidence.span.start.offset - y.evidence.span.start.offset
10623
11868
  );
10624
11869
  return {
10625
11870
  edges,
@@ -10652,7 +11897,7 @@ function pairOf(reader, end2, from, to) {
10652
11897
  }
10653
11898
  };
10654
11899
  }
10655
- function cmp7(a, b) {
11900
+ function cmp9(a, b) {
10656
11901
  return a < b ? -1 : a > b ? 1 : 0;
10657
11902
  }
10658
11903
  function ender(engine, project2, reader) {
@@ -10714,10 +11959,12 @@ var init_src7 = __esm({
10714
11959
  init_src();
10715
11960
  init_nesting();
10716
11961
  init_reads();
11962
+ init_reads();
10717
11963
  init_explain();
10718
11964
  init_reach();
10719
11965
  init_exits();
10720
11966
  init_check();
11967
+ init_connected();
10721
11968
  init_totals();
10722
11969
  init_file_summary();
10723
11970
  init_impact();
@@ -11489,7 +12736,7 @@ var require_cmp = __commonJS({
11489
12736
  var gte = require_gte();
11490
12737
  var lt = require_lt();
11491
12738
  var lte = require_lte();
11492
- var cmp9 = (a, op, b, loose) => {
12739
+ var cmp11 = (a, op, b, loose) => {
11493
12740
  switch (op) {
11494
12741
  case "===":
11495
12742
  if (typeof a === "object") {
@@ -11525,7 +12772,7 @@ var require_cmp = __commonJS({
11525
12772
  throw new TypeError(`Invalid operator: ${op}`);
11526
12773
  }
11527
12774
  };
11528
- module.exports = cmp9;
12775
+ module.exports = cmp11;
11529
12776
  }
11530
12777
  });
11531
12778
 
@@ -12100,7 +13347,7 @@ var require_comparator = __commonJS({
12100
13347
  return false;
12101
13348
  }
12102
13349
  }
12103
- return cmp9(version3, this.operator, this.semver, this.options);
13350
+ return cmp11(version3, this.operator, this.semver, this.options);
12104
13351
  }
12105
13352
  intersects(comp, options2) {
12106
13353
  if (!(comp instanceof _Comparator)) {
@@ -12133,10 +13380,10 @@ var require_comparator = __commonJS({
12133
13380
  if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
12134
13381
  return true;
12135
13382
  }
12136
- if (cmp9(this.semver, "<", comp.semver, options2) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
13383
+ if (cmp11(this.semver, "<", comp.semver, options2) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
12137
13384
  return true;
12138
13385
  }
12139
- if (cmp9(this.semver, ">", comp.semver, options2) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
13386
+ if (cmp11(this.semver, ">", comp.semver, options2) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
12140
13387
  return true;
12141
13388
  }
12142
13389
  return false;
@@ -12145,7 +13392,7 @@ var require_comparator = __commonJS({
12145
13392
  module.exports = Comparator;
12146
13393
  var parseOptions = require_parse_options();
12147
13394
  var { safeRe: re, t } = require_re();
12148
- var cmp9 = require_cmp();
13395
+ var cmp11 = require_cmp();
12149
13396
  var debug = require_debug();
12150
13397
  var SemVer = require_semver();
12151
13398
  var Range = require_range();
@@ -12656,7 +13903,7 @@ var require_semver2 = __commonJS({
12656
13903
  var neq = require_neq();
12657
13904
  var gte = require_gte();
12658
13905
  var lte = require_lte();
12659
- var cmp9 = require_cmp();
13906
+ var cmp11 = require_cmp();
12660
13907
  var coerce = require_coerce();
12661
13908
  var truncate = require_truncate();
12662
13909
  var Comparator = require_comparator();
@@ -12695,7 +13942,7 @@ var require_semver2 = __commonJS({
12695
13942
  neq,
12696
13943
  gte,
12697
13944
  lte,
12698
- cmp: cmp9,
13945
+ cmp: cmp11,
12699
13946
  coerce,
12700
13947
  truncate,
12701
13948
  Comparator,
@@ -12725,7 +13972,7 @@ var require_semver2 = __commonJS({
12725
13972
  });
12726
13973
 
12727
13974
  // packages/stage2/src/gitignore.ts
12728
- import { posix as posix2 } from "node:path";
13975
+ import { posix as posix4 } from "node:path";
12729
13976
  function toRegExp(pattern, anchored) {
12730
13977
  let re = "";
12731
13978
  for (let i = 0; i < pattern.length; i++) {
@@ -12759,7 +14006,7 @@ function gitignoreMatcher(files) {
12759
14006
  const depth = (p) => p.split("/").length;
12760
14007
  const sorted = [...files].sort((a, b) => depth(a.path) - depth(b.path) || (a.path < b.path ? -1 : 1));
12761
14008
  for (const f of sorted) {
12762
- const dir = posix2.dirname(f.path) === "." ? "" : posix2.dirname(f.path);
14009
+ const dir = posix4.dirname(f.path) === "." ? "" : posix4.dirname(f.path);
12763
14010
  for (const raw of f.content.split(/\r?\n/)) {
12764
14011
  let line = raw.replace(/(?<!\\)\s+$/, "");
12765
14012
  if (!line || line.startsWith("#")) continue;
@@ -12816,7 +14063,7 @@ var init_gitignore = __esm({
12816
14063
 
12817
14064
  // packages/stage2/src/imports.ts
12818
14065
  import { builtinModules } from "node:module";
12819
- import { isAbsolute as isAbsolute2, posix as posix3, relative as relativePath, resolve as resolvePath, sep as sep7 } from "node:path";
14066
+ import { isAbsolute as isAbsolute2, posix as posix5, relative as relativePath, resolve as resolvePath, sep as sep7 } from "node:path";
12820
14067
  function packageName(specifier) {
12821
14068
  const parts = specifier.split("/");
12822
14069
  return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
@@ -12900,7 +14147,7 @@ function declared(pkg, name) {
12900
14147
  }
12901
14148
  function lockedVersions(path, text) {
12902
14149
  const out = /* @__PURE__ */ new Map();
12903
- const base2 = posix3.basename(path);
14150
+ const base2 = posix5.basename(path);
12904
14151
  if (base2 === "package-lock.json") {
12905
14152
  const lock = parseJson(text);
12906
14153
  for (const [key, v] of Object.entries(lock?.packages ?? {})) {
@@ -12926,6 +14173,11 @@ function statements(source, path, result2) {
12926
14173
  const fileId = ids.file(source, path);
12927
14174
  const byKey2 = /* @__PURE__ */ new Map();
12928
14175
  const formOf = (i) => i.kind === "require" ? "require" : i.kind === "dynamic" ? "dynamic" : i.typeOnly ? "type-only" : "static";
14176
+ const typesOnlyOf = (i) => {
14177
+ if (i.typeOnly) return true;
14178
+ const u = i.uses;
14179
+ return u !== void 0 && u.calls + u.values + u.jsx + u.extends + u.reexports === 0;
14180
+ };
12929
14181
  for (const i of result2.imports) {
12930
14182
  const key = `${i.span.start.offset}\0${i.specifier}`;
12931
14183
  const existing = byKey2.get(key);
@@ -12936,6 +14188,7 @@ function statements(source, path, result2) {
12936
14188
  if (existing) {
12937
14189
  existing.bindings.push(binding2);
12938
14190
  if (existing.form === "type-only" && !i.typeOnly) existing.form = "static";
14191
+ existing.typesOnly &&= typesOnlyOf(i);
12939
14192
  continue;
12940
14193
  }
12941
14194
  byKey2.set(key, {
@@ -12945,7 +14198,9 @@ function statements(source, path, result2) {
12945
14198
  specifier: i.specifier,
12946
14199
  form: formOf(i),
12947
14200
  span: i.span,
12948
- bindings: [binding2]
14201
+ bindings: [binding2],
14202
+ language: result2.language,
14203
+ typesOnly: typesOnlyOf(i)
12949
14204
  });
12950
14205
  }
12951
14206
  const reexports = (e) => (e.kind === "reexport" || e.kind === "reexport-all") && e.fromSpecifier;
@@ -12960,6 +14215,7 @@ function statements(source, path, result2) {
12960
14215
  if (existing) {
12961
14216
  existing.bindings.push(binding2);
12962
14217
  if (existing.form === "type-only" && !e.typeOnly) existing.form = "re-export";
14218
+ existing.typesOnly &&= e.typeOnly;
12963
14219
  } else
12964
14220
  byKey2.set(key, {
12965
14221
  source,
@@ -12968,7 +14224,9 @@ function statements(source, path, result2) {
12968
14224
  specifier,
12969
14225
  form: e.typeOnly ? "type-only" : "re-export",
12970
14226
  span: e.span,
12971
- bindings: [binding2]
14227
+ bindings: [binding2],
14228
+ language: result2.language,
14229
+ typesOnly: e.typeOnly
12972
14230
  });
12973
14231
  }
12974
14232
  const list = [...byKey2.values()].sort(
@@ -13021,8 +14279,8 @@ function resolveImports2(plans, files) {
13021
14279
  const links = /* @__PURE__ */ new Map();
13022
14280
  for (const tree of trees) {
13023
14281
  for (const [path, json2] of tree.manifests) {
13024
- if (posix3.basename(path) !== "package.json") continue;
13025
- const dir = posix3.dirname(path) === "." ? "" : posix3.dirname(path);
14282
+ if (posix5.basename(path) !== "package.json") continue;
14283
+ const dir = posix5.dirname(path) === "." ? "" : posix5.dirname(path);
13026
14284
  const name = json2?.name;
13027
14285
  if (typeof name === "string" && name && !links.has(name) && (dir === "" || sourceMembers.get(tree)(dir)))
13028
14286
  links.set(name, { tree, dir });
@@ -13082,10 +14340,10 @@ function resolveImports2(plans, files) {
13082
14340
  const escapes = /* @__PURE__ */ new Map();
13083
14341
  for (const s of toResolve) {
13084
14342
  if (!isRelative(s.specifier)) continue;
13085
- const inside3 = posix3.normalize(posix3.join(posix3.dirname(s.path), s.specifier));
13086
- if (inside3 !== ".." && !inside3.startsWith("../")) continue;
14343
+ const inside4 = posix5.normalize(posix5.join(posix5.dirname(s.path), s.specifier));
14344
+ if (inside4 !== ".." && !inside4.startsWith("../")) continue;
13087
14345
  const plan = treeOf.get(s.source).plan;
13088
- const abs = resolvePath(plan.root, ...posix3.dirname(s.path).split("/"), ...s.specifier.split("/"));
14346
+ const abs = resolvePath(plan.root, ...posix5.dirname(s.path).split("/"), ...s.specifier.split("/"));
13089
14347
  const within = (root) => {
13090
14348
  const r = relativePath(root, abs);
13091
14349
  return r === "" || !(r === ".." || r.startsWith(`..${sep7}`) || isAbsolute2(r)) ? r.split(sep7).join("/") : null;
@@ -13133,7 +14391,7 @@ function resolveImports2(plans, files) {
13133
14391
  };
13134
14392
  const versions = /* @__PURE__ */ new Map();
13135
14393
  const lockfileVersion = (tree, from, name) => {
13136
- for (let dir = posix3.dirname(from); ; dir = posix3.dirname(dir)) {
14394
+ for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
13137
14395
  for (const lock of ["package-lock.json", "pnpm-lock.yaml", "yarn.lock"]) {
13138
14396
  const path = dir === "." ? lock : `${dir}/${lock}`;
13139
14397
  const m = tree.plan.manifests.find((x) => x.path === path);
@@ -13147,7 +14405,7 @@ function resolveImports2(plans, files) {
13147
14405
  }
13148
14406
  };
13149
14407
  const nearest = (tree, from, base2) => {
13150
- for (let dir = posix3.dirname(from); ; dir = posix3.dirname(dir)) {
14408
+ for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
13151
14409
  const path = dir === "." ? base2 : `${dir}/${base2}`;
13152
14410
  if (tree.plan.manifests.some((m) => m.path === path)) return path;
13153
14411
  if (dir === "." || dir === "") return null;
@@ -13155,7 +14413,7 @@ function resolveImports2(plans, files) {
13155
14413
  };
13156
14414
  const packageJsons = (tree, from) => {
13157
14415
  const out2 = [];
13158
- for (let dir = posix3.dirname(from); ; dir = posix3.dirname(dir)) {
14416
+ for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
13159
14417
  const path = dir === "." ? "package.json" : `${dir}/package.json`;
13160
14418
  const json2 = tree.manifests.get(path);
13161
14419
  if (json2 && typeof json2 === "object") out2.push(json2);
@@ -13193,7 +14451,7 @@ function resolveImports2(plans, files) {
13193
14451
  if (variants.some((v) => exclude.some((re) => re.test(v))) || variants.some((v) => !filter.matches(v) && include.length === 0) || filter.excludesDir(path))
13194
14452
  return "excluded-by-rule";
13195
14453
  if (include.length > 0) {
13196
- const candidates = [...posix3.extname(path) ? [path] : [], ...files2.slice(1), ...indexes];
14454
+ const candidates = [...posix5.extname(path) ? [path] : [], ...files2.slice(1), ...indexes];
13197
14455
  if (candidates.every((v) => !include.some((re) => re.test(v)))) return "excluded-by-rule";
13198
14456
  }
13199
14457
  return null;
@@ -13227,7 +14485,7 @@ function resolveImports2(plans, files) {
13227
14485
  );
13228
14486
  const probe = (t, base2) => {
13229
14487
  const set2 = pathSets.get(t);
13230
- const clean = posix3.normalize(base2).replace(/^\.\/?/, "");
14488
+ const clean = posix5.normalize(base2).replace(/^\.\/?/, "");
13231
14489
  const js = /\.(m|c)?jsx?$/.exec(clean);
13232
14490
  const ts = js ? [".ts", ".tsx", ".mts", ".cts"].map(
13233
14491
  (e) => clean.slice(0, -js[0].length) + (js[0] === ".jsx" ? ".tsx" : js[1] ? `.${js[1]}ts` : e)
@@ -13242,7 +14500,7 @@ function resolveImports2(plans, files) {
13242
14500
  return null;
13243
14501
  };
13244
14502
  const nearestPackage = (t, from) => {
13245
- for (let dir = posix3.dirname(from); ; dir = posix3.dirname(dir)) {
14503
+ for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
13246
14504
  const path = dir === "." ? "package.json" : `${dir}/package.json`;
13247
14505
  const json2 = t.manifests.get(path);
13248
14506
  if (json2 && typeof json2 === "object")
@@ -13274,7 +14532,7 @@ function resolveImports2(plans, files) {
13274
14532
  };
13275
14533
  const siteDir = (t, from) => {
13276
14534
  const set2 = pathSets.get(t);
13277
- for (let dir = posix3.dirname(from); ; dir = posix3.dirname(dir)) {
14535
+ for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
13278
14536
  const d = dir === "." ? "" : dir;
13279
14537
  if (["js", "ts", "mjs", "cjs", "mts"].some((e) => set2.has(join14(d, `docusaurus.config.${e}`)))) return d;
13280
14538
  if (d === "") return null;
@@ -13282,18 +14540,18 @@ function resolveImports2(plans, files) {
13282
14540
  };
13283
14541
  const bundlerCache = /* @__PURE__ */ new Map();
13284
14542
  const bundlerAliases = (t, from) => {
13285
- const key = `${t.plan.sourceId}\0${posix3.dirname(from)}`;
14543
+ const key = `${t.plan.sourceId}\0${posix5.dirname(from)}`;
13286
14544
  const cached2 = bundlerCache.get(key);
13287
14545
  if (cached2) return cached2;
13288
14546
  const files2 = fileContent.get(t);
13289
14547
  const out2 = [];
13290
14548
  for (const kind of ["vite", "webpack"]) {
13291
- for (let dir = posix3.dirname(from); ; dir = posix3.dirname(dir)) {
14549
+ for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
13292
14550
  const d = dir === "." ? "" : dir;
13293
14551
  const config2 = ["ts", "js", "mjs", "mts", "cjs", "cts"].map((e) => join14(d, `${kind}.config.${e}`)).find((p) => files2.get(p) !== void 0);
13294
14552
  if (config2) {
13295
14553
  const aliases = parseAliases(files2.get(config2)).map(
13296
- ([k, v]) => [k, posix3.normalize(join14(d, v)).replace(/^\.\/?$/, "")]
14554
+ ([k, v]) => [k, posix5.normalize(join14(d, v)).replace(/^\.\/?$/, "")]
13297
14555
  );
13298
14556
  if (aliases.length)
13299
14557
  out2.push({ config: config2, aliases: aliases.sort((a, b) => b[0].length - a[0].length) });
@@ -13398,7 +14656,7 @@ function resolveImports2(plans, files) {
13398
14656
  for (const { config: config2, aliases } of bundlerAliases(t, from)) {
13399
14657
  for (const [key, value] of aliases) {
13400
14658
  if (specifier !== key && !specifier.startsWith(`${key}/`)) continue;
13401
- const target2 = posix3.normalize(join14(value, specifier.slice(key.length + 1)));
14659
+ const target2 = posix5.normalize(join14(value, specifier.slice(key.length + 1)));
13402
14660
  if (target2 === ".." || target2.startsWith("../")) {
13403
14661
  const abs = resolvePath(t.plan.root, ...target2.split("/"));
13404
14662
  let holder = null;
@@ -13650,14 +14908,37 @@ function resolveImports2(plans, files) {
13650
14908
  return m;
13651
14909
  };
13652
14910
  const workspaceOf = new Map(trees.map((t) => [t, t.plan.workspace?.realRoot ?? null]));
14911
+ const typesPackage = (t, s, name) => {
14912
+ if (!s.typesOnly || s.form !== "static" && s.form !== "type-only") return null;
14913
+ if (s.language !== "typescript" && s.language !== "tsx") return null;
14914
+ const types = name.startsWith("@") ? `@types/${name.slice(1).replace("/", "__")}` : `@types/${name}`;
14915
+ const spec = packageJsons(t, s.path).map((p) => declared(p, types)).find((v) => v !== void 0);
14916
+ const m = managerOf(t);
14917
+ const declarers = spec === void 0 && m.hoists ? workspaceDeclarers(t, types) : [];
14918
+ if (spec === void 0 && !declarers.length) return null;
14919
+ const how = s.form === "type-only" ? "is type-only" : "is used only as types";
14920
+ const erased = s.form === "type-only" ? "TypeScript resolves it to the type package and erases it" : "TypeScript would resolve it to the type package and erase it";
14921
+ const where = spec !== void 0 ? `${types} is a declared dependency (${spec})` : `${declarers.join(", ")} declare${declarers.length === 1 ? "s" : ""} ${types}, which ${m.name} hoists into reach`;
14922
+ return {
14923
+ kind: "package",
14924
+ pkg: external(s.source, "npm", name, lockfileVersion(t, s.path, name)),
14925
+ via: "dependency",
14926
+ steps: [
14927
+ {
14928
+ kind: "types",
14929
+ detail: `no package.json up from ${s.path} declares ${name}, but the import ${how} and ${where}: ${erased}`
14930
+ }
14931
+ ]
14932
+ };
14933
+ };
13653
14934
  const workspaceDeclarers = (t, name) => {
13654
14935
  const ws = workspaceOf.get(t);
13655
14936
  const out2 = [];
13656
14937
  for (const u of trees) {
13657
14938
  if (u !== t && (ws === null || workspaceOf.get(u) !== ws)) continue;
13658
14939
  for (const [path, json2] of u.manifests) {
13659
- if (posix3.basename(path) !== "package.json" || !json2 || typeof json2 !== "object") continue;
13660
- const dir = posix3.dirname(path) === "." ? "" : posix3.dirname(path);
14940
+ if (posix5.basename(path) !== "package.json" || !json2 || typeof json2 !== "object") continue;
14941
+ const dir = posix5.dirname(path) === "." ? "" : posix5.dirname(path);
13661
14942
  const member = dir === "" && u === t ? true : sourceMembers.get(u)(dir) || dir === "" && coversAbove(u.plan, "");
13662
14943
  if (member && declared(json2, name) !== void 0)
13663
14944
  out2.push(u === t ? path : `${u.plan.sourceId}:${path}`);
@@ -13698,14 +14979,14 @@ function resolveImports2(plans, files) {
13698
14979
  return { pick: "npm", detail: `${name} is declared as ${spec}, not as a workspace package` };
13699
14980
  };
13700
14981
  const baseUrlMiss = (t, from, specifier) => {
13701
- for (let dir = posix3.dirname(from); ; dir = posix3.dirname(dir)) {
14982
+ for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
13702
14983
  const d = dir === "." ? "" : dir;
13703
14984
  for (const c of ["tsconfig.json", "jsconfig.json"]) {
13704
14985
  const json2 = t.manifests.get(join14(d, c));
13705
14986
  if (!json2) continue;
13706
14987
  const baseUrl = json2.compilerOptions?.baseUrl;
13707
14988
  if (typeof baseUrl !== "string") return null;
13708
- const base2 = posix3.normalize(join14(d, baseUrl.replace(/^\.\/?/, ""))).replace(/^\.$/, "");
14989
+ const base2 = posix5.normalize(join14(d, baseUrl.replace(/^\.\/?/, ""))).replace(/^\.$/, "");
13709
14990
  const folder = `${join14(base2, specifier.split("/")[0])}/`;
13710
14991
  for (const p of pathSets.get(t)) if (p.startsWith(folder)) return join14(d, c);
13711
14992
  return null;
@@ -13717,7 +14998,7 @@ function resolveImports2(plans, files) {
13717
14998
  for (const s of all2) {
13718
14999
  const tree = treeOf.get(s.source);
13719
15000
  const plan = tree.plan;
13720
- const rel = (p) => posix3.relative(posix3.dirname(s.path), p) || ".";
15001
+ const rel = (p) => posix5.relative(posix5.dirname(s.path), p) || ".";
13721
15002
  let target2;
13722
15003
  if (isUrl(s.specifier)) {
13723
15004
  const { name, version: version3 } = urlPackage(s.specifier);
@@ -13738,7 +15019,7 @@ function resolveImports2(plans, files) {
13738
15019
  };
13739
15020
  } else {
13740
15021
  const answer = answers.get(s);
13741
- const ownExt = posix3.extname(s.specifier.replace(/\?[^/]*$/, ""));
15022
+ const ownExt = posix5.extname(s.specifier.replace(/\?[^/]*$/, ""));
13742
15023
  const shown = OWN_EXTENSIONS.has(ownExt) ? answer.tried.filter(
13743
15024
  (t) => ![...PROBE_EXTENSIONS, ".d.ts", ".node"].some((e) => t.endsWith(`${ownExt}${e}`))
13744
15025
  ) : answer.tried;
@@ -13889,7 +15170,7 @@ function resolveImports2(plans, files) {
13889
15170
  };
13890
15171
  } else if (isRelative(s.specifier) || s.specifier.startsWith("/")) {
13891
15172
  const holder = escape2?.holder ?? tree;
13892
- const candidate = escape2?.holder ? escape2.rel : posix3.normalize(posix3.join(posix3.dirname(s.path), s.specifier));
15173
+ const candidate = escape2?.holder ? escape2.rel : posix5.normalize(posix5.join(posix5.dirname(s.path), s.specifier));
13893
15174
  const ignored = holder.plan.unpinned.some(
13894
15175
  (u) => u.reason === "gitignored" && (u.path.endsWith("/") ? `${candidate}/`.startsWith(u.path) : [
13895
15176
  candidate,
@@ -14065,7 +15346,8 @@ function resolveImports2(plans, files) {
14065
15346
  } else {
14066
15347
  const declarers = workspaceDeclarers(tree, name);
14067
15348
  const m = managerOf(tree);
14068
- const config2 = declarers.length && m.hoists ? null : baseUrlMiss(tree, s.path, s.specifier);
15349
+ const types = typesPackage(tree, s, name);
15350
+ const config2 = declarers.length && m.hoists || types ? null : baseUrlMiss(tree, s.path, s.specifier);
14069
15351
  target2 = config2 ? {
14070
15352
  kind: "unresolved",
14071
15353
  outcome: "broken",
@@ -14087,7 +15369,7 @@ function resolveImports2(plans, files) {
14087
15369
  detail: `${name} isn't declared by a package.json up from ${s.path}; ${declarers.join(", ")} declare${declarers.length === 1 ? "s" : ""} it, and ${m.name} hoists it into reach`
14088
15370
  }
14089
15371
  ]
14090
- } : declarers.length ? {
15372
+ } : types ? types : declarers.length ? {
14091
15373
  kind: "unresolved",
14092
15374
  outcome: "broken",
14093
15375
  reason: "undeclared-dependency",
@@ -14113,7 +15395,7 @@ function resolveImports2(plans, files) {
14113
15395
  }
14114
15396
  if (target2.kind === "unresolved")
14115
15397
  for (const n2 of notes) {
14116
- const base2 = posix3.basename(n2.path);
15398
+ const base2 = posix5.basename(n2.path);
14117
15399
  if (n2.source !== s.source || !["package.json", "tsconfig.json", "jsconfig.json"].includes(base2))
14118
15400
  continue;
14119
15401
  if (nearest(tree, s.path, base2) === n2.path) target2.steps.push(n2.step);
@@ -14151,14 +15433,14 @@ function parseAliases(source) {
14151
15433
  const tpl = /^`\$\{([\s\S]+)\}([^`$]*)`$/.exec(e);
14152
15434
  if (tpl) {
14153
15435
  const base2 = path(tpl[1]);
14154
- return base2 === null ? null : posix3.join(base2, tpl[2] || ".");
15436
+ return base2 === null ? null : posix5.join(base2, tpl[2] || ".");
14155
15437
  }
14156
15438
  const lit = /^(['"`])([^'"`]*)\1$/.exec(e);
14157
15439
  if (lit)
14158
15440
  return lit[2].includes("${") || !/^(\.\.?\/|\/|\.$)/.test(lit[2]) ? null : lit[2].replace(/^\//, "");
14159
15441
  const dirname10 = /^(?:path\.)?(?:resolve|join)\(\s*__dirname\s*((?:,\s*(['"`])[^'"`]*\2\s*)*)\)$/.exec(e);
14160
15442
  if (dirname10)
14161
- return posix3.join(".", ...[...dirname10[1].matchAll(/(['"`])([^'"`]*)\1/g)].map((m) => m[2]));
15443
+ return posix5.join(".", ...[...dirname10[1].matchAll(/(['"`])([^'"`]*)\1/g)].map((m) => m[2]));
14162
15444
  const url2 = /^(?:fileURLToPath\(\s*)?new URL\(\s*(['"`])([^'"`]*)\1\s*,\s*import\.meta\.url\s*\)(?:\s*\)|\.pathname)?$/.exec(
14163
15445
  e
14164
15446
  );
@@ -14259,13 +15541,13 @@ function coversAbove(plan, dir) {
14259
15541
  );
14260
15542
  aboveCache.set(ws, members2);
14261
15543
  }
14262
- return members2(posix3.join(ws.prefix, dir).replace(/\/$/, ""));
15544
+ return members2(posix5.join(ws.prefix, dir).replace(/\/$/, ""));
14263
15545
  }
14264
15546
  function workspaceMembers(raw, parsed) {
14265
15547
  const include = [];
14266
15548
  const exclude = [];
14267
15549
  const anchored = (base2, glob) => {
14268
- const p = posix3.join(base2, glob.replace(/^\.\//, "")).replace(/\/+$/, "");
15550
+ const p = posix5.join(base2, glob.replace(/^\.\//, "")).replace(/\/+$/, "");
14269
15551
  let re = "";
14270
15552
  for (let i = 0; i < p.length; i++) {
14271
15553
  const c = p[i];
@@ -14288,14 +15570,14 @@ function workspaceMembers(raw, parsed) {
14288
15570
  (g.startsWith("!") ? exclude : include).push(anchored(base2, g.replace(/^!/, "")));
14289
15571
  };
14290
15572
  for (const [path, json2] of parsed) {
14291
- if (posix3.basename(path) !== "package.json" || !json2 || typeof json2 !== "object") continue;
14292
- const base2 = posix3.dirname(path) === "." ? "" : posix3.dirname(path);
15573
+ if (posix5.basename(path) !== "package.json" || !json2 || typeof json2 !== "object") continue;
15574
+ const base2 = posix5.dirname(path) === "." ? "" : posix5.dirname(path);
14293
15575
  const ws = json2.workspaces;
14294
15576
  add2(base2, Array.isArray(ws) ? ws : ws?.packages);
14295
15577
  }
14296
15578
  for (const m of raw) {
14297
- if (posix3.basename(m.path) !== "pnpm-workspace.yaml") continue;
14298
- add2(posix3.dirname(m.path) === "." ? "" : posix3.dirname(m.path), pnpmWorkspacePackages(m.content));
15579
+ if (posix5.basename(m.path) !== "pnpm-workspace.yaml") continue;
15580
+ add2(posix5.dirname(m.path) === "." ? "" : posix5.dirname(m.path), pnpmWorkspacePackages(m.content));
14299
15581
  }
14300
15582
  return (dir) => include.some((re) => re.test(dir)) && !exclude.some((re) => re.test(dir));
14301
15583
  }
@@ -14490,10 +15772,10 @@ function typeGraph(input2) {
14490
15772
  return via?.target.kind === "file" ? exportedAt(via.target.file.id, e.sourceName ?? name, depth + 1) : null;
14491
15773
  }
14492
15774
  if (e.kind === "default" && !e.localName && !e.sourceName) {
14493
- const inside3 = result2.types.find(
15775
+ const inside4 = result2.types.find(
14494
15776
  (t) => t.span.start.offset >= e.span.start.offset && t.span.end.offset <= e.span.end.offset
14495
15777
  );
14496
- return inside3 ? { file: file2, name: inside3.name } : null;
15778
+ return inside4 ? { file: file2, name: inside4.name } : null;
14497
15779
  }
14498
15780
  if (e.kind === "named" || e.kind === "default") {
14499
15781
  const local = e.localName ?? e.sourceName ?? name;
@@ -17592,7 +18874,7 @@ var init_closed = __esm({
17592
18874
  });
17593
18875
 
17594
18876
  // packages/stage2/src/components.ts
17595
- import { posix as posix4 } from "node:path";
18877
+ import { posix as posix6 } from "node:path";
17596
18878
  function linkComponents(input2) {
17597
18879
  const fn = new Map(input2.functions.map((f) => [`${f.file}\0${f.qualifiedName}`, f.id]));
17598
18880
  const statementsByFile = /* @__PURE__ */ new Map();
@@ -17669,7 +18951,7 @@ function linkComponents(input2) {
17669
18951
  if (inline) return inline;
17670
18952
  const declared2 = input2.templates.find((t) => t.file === fileId && t.component === cls && t.specifier);
17671
18953
  if (!declared2) return null;
17672
- const target2 = `${sourceOf5(fileId)}:${posix4.normalize(posix4.join(posix4.dirname(pathOf7(fileId)), declared2.specifier))}`;
18954
+ const target2 = `${sourceOf5(fileId)}:${posix6.normalize(posix6.join(posix6.dirname(pathOf7(fileId)), declared2.specifier))}`;
17673
18955
  return fn.get(`${target2}\0<template>`) ?? null;
17674
18956
  };
17675
18957
  const usingClasses = (site) => {
@@ -17680,7 +18962,7 @@ function linkComponents(input2) {
17680
18962
  return [{ file: site.file, cls: caller.slice(0, -".<template>".length) }];
17681
18963
  const path = pathOf7(site.file);
17682
18964
  return input2.templates.filter(
17683
- (t) => t.specifier && sourceOf5(t.file) === sourceOf5(site.file) && posix4.normalize(posix4.join(posix4.dirname(pathOf7(t.file)), t.specifier)) === path
18965
+ (t) => t.specifier && sourceOf5(t.file) === sourceOf5(site.file) && posix6.normalize(posix6.join(posix6.dirname(pathOf7(t.file)), t.specifier)) === path
17684
18966
  ).map((t) => ({ file: t.file, cls: t.component }));
17685
18967
  };
17686
18968
  const modules = fileIds.flatMap(
@@ -17952,7 +19234,7 @@ var init_components = __esm({
17952
19234
  });
17953
19235
 
17954
19236
  // packages/stage2/src/exits.ts
17955
- import { posix as posix5 } from "node:path";
19237
+ import { posix as posix7 } from "node:path";
17956
19238
  function renderPath(segs) {
17957
19239
  let out = "";
17958
19240
  for (const s of segs) {
@@ -18745,8 +20027,8 @@ function startCandidates(input2, s, exitAt, nodeAt) {
18745
20027
  for (const plan of input2.plans) {
18746
20028
  const parsed = new Map(plan.manifests.map((m) => [m.path, parseManifest(m.content)]));
18747
20029
  for (const m of plan.manifests) {
18748
- if (posix5.basename(m.path) !== "package.json") continue;
18749
- const dir = posix5.dirname(m.path) === "." ? "" : posix5.dirname(m.path);
20030
+ if (posix7.basename(m.path) !== "package.json") continue;
20031
+ const dir = posix7.dirname(m.path) === "." ? "" : posix7.dirname(m.path);
18750
20032
  const json2 = parsed.get(m.path);
18751
20033
  if (!json2 || typeof json2 !== "object") continue;
18752
20034
  const pkg = typeof json2.name === "string" && json2.name ? json2.name : dir || plan.sourceId;
@@ -18879,7 +20161,7 @@ function scriptFiles(command, depth = 0) {
18879
20161
  const tokens = [...command.matchAll(/"([^"]*)"|'([^']*)'|(&&|\|\||[;|&])|([^\s"';|&]+)/g)];
18880
20162
  let part = [];
18881
20163
  const end2 = () => {
18882
- const at = part.findIndex((t) => !t.quoted && RUNNERS.has(posix5.basename(t.text)));
20164
+ const at = part.findIndex((t) => !t.quoted && RUNNERS.has(posix7.basename(t.text)));
18883
20165
  if (at !== -1)
18884
20166
  for (let i = at + 1; i < part.length; i++) {
18885
20167
  const t = part[i].text;
@@ -18913,7 +20195,7 @@ function stringLeaves(v) {
18913
20195
  return [];
18914
20196
  }
18915
20197
  function sourceFile(files, source, dir, p, json2) {
18916
- const rel = posix5.normalize(posix5.join(dir, p));
20198
+ const rel = posix7.normalize(posix7.join(dir, p));
18917
20199
  if (rel.startsWith("..")) return void 0;
18918
20200
  const exts = [
18919
20201
  "",
@@ -18939,10 +20221,10 @@ function sourceFile(files, source, dir, p, json2) {
18939
20221
  const hit = probe(rel) ?? probe(noExt);
18940
20222
  if (hit) return hit;
18941
20223
  const built = /^(dist|build|lib|out)\//;
18942
- const inside3 = dir ? noExt.slice(dir.length + 1) : noExt;
18943
- if (!built.test(inside3)) return void 0;
18944
- const srcRel = posix5.join(dir, inside3.replace(built, "src/"));
18945
- return probe(srcRel) ?? (typeof json2.source === "string" ? probe(posix5.join(dir, json2.source).replace(/\.(m?[jt]sx?)$/, "")) : void 0) ?? probe(posix5.join(dir, "src/index"));
20224
+ const inside4 = dir ? noExt.slice(dir.length + 1) : noExt;
20225
+ if (!built.test(inside4)) return void 0;
20226
+ const srcRel = posix7.join(dir, inside4.replace(built, "src/"));
20227
+ return probe(srcRel) ?? (typeof json2.source === "string" ? probe(posix7.join(dir, json2.source).replace(/\.(m?[jt]sx?)$/, "")) : void 0) ?? probe(posix7.join(dir, "src/index"));
18946
20228
  }
18947
20229
  function exportedFunctions(input2, file2) {
18948
20230
  const result2 = input2.results.get(`${file2.source}\0${file2.path}`);
@@ -19036,7 +20318,7 @@ var init_exits2 = __esm({
19036
20318
  });
19037
20319
 
19038
20320
  // packages/stage2/src/groups.ts
19039
- import { posix as posix6 } from "node:path";
20321
+ import { posix as posix8 } from "node:path";
19040
20322
  function groups(input2) {
19041
20323
  const threshold = input2.clusterThreshold ?? DEFAULT_CLUSTER_THRESHOLD;
19042
20324
  const fnFile = new Map(input2.functions.map((f) => [f.id, f.file]));
@@ -19048,16 +20330,16 @@ function groups(input2) {
19048
20330
  const rootName = manifests.get("package.json")?.name;
19049
20331
  const packages = [];
19050
20332
  for (const [path, json2] of manifests) {
19051
- if (posix6.basename(path) !== "package.json" || path === "package.json") continue;
19052
- const dir = posix6.dirname(path);
20333
+ if (posix8.basename(path) !== "package.json" || path === "package.json") continue;
20334
+ const dir = posix8.dirname(path);
19053
20335
  const name = json2?.name;
19054
20336
  if (typeof name === "string" && name && members2(dir)) packages.push({ dir, name });
19055
20337
  }
19056
- packages.sort((a, b) => b.dir.length - a.dir.length || cmp8(a.dir, b.dir));
20338
+ packages.sort((a, b) => b.dir.length - a.dir.length || cmp10(a.dir, b.dir));
19057
20339
  const named = /* @__PURE__ */ new Map();
19058
20340
  for (const p of packages) named.set(p.name, (named.get(p.name) ?? 0) + 1);
19059
20341
  for (const p of packages) if (named.get(p.name) > 1) p.name = `${p.name} (${p.dir})`;
19060
- const files = input2.files.filter((f) => f.source === plan.sourceId).sort((a, b) => cmp8(a.path, b.path));
20342
+ const files = input2.files.filter((f) => f.source === plan.sourceId).sort((a, b) => cmp10(a.path, b.path));
19061
20343
  const boundaries = /* @__PURE__ */ new Map();
19062
20344
  for (const f of files) {
19063
20345
  const pkg = packages.find((p) => f.path.startsWith(`${p.dir}/`));
@@ -19078,7 +20360,10 @@ function groups(input2) {
19078
20360
  out.push({ type: "Group", ...g, externalPackages: [] });
19079
20361
  for (const f of g.files) groupOf.set(f, g.id);
19080
20362
  };
19081
- const asClusters = (files2) => {
20363
+ const within = (b, split) => ({
20364
+ boundary: { kind: b.kind, name: b.name, root: b.root, split }
20365
+ });
20366
+ const asClusters = (files2, b) => {
19082
20367
  for (const c of clusters(files2, input2.imports, input2.calls, fnFile))
19083
20368
  push({
19084
20369
  id: ids.cluster(plan.sourceId, c.key),
@@ -19086,14 +20371,16 @@ function groups(input2) {
19086
20371
  kind: "cluster",
19087
20372
  source: plan.sourceId,
19088
20373
  root: c.root,
19089
- files: c.files.map((f) => f.id)
20374
+ files: c.files.map((f) => f.id),
20375
+ ...within(b, "connections")
19090
20376
  });
19091
20377
  };
19092
- for (const b of [...boundaries.values()].sort((x, y) => cmp8(x.root, y.root))) {
20378
+ for (const b of [...boundaries.values()].sort((x, y) => cmp10(x.root, y.root))) {
19093
20379
  const units = b.kind === "repository" && packages.length === 0 ? folderUnits(b.files) : null;
20380
+ const repo = { kind: "repository", name: b.name, root: b.root };
19094
20381
  if (units) {
19095
20382
  for (const u of units) {
19096
- if (u.root === "" && u.files.length > threshold) asClusters(u.files);
20383
+ if (u.root === "" && u.files.length > threshold) asClusters(u.files, repo);
19097
20384
  else if (u.root === "") {
19098
20385
  push({
19099
20386
  id: ids.group(plan.sourceId, ""),
@@ -19103,7 +20390,8 @@ function groups(input2) {
19103
20390
  root: "",
19104
20391
  files: u.files.map((f) => f.id)
19105
20392
  });
19106
- } else if (u.files.length > threshold) asClusters(u.files);
20393
+ } else if (u.files.length > threshold)
20394
+ asClusters(u.files, { kind: "folder", name: u.root, root: u.root });
19107
20395
  else
19108
20396
  push({
19109
20397
  id: ids.cluster(plan.sourceId, u.root),
@@ -19111,13 +20399,14 @@ function groups(input2) {
19111
20399
  kind: "cluster",
19112
20400
  source: plan.sourceId,
19113
20401
  root: u.root,
19114
- files: u.files.map((f) => f.id)
20402
+ files: u.files.map((f) => f.id),
20403
+ ...within({ kind: "folder", name: u.root, root: u.root }, "folders")
19115
20404
  });
19116
20405
  }
19117
20406
  continue;
19118
20407
  }
19119
20408
  if (b.files.length > threshold) {
19120
- asClusters(b.files);
20409
+ asClusters(b.files, { kind: b.kind, name: b.name, root: b.root });
19121
20410
  continue;
19122
20411
  }
19123
20412
  push({
@@ -19130,64 +20419,7 @@ function groups(input2) {
19130
20419
  });
19131
20420
  }
19132
20421
  }
19133
- const byId = new Map(out.map((g) => [g.id, g]));
19134
- const roll = /* @__PURE__ */ new Map();
19135
- const rollOf = (from, to) => {
19136
- const key = `${from}\0${to}`;
19137
- let r = roll.get(key);
19138
- if (!r) roll.set(key, r = { imports: [], calls: [], references: [] });
19139
- return r;
19140
- };
19141
- for (const e of input2.imports) {
19142
- const from = groupOf.get(e.from);
19143
- if (!from) continue;
19144
- if (e.to.startsWith("package|")) {
19145
- const g = byId.get(from);
19146
- if (!g.externalPackages.includes(e.to)) g.externalPackages.push(e.to);
19147
- continue;
19148
- }
19149
- const to = groupOf.get(e.to);
19150
- if (to && to !== from) rollOf(from, to).imports.push(e);
19151
- }
19152
- for (const c of input2.calls) {
19153
- const fromFile = fnFile.get(c.from);
19154
- const toFile = fnFile.get(c.to);
19155
- const from = fromFile ? groupOf.get(fromFile) : void 0;
19156
- const to = toFile ? groupOf.get(toFile) : void 0;
19157
- if (from && to && from !== to) rollOf(from, to).calls.push(c);
19158
- }
19159
- for (const c of input2.references ?? []) {
19160
- const fromFile = fnFile.get(c.from);
19161
- const toFile = fnFile.get(c.to);
19162
- const from = fromFile ? groupOf.get(fromFile) : void 0;
19163
- const to = toFile ? groupOf.get(toFile) : void 0;
19164
- if (from && to && from !== to) rollOf(from, to).references.push(c);
19165
- }
19166
- for (const g of out) g.externalPackages.sort(cmp8);
19167
- const carries = /* @__PURE__ */ new Map();
19168
- for (const s of input2.symbols ?? []) {
19169
- const key = s.id.slice("IMPORTS_SYMBOL|".length, s.id.lastIndexOf("|"));
19170
- const u = s.uses;
19171
- const yes = u === null || u.calls + u.jsx + u.extends > 0;
19172
- carries.set(key, (carries.get(key) ?? false) || yes);
19173
- }
19174
- const carrying = (e) => carries.get(e.id.slice("IMPORTS|".length)) ?? true;
19175
- const dependsOn = [...roll].map(([key, r]) => {
19176
- const [from, to] = key.split("\0");
19177
- const first = (xs) => [...xs].sort((a, b) => cmp8(a.id, b.id))[0];
19178
- const evidence = (first(r.imports) ?? first(r.calls) ?? first(r.references)).evidence;
19179
- return {
19180
- type: "DEPENDS_ON",
19181
- id: ids.dependsOn(from, to),
19182
- from,
19183
- to,
19184
- imports: r.imports.length,
19185
- calls: r.calls.length,
19186
- ...r.references.length ? { references: r.references.length } : {},
19187
- carrying: r.imports.filter(carrying).length,
19188
- evidence
19189
- };
19190
- }).sort((a, b) => cmp8(a.id, b.id));
20422
+ const dependsOn = rollUp(out, groupOf, input2, fnFile);
19191
20423
  return { groups: out, dependsOn };
19192
20424
  }
19193
20425
  function folderUnits(files) {
@@ -19199,10 +20431,10 @@ function folderUnits(files) {
19199
20431
  roots.add("");
19200
20432
  continue;
19201
20433
  }
19202
- const inside3 = analyzed.filter((f) => top(f) === dir);
19203
- const direct = inside3.filter((f) => f.path.split("/").length === 2);
20434
+ const inside4 = analyzed.filter((f) => top(f) === dir);
20435
+ const direct = inside4.filter((f) => f.path.split("/").length === 2);
19204
20436
  const children = new Set(
19205
- inside3.filter((f) => f.path.split("/").length > 2).map((f) => f.path.split("/")[1])
20437
+ inside4.filter((f) => f.path.split("/").length > 2).map((f) => f.path.split("/")[1])
19206
20438
  );
19207
20439
  if (direct.length === 0 && children.size >= 2) for (const c of children) roots.add(`${dir}/${c}`);
19208
20440
  else roots.add(dir);
@@ -19216,7 +20448,7 @@ function folderUnits(files) {
19216
20448
  list.push(f);
19217
20449
  units.set(root, list);
19218
20450
  }
19219
- return [...units].map(([root, list]) => ({ root, files: list })).sort((a, b) => cmp8(a.root, b.root));
20451
+ return [...units].map(([root, list]) => ({ root, files: list })).sort((a, b) => cmp10(a.root, b.root));
19220
20452
  }
19221
20453
  function clusters(files, imports, calls, fnFile) {
19222
20454
  const index = new Map(files.map((f, i) => [f.id, i]));
@@ -19239,7 +20471,7 @@ function clusters(files, imports, calls, fnFile) {
19239
20471
  });
19240
20472
  let community = louvain(n2, edges);
19241
20473
  const touched = new Set(edges.flatMap((e) => [e.a, e.b]));
19242
- const dir = (i) => posix6.dirname(files[i].path);
20474
+ const dir = (i) => posix8.dirname(files[i].path);
19243
20475
  const folderCommunity = /* @__PURE__ */ new Map();
19244
20476
  for (let i = 0; i < n2; i++)
19245
20477
  if (touched.has(i) && !folderCommunity.has(dir(i))) folderCommunity.set(dir(i), community[i]);
@@ -19260,150 +20492,16 @@ function clusters(files, imports, calls, fnFile) {
19260
20492
  });
19261
20493
  return [...members2.values()].map(nameCluster).sort(byKey).map(disambiguate());
19262
20494
  }
19263
- function ancestors(dir) {
19264
- if (!dir) return [""];
19265
- const parts = dir.split("/");
19266
- return ["", ...parts.map((_, i) => parts.slice(0, i + 1).join("/"))];
19267
- }
19268
- function nameCluster(list) {
19269
- const dirs = list.map((f) => {
19270
- const d = posix6.dirname(f.path);
19271
- return d === "." ? "" : d;
19272
- });
19273
- const counts = /* @__PURE__ */ new Map();
19274
- for (const d of dirs) for (const a of ancestors(d)) counts.set(a, (counts.get(a) ?? 0) + 1);
19275
- const root = [...counts].filter(([, n2]) => n2 === list.length).sort((x, y) => y[0].length - x[0].length)[0][0];
19276
- const need = Math.ceil(list.length * 0.75);
19277
- const main2 = [...counts].filter(([dir, n2]) => n2 >= need && inside2(`${dir}/x`, root)).sort((x, y) => y[0].length - x[0].length || y[1] - x[1] || cmp8(x[0], y[0]))[0][0];
19278
- const outside = list.length - counts.get(main2);
19279
- const roles = /* @__PURE__ */ new Map();
19280
- for (const f of list) {
19281
- const parts = posix6.basename(f.path).split(".");
19282
- if (parts.length >= 3)
19283
- roles.set(parts[parts.length - 2], (roles.get(parts[parts.length - 2]) ?? 0) + 1);
19284
- }
19285
- const [role, shared] = [...roles].sort((x, y) => y[1] - x[1] || cmp8(x[0], y[0]))[0] ?? ["", 0];
19286
- const base2 = `${main2 || "(root)"}${list.length > 1 && shared >= Math.ceil(list.length * 0.6) ? ` \xB7 ${role} files` : ""}`;
19287
- const name = outside > 0 ? `${base2} (+${outside} elsewhere in ${root || "the repository"})` : base2;
19288
- return { name, root, main: main2, files: list };
19289
- }
19290
- function disambiguate() {
19291
- const seen = /* @__PURE__ */ new Set();
19292
- return (c) => {
19293
- const key = c.main || "(root)";
19294
- const taken = seen.has(key);
19295
- seen.add(key);
19296
- if (!taken) return { key, name: c.name, root: c.root, files: c.files };
19297
- const first = [...c.files].map((f) => f.path).sort(cmp8).find((p) => inside2(p, c.main));
19298
- const within = c.main ? first.slice(c.main.length + 1) : first;
19299
- const counts = /* @__PURE__ */ new Map();
19300
- for (const f of c.files) {
19301
- if (!inside2(f.path, c.main)) continue;
19302
- const rel = posix6.dirname(c.main ? f.path.slice(c.main.length + 1) : f.path);
19303
- if (rel === ".") continue;
19304
- const parts = rel.split("/");
19305
- for (let i = 1; i <= parts.length; i++) {
19306
- const d = parts.slice(0, i).join("/");
19307
- counts.set(d, (counts.get(d) ?? 0) + 1);
19308
- }
19309
- }
19310
- const [folder, n2] = [...counts].sort(
19311
- (a, b) => b[1] - a[1] || b[0].split("/").length - a[0].split("/").length || cmp8(a[0], b[0])
19312
- )[0] ?? ["", 0];
19313
- const name = n2 >= 2 ? `${c.name} \xB7 mostly ${folder} (${n2} of ${c.files.length})` : `${c.name} (${within})`;
19314
- return { key: `${key} (${within})`, name, root: c.root, files: c.files };
19315
- };
19316
- }
19317
- function louvain(n2, edges) {
19318
- let assignment = Array.from({ length: n2 }, (_, i) => i);
19319
- let nodes = n2;
19320
- let graph = edges;
19321
- for (let level = 0; level < 10; level++) {
19322
- const { community, moved } = localMoves(nodes, graph);
19323
- if (!moved) break;
19324
- const renumber2 = /* @__PURE__ */ new Map();
19325
- for (let i = 0; i < nodes; i++)
19326
- if (!renumber2.has(community[i])) renumber2.set(community[i], renumber2.size);
19327
- assignment = assignment.map((c) => renumber2.get(community[c]));
19328
- const agg = /* @__PURE__ */ new Map();
19329
- for (const e of graph) {
19330
- const a = renumber2.get(community[e.a]);
19331
- const b = renumber2.get(community[e.b]);
19332
- const key = a < b ? `${a} ${b}` : `${b} ${a}`;
19333
- agg.set(key, (agg.get(key) ?? 0) + e.w);
19334
- }
19335
- nodes = renumber2.size;
19336
- graph = [...agg].map(([k, w]) => {
19337
- const [a, b] = k.split(" ").map(Number);
19338
- return { a, b, w };
19339
- });
19340
- }
19341
- const refined = localMoves(n2, edges, assignment).community;
19342
- const renumber = /* @__PURE__ */ new Map();
19343
- return refined.map((c) => {
19344
- if (!renumber.has(c)) renumber.set(c, renumber.size);
19345
- return renumber.get(c);
19346
- });
19347
- }
19348
- function localMoves(n2, edges, initial) {
19349
- const adj = Array.from({ length: n2 }, () => /* @__PURE__ */ new Map());
19350
- const selfLoop = new Array(n2).fill(0);
19351
- let total = 0;
19352
- for (const e of edges) {
19353
- if (e.a === e.b) selfLoop[e.a] += e.w;
19354
- else {
19355
- adj[e.a].set(e.b, (adj[e.a].get(e.b) ?? 0) + e.w);
19356
- adj[e.b].set(e.a, (adj[e.b].get(e.a) ?? 0) + e.w);
19357
- }
19358
- total += e.w;
19359
- }
19360
- const community = initial ? [...initial] : Array.from({ length: n2 }, (_, i) => i);
19361
- if (total === 0) return { community, moved: false };
19362
- const m2 = 2 * total;
19363
- const degree = adj.map((m, i) => [...m.values()].reduce((s, w) => s + w, 0) + 2 * selfLoop[i]);
19364
- let size = n2;
19365
- for (const c of community) if (c + 1 > size) size = c + 1;
19366
- const communityDegree = new Array(size).fill(0);
19367
- for (let i = 0; i < n2; i++) communityDegree[community[i]] += degree[i];
19368
- let moved = false;
19369
- for (let pass = 0; pass < 50; pass++) {
19370
- let changed = false;
19371
- for (let i = 0; i < n2; i++) {
19372
- const own2 = community[i];
19373
- const links = /* @__PURE__ */ new Map();
19374
- for (const [j, w] of adj[i]) links.set(community[j], (links.get(community[j]) ?? 0) + w);
19375
- communityDegree[own2] -= degree[i];
19376
- const gain = (c) => (links.get(c) ?? 0) - communityDegree[c] * degree[i] / m2;
19377
- let best = own2;
19378
- let bestGain = gain(own2);
19379
- for (const c of [...links.keys()].sort((x, y) => x - y)) {
19380
- const g = gain(c);
19381
- if (g > bestGain + 1e-12 || Math.abs(g - bestGain) <= 1e-12 && c < best) {
19382
- best = c;
19383
- bestGain = g;
19384
- }
19385
- }
19386
- communityDegree[best] += degree[i];
19387
- if (best !== own2) {
19388
- community[i] = best;
19389
- changed = true;
19390
- moved = true;
19391
- }
19392
- }
19393
- if (!changed) break;
19394
- }
19395
- return { community, moved };
19396
- }
19397
- var DEFAULT_CLUSTER_THRESHOLD, cmp8, inside2, byKey;
20495
+ var DEFAULT_CLUSTER_THRESHOLD, cmp10;
19398
20496
  var init_groups = __esm({
19399
20497
  "packages/stage2/src/groups.ts"() {
19400
20498
  "use strict";
19401
20499
  init_src();
20500
+ init_cluster();
19402
20501
  init_imports();
20502
+ init_cluster();
19403
20503
  DEFAULT_CLUSTER_THRESHOLD = 200;
19404
- cmp8 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
19405
- inside2 = (path, dir) => dir === "" || path.startsWith(`${dir}/`);
19406
- byKey = (a, b) => cmp8(a.main, b.main) || b.files.length - a.files.length || cmp8(a.files[0].path, b.files[0].path);
20504
+ cmp10 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
19407
20505
  }
19408
20506
  });
19409
20507
 
@@ -20845,6 +21943,8 @@ function typedResolutions(input2, graph, s) {
20845
21943
  let a = member !== null ? answer(type, member, 0, subject.kind === ts.SyntaxKind.SuperKeyword) : answerCall(call);
20846
21944
  const fallback = a.kind === "candidates" ? defaultOf(subject) : void 0;
20847
21945
  if (fallback) a = { kind: "default", text: fallback.getText(sf) };
21946
+ const earlier = input2.resolutions.get(base2.id);
21947
+ if (earlier && stoppedAtValue(earlier) && a.kind !== "runtime") continue;
20848
21948
  const at = declOf(type.getSymbol()?.declarations?.[0]);
20849
21949
  const where = at ? ` (${at.file.slice(at.file.indexOf(":") + 1)})` : "";
20850
21950
  const typed = { kind: "type", detail: `${written2} is ${typeName}${where}` };
@@ -20934,9 +22034,13 @@ function typedResolutions(input2, graph, s) {
20934
22034
  function wanted(site, existing) {
20935
22035
  if (site.reason === "dynamic-dispatch") return !existing;
20936
22036
  if (site.reason !== "imported-symbol" || !existing) return false;
22037
+ if (stoppedAtValue(existing)) return true;
20937
22038
  const last = existing.steps.at(-1);
20938
22039
  return existing.status === "unresolved" && existing.importOutcome === null && !existing.candidates && last?.kind === "member" && last.detail.includes(` ${MEMBER_OF_FUNCTION} `);
20939
22040
  }
22041
+ function stoppedAtValue(existing) {
22042
+ return existing.status === "unresolved" && existing.importOutcome === null && !existing.candidates && existing.steps.at(-1)?.kind === "not-a-function";
22043
+ }
20940
22044
  function plural2(n2, one, many = `${one}s`) {
20941
22045
  return `${n2} ${n2 === 1 ? one : many}`;
20942
22046
  }
@@ -21172,7 +22276,7 @@ function folderOf(fileId, head) {
21172
22276
  }
21173
22277
  function aliasesOf(plans) {
21174
22278
  const out = [];
21175
- const dirOf = (path) => path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
22279
+ const dirOf2 = (path) => path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
21176
22280
  const under = (dir, rel) => {
21177
22281
  const parts = dir ? dir.split("/") : [];
21178
22282
  for (const r of rel.split("/")) {
@@ -21190,7 +22294,7 @@ function aliasesOf(plans) {
21190
22294
  } catch {
21191
22295
  continue;
21192
22296
  }
21193
- const base2 = under(dirOf(m.path), json2?.compilerOptions?.baseUrl ?? ".");
22297
+ const base2 = under(dirOf2(m.path), json2?.compilerOptions?.baseUrl ?? ".");
21194
22298
  for (const [key, targets] of Object.entries(json2?.compilerOptions?.paths ?? {}))
21195
22299
  for (const target2 of targets ?? [])
21196
22300
  out.push([p.sourceId, key.replace(/\*$/, ""), under(base2, target2.replace(/\*.*$/, ""))]);
@@ -21200,11 +22304,11 @@ function aliasesOf(plans) {
21200
22304
  const name = f.path.slice(f.path.lastIndexOf("/") + 1);
21201
22305
  if (/^(vite|webpack)\.config\.[cm]?[jt]s$/.test(name))
21202
22306
  for (const [key, folder] of parseAliases(f.content))
21203
- out.push([p.sourceId, key, under(dirOf(f.path), folder)]);
22307
+ out.push([p.sourceId, key, under(dirOf2(f.path), folder)]);
21204
22308
  else if (/^svelte\.config\.[cm]?[jt]s$/.test(name)) {
21205
22309
  const block = /alias\s*:\s*\{([^}]*)\}/.exec(f.content)?.[1] ?? "";
21206
22310
  for (const m of block.matchAll(/['"]?([$@~\w/-]+)['"]?\s*:\s*['"]([^'"*]+)\/?\*?['"]/g))
21207
- out.push([p.sourceId, m[1].replace(/\/\*$/, ""), under(dirOf(f.path), m[2].replace(/\/$/, ""))]);
22311
+ out.push([p.sourceId, m[1].replace(/\/\*$/, ""), under(dirOf2(f.path), m[2].replace(/\/$/, ""))]);
21208
22312
  }
21209
22313
  }
21210
22314
  }
@@ -21523,7 +22627,7 @@ var init_src8 = __esm({
21523
22627
  symbolsScope = (fileId) => `${STAGE23}:symbols:${fileId}`;
21524
22628
  groupSource = (groupId) => groupId.split("|")[1];
21525
22629
  STEPS = 5;
21526
- STAGE2_VERSION = 5;
22630
+ STAGE2_VERSION = 8;
21527
22631
  stage2 = createStage2();
21528
22632
  }
21529
22633
  });
@@ -59478,7 +60582,8 @@ var init_server3 = __esm({
59478
60582
  from: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).optional().describe("With to: the calling groups, files or a group's folders (folder|<group>|<path>)"),
59479
60583
  to: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).optional().describe("With from: the called groups, files or a group's folders"),
59480
60584
  offset: external_exports.number().int().optional().describe("Skip this many first (default 0)"),
59481
- limit: external_exports.number().int().optional().describe(`At most this many calls (1 to ${CROSS_FILE_CALLS_MAX}; default 100)`)
60585
+ limit: external_exports.number().int().optional().describe(`At most this many calls (1 to ${CROSS_FILE_CALLS_MAX}; default 100)`),
60586
+ grouping: external_exports.enum(GROUPINGS).optional().describe("The grouping the group ids are of: declared (default) or connected (#304)")
59482
60587
  },
59483
60588
  call: (e, a, cwd) => crossFileCalls(e, a, cwd)
59484
60589
  },
@@ -59496,13 +60601,16 @@ var init_server3 = __esm({
59496
60601
  call: (e, a, cwd) => projectTotals(e, a, cwd)
59497
60602
  },
59498
60603
  list_groups: {
59499
- description: "The project map (R2): groups of files (workspace packages, repositories, and clusters inside large ones), each with file, function and external-package counts and finding counts; DEPENDS_ON edges between them (imports, cross-file calls, references, and `carrying`: imports whose names are called, rendered or extended; with one as evidence; A calls into B when calls, references or carrying are above zero, else the link is type-only, value-only or unused imports); the external packages (how many, and the most imported); and project totals. `stage2: false` means Stage 2 hasn't run.",
60604
+ description: "The project map (R2): groups of files (workspace packages, repositories, and clusters inside large ones), each with file, function and external-package counts and finding counts; DEPENDS_ON edges between them (imports, cross-file calls, references, and `carrying`: imports whose names are called, rendered or extended; with one as evidence; A calls into B when calls, references or carrying are above zero, else the link is type-only, value-only or unused imports); the external packages (how many, and the most imported); and project totals. Each group says `why` its files are together; with grouping connected, `differences` lists the declared and connected groups that map onto each other other than one to one (a split, a merge). `stage2: false` means Stage 2 hasn't run.",
59500
60605
  input: {
59501
60606
  project,
59502
60607
  run,
59503
60608
  source: external_exports.string().optional().describe("One source only"),
59504
60609
  limit: external_exports.number().int().optional().describe(`At most this many groups (1 to ${GROUPS_MAX}; default ${GROUPS_MAX})`),
59505
- offset: external_exports.number().int().optional().describe("Skip this many groups first (paging; default 0)")
60610
+ offset: external_exports.number().int().optional().describe("Skip this many groups first (paging; default 0)"),
60611
+ grouping: external_exports.enum(GROUPINGS).optional().describe(
60612
+ "declared (default): workspace packages, repositories and folders; connected: how files connect (#304): modules joined by calls within their packages, a shared layer apart, packages calling into each other merged"
60613
+ )
59506
60614
  },
59507
60615
  call: (e, a, cwd) => listGroups(e, a, cwd)
59508
60616
  },
@@ -59513,13 +60621,21 @@ var init_server3 = __esm({
59513
60621
  run,
59514
60622
  group: external_exports.string().describe("A group id, as returned by list_groups"),
59515
60623
  expand: external_exports.array(external_exports.string()).optional().describe("Folder paths to show open"),
59516
- pending: external_exports.boolean().optional().describe("Include imports waiting for another source")
60624
+ pending: external_exports.boolean().optional().describe("Include imports waiting for another source"),
60625
+ grouping: external_exports.enum(GROUPINGS).optional().describe(
60626
+ "The grouping the group id is of: declared (default): workspace packages, repositories and folders; connected: how files connect (#304): modules joined by calls within their packages, a shared layer apart, packages calling into each other merged"
60627
+ )
59517
60628
  },
59518
60629
  call: (e, a, cwd) => getGroup(e, a, cwd)
59519
60630
  },
59520
60631
  resolve_imports: {
59521
60632
  description: "A file's imports (R2), each with its outcome (a file, an external package, or broken, not analyzed or pending with the reason) and how it was resolved; and the files importing it.",
59522
- input: { project, run, file: external_exports.string().describe("A file id") },
60633
+ input: {
60634
+ project,
60635
+ run,
60636
+ file: external_exports.string().describe("A file id"),
60637
+ grouping: external_exports.enum(GROUPINGS).optional().describe("The grouping each end's group is of: declared (default) or connected (#304)")
60638
+ },
59523
60639
  call: (e, a, cwd) => resolveImports(e, a, cwd)
59524
60640
  },
59525
60641
  file_summary: {
@@ -59652,7 +60768,10 @@ var init_server3 = __esm({
59652
60768
  "impact (default): by what resolving each would open, the own-code functions whose paths stop at it (#307), most first; place: by file and line"
59653
60769
  ),
59654
60770
  limit: external_exports.number().int().optional().describe(`At most this many (1 to ${FINDINGS_MAX}; default 100)`),
59655
- offset: external_exports.number().int().optional().describe("Skip this many first (paging; default 0); `total` counts them all")
60771
+ offset: external_exports.number().int().optional().describe("Skip this many first (paging; default 0); `total` counts them all"),
60772
+ grouping: external_exports.enum(GROUPINGS).optional().describe(
60773
+ "The grouping `group` and each row's group are of: declared (default): workspace packages, repositories and folders; connected: how files connect (#304): modules joined by calls within their packages, a shared layer apart, packages calling into each other merged"
60774
+ )
59656
60775
  },
59657
60776
  call: (e, a, cwd) => listFindings(e, a, cwd)
59658
60777
  },
@@ -102083,6 +103202,12 @@ async function createServer(engine, options2 = {}) {
102083
103202
  const run2 = pinned.get(req);
102084
103203
  if (run2 !== void 0 && req.params && typeof req.params === "object")
102085
103204
  req.params.run = run2;
103205
+ const project2 = req.params?.project;
103206
+ const route = req.routeOptions.url ?? "";
103207
+ const reads = req.method === "GET" ? !route.endsWith("/status") : route.endsWith("/ask");
103208
+ const connected = req.query?.grouping === "connected";
103209
+ if (typeof project2 === "string" && reads)
103210
+ await engine.finishing(project2, void 0, connected).catch(() => void 0);
102086
103211
  });
102087
103212
  app.addHook("onClose", async () => {
102088
103213
  engine.events.off("event", forward);
@@ -102464,7 +103589,12 @@ async function createServer(engine, options2 = {}) {
102464
103589
  querystring: {
102465
103590
  type: "object",
102466
103591
  additionalProperties: false,
102467
- properties: { source: str2, limit: positive2, offset: count2 }
103592
+ properties: {
103593
+ source: str2,
103594
+ limit: positive2,
103595
+ offset: count2,
103596
+ grouping: { type: "string", enum: [...GROUPINGS] }
103597
+ }
102468
103598
  }
102469
103599
  }
102470
103600
  },
@@ -102472,7 +103602,8 @@ async function createServer(engine, options2 = {}) {
102472
103602
  ...req.params,
102473
103603
  ...req.query.source !== void 0 ? { source: req.query.source } : {},
102474
103604
  ...req.query.limit ? { limit: Number(req.query.limit) } : {},
102475
- ...req.query.offset ? { offset: Number(req.query.offset) } : {}
103605
+ ...req.query.offset ? { offset: Number(req.query.offset) } : {},
103606
+ ...req.query.grouping !== void 0 ? { grouping: req.query.grouping } : {}
102476
103607
  })
102477
103608
  );
102478
103609
  app.get(
@@ -102487,7 +103618,8 @@ async function createServer(engine, options2 = {}) {
102487
103618
  properties: {
102488
103619
  group: str2,
102489
103620
  expand: oneOrMore(str2),
102490
- pending: { type: "string", enum: ["true", "false"] }
103621
+ pending: { type: "string", enum: ["true", "false"] },
103622
+ grouping: { type: "string", enum: [...GROUPINGS] }
102491
103623
  }
102492
103624
  }
102493
103625
  }
@@ -102496,7 +103628,8 @@ async function createServer(engine, options2 = {}) {
102496
103628
  ...req.params,
102497
103629
  group: req.query.group,
102498
103630
  ...req.query.expand !== void 0 ? { expand: list(req.query.expand) } : {},
102499
- ...req.query.pending === "true" ? { pending: true } : {}
103631
+ ...req.query.pending === "true" ? { pending: true } : {},
103632
+ ...req.query.grouping !== void 0 ? { grouping: req.query.grouping } : {}
102500
103633
  })
102501
103634
  );
102502
103635
  app.get(
@@ -102508,11 +103641,15 @@ async function createServer(engine, options2 = {}) {
102508
103641
  type: "object",
102509
103642
  additionalProperties: false,
102510
103643
  required: ["file"],
102511
- properties: { file: str2 }
103644
+ properties: { file: str2, grouping: { type: "string", enum: [...GROUPINGS] } }
102512
103645
  }
102513
103646
  }
102514
103647
  },
102515
- async (req) => resolveImports(engine, { ...req.params, file: req.query.file })
103648
+ async (req) => resolveImports(engine, {
103649
+ ...req.params,
103650
+ file: req.query.file,
103651
+ ...req.query.grouping !== void 0 ? { grouping: req.query.grouping } : {}
103652
+ })
102516
103653
  );
102517
103654
  app.get(
102518
103655
  "/api/projects/:project/file-summary",
@@ -102545,7 +103682,8 @@ async function createServer(engine, options2 = {}) {
102545
103682
  own: { type: "string", enum: ["true", "false"] },
102546
103683
  sort: { type: "string", enum: ["impact", "place"] },
102547
103684
  limit: positive2,
102548
- offset: count2
103685
+ offset: count2,
103686
+ grouping: { type: "string", enum: [...GROUPINGS] }
102549
103687
  }
102550
103688
  }
102551
103689
  }
@@ -102577,7 +103715,8 @@ async function createServer(engine, options2 = {}) {
102577
103715
  from: oneOrMore(str2),
102578
103716
  to: oneOrMore(str2),
102579
103717
  limit: positive2,
102580
- offset: { type: "string", pattern: "^[0-9]+$" }
103718
+ offset: { type: "string", pattern: "^[0-9]+$" },
103719
+ grouping: { type: "string", enum: [...GROUPINGS] }
102581
103720
  }
102582
103721
  }
102583
103722
  }
@@ -103545,6 +104684,8 @@ async function serveRun(io) {
103545
104684
  const engine = new Engine(io.home, {
103546
104685
  stages: request.stages.map((n2) => known[n2]),
103547
104686
  afterCommit: summarizeFindings,
104687
+ // The connected grouping kept with each run, once its counts are (#374).
104688
+ afterSummaries: keepConnectedGrouping,
103548
104689
  ...request.retention ? { retention: request.retention } : {},
103549
104690
  license: request.license,
103550
104691
  killableRuns: true
@@ -103559,12 +104700,12 @@ async function serveRun(io) {
103559
104700
  }
103560
104701
  function usageFor(command) {
103561
104702
  const out = [];
103562
- let inside3 = false;
104703
+ let inside4 = false;
103563
104704
  for (const line of USAGE.split("\n")) {
103564
104705
  if (/^ {2}veoflow /.test(line))
103565
- inside3 = line.startsWith(` veoflow ${command} `) || line === ` veoflow ${command}`;
103566
- else if (!/^ {3,}/.test(line)) inside3 = false;
103567
- if (inside3) out.push(line);
104706
+ inside4 = line.startsWith(` veoflow ${command} `) || line === ` veoflow ${command}`;
104707
+ else if (!/^ {3,}/.test(line)) inside4 = false;
104708
+ if (inside4) out.push(line);
103568
104709
  }
103569
104710
  return out.length ? out.join("\n") : null;
103570
104711
  }
@@ -103601,6 +104742,7 @@ async function main(argv, io) {
103601
104742
  const engine2 = new Engine(io.home);
103602
104743
  try {
103603
104744
  summarizeFindings(engine2, project2, Number(run2));
104745
+ keepConnectedGrouping(engine2, project2, Number(run2));
103604
104746
  } finally {
103605
104747
  engine2.close();
103606
104748
  }
@@ -103615,6 +104757,8 @@ async function main(argv, io) {
103615
104757
  stages: [stage2],
103616
104758
  // Finding counts kept with each run, so the projects home never scans findings (#249).
103617
104759
  afterCommit: summarizeFindings,
104760
+ // The connected grouping kept with each run, once its counts are (#374).
104761
+ afterSummaries: keepConnectedGrouping,
103618
104762
  ...command === "serve" ? { runner: { command: self2 } } : ["run", "add", "include", "exclude"].includes(command) ? { killableRuns: true } : {}
103619
104763
  });
103620
104764
  let keepOpen = false;