Repository navigation
Expand file tree
/
Copy pathmap.ts
More file actions
855 lines (802 loc) · 33 KB
/
Copy pathmap.ts
File metadata and controls
855 lines (802 loc) · 33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
/**
* `GET /api/map` — the repository at module granularity.
*
* The Map answers "what is in here and how is it organised" without anybody
* having drawn a diagram: modules are directories, the arrows between them are
* the edges the index already holds, and the vertical order falls out of the
* dependency direction (design spec §3.6). This module produces the *data*;
* the layering, cycle-breaking and geometry are pure functions in the viewer
* (`ui/src/lib/map-model.ts`), so toggling tests or selecting a module never
* costs a round-trip.
*
* Three decisions shape the payload, and all three are about not lying:
*
* **A module is a directory, not a guess.** `moduleIdFor` maps each indexed
* file to the first {@link MapQuery.depth} path segments under the chosen root.
* A file sitting loose in the root gets folded into one `(root files)` box —
* except a façade (`index.ts`, `lib.rs`, `__init__.py`), which is its own box
* because it is the thing everything else imports. No clustering, no
* heuristics about "what belongs together": if two files are in the same
* directory the repository already said they belong together.
*
* **Weight counts edges; layering counts *declared* edges.** A link's `count`
* is every confident cross-module edge behind it, which is what the reader
* sees as thickness. Its `declared` count is the subset resolved through an
* import, a qualified name, an inheritance clause or a typed receiver — and
* that is what the layout layers on. The difference is not academic: on this
* repository, bare name matching resolves calls to `run`, `push` and `finish`
* across unrelated directories, and layering on raw counts puts the storage
* layer directly under the CLI. Layering on declared edges reproduces the
* pipeline the project's own docs describe.
*
* **Nothing is dropped silently.** Uncertain edges (confidence below
* {@link UNCERTAIN_BELOW}) are excluded from every count, and how many were
* excluded rides on the payload so the side panel can say so.
*/
import type { CodeGraph } from '../../index';
import type { EdgeKind, Language } from '../../types';
import { findFileCycles } from '../../graph/file-cycles';
import { isTestFile } from '../../search/query-utils';
import { badRequest } from './respond';
import { UNCERTAIN_BELOW, toPosixPath, wireList, type WireList } from './wire';
/**
* The edge kinds that count as "module A reaches into module B".
*
* `contains` is absent on purpose — a file containing its own symbols is not a
* dependency, and including it would make every module depend on itself.
*/
export const MAP_EDGE_KINDS: readonly EdgeKind[] = [
'calls',
'imports',
'references',
'instantiates',
'extends',
'implements',
'navigates',
];
/**
* The kinds whose symbol pairs the tooltip names.
*
* A `references` edge to a type is real traffic but "Config → Config" is not
* an interesting row; calls and imports are what a reader wants named.
*/
const PAIR_EDGE_KINDS: readonly EdgeKind[] = ['calls', 'imports', 'instantiates', 'navigates'];
/** Symbol pairs kept per link — the tooltip shows four (design spec §3.6). */
const TOP_PAIRS_PER_LINK = 4;
/**
* File paths listed per module.
*
* The panel's file list is a drill-down, not a directory listing, and it rides
* on this payload so that clicking a module and then one of its files costs no
* round-trip at all. Capped because a module can hold hundreds of files and the
* map is not where you read them; `total` stays the real number.
*/
const MAX_FILES_PER_MODULE = 40;
/** Longest cycle reported, and how many. Beyond this a cycle list stops being readable. */
const MAX_FILE_CYCLES = 40;
const MAX_CYCLE_LENGTH = 12;
/** Default segments below the root that name a module. */
const DEFAULT_DEPTH = 1;
const MAX_DEPTH = 4;
/**
* Basenames that stay their own box when they sit loose in a module root.
*
* These are façades — the file every other module imports the directory
* *through*. Folding `src/index.ts` into a "(root files)" bucket with the type
* declarations next to it hides the busiest node on the map.
*/
const FACADE_STEMS = new Set(['index', 'main', 'lib', 'mod', '__init__', 'init']);
/** Id of the bucket loose files fall into. Deliberately not a real directory name. */
export function rootFilesId(root: string): string {
return root ? `${root}/(root files)` : '(root files)';
}
// =============================================================================
// Wire shapes
// =============================================================================
export interface WireMapModule {
/** Directory path, or the `(root files)` bucket, or a façade file's own path. */
id: string;
/**
* What the box says: the id, with a folder chain the repository never forks
* in written `first/…/last` — Maven's `src/main/java/…/petclinic/owner`
* rather than all seven segments. Equal to `id` everywhere else.
*/
label: string;
files: number;
symbols: number;
/** File count by language, most files first. */
languages: Array<{ language: Language; files: number }>;
/** More than half its files are tests — drawn dashed, hidden by default. */
test: boolean;
/**
* How many of its files are tool-generated. A module whose files are ALL
* generated is drawn in ink-4 (design spec §2.6): code nobody wrote by hand
* and nobody deletes by hand.
*/
generated: number;
/** Which of {@link fileList}'s entries are generated, so a row can dim too. */
generatedFiles: string[];
/** True when this box is a single file kept out of the root bucket (a façade). */
facade: boolean;
/** Its files, capped — what the side panel lists when the module is selected. */
fileList: WireList<string>;
/**
* What a change in here reaches: files OUTSIDE this module holding a direct,
* confident reference into one of its files, and how many modules those
* files span.
*
* DIRECT, deliberately. The transitive closure was measured first and it is
* useless on a real repository: any dependency cycle — and a mobile app had
* nine mutual pairs — saturates it, so every module comes out reaching
* nearly every file (139–282 of 377, a flat 2× spread that says nothing but
* "this repo has cycles"). The direct count on the same repository spreads
* 0–127 and names the modules a reader would name by hand: the shared types
* at the top, the CLI at zero.
*
* The counts are FILES, not symbols: a module is a set of files, and "94
* files would have to be re-read if this changed" is a claim the index can
* stand behind. It is a floor on blast radius, not the whole of it — a
* symbol-level answer for one symbol is what the Symbol view is for.
*/
dependents: { files: number; modules: number };
}
export interface WireMapLink {
source: string;
target: string;
/** Every confident cross-module edge behind this link. Drives thickness. */
count: number;
/**
* The subset resolved through an import, a qualified name, an inheritance
* clause or a typed receiver. Drives the layering — see the module header.
*/
declared: number;
/** `count` broken down by edge kind, biggest first. */
byKind: Array<{ kind: EdgeKind; count: number }>;
/**
* The busiest symbol pairs behind the link, at most
* {@link TOP_PAIRS_PER_LINK}, declared ones first.
*/
topPairs: Array<{ from: string; to: string; count: number; declared: number }>;
}
export interface WireMapCycle {
/** How many files are in the component. `files` may be shorter. */
size: number;
/** The files, capped — a 200-file knot is a fact, not a list anybody reads. */
files: string[];
/** The modules the cycle passes through, deduped in order. */
modules: string[];
}
export interface WireMapPayload {
root: string;
depth: number;
/** Every root the selector may offer, this index's own directories. */
roots: Array<{ root: string; label: string; files: number }>;
modules: WireMapModule[];
links: WireMapLink[];
/**
* File-level circular dependencies — the strongly connected components of
* the file graph, which is what `findCircularDependencies` reports, computed
* from one query so it stays affordable on a large index.
*/
cycles: { total: number; shown: number; truncated: boolean; items: WireMapCycle[] };
excluded: {
/** Cross-module edges left out for being name-only guesses. */
uncertainEdges: number;
/** The confidence floor applied. */
confidenceBelow: number;
};
index: { lastIndexedAt: number | null; edges: number; files: number };
/** How long the aggregation took, and whether this answer came from the cache. */
timing: { elapsedMs: number; cached: boolean };
}
export interface MapQuery {
root: string;
depth: number;
}
// =============================================================================
// Module naming
// =============================================================================
/** Strip a trailing slash and any leading `./`, so `src/` and `src` are one root. */
export function normalizeRoot(raw: string | undefined): string {
let root = (raw ?? '').trim().replace(/\\/g, '/');
while (root.startsWith('./')) root = root.slice(2);
while (root.endsWith('/')) root = root.slice(0, -1);
if (root === '.' || root === '/') return '';
return root;
}
function stemOf(basename: string): string {
const dot = basename.indexOf('.');
return dot <= 0 ? basename : basename.slice(0, dot);
}
/**
* Directories a module boundary never falls on: exactly one subdirectory and
* no file of their own. A Maven project keeps every line of Java under
* `src/main/java/org/springframework/samples/petclinic/`, and the first four
* of those folders split nothing — cutting at any of them draws the whole
* program as one box, and no depth the reader can pick gets past them. Such a
* folder joins the level below it, so depth counts folders that fork.
*
* Read from every indexed file, tests included, so a module's id does not
* change when the reader toggles tests. The repository root is never one.
*/
export function passThroughDirs(paths: Iterable<string>): Set<string> {
const children = new Map<string, Set<string>>();
const holdsFiles = new Set<string>();
for (const raw of paths) {
const parts = toPosixPath(raw).split('/').filter(Boolean);
let dir = '';
for (let i = 0; i < parts.length - 1; i++) {
let kids = children.get(dir);
if (!kids) children.set(dir, (kids = new Set()));
kids.add(parts[i]!);
dir = dir ? `${dir}/${parts[i]}` : parts[i]!;
}
holdsFiles.add(dir);
}
const out = new Set<string>();
for (const [dir, kids] of children) {
if (dir !== '' && kids.size === 1 && !holdsFiles.has(dir)) out.add(dir);
}
return out;
}
/**
* Where each level of a file's directory path ends, as indexes into `dirs`: a
* level is one folder plus every pass-through folder that follows it.
*/
function levelEnds(root: string, dirs: readonly string[], passThrough: ReadonlySet<string> | undefined): number[] {
const ends: number[] = [];
for (let i = 0; i < dirs.length; ) {
i++;
while (passThrough && i < dirs.length && passThrough.has(joinPath(root, dirs.slice(0, i)))) i++;
ends.push(i);
}
return ends;
}
function joinPath(root: string, segments: readonly string[]): string {
return [root, ...segments].filter(Boolean).join('/');
}
/** The first `levels` levels of `dirs`, a chain of three or more folders written `first/…/last`. */
function levelLabel(root: string, dirs: readonly string[], ends: readonly number[]): string {
const out: string[] = root ? [root] : [];
let from = 0;
for (const end of ends) {
const chain = dirs.slice(from, end);
out.push(chain.length >= 3 ? `${chain[0]}/…/${chain[chain.length - 1]}` : chain.join('/'));
from = end;
}
return out.join('/');
}
/**
* Which module a file belongs to, or `null` when it is outside the root.
*
* `depth` levels under the root name the module — a level being a folder and
* the {@link passThroughDirs} that follow it (without them, one level per
* folder). A file with fewer levels than that is loose in the root: a façade
* keeps its own box, everything else joins the `(root files)` bucket.
*/
export function moduleIdFor(
filePath: string,
root: string,
depth: number,
passThrough?: ReadonlySet<string>
): { id: string; facade: boolean; label: string } | null {
const path = toPosixPath(filePath);
let rel = path;
if (root) {
if (!path.startsWith(`${root}/`)) return null;
rel = path.slice(root.length + 1);
}
const parts = rel.split('/').filter(Boolean);
if (parts.length === 0) return null;
const dirs = parts.slice(0, -1);
const ends = levelEnds(root, dirs, passThrough);
if (ends.length < depth) {
// A loose file. The directories it DOES have still qualify it, so
// `src/a/b.ts` at depth 2 lands in `src/a/(root files)`, not the top one.
const dir = joinPath(root, dirs);
const dirLabel = levelLabel(root, dirs, ends);
const file = parts[parts.length - 1] ?? '';
if (FACADE_STEMS.has(stemOf(file))) {
return { id: joinPath(root, parts), facade: true, label: dirLabel ? `${dirLabel}/${file}` : file };
}
return { id: rootFilesId(dir), facade: false, label: rootFilesId(dirLabel) };
}
return {
id: joinPath(root, dirs.slice(0, ends[depth - 1])),
facade: false,
label: levelLabel(root, dirs, ends.slice(0, depth)),
};
}
/**
* The root the map opens on: the directory holding the most non-test symbols.
*
* A repository's source almost always lives under one directory (`src`, `lib`,
* `pkg`, `app`), and opening there is what keeps the default map about the
* program rather than about its tests, scripts and sibling packages. The
* fallback is the repository root, which is correct for a flat project.
*
* A directory only wins if it holds a clear majority of the symbols — anything
* less and the honest answer is "this repository has no single source root".
*/
export function pickDefaultRoot(
files: ReadonlyArray<{ path: string; symbols: number; test: boolean }>
): string {
const byDir = new Map<string, number>();
let total = 0;
for (const file of files) {
if (file.test) continue;
// A file loose in the repository root is program too: git's hundreds of
// top-level `.c` files made `builtin/` look like the majority of the code.
total += file.symbols;
const slash = file.path.indexOf('/');
if (slash <= 0) continue;
const dir = file.path.slice(0, slash);
byDir.set(dir, (byDir.get(dir) ?? 0) + file.symbols);
}
if (total === 0) return '';
let best = '';
let bestSymbols = 0;
let second = 0;
for (const [dir, symbols] of [...byDir].sort((a, b) => a[0].localeCompare(b[0]))) {
if (symbols > bestSymbols) {
second = bestSymbols;
best = dir;
bestSymbols = symbols;
} else if (symbols > second) second = symbols;
}
// A second root holding a fifth of the code (a React Native app's `ios/`
// beside its `src/`) belongs on the picture: map the whole project.
if (second * 5 >= total) return '';
return bestSymbols * 2 > total ? best : '';
}
/**
* A box holding more than this share of the mapped symbols IS the program, and
* a map whose subject is one box has not said anything.
*/
const DOMINANT_SHARE = 0.4;
/**
* …but only if there is something inside it. A dominant box of four files is a
* small project honestly drawn; opening it just spreads four files over four
* boxes. This is the line between "grouped too coarsely" and "actually small".
*/
const DOMINANT_MIN_FILES = 25;
/** Fewer boxes than this is a list, not a picture. */
const MIN_MODULES = 4;
/** More than this and a deeper grouping has traded one unreadable map for another. */
const MAX_MODULES = 60;
/** The non-test modules a given depth would draw, and how concentrated they are. */
function tallyModules(
files: ReadonlyArray<{ path: string; symbols: number; test: boolean }>,
root: string,
depth: number,
passThrough?: ReadonlySet<string>
): { count: number; share: number; largestFiles: number } {
const byModule = new Map<string, { symbols: number; files: number }>();
let total = 0;
for (const file of files) {
if (file.test) continue;
const assigned = moduleIdFor(file.path, root, depth, passThrough);
if (assigned === null) continue;
let entry = byModule.get(assigned.id);
if (!entry) byModule.set(assigned.id, (entry = { symbols: 0, files: 0 }));
entry.symbols += file.symbols;
entry.files += 1;
total += file.symbols;
}
let largest = { symbols: 0, files: 0 };
for (const entry of byModule.values()) {
if (entry.symbols > largest.symbols) largest = entry;
}
return {
count: byModule.size,
share: total === 0 ? 0 : largest.symbols / total,
largestFiles: largest.files,
};
}
/**
* How many segments name a module, when the reader has not said.
*
* Depth is not a property of the reader's taste, it is a property of the
* repository: one level under the root is the right grouping for a project
* whose directories ARE its modules, and the wrong one for the very common
* shape where every line of the program lives under a single `src/`. Drawing
* that project at depth 1 produces the map this rule exists to prevent — a box
* labelled `src`, holding two thirds of the code, with nothing to say about it.
*
* So: take the shallowest depth that is neither dominated by one box worth
* opening nor too small to be a picture; stop before a deeper one becomes a
* crowd; and never go past the last level the directory tree actually has.
*
* The walk does NOT stop at the first depth that fails to add boxes. A repo
* packaged as `frontend/src/...` plateaus at two boxes for two levels running
* before the third splits it, and a rule that gave up on the plateau would
* draw exactly the picture this function exists to avoid.
*/
export function pickDefaultDepth(
files: ReadonlyArray<{ path: string; symbols: number; test: boolean }>,
root: string,
passThrough?: ReadonlySet<string>
): number {
// Past the deepest directory, a bigger number only renames boxes to
// `src/a/(root files)`. There is nothing below the leaves.
let deepest = DEFAULT_DEPTH;
for (const file of files) {
if (file.test) continue;
const path = toPosixPath(file.path);
if (root && !path.startsWith(`${root}/`)) continue;
const rel = root ? path.slice(root.length + 1) : path;
const dirs = rel.split('/').filter(Boolean).slice(0, -1);
deepest = Math.max(deepest, levelEnds(root, dirs, passThrough).length);
}
let fallback = DEFAULT_DEPTH;
let fallbackCount = 0;
for (let depth = DEFAULT_DEPTH; depth <= Math.min(MAX_DEPTH, deepest); depth += 1) {
const tally = tallyModules(files, root, depth, passThrough);
if (tally.count === 0) break;
// Deeper only gets more crowded from here.
if (tally.count > MAX_MODULES) break;
const dominated = tally.share > DOMINANT_SHARE && tally.largestFiles >= DOMINANT_MIN_FILES;
if (tally.count >= MIN_MODULES && !dominated) return depth;
// Not a picture yet. Worth keeping only if it drew more than the last one:
// a deeper grouping that splits nothing is the same map with longer labels.
if (tally.count > fallbackCount) {
fallback = depth;
fallbackCount = tally.count;
}
}
return fallback;
}
/**
* The root and depth the map opens on when the reader named neither.
*
* A source directory whose files all sit in one folder — Express's `lib/`, an
* R package's `R/`, an Erlang app's `src/`, fmt's `include/fmt/` — draws as one
* box at any depth, and a map whose subject is one box has said nothing. The
* repository around it (that folder beside a CLI, a `src/`, the examples) is
* then the picture worth opening on, when it draws more than one box.
*/
export function pickDefaultView(
files: ReadonlyArray<{ path: string; symbols: number; test: boolean }>,
passThrough?: ReadonlySet<string>
): { root: string; depth: number } {
const root = pickDefaultRoot(files);
const depth = pickDefaultDepth(files, root, passThrough);
if (root === '' || tallyModules(files, root, depth, passThrough).count > 1) return { root, depth };
const wholeDepth = pickDefaultDepth(files, '', passThrough);
return tallyModules(files, '', wholeDepth, passThrough).count > 1 ? { root: '', depth: wholeDepth } : { root, depth };
}
// =============================================================================
// Cache
// =============================================================================
/**
* One aggregation per (project, index build, root, depth).
*
* The map is the one screen whose cost is proportional to the whole edge
* table, so it is also the one screen worth caching. Keyed on the index's
* stamp AND its edge count, exactly as the blast scale is: a re-index or a
* sync that only moved edges must invalidate it, or the map draws a shape the
* code no longer has. A handful of entries, because the root selector is the
* only thing that varies.
*/
const CACHE_LIMIT = 8;
const cache = new Map<string, WireMapPayload>();
export function resetMapCache(): void {
cache.clear();
}
// =============================================================================
// Build
// =============================================================================
/**
* `null` for either field means "nobody said" — the answer picks. Absence has
* to survive parsing: a depth defaulted to 1 here is indistinguishable from a
* reader who asked for 1, and {@link pickDefaultDepth} would never run.
*/
export function parseMapQuery(query: URLSearchParams): {
root: string | null;
depth: number | null;
} {
const rawDepth = query.get('depth');
let depth: number | null = null;
if (rawDepth !== null && rawDepth !== '') {
depth = Number.parseInt(rawDepth, 10);
if (!Number.isFinite(depth) || depth < 1 || depth > MAX_DEPTH) {
throw badRequest(`depth must be a whole number from 1 to ${MAX_DEPTH}.`);
}
}
const rawRoot = query.get('root');
return { root: rawRoot === null ? null : normalizeRoot(rawRoot), depth };
}
/**
* Rename `x/(root files)` to `x` wherever the bucket is all `x` has.
*
* The bucket earns its name only when it stands beside something: `src` holding
* both `src/api` and three loose files needs a box for the loose ones, and that
* box has to say it is not the whole of `src`. But a `backend/controllers` with
* no subdirectories in it is not a directory with a bucket in it — it IS the
* directory, and drawing it as `backend/controllers/(root files)` names a thing
* the repository does not have. Deeper groupings hit this constantly (every
* leaf directory becomes a bucket), which is what makes it worth a pass.
*
* Returns only the ids that move, so a caller can leave the rest alone.
*/
function collapseLoneRootFiles(ids: ReadonlySet<string>): Map<string, string> {
const renamed = new Map<string, string>();
for (const id of ids) {
const cut = id.lastIndexOf('/(root files)');
// A bucket at the very top (`(root files)`) has no directory to become.
if (cut <= 0 || cut + '/(root files)'.length !== id.length) continue;
const dir = id.slice(0, cut);
let alone = true;
for (const other of ids) {
// A façade counts: `src/utils` beside `src/utils/index.tsx` would read as
// if the box contained the file drawn next to it.
if (other !== id && other.startsWith(`${dir}/`)) {
alone = false;
break;
}
}
// `dir` can only already be a module if something lives BELOW it, which is
// exactly the case `alone` just ruled out — so this rename cannot collide.
if (alone) renamed.set(id, dir);
}
return renamed;
}
export function buildMap(cg: CodeGraph, projectRoot: string, query: URLSearchParams): WireMapPayload {
const started = Date.now();
const { root: requestedRoot, depth: requestedDepth } = parseMapQuery(query);
const fileRecords = cg.getFiles().map((file) => {
const path = toPosixPath(file.path);
return {
path,
language: file.language,
symbols: file.nodeCount ?? 0,
test: isTestFile(path),
generated: file.generated === true,
};
});
const passThrough = passThroughDirs(fileRecords.map((f) => f.path));
// Root first, then depth against THAT root: how finely to cut depends on
// what is being cut. Choosing `src` and then asking for one level under it
// is the same question as choosing the whole project and asking for two.
const view = requestedRoot === null ? pickDefaultView(fileRecords, passThrough) : null;
const root = view?.root ?? requestedRoot ?? '';
const depth = requestedDepth ?? view?.depth ?? pickDefaultDepth(fileRecords, root, passThrough);
const stats = cg.getStats();
const key = [
projectRoot,
cg.getLastIndexedAt() ?? 0,
stats.edgeCount,
stats.fileCount,
root,
depth,
].join('\u0000');
const hit = cache.get(key);
if (hit) {
// Re-stamp rather than mutate: the cached body is shared, and a caller
// must not see another request's elapsed time.
return { ...hit, timing: { elapsedMs: Date.now() - started, cached: true } };
}
const assignments: Array<{ filePath: string; module: string }> = [];
const modules = new Map<
string,
{
id: string;
facade: boolean;
files: number;
symbols: number;
testFiles: number;
generatedFiles: number;
generatedPaths: Set<string>;
languages: Map<Language, number>;
paths: string[];
}
>();
const moduleOfFile = new Map<string, string>();
const assigned = new Map<string, { id: string; facade: boolean; label: string }>();
const labelOf = new Map<string, string>();
for (const file of fileRecords) {
const at = moduleIdFor(file.path, root, depth, passThrough);
if (at === null) continue;
assigned.set(file.path, at);
labelOf.set(at.id, at.label);
}
const renamed = collapseLoneRootFiles(new Set([...assigned.values()].map((a) => a.id)));
for (const [from, to] of renamed) {
labelOf.set(to, (labelOf.get(from) ?? to).replace(/\/\(root files\)$/, ''));
}
for (const file of fileRecords) {
const at = assigned.get(file.path);
if (at === undefined) continue;
const id = renamed.get(at.id) ?? at.id;
assignments.push({ filePath: file.path, module: id });
moduleOfFile.set(file.path, id);
let entry = modules.get(id);
if (!entry) {
entry = {
id,
facade: at.facade,
files: 0,
symbols: 0,
testFiles: 0,
generatedFiles: 0,
generatedPaths: new Set(),
languages: new Map(),
paths: [],
};
modules.set(id, entry);
}
entry.files += 1;
entry.paths.push(file.path);
entry.symbols += file.symbols;
if (file.test) entry.testFiles += 1;
if (file.generated) {
entry.generatedFiles += 1;
entry.generatedPaths.add(file.path);
}
entry.languages.set(file.language, (entry.languages.get(file.language) ?? 0) + 1);
}
const aggregation = cg.getModuleAggregation(assignments, {
kinds: MAP_EDGE_KINDS,
minConfidence: UNCERTAIN_BELOW,
topPairsPerLink: TOP_PAIRS_PER_LINK,
pairKinds: PAIR_EDGE_KINDS,
});
const links = new Map<string, WireMapLink>();
let uncertainEdges = 0;
for (const row of aggregation.links) {
// The same pass counts what the confidence floor left out, so the "N
// name-only matches excluded" note reports the number the map actually
// applied rather than a second query's opinion of it.
uncertainEdges += row.uncertain;
if (row.count === 0) continue;
const id = `${row.source}\u0000${row.target}`;
let link = links.get(id);
if (!link) {
link = { source: row.source, target: row.target, count: 0, declared: 0, byKind: [], topPairs: [] };
links.set(id, link);
}
link.count += row.count;
link.declared += row.declared;
link.byKind.push({ kind: row.kind, count: row.count });
}
for (const link of links.values()) {
link.byKind.sort((a, b) => b.count - a.count || a.kind.localeCompare(b.kind));
}
for (const pair of aggregation.pairs) {
const link = links.get(`${pair.source}\u0000${pair.target}`);
if (link && link.topPairs.length < TOP_PAIRS_PER_LINK) {
link.topPairs.push({
from: pair.from,
to: pair.to,
count: pair.count,
declared: pair.declared,
});
}
}
const dependents = countDependents(cg.getFileDependencyPairs(UNCERTAIN_BELOW), moduleOfFile);
const payload: WireMapPayload = {
root,
depth,
roots: rootOptions(fileRecords),
modules: [...modules.values()]
.map((entry) => {
const shown = entry.paths.slice().sort().slice(0, MAX_FILES_PER_MODULE);
return {
id: entry.id,
label: labelOf.get(entry.id) ?? entry.id,
files: entry.files,
symbols: entry.symbols,
languages: [...entry.languages]
.map(([language, files]) => ({ language, files }))
.sort((a, b) => b.files - a.files || a.language.localeCompare(b.language)),
test: entry.testFiles * 2 > entry.files,
generated: entry.generatedFiles,
facade: entry.facade,
// Only the SHOWN paths, so the list the panel dims and the list it
// draws are the same list — the count-equals-list rule.
generatedFiles: shown.filter((path) => entry.generatedPaths.has(path)),
fileList: wireList(shown, entry.files),
dependents: dependents.get(entry.id) ?? { files: 0, modules: 0 },
};
})
// Sorted so two runs over one index produce byte-identical payloads —
// the layout is deterministic, and it cannot be if its input is not.
.sort((a, b) => a.id.localeCompare(b.id)),
links: [...links.values()].sort(
(a, b) => a.source.localeCompare(b.source) || a.target.localeCompare(b.target)
),
cycles: fileCycles(cg.getFileImportPairs(), moduleOfFile),
excluded: { uncertainEdges, confidenceBelow: UNCERTAIN_BELOW },
index: {
lastIndexedAt: cg.getLastIndexedAt(),
edges: stats.edgeCount,
files: stats.fileCount,
},
timing: { elapsedMs: Date.now() - started, cached: false },
};
if (cache.size >= CACHE_LIMIT) {
const oldest = cache.keys().next();
if (!oldest.done) cache.delete(oldest.value);
}
cache.set(key, payload);
return payload;
}
/**
* Per module: how many files outside it reference into it, and across how many
* modules those files sit.
*
* One pass over the edge list. A pair whose two ends land in the same module is
* internal cohesion, not blast radius, and is skipped; a pair touching a file
* outside the chosen root has no module and is skipped too. The `Set` per
* module is what makes the count DISTINCT FILES rather than distinct
* references — twelve calls from one file are one file that has to be re-read.
*/
function countDependents(
pairs: ReadonlyArray<{ source: string; target: string }>,
moduleOfFile: Map<string, string>
): Map<string, { files: number; modules: number }> {
const incoming = new Map<string, Set<string>>();
for (const pair of pairs) {
const from = moduleOfFile.get(pair.source);
const to = moduleOfFile.get(pair.target);
if (from === undefined || to === undefined || from === to) continue;
let seen = incoming.get(to);
if (!seen) incoming.set(to, (seen = new Set()));
seen.add(pair.source);
}
const out = new Map<string, { files: number; modules: number }>();
for (const [module, files] of incoming) {
const modules = new Set<string>();
for (const file of files) modules.add(moduleOfFile.get(file)!);
out.set(module, { files: files.size, modules: modules.size });
}
return out;
}
/**
* The circular imports inside the chosen root (see {@link findFileCycles}).
*
* A component longer than {@link MAX_CYCLE_LENGTH} is reported truncated rather
* than printed — a 200-file knot is a fact about the repository, not a list
* anybody reads.
*/
function fileCycles(
pairs: ReadonlyArray<{ source: string; target: string }>,
moduleOfFile: Map<string, string>
): WireMapPayload['cycles'] {
const cycles = findFileCycles(
pairs.filter((pair) => moduleOfFile.has(pair.source) && moduleOfFile.has(pair.target))
);
const items = cycles.slice(0, MAX_FILE_CYCLES).map((files) => ({
size: files.length,
files: files.slice(0, MAX_CYCLE_LENGTH),
modules: [...new Set(files.map((file) => moduleOfFile.get(file) ?? file))].sort(),
}));
return {
total: cycles.length,
shown: items.length,
truncated: cycles.length > items.length,
items,
};
}
/**
* The roots the selector offers: the repository root plus every top-level
* directory that holds indexed files, biggest first.
*
* A monorepo's answer to "which project am I looking at" — and on a single
* project it is a one-line list nobody has to use.
*/
function rootOptions(
files: ReadonlyArray<{ path: string; symbols: number }>
): WireMapPayload['roots'] {
const byDir = new Map<string, number>();
for (const file of files) {
const slash = file.path.indexOf('/');
if (slash <= 0) continue;
const dir = file.path.slice(0, slash);
byDir.set(dir, (byDir.get(dir) ?? 0) + 1);
}
const dirs = [...byDir]
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.map(([root, count]) => ({ root, label: root, files: count }));
return [{ root: '', label: 'whole repository', files: files.length }, ...dirs];
}