@exodus/stasis 1.0.0-beta.14 → 1.0.0-beta.16

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.
Files changed (67) hide show
  1. package/README.md +2 -1
  2. package/bin/stasis.js +99 -16
  3. package/package.json +22 -9
  4. package/src/audit-corrections.js +11 -42
  5. package/src/audit.js +241 -190
  6. package/src/babel.js +39 -122
  7. package/src/bundle-from-lockfile.js +9 -21
  8. package/src/bundle-reader.js +5 -9
  9. package/src/bundle.js +0 -3
  10. package/src/cmd/build.js +82 -174
  11. package/src/cmd/bundle-options.js +113 -167
  12. package/src/cmd/bundle.js +942 -1294
  13. package/src/cmd/diff.js +1 -4
  14. package/src/cmd/github-bundle.js +21 -26
  15. package/src/cmd/output.js +15 -12
  16. package/src/cmd/sbom.js +3 -8
  17. package/src/cmd/tokens.js +16 -23
  18. package/src/define.js +36 -94
  19. package/src/diff.js +72 -128
  20. package/src/esbuild.js +0 -4
  21. package/src/flow.js +18 -13
  22. package/src/installed.js +265 -0
  23. package/src/json-stream.js +4 -9
  24. package/src/loader-mock.js +3 -8
  25. package/src/loader.js +1 -5
  26. package/src/loaders/bash.js +41 -93
  27. package/src/loaders/cargo.js +298 -805
  28. package/src/loaders/foundry.js +109 -285
  29. package/src/loaders/paths.js +13 -13
  30. package/src/loaders/php.js +210 -489
  31. package/src/loaders/rust.js +507 -1430
  32. package/src/loaders/solidity-ownership.js +48 -128
  33. package/src/loaders/solidity.js +39 -122
  34. package/src/loaders/toml.js +7 -17
  35. package/src/lockfile.js +0 -3
  36. package/src/metro-assets.js +10 -384
  37. package/src/metro-resolver.js +58 -134
  38. package/src/metro-transformer.js +0 -5
  39. package/src/metro.js +0 -4
  40. package/src/mock.js +32 -80
  41. package/src/parse.js +4 -4
  42. package/src/prune.js +0 -3
  43. package/src/resolve-fields.js +137 -532
  44. package/src/resolve-node.js +27 -45
  45. package/src/resolve-typescript.js +166 -298
  46. package/src/rollup.js +0 -4
  47. package/src/run-installed.js +10 -0
  48. package/src/sbom.js +52 -128
  49. package/src/scan.js +142 -284
  50. package/src/sixel.js +310 -0
  51. package/src/table.js +63 -31
  52. package/src/validate-notes.d.ts +19 -0
  53. package/src/validate-notes.js +72 -0
  54. package/src/validate.d.ts +159 -0
  55. package/src/validate.js +596 -522
  56. package/src/vfs-bundle/entries.js +40 -57
  57. package/src/vfs-bundle/github.js +80 -122
  58. package/src/vfs-bundle/glob.js +4 -45
  59. package/src/vfs-bundle/lazy.js +27 -56
  60. package/src/vfs-bundle/prisma.js +235 -105
  61. package/src/vfs-bundle/soldeer.js +28 -49
  62. package/src/vfs-bundle/tree.js +295 -318
  63. package/src/vfs-bundle/yarnclean.js +10 -31
  64. package/src/vfs-bundle.js +23 -64
  65. package/src/webpack.js +0 -4
  66. package/src/why.js +78 -232
  67. package/src/installed-commits.js +0 -184
package/src/why.js CHANGED
@@ -1,62 +1,41 @@
1
- import { hasNodeModulesSegment, moduleFileKey, packageRecords } from '@exodus/stasis-core/util'
1
+ import { entryDirOf, hasNodeModulesSegment, moduleFileKey, upsert } from '@exodus/stasis-core/util'
2
2
  import { isEvidenceFile } from './audit-corrections.js'
3
3
  import { parseFile } from './parse.js'
4
4
 
5
- // `stasis audit --why` support: from an artifact's resolution graph (`imports`)
6
- // and its per-consumer provenance (`reason`), explain WHY a vulnerable module is
7
- // present by listing the cross-module import chains that reach it.
8
- //
9
- // Corrections apply at the EDGE level (see audit-corrections.js): an edge whose
10
- // target file is not evidence of the module's real code -- a package.json
11
- // manifest read, or a corrected file like ws's noop browser.js stub -- never
12
- // enters the graph, so no displayed chain ends with (or passes through) one, and
13
- // a consumer that recorded only such files of a package is not one of its reasons.
14
- //
15
- // A "path" is a chain of node_modules packages ending at the target module, e.g.
16
- // `a -> b -> c`. The first-party (`src`) node is never shown: a chain is walked
17
- // back through cross-module edges and stops at a HEAD -- a module that a src file
18
- // imports directly, OR one nothing else in node_modules imports (the top of its
19
- // dependency subtree). So `a -> b -> c` surfaces even when no src file imports
20
- // `a` directly (a is the top of the chain), and `b -> c` surfaces additionally
21
- // when `b` is itself imported by src.
22
- //
23
- // The reasons shown for a flagged package are EXACTLY the ones that recorded the
24
- // package itself -- the same set the non-`--why` column reports (see collectReasons).
25
- // `--why` only adds, per reason, HOW that reason reaches it. So a consumer that
26
- // imports a package but never recorded it (externalized it) is not one of its
27
- // reasons and is never shown; and every reason that did record it appears, at least
28
- // as a bare line.
29
- //
30
- // The per-reason PATH is file-level. A consumer "has" the edge `b -> c` only if it
31
- // recorded the specific file in `b` that imports `c`, so a chain belongs to a
32
- // consumer only when it recorded the file forming EVERY edge -- `metro: a -> b -> c`
33
- // can't appear if the file importing `c` from `b` isn't metro's. Each reason's
34
- // chains are enumerated on its own subgraph (only its edges), so it shows its
35
- // MAXIMAL file-level path: if metro's edges only reach up to `b`, its line is the
36
- // shorter `metro: b -> c`; a reason that recorded the package but never imports it
37
- // through the graph shows a bare `metro: c`. A bundle with a single consumer omits
38
- // the `reason` map entirely; there every chain renders bare, with no prefix.
5
+ // Every record of a module map, and after a dependency's, each `vendored` copy in it as a record at its directory,
6
+ // with its host's `ecosystem`, `vendoredIn` its host's dir, and the `files` it holds. A host keeps all its files.
7
+ export function* packageRecords(modules) {
8
+ for (const [dir, record] of modules) {
9
+ yield [dir, record]
10
+ if (record.vendored === undefined) continue
11
+ const held = new Map()
12
+ for (const rel of Object.keys(record.files)) {
13
+ const sub = entryDirOf(record.vendored, rel)
14
+ if (sub === undefined) continue
15
+ // A descriptor, so a contents-free bundle's locked values stay unread.
16
+ Object.defineProperty(upsert(held, sub, () => Object.create(null)), rel.slice(sub.length + 1), Object.getOwnPropertyDescriptor(record.files, rel))
17
+ }
18
+ for (const [sub, files] of held) {
19
+ const { name, version } = record.vendored[sub]
20
+ yield [moduleFileKey(dir, sub), { name, version, ecosystem: record.ecosystem, vendoredIn: dir, files }]
21
+ }
22
+ }
23
+ }
24
+
25
+ // `stasis audit --why`: the import chains (`a -> b -> c`) by which each consumer that recorded a flagged package
26
+ // reaches it, on its own file-level subgraph, climbing to a HEAD: a package src imports, or one nothing in
27
+ // node_modules does. An edge into a file that is no evidence of real code (audit-corrections.js) is none.
39
28
 
40
- // Cap on paths enumerated per target to bound pathological graphs (many diamond
41
- // dependencies compound into a combinatorial number of simple paths). Hitting it
42
- // is surfaced as a marker line rather than silently dropped.
29
+ // Diamond dependencies compound into a combinatorial number of simple paths; a cut is marked, not silently dropped.
43
30
  const PATH_CAP = 2000
44
31
 
45
- // Packages a chain never walks PAST: everything imports these build/runtime hubs,
46
- // so continuing up from them just adds noise. When a chain reaches one it stops
47
- // there, and the hub becomes the chain's head (`@babel/core -> a -> b -> c`),
48
- // still prefixed with its own reason.
32
+ // Build/runtime hubs everything imports: a chain reaching one stops there, the hub its head.
49
33
  const TERMINAL_PACKAGES = new Set(['@babel/core', 'react-native', 'metro'])
50
34
 
51
- // Index one parsed artifact: map every project-relative file to its owning module
52
- // dir, record each dir's package identity + whether it's a node_modules dep, and
53
- // keep each dir's EVIDENCE file list (for the target's-own-reason lookup).
54
- // `fileToDir` is complete; `dirFiles` only holds files that count as real code of
55
- // the dir (see audit-corrections.js) -- a consumer that recorded nothing of a
56
- // package but a corrected file / its package.json manifest is not one of its
57
- // reasons, exactly as in collectReasons. A copy a dependency ships (packageRecords) is a module of its
58
- // own here, so a chain can end at it (`next -> react-is`): its files are its node's, while its host's
59
- // evidence keeps them too, the host's reasons being those of all its files, as in collectReasons.
35
+ const EMPTY_GRAPH = { adjRev: new Map(), srcImporters: new Map() }
36
+
37
+ // Each dir's evidence files (`dirFiles`) as collectReasons counts them. A copy a dependency ships is a module of its
38
+ // own, so a chain can end at it, its files its host's evidence too.
60
39
  function moduleIndex(artifact) {
61
40
  const fileToDir = new Map()
62
41
  const dirInfo = new Map()
@@ -74,91 +53,54 @@ function moduleIndex(artifact) {
74
53
  return { fileToDir, dirInfo, dirFiles }
75
54
  }
76
55
 
77
- // Flatten the imports graph (conditions -> parent -> specifier -> target) into
78
- // deduped file-level edges [parentFile, targetFile]. A `--metro` target may be a
79
- // { platform: file } map; each platform's file becomes its own edge.
56
+ // Deduped [parentFile, targetFile] edges; a `--metro` target may be a { platform: file } map.
80
57
  function fileEdges(imports) {
81
- const edges = []
82
- const seen = new Set()
58
+ const edges = new Map()
83
59
  for (const [, byParent] of imports) {
84
60
  for (const [parent, specifiers] of byParent) {
85
61
  for (const [, target] of specifiers) {
86
- const targets = target instanceof Map ? [...target.values()] : [target]
87
- for (const t of targets) {
88
- const key = `${parent}\0${t}`
89
- if (seen.has(key)) continue
90
- seen.add(key)
91
- edges.push([parent, t])
92
- }
62
+ for (const t of target instanceof Map ? target.values() : [target]) edges.set(`${parent}\0${t}`, [parent, t])
93
63
  }
94
64
  }
95
65
  }
96
- return edges
66
+ return edges.values()
97
67
  }
98
68
 
99
- // Per-reason cross-module subgraphs. Every import edge is a FILE edge (a specific
100
- // file in the parent importing the target), and a consumer only "has" that edge if
101
- // it recorded the PARENT file. So a chain belongs to a reason only when that reason
102
- // bundled the file forming EVERY one of its edges. We build one subgraph per
103
- // consumer (bucket) -- holding only the edges that consumer's files created -- and
104
- // later enumerate that consumer's chains on it. With no reason map there is a single
105
- // bucket '' holding the full graph (chains render bare). Each subgraph:
106
- // adjRev: depDir -> Set(dep predecessor dir) -- dep->dep edges, reversed
107
- // srcImporters: depDir -> Set(src file) -- src->dep edges
108
- // Intra-module edges and edges into a src module are dropped.
69
+ // Per-consumer subgraphs ('' the whole graph where there is no reason map), an edge a consumer's where it recorded
70
+ // the importing file: `adjRev` dep dir -> the dep dirs importing it, `srcImporters` dep dir -> the src files.
109
71
  function bucketGraphs(edges, fileToDir, dirInfo, fileReasons) {
110
72
  const graphs = new Map()
111
- const graphFor = (bucket) => {
112
- let g = graphs.get(bucket)
113
- if (g === undefined) graphs.set(bucket, (g = { adjRev: new Map(), srcImporters: new Map() }))
114
- return g
115
- }
116
73
  for (const [pf, tf] of edges) {
117
74
  const pd = fileToDir.get(pf)
118
75
  const td = fileToDir.get(tf)
119
76
  if (pd === undefined || td === undefined || pd === td) continue
120
77
  const tdi = dirInfo.get(td)
121
78
  if (!tdi.dep) continue
122
- // An edge counts only when it targets the module's real code (see
123
- // audit-corrections.js): a `package.json` manifest read (react-native scans
124
- // sibling packages' manifests for Haste/asset resolution) or a corrected file
125
- // (ws's noop browser.js stub) is not a dependency on the module and must not
126
- // pull it into the --why graph -- no chain may end (or pass) through one.
79
+ // A manifest read (react-native scans its siblings' for Haste) or a corrected file (ws's noop
80
+ // browser.js) is no dependency on the module: no chain may end at or pass through one.
127
81
  if (!isEvidenceFile(tdi.name, tdi.version, tf.slice(td.length + 1))) continue
128
- // The consumers this edge belongs to: those that recorded its parent file.
129
82
  const buckets = fileReasons === null ? [''] : (fileReasons.get(pf) ?? [])
130
83
  const dep = dirInfo.get(pd).dep
131
84
  for (const bucket of buckets) {
132
- const map = dep ? graphFor(bucket).adjRev : graphFor(bucket).srcImporters
133
- let set = map.get(td)
134
- if (set === undefined) map.set(td, (set = new Set()))
135
- set.add(dep ? pd : pf)
85
+ const graph = upsert(graphs, bucket, () => ({ adjRev: new Map(), srcImporters: new Map() }))
86
+ upsert(dep ? graph.adjRev : graph.srcImporters, td, () => new Set()).add(dep ? pd : pf)
136
87
  }
137
88
  }
138
89
  return graphs
139
90
  }
140
91
 
141
- // Invert the reason map to file -> Set(consumer). null when the artifact carries
142
- // no reason map (single-consumer bundle / lockfile) -> chains render bare.
143
- export function invertReason(reason) {
92
+ // file -> Set(consumer), or null without a reason map (a single-consumer bundle, a lockfile): chains render bare.
93
+ export function invertReason(reason, name = (consumer) => consumer) {
144
94
  if (!reason) return null
145
95
  const byFile = new Map()
146
96
  for (const [consumer, list] of Object.entries(reason)) {
147
97
  if (!Array.isArray(list)) continue
148
- for (const f of list) {
149
- let set = byFile.get(f)
150
- if (set === undefined) byFile.set(f, (set = new Set()))
151
- set.add(consumer)
152
- }
98
+ for (const f of list) upsert(byFile, f, () => new Set()).add(name(consumer))
153
99
  }
154
100
  return byFile
155
101
  }
156
102
 
157
- // dir -> Set(consumer): the consumers that recorded any of the dir's own EVIDENCE
158
- // files (dirFiles is pre-filtered -- a consumer that recorded only a corrected
159
- // file / manifest of the dir doesn't count; see moduleIndex). null when the
160
- // artifact has no reason map. Used to decide whether a bare target belongs to a
161
- // reason that never imports it (a flagged package a bundler shipped).
103
+ // dir -> the consumers that recorded any of its evidence files: whether a target belongs to one never importing it.
162
104
  function dirReasonsIndex(dirFiles, fileReasons) {
163
105
  if (fileReasons === null) return null
164
106
  const byDir = new Map()
@@ -170,13 +112,8 @@ function dirReasonsIndex(dirFiles, fileReasons) {
170
112
  return byDir
171
113
  }
172
114
 
173
- // Every simple dep-only path (within one reason's subgraph) that ends at
174
- // `targetDir`, walking predecessors backward and emitting a path each time its
175
- // head is a HEAD node (`isHead`) or a terminal package (`isTerminal`). A terminal
176
- // node ALSO stops the walk -- the chain never goes past @babel/core / react-native
177
- // / metro, and this applies to `targetDir` too: a terminal target is emitted bare
178
- // (just `[targetDir]`), never climbed above. Its provenance instead comes from the
179
- // reason whose subgraph this is. Returns dirs head-first; `truncated` flags the cap.
115
+ // Every simple path of `adjRev` ending at `targetDir`, head first, where its head is a HEAD or a terminal package,
116
+ // which the walk never climbs past.
180
117
  function pathsTo(adjRev, isHead, isTerminal, targetDir) {
181
118
  const results = []
182
119
  let truncated = false
@@ -187,7 +124,7 @@ function pathsTo(adjRev, isHead, isTerminal, targetDir) {
187
124
  }
188
125
  const terminal = isTerminal(node)
189
126
  if (isHead(node) || terminal) results.push(suffix)
190
- if (terminal) return // don't walk past @babel/core / react-native / metro
127
+ if (terminal) return
191
128
  for (const pred of adjRev.get(node) ?? []) {
192
129
  if (inPath.has(pred)) continue // no repeated module -> break cycles
193
130
  inPath.add(pred)
@@ -203,24 +140,13 @@ function pathsTo(adjRev, isHead, isTerminal, targetDir) {
203
140
  const chainKey = (c, i = 0) => c.slice(i).join('\0')
204
141
  const renderChain = (c) => c.join(' -> ')
205
142
 
206
- // Display order for one bucket's (deduped) chains:
207
- // 1. a chain that is a full proper suffix of another always renders before it
208
- // (`B -> C` before `A -> B -> C`) -- a hard constraint;
209
- // 2. chains sharing a head stay contiguous, and recursively chains sharing a
210
- // longer prefix stay contiguous within their group -- never interleaved
211
- // with other groups;
212
- // 3. among sibling groups (at every level), the group whose LONGEST chain is
213
- // shortest renders first; ties alphabetically.
214
- // All chains end at the same target, so a full suffix always has a DIFFERENT
215
- // head: rule 1 only ever orders head groups against each other, never members of
216
- // one group, and is enforced with a topological pass over the head groups. In
217
- // the rare cyclic case (mutual suffix constraints through an import cycle) the
218
- // preferred group order wins and one constraint is dropped.
143
+ // One bucket's chains in display order: a full suffix of another first (`B -> C` before `A -> B -> C`), chains
144
+ // sharing a prefix contiguous, sibling groups by their longest chain, shortest first, then name. A suffix only orders
145
+ // head groups (all chains end at one target): a topological pass, a cycle's constraints broken by that preference.
219
146
  function orderChains(chains) {
220
147
  if (chains.length <= 1) return chains
221
148
 
222
- // Recursive contiguous grouping: `list` shares its first `depth` nodes; group
223
- // by the node AT `depth` and order sibling groups shortest-max first.
149
+ // `list` shares its first `depth` nodes: group it by the node at `depth`, recursively.
224
150
  const arrange = (list, depth) => {
225
151
  if (list.length <= 1) return list
226
152
  return [...Map.groupBy(list, (c) => c[depth])]
@@ -231,8 +157,7 @@ function orderChains(chains) {
231
157
 
232
158
  const byHead = Map.groupBy(chains, (c) => c[0])
233
159
 
234
- // Rule 1: whenever a chain is a full suffix of another, its head group must
235
- // render before the extension's head group.
160
+ // A chain's full suffix's head group renders before the chain's.
236
161
  const keys = new Set(chains.map((c) => chainKey(c)))
237
162
  const succ = new Map([...byHead.keys()].map((h) => [h, new Set()]))
238
163
  const indeg = new Map([...byHead.keys()].map((h) => [h, 0]))
@@ -261,42 +186,19 @@ function orderChains(chains) {
261
186
  return out
262
187
  }
263
188
 
264
- // Compress one reason bucket's chains (node-name arrays, all ending at the same
265
- // target). Chains are emitted in display order (orderChains -- prefix groups
266
- // kept contiguous, a full-suffix chain always before its extensions); each collapses
267
- // at the earliest node whose remaining sub-path to the target is already
268
- // recoverable from the lines above it, rendering `prefix -> node -> ... -> target`.
269
- // A sub-path is recoverable once ANY emitted line shows its head node in the
270
- // line's visible part -- a full line shows every node, a collapsed line its prefix
271
- // down to the collapse point -- because from there the earlier lines spell out the
272
- // rest. So a repeated tail is written out once and referenced with `...`
273
- // everywhere else, transitively:
274
- // D -> C -> B -> A (full)
275
- // P -> E -> D -> ... -> A (D's tail is in the full line)
276
- // Q -> E -> ... -> A (E's tail is now visible in P's line)
277
- // G -> F -> E -> ... -> A
278
- // H -> F -> ... -> A (F's tail is visible in G's line)
279
- // A collapse hides only nodes between the visible ones and the target, and lines
280
- // that collapse to identical text are emitted once (a hub reached by several shown
281
- // sub-paths yields a single `importer -> hub -> ... -> target` per importer).
189
+ // One bucket's chains, in orderChains' order, each collapsed at its earliest node whose sub-path to the
190
+ // target an earlier line shows (a line shows its nodes down to its collapse point), so `D -> C -> B -> A`
191
+ // then gives `P -> E -> D -> ... -> A`, then `Q -> E -> ... -> A`. Lines collapsing alike are emitted once.
282
192
  function compressChains(chains) {
283
193
  const uniq = [...new Map(chains.map((c) => [renderChain(c), c])).values()]
284
194
  if (uniq.length <= 1) return uniq.map(renderChain)
285
195
  const sorted = orderChains(uniq)
286
- const target = sorted[0][sorted[0].length - 1]
196
+ const target = sorted[0].at(-1)
287
197
 
288
198
  const revealed = new Set() // sub-paths recoverable from lines already emitted
289
- const out = []
290
- const seen = new Set()
291
- const push = (line) => {
292
- if (!seen.has(line)) {
293
- seen.add(line)
294
- out.push(line)
295
- }
296
- }
199
+ const out = new Set()
297
200
  for (const c of sorted) {
298
- // Collapse at the longest proper tail (earliest position, >= 3 nodes so >= 1 is
299
- // hidden) that an earlier line already made recoverable.
201
+ // Collapse at the longest proper tail (>= 3 nodes, so one is hidden) an earlier line made recoverable.
300
202
  let at = -1
301
203
  for (let i = 1; c.length - i >= 3; i++) {
302
204
  if (revealed.has(chainKey(c, i))) {
@@ -304,128 +206,72 @@ function compressChains(chains) {
304
206
  break
305
207
  }
306
208
  }
307
- // Index of the last node this line shows: all of them when full, the collapse
308
- // point otherwise.
309
- const visible = at === -1 ? c.length - 1 : at
310
- if (at === -1) push(renderChain(c))
311
- else push(`${renderChain(c.slice(0, at + 1))} -> ... -> ${target}`)
209
+ out.add(at === -1 ? renderChain(c) : `${renderChain(c.slice(0, at + 1))} -> ... -> ${target}`)
312
210
  // Every sub-path headed by a node this line shows is now recoverable.
211
+ const visible = at === -1 ? c.length - 1 : at
313
212
  for (let i = 0; i <= visible; i++) revealed.add(chainKey(c, i))
314
213
  }
315
- return out
214
+ return [...out]
316
215
  }
317
216
 
318
- // Default (non `--why-deep`) pruning: drop a chain when another chain in the SAME
319
- // bucket is a full proper suffix of it. Those longer chains only tell how the
320
- // suffix's head is reached through further subdeps -- when that head is itself a
321
- // direct dependency of src (or the flagged target itself), its own line already
322
- // explains the pull-in, so `A -> B -> C -> D` is noise next to `B -> C -> D` (and
323
- // everything is noise next to a bare `D`). Only a FULL suffix counts: chains that
324
- // merely share a tail (`E -> C -> B -> A` vs `D -> C -> B -> A`) both survive and
325
- // are left to compressChains. The shortest chain always survives.
217
+ // Without --why-deep, drop a chain when another in its bucket is a full proper suffix of it: the suffix's
218
+ // line already explains the pull-in. Chains that merely share a tail both stay, for compressChains.
326
219
  function dropSuffixed(chains) {
327
220
  const keys = new Set(chains.map((c) => chainKey(c)))
328
- return chains.filter((c) => {
329
- for (let i = 1; i < c.length; i++) {
330
- if (keys.has(chainKey(c, i))) return false
331
- }
332
- return true
333
- })
221
+ return chains.filter((c) => !c.keys().drop(1).some((i) => keys.has(chainKey(c, i))))
334
222
  }
335
223
 
336
- // Map each targeted package (`name@version`) to its ordered `--why` lines.
337
- // `targetKeys` (optional) restricts work to the packages that matter (the ones
338
- // carrying advisories); omit it to compute for every node_modules package.
339
- // `reasonFilter` (optional, from --reason) keeps only chains attributed to that
340
- // consumer, dropping every other chain (and bare, unattributed chains).
341
- // By default a chain is dropped when a same-bucket chain is a full suffix of it
342
- // (see dropSuffixed); `deep` (--why-deep) keeps every chain. Chains are then
343
- // deduplicated and compressed per reason bucket (see compressChains), unless
344
- // `full` (--why-full) -- then every surviving chain is spelled out with no `...`
345
- // collapse, in the same shortest-first order. The flags compose: deep + full is
346
- // the complete raw listing. Artifacts without a resolution graph (`imports`)
347
- // contribute nothing.
348
- export function collectWhy(files, targetKeys, reasonFilter = null, { deep = false, full = false } = {}) {
349
- // key -> reason bucket ('' = unattributed) -> Map(chainKey -> node-name array)
224
+ // Each package of `targetKeys` (`name@version`, else every dependency) -> its --why lines, `consumer: chain`, or a
225
+ // bare chain without a reason map. Pruned (dropSuffixed) unless `deep`, compressed (compressChains) unless `full`.
226
+ export function collectWhy(files, targetKeys, reasonFilter = null, { deep = false, full = false, consumerName } = {}) {
227
+ // key -> reason bucket ('' unattributed) -> Map(chainKey -> node names)
350
228
  const acc = new Map()
351
229
  const truncatedKeys = new Set()
352
- const bucketChains = (key, bucket) => {
353
- let buckets = acc.get(key)
354
- if (buckets === undefined) acc.set(key, (buckets = new Map()))
355
- let chains = buckets.get(bucket)
356
- if (chains === undefined) buckets.set(bucket, (chains = new Map()))
357
- return chains
358
- }
359
- const addChain = (key, bucket, nodes) => bucketChains(key, bucket).set(chainKey(nodes), nodes)
360
-
361
- const EMPTY_GRAPH = { adjRev: new Map(), srcImporters: new Map() }
230
+ const addChain = (key, bucket, nodes) => upsert(upsert(acc, key, () => new Map()), bucket, () => new Map()).set(chainKey(nodes), nodes)
362
231
 
363
232
  for (const file of files) {
364
233
  const artifact = parseFile(file)
365
- const imports = artifact.imports
366
- if (!imports || imports.size === 0) continue
234
+ if (!artifact.imports || artifact.imports.size === 0) continue
367
235
 
368
236
  const { fileToDir, dirInfo, dirFiles } = moduleIndex(artifact)
369
- const edges = fileEdges(imports)
370
- const fileReasons = invertReason(artifact.reason)
371
- const graphs = bucketGraphs(edges, fileToDir, dirInfo, fileReasons)
237
+ const fileReasons = invertReason(artifact.reason, consumerName)
238
+ const graphs = bucketGraphs(fileEdges(artifact.imports), fileToDir, dirInfo, fileReasons)
372
239
  const dirReasons = dirReasonsIndex(dirFiles, fileReasons)
373
- // Terminal packages end a chain regardless of what imports them.
374
240
  const isTerminal = (node) => TERMINAL_PACKAGES.has(dirInfo.get(node)?.name)
375
241
 
376
- // Group target dirs by `name@version` (a package can appear at several dirs,
377
- // e.g. nested node_modules); paths from every matching dir are unioned.
242
+ // A package can be at several dirs (nested node_modules): their paths are unioned.
378
243
  const dirsByKey = new Map()
379
244
  for (const [dir, info] of dirInfo) {
380
245
  if (!info.dep || !info.name || !info.version) continue
381
246
  const key = `${info.name}@${info.version}`
382
247
  if (targetKeys && !targetKeys.has(key)) continue
383
- let arr = dirsByKey.get(key)
384
- if (arr === undefined) dirsByKey.set(key, (arr = []))
385
- arr.push(dir)
248
+ upsert(dirsByKey, key, () => []).push(dir)
386
249
  }
387
- if (dirsByKey.size === 0) continue
388
250
 
389
251
  for (const [key, dirs] of dirsByKey) {
390
252
  for (const targetDir of dirs) {
391
- // The reasons to report are exactly the ones the FLAGGED package itself was
392
- // recorded under -- identical to the non-`--why` column (see collectReasons).
393
- // For each, enumerate that reason's MAXIMAL file-level chains on its own
394
- // subgraph; a reason that recorded the package but doesn't import it through
395
- // the graph still yields a bare line. A reason that IMPORTS the package but
396
- // never recorded it (externalized it) is not one of the package's reasons and
397
- // is not shown -- so the --why reason set matches non-`--why` exactly.
253
+ // The consumers that recorded the package itself, as collectReasons': one importing it unrecorded is none.
398
254
  const own = fileReasons === null ? [''] : (dirReasons.get(targetDir) ?? [])
399
255
  for (const bucket of own) {
400
256
  if (reasonFilter !== null && bucket !== reasonFilter) continue
401
257
  const { adjRev, srcImporters } = graphs.get(bucket) ?? EMPTY_GRAPH
402
- // A head tops a chain: a src file imports it directly, or nothing else
403
- // in this bucket's graph imports it.
404
258
  const isHead = (node) => srcImporters.has(node) || !adjRev.has(node)
405
259
  const { results, truncated } = pathsTo(adjRev, isHead, isTerminal, targetDir)
406
260
  if (truncated) truncatedKeys.add(key)
407
- for (const p of results) {
408
- const nodes = p.map((d) => dirInfo.get(d)?.name ?? d)
409
- addChain(key, reasonFilter !== null ? '' : bucket, nodes)
410
- }
261
+ for (const p of results) addChain(key, reasonFilter !== null ? '' : bucket, p.map((d) => dirInfo.get(d)?.name ?? d))
411
262
  }
412
263
  }
413
264
  }
414
265
  }
415
266
 
416
- // --why-full: no `...` collapse -- every chain spelled out, in the same display
417
- // order as the collapsed rendering (see orderChains).
418
- const renderFull = (chains) => orderChains(chains).map(renderChain)
419
-
420
- // Prune (unless deep), compress (unless full), and render each bucket (buckets
421
- // sorted so a consumer's chains group together; bare '' sorts first).
267
+ // Buckets sorted, so bare '' first.
422
268
  const byPkg = new Map()
423
269
  for (const [key, buckets] of acc) {
424
270
  const lines = []
425
271
  for (const bucket of [...buckets.keys()].toSorted((a, b) => a.localeCompare(b))) {
426
272
  let chains = [...buckets.get(bucket).values()]
427
273
  if (!deep) chains = dropSuffixed(chains)
428
- for (const rendered of (full ? renderFull(chains) : compressChains(chains))) {
274
+ for (const rendered of (full ? orderChains(chains).map(renderChain) : compressChains(chains))) {
429
275
  lines.push(bucket ? `${bucket}: ${rendered}` : rendered)
430
276
  }
431
277
  }