npm-dependency-visualizer 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,439 @@
1
+ # npm Dependency Visualizer
2
+
3
+ Status: Draft.
4
+
5
+ ## 1. Scope and usage
6
+
7
+ ### Goal
8
+
9
+ Given a local `package.json` and `package-lock.json`, generate a dependency graph as a Markdown document containing a Mermaid diagram.
10
+ Show the requested dependency specification on each edge and the selected version from the lockfile on each package node.
11
+
12
+ The audience is developers investigating a project's resolved dependencies.
13
+ The initial experience is a CLI and a generated document, not a website.
14
+ The visual model follows DependencyVisualizer: project/package nodes, resolved versions on nodes, and requested ranges on arrows.
15
+
16
+ ### MVP scope
17
+
18
+ - Read local files only, without requiring an installation or `node_modules`.
19
+ - Support lockfile versions 2 and 3, rejecting version 1 with an actionable error.
20
+ - Generate the root package's production dependency graph by default.
21
+ - Offer an option to include development dependencies.
22
+ - Include reachable optional and peer dependency relationships, distinguishing their types.
23
+ - Preserve separate installed instances, even when their names and versions match.
24
+ - Generate the complete graph by default, with optional depth filtering and package-focus highlighting or filtering.
25
+ - Write Markdown only; there is no output-format option.
26
+ - Perform no network requests, package installation, or lifecycle script execution.
27
+ - Do not modify the input files.
28
+
29
+ ### Workspaces
30
+
31
+ When the root declares npm workspaces, include workspace projects by default.
32
+ A workspace is a lockfile project record whose location matches the root's `workspaces` patterns.
33
+ A dependency that resolves to a `link: true` record whose `resolved` target is a workspace points to a workspace node, and traversal continues from that workspace's lockfile record.
34
+ Without `--include-dev`, only workspaces reachable through declared dependencies appear; the root does not receive synthetic edges to every workspace.
35
+ With `--include-dev` from the root, every declared workspace is an additional traversal entry point, because npm installs every workspace's development dependencies. Workspaces that no declaration reaches appear as separate entry nodes without incoming edges; still no synthetic root edges are added.
36
+ Report how many declared workspace projects are reached, or that all of them are entry points.
37
+ `--workspace <name>` starts the graph at one workspace, identified by package name or lockfile location, instead of the root. With `--include-dev`, it follows development dependencies of that workspace and of workspaces it reaches, not of every workspace.
38
+ `--no-workspaces` restores the root-only behavior: workspace project nodes, workspace links, and traversal through those links are excluded and reported in both stderr and the generated document.
39
+
40
+ Non-workspace local links, such as `file:` directory dependencies, are not supported and remain excluded boundaries in every mode.
41
+
42
+ ### Non-goals
43
+
44
+ The MVP does not render HTML, SVG, or PNG; host a website; fetch GitHub inputs; query a registry; audit vulnerabilities; compare lockfiles; modify dependencies; or recommend upgrade chains.
45
+ It does not visualize the physical contents of an existing `node_modules` directory.
46
+ Optional registry access is a future extension, not an MVP command-line switch.
47
+ Other package managers' lockfiles, npm shrinkwrap files, and non-workspace local-directory links are outside the initial support contract.
48
+ The tool does not read workspace `package.json` files; workspace declarations come from the lockfile.
49
+
50
+ ### Proposed CLI
51
+
52
+ `npm-dependency-visualizer` is a working command name.
53
+
54
+ ```powershell
55
+ # Read the two files from the current directory; write Markdown to stdout.
56
+ npm-dependency-visualizer
57
+
58
+ # Read files from a project directory and write a report.
59
+ npm-dependency-visualizer C:\src\project --output graph.md
60
+
61
+ # Include root development dependencies and their reachable dependencies.
62
+ npm-dependency-visualizer C:\src\project --include-dev --output graph.md
63
+
64
+ # Show the root, direct dependencies, and their immediate dependencies.
65
+ npm-dependency-visualizer C:\src\project --depth 2 --output overview.md
66
+
67
+ # Highlight every matching instance and its ancestor paths, keeping the full graph.
68
+ npm-dependency-visualizer C:\src\project --focus glob --output glob.md
69
+
70
+ # Keep only matching instances and their ancestor context.
71
+ npm-dependency-visualizer C:\src\project --focus glob --focus-mode filter --output glob-filtered.md
72
+
73
+ # Start the graph at one workspace.
74
+ npm-dependency-visualizer C:\src\project --workspace @npmcli/arborist --output arborist.md
75
+
76
+ # Visualize only the root graph, excluding workspaces.
77
+ npm-dependency-visualizer C:\src\project --no-workspaces --output root-only.md
78
+ ```
79
+
80
+ The positional directory defaults to the current directory.
81
+ Both input files must be present in that directory.
82
+ Arbitrarily named or independently located input files are outside the initial CLI contract.
83
+
84
+ | Option | Meaning | Default |
85
+ | --- | --- | --- |
86
+ | `--output <file>` | Write the result to this file instead of stdout | stdout |
87
+ | `--include-dev` | Include development dependencies of the root and of every workspace (or, with `--workspace`, of the selected and reached workspaces) | Off |
88
+ | `--depth <n>` | Maximum dependency-edge distance from the start node; nonnegative integer | Unlimited |
89
+ | `--workspace <name>` | Start at the workspace with this package name or lockfile location | Root |
90
+ | `--no-workspaces` | Exclude workspaces and visualize only the root graph; incompatible with `--workspace` | Workspaces included |
91
+ | `--focus <name>` | Highlight instances with this exact declared dependency name and their ancestor paths | None |
92
+ | `--focus-mode highlight\|filter` | Keep the rest of the graph or remove unrelated branches; requires `--focus` | `highlight` |
93
+ | `--help` | Show usage | |
94
+ | `--version` | Show tool version | |
95
+
96
+ File output must not overwrite either input file, including through a filesystem alias.
97
+ Diagnostics go to stderr, not into stdout's document stream.
98
+ An explicitly specified existing output file may be replaced by a complete normal or diagnostic report.
99
+ An invocation that fails before producing a complete report must preserve any existing output file.
100
+
101
+ ## 2. Graph and output behavior
102
+
103
+ ### Nodes and edges
104
+
105
+ A node represents the root project, a workspace project, or a locked package instance.
106
+ Workspace nodes use the Mermaid subroutine shape and a `(workspace)` label suffix, so they are distinguishable without color.
107
+ The start node is the root, or the selected workspace with `--workspace`; "root" in depth and focus rules means the start node.
108
+ Identify package instances by their lockfile locations, not just `name@version`.
109
+ For example, two installations of `shared@2.3.1` remain separate nodes if they occupy different locations.
110
+
111
+ Each package label contains its name and selected version.
112
+ If labels would otherwise be identical, append the lockfile-relative location to distinguish the instances.
113
+ The report's node index lists every displayed node's location.
114
+ If a version is not recorded, show `version not recorded`; do not invent one.
115
+ If the root name is absent, use the fixed label `root project` rather than a machine-specific directory name.
116
+
117
+ An arrow goes from the package declaring a dependency to the package instance resolved for that dependency in the lockfile.
118
+ Its label contains the original requested specification, for example `^13.0.0`, and the dependency type.
119
+ Preserve non-semver specs such as aliases, Git references, and tarball references rather than converting them into ranges.
120
+ For aliases, identify both the declared dependency name and the actual package name when the latter is recorded.
121
+ If an alias's actual package name is not recorded, derive it only from an unambiguous alias specification or label it `package name not recorded`.
122
+
123
+ The graph represents dependency relationships, not directory nesting.
124
+ A package hoisted into the root's `node_modules` is not necessarily a direct dependency of the root.
125
+ Several parents may point at one instance.
126
+
127
+ Cycles and shared dependencies are valid graph structures: emit each node once and retain the relationships without recursively duplicating nodes.
128
+
129
+ ### Dependency selection
130
+
131
+ Start at the root and follow production, optional, and peer dependency edges.
132
+ Include only reachable instances; do not emit every entry in the lockfile.
133
+ `--include-dev` additionally admits development dependency edges of the root and of every included workspace, and their reachable dependency graphs.
134
+ It does not add published dependencies' own development requirements.
135
+ When the same dependency name occurs in both `dependencies` and `optionalDependencies`, treat it as optional.
136
+ When declarations give one dependency multiple applicable roles, preserve those roles without inventing separate installed instances.
137
+ Resolve each applicable role independently and emit a separate edge for each role/specification.
138
+ Ordinary and peer roles may therefore point to different existing instances; a missing role-specific target gets its own placeholder.
139
+
140
+ An instance reachable through both production and development paths remains visible without `--include-dev`.
141
+ Selection is based on relationships and reachability, not solely on a package-level development flag.
142
+
143
+ This is the graph recorded by the lockfile, not a claim that every optional package would be installed on the current operating system or architecture.
144
+ Bundled packages with recorded dependency metadata are handled like other locked instances.
145
+ Do not invent internal dependency edges when a bundled package's metadata is incomplete.
146
+
147
+ ### Focus and depth
148
+
149
+ Apply dependency-type selection and workspace/link exclusions before view filters.
150
+
151
+ With `--focus <name>`, match every reachable instance with that exact declared dependency name, including aliases.
152
+ Compute the root, matching instances, and their ancestors: the reverse-reachable dependency subgraph that leads to the matches.
153
+ Highlight matching nodes, ancestor nodes, and relationships whose endpoints both belong to this subgraph.
154
+ Use the Sunset Boulevard palette: coral (`#f4a261`) for matches, warm sand (`#e9c46a`) for ancestors, burnt orange (`#e76f51`) for path edges, and dark contrast (`#264653`) for highlighted node text and borders.
155
+ Matching nodes have thicker borders, and highlighted edges are thicker than ordinary edges.
156
+ Identify matches and ancestors in the node index and explain styling in the legend so color is not the only signal.
157
+ Use DejaVu Sans for highlighted node text when available, falling back to the viewer's fonts.
158
+ By default, keep the rest of the graph with its normal styling (`--focus-mode highlight`).
159
+ With `--focus-mode filter`, keep only the computed subgraph and omit unrelated descendants and branches.
160
+ Without focus, keep the complete selected graph without highlighting.
161
+ Use graph traversal with visited sets, not enumeration of every possible path.
162
+
163
+ With `--depth <n>`, retain nodes whose shortest dependency-edge distance from the root is at most `n` within the selected graph.
164
+ The root has depth zero.
165
+ Keep relationships whose endpoints both survive the filters.
166
+
167
+ If focus and depth are supplied, compute focus first, optionally filter to its subgraph, and apply depth second.
168
+ A matching package may therefore be outside the displayed depth; report that explicitly.
169
+ Visible ancestors and their relationships can remain highlighted even when a matching instance is outside the depth limit.
170
+ A focus name with no reachable matches is a command error.
171
+ Unresolved dependency placeholders participate in focus and depth selection using their declared names and parent relationships.
172
+
173
+ Report the active filters and the number of omitted nodes and relationships relative to the selected root graph before view filtering.
174
+ Report excluded workspace/link boundaries separately; do not claim to count dependency graphs that were not traversed.
175
+ Do not silently truncate large graphs.
176
+ Mermaid generation and successful rendering by a particular Markdown viewer are separate concerns.
177
+
178
+ ### Markdown document
179
+
180
+ The default report contains:
181
+
182
+ 1. A title naming the start project (the root, or the workspace selected with `--workspace`).
183
+ 2. Relative input filenames, lockfile version, dependency selection, and filters.
184
+ 3. Displayed node/edge counts and omission/exclusion counts.
185
+ 4. Warnings about missing information or excluded workspace content, if any.
186
+ 5. A legend explaining arrow direction, edge types, and selected versions.
187
+ 6. One fenced `mermaid` block using a left-to-right flowchart.
188
+ 7. A node index mapping diagram IDs to names, selected versions, and locations.
189
+
190
+ Output must be deterministic for identical inputs and options, including node IDs, ordering, and line endings.
191
+ Do not include generation timestamps or absolute machine-specific paths.
192
+
193
+ The Mermaid block contains only the diagram; summary, filter, and warning information appear in the surrounding Markdown.
194
+
195
+ ### Illustrative graph
196
+
197
+ This is a fictional example, not a snapshot of npm/cli.
198
+ It illustrates how a developer can see two parents requesting different major versions.
199
+
200
+ ```mermaid
201
+ flowchart LR
202
+ n0["example-app@1.0.0"]
203
+ n1["parent-a@2.1.0"]
204
+ n2["parent-b@3.0.0"]
205
+ n3["glob@13.0.4"]
206
+ n4["glob@14.0.3"]
207
+ n0 -->|"prod: ^2.0.0"| n1
208
+ n0 -->|"prod: ^3.0.0"| n2
209
+ n1 -->|"prod: ^13.0.0"| n3
210
+ n2 -->|"prod: ^14.0.0"| n4
211
+ ```
212
+
213
+ The MVP displays these facts; it does not calculate which parent releases would permit moving all instances to a particular version.
214
+
215
+ ### Incomplete or inconsistent inputs
216
+
217
+ Malformed input, missing input files, unsupported lockfile versions, and inconsistent root dependency declarations are errors.
218
+ Never silently regenerate the lockfile or select replacement versions.
219
+
220
+ For readable lockfiles with unresolved required dependencies, preserve the available evidence and report the problem in the document and stderr.
221
+ An unresolved dependency uses a placeholder node marked `unresolved`, never a fabricated selected version.
222
+ An absent optional dependency or optional peer is labeled `not recorded (optional)`, not asserted to be an invalid installation.
223
+ Absent dependency maps are treated as empty, since a package may legitimately have no dependencies.
224
+ If the lockfile omits internal package metadata, the tool cannot independently detect or reconstruct unrecorded dependencies.
225
+
226
+ The MVP reports declared specifications and locked resolutions, not a complete npm installation-validity verdict.
227
+ Do not label an edge invalid merely because its selected version falls outside its original range: root overrides may explain that selection.
228
+ When the root declares `overrides`, state that overrides are present and that displayed edge labels are the original declarations, not computed effective override specifications.
229
+ Do not infer transitive override rules from selected versions.
230
+
231
+ Workspace and link exclusions are intentional omissions, not unresolved-package errors.
232
+ If a dependency resolves to an excluded link, identify that dependency and the exclusion rather than drawing a misleading replacement.
233
+ A link whose target is not a recorded workspace project, including any local-directory link, is excluded using this rule.
234
+
235
+ ## 3. Technical approach
236
+
237
+ ### Implementation shape
238
+
239
+ Implement a Node.js CLI with a direct reader for `package-lock.json`.
240
+ Do not require Arborist for the MVP.
241
+ The lockfile is the source of selected package instances and transitive dependency declarations.
242
+ The root `package.json` supplies the project's declarations and is checked against the lockfile's root record.
243
+
244
+ Separate input validation, graph construction, graph selection, and output formatting.
245
+ Keep the graph model independent of Mermaid so that a later HTML viewer can consume the same data without changing resolution behavior.
246
+ No database, backend service, registry client, or browser runtime is required to generate a document.
247
+
248
+ ### Input validation
249
+
250
+ Read both JSON files and validate their top-level shapes before constructing the graph.
251
+ Require `lockfileVersion` to be 2 or 3 and require a `packages` object containing the root entry `""`.
252
+ For v2 lockfiles, use `packages` as authoritative and do not also traverse the legacy top-level `dependencies` tree.
253
+ Compare root `dependencies`, `devDependencies`, `optionalDependencies`, `peerDependencies`, and `peerDependenciesMeta`, treating absent maps as empty and ignoring object-key order.
254
+ Before comparing dependency maps, remove each production declaration whose name also occurs in the same file's optional dependency map.
255
+ Thus, a shadowed production declaration does not cause a mismatch when the effective optional declarations agree.
256
+ Report differing declaration names/specifications and stop when these root dependency declarations disagree.
257
+ Do not require optional project metadata such as name or version to be present in both files.
258
+
259
+ Keep lockfile locations as logical, slash-separated keys independently of the host operating system.
260
+ Use platform-native paths only to open input and output files.
261
+ Do not follow locations or dependency specifications onto the filesystem.
262
+
263
+ ### Graph construction
264
+
265
+ Index the root and supported package records by their exact lockfile location.
266
+ Derive an instance's declared installation name from its location, preserving scoped names.
267
+ Use a package record's `name` for its actual package identity when present.
268
+ Read selected versions only from the corresponding records, not from dependency ranges.
269
+
270
+ For ordinary and optional dependencies, search for `<requester>/node_modules/<dependency-name>` first, then the equivalent locations in each enclosing package scope up to the root.
271
+ For peers declared by a non-project package, start in its enclosing package scope rather than its private `node_modules`.
272
+ For peers declared by the root or a workspace, start in that project's own `node_modules`.
273
+ A workspace's enclosing scope is the root.
274
+ Select the first recorded candidate at the appropriate location; never search globally by name or choose the highest matching version.
275
+ An occupied candidate that is an excluded link stops that lookup; do not skip it and resolve a different package farther up.
276
+ If a peer is recorded only in the declaring package's private `node_modules`, report unsupported peer placement rather than presenting it as a valid peer resolution.
277
+ In that case, emit an unresolved peer placeholder and identify the private candidate in its diagnostic.
278
+ Do not traverse that private candidate through the peer edge; include it only if another supported relationship independently reaches it.
279
+
280
+ Read workspace patterns from the root manifest's `workspaces` array or `workspaces.packages` array, falling back to the lockfile root record.
281
+ Match logical locations against the patterns with `*` and `?` within one path segment and `**` across segments; a leading `!` excludes matches.
282
+ A workspace is a project record (a location without a `node_modules` segment) matching those patterns.
283
+ When a resolved candidate is a `link: true` record whose `resolved` location is a workspace, the edge targets the workspace node keyed by that location.
284
+ Several links to one workspace share its node.
285
+ Any other link record, or every link with `--no-workspaces`, is an excluded boundary: do not traverse it or load its target.
286
+ Never read workspace files from disk.
287
+ With `--no-workspaces`, packages used by both the root graph and workspace graphs remain included when independently reachable without crossing an excluded boundary.
288
+ Unreachable lockfile records, including unreached workspaces when development dependencies are disabled, are not part of the graph.
289
+ When development dependencies are enabled and traversal starts at the root, seed traversal with the root followed by every workspace in sorted location order; depth limits measure distance from the nearest entry point.
290
+ Report project records that are not included workspaces as excluded project records.
291
+
292
+ Read dependency roles from `dependencies`, `optionalDependencies`, `peerDependencies`, and `peerDependenciesMeta`.
293
+ Use `devDependencies` only from the root and from workspaces, and only when development dependencies are enabled.
294
+ Create a separate unresolved placeholder for each missing parent/name/role relationship so unrelated missing requirements cannot be accidentally merged.
295
+ Preserve the original declaration and selected instance even when the tool cannot validate their compatibility.
296
+
297
+ ### Internal model
298
+
299
+ | Record | Required data |
300
+ | --- | --- |
301
+ | Project | Name, optional version, lockfile version, root node ID, input filenames |
302
+ | Package node | Stable identity, lockfile location, installation name, actual name if known, selected version if known |
303
+ | Placeholder node | Parent identity, declared name, role, missing/optional status |
304
+ | Dependency edge | Source ID, target ID, declared name, original specification, dependency role |
305
+ | Diagnostic | Code, severity, affected node/edge or excluded boundary, explanatory message |
306
+ | Selected view | Included nodes/edges, matched and ancestor node identities, highlighted relationships, focus mode, active filters, omission counts, exclusions, diagnostics |
307
+
308
+ Maintain outgoing and incoming adjacency indexes for reachability, reverse-focus selection, and future dependency investigations.
309
+ Use iterative traversal with visited sets so cycles and deep dependency chains cannot overflow the call stack.
310
+ View selection should take linear time in the size of the constructed graph; deterministic output sorting may take additional sorting time.
311
+ Do not enumerate root-to-target paths as a preprocessing step.
312
+
313
+ ### Mermaid and Markdown writers
314
+
315
+ Assign node IDs from a stable ordering of identities, using generated identifiers such as `n0` rather than package names as Mermaid syntax.
316
+ Sort by logical lockfile location and then by explicit placeholder identity using a locale-independent ordinal comparison.
317
+ Sort edges by source identity, target identity, declared name, role, and specification.
318
+ Keep node IDs stable across view filters for the same input graph and dependency selection.
319
+ Emit fixed Mermaid classes for focus nodes and style only highlighted edges using their final emitted indices after filtering and sorting.
320
+
321
+ Quote labels and escape input text for its destination: Mermaid labels, Markdown headings, and Markdown table cells.
322
+ Handle quotes, pipes, brackets, angle brackets, ampersands, backticks, and line breaks without creating new diagram statements or closing a Markdown fence.
323
+ Do not emit executable HTML, clickable links, or Mermaid directives sourced from input values.
324
+ Use conservative flowchart syntax and verify it against the Mermaid version used by the output tests.
325
+ Document the tested Mermaid version without requiring users to install it to generate source.
326
+
327
+ Emit UTF-8 with LF line endings and a final newline.
328
+ Build and validate the entire report before writing stdout or replacing an output file.
329
+ Normal reports and exit-code-2 diagnostic reports are both complete reports eligible for writing.
330
+ Use a temporary sibling file and an atomic replacement where supported to avoid leaving a partial destination.
331
+ Remove temporary output files on failure.
332
+ An stdout write failure produces exit code `1`, but bytes already consumed by a pipe cannot be recalled.
333
+
334
+ ### Diagnostics and exit codes
335
+
336
+ | Exit code | Meaning | Report produced |
337
+ | --- | --- | --- |
338
+ | `0` | Supported graph generated, possibly with explicitly documented optional omissions or workspace/link exclusions | Yes |
339
+ | `1` | Invalid arguments/input, inconsistent root declarations, unmatched focus, or output failure | No intentional report; stdout may be partial on a write failure |
340
+ | `2` | Diagnostic report generated with unresolved required dependencies, missing non-root versions, or unsupported peer placement | Yes |
341
+
342
+ Known unsupported workspace/link exclusions remain warnings rather than exit-code-2 graph defects.
343
+ Missing versions or unsupported peer placement on included non-root records produce exit code `2`.
344
+ These and unresolved required targets are the detectable graph defects covered by exit code `2`; absent dependency maps alone are not defects.
345
+ Absence of optional dependencies or optional peers alone does not produce exit code `2`.
346
+ Validate the whole dependency-selected root graph before view filtering so a depth or focus filter does not hide an exit-code-2 defect.
347
+ For a valid dependency-free project, emit a root-only graph with exit code `0`.
348
+ Diagnostics must identify the affected logical location and declared dependency without exposing absolute local paths in the report.
349
+
350
+ ## 4. Acceptance tests and future work
351
+
352
+ ### Focused acceptance tests
353
+
354
+ | Scenario | Expected result |
355
+ | --- | --- |
356
+ | Direct and transitive dependencies | Every included node shows its locked version and every edge shows its declared specification and role |
357
+ | Hoisted transitive package | The declaring parent points to the hoisted instance without creating a false root dependency |
358
+ | Nested conflicting versions | Each parent points to the correct location-specific instance |
359
+ | Duplicate name and version at different locations | Instances remain distinct and their visible labels are disambiguated |
360
+ | Shared production/development dependency | Default output retains the production-reachable instance and omits the development-only root edge |
361
+ | `--include-dev` | Root development dependencies and their reachable dependencies appear without adding transitive development requirements |
362
+ | Optional dependencies and optional peers | Recorded instances appear; absent instances are explicitly optional placeholders |
363
+ | Peer placement | Peers resolve from the proper enclosing scope; unsupported private placement creates an unresolved peer placeholder without traversing that private target |
364
+ | Multiple dependency roles | Ordinary and peer roles resolve independently, with distinct edges to the appropriate recorded instances or placeholders |
365
+ | Scoped package and alias | Names remain intact and alias requirements point to the correct installation location |
366
+ | Git or tarball specification | Original specification is preserved without registry access or conversion into a range |
367
+ | Root overrides | Original edge declarations remain visible and an override notice prevents a false compatibility claim |
368
+ | Cycle and shared subgraph | Generation terminates, nodes are emitted once, and relationships remain present |
369
+ | Depth zero and depth two | Output uses shortest root distance, with exact omission counts |
370
+ | Focus highlighting with multiple versions | Every matching reachable instance and its ancestor context are colored while unrelated branches remain unchanged |
371
+ | Focus filter mode | Only matching reachable instances and their ancestors appear, using the same focus colors |
372
+ | Focus edge styles | Only ancestor-subgraph edges are colored, with correct indices after filtering and sorting |
373
+ | Combined focus and depth | Focus is evaluated first and depth-hidden matches are reported |
374
+ | Missing focus name | Exit code `1`, actionable stderr, and no document written |
375
+ | v2 and v3 equivalent fixtures | Equivalent logical graphs without duplicate traversal of the v2 legacy tree |
376
+ | v1 or unknown lockfile version | Exit code `1` and an unsupported-version diagnostic |
377
+ | Stale root declarations | Exit code `1` identifies mismatched effective declarations, ignoring production declarations shadowed by optional declarations |
378
+ | Missing required record/version | Diagnostic report uses explicit unknowns and exit code `2`, without invented versions or edges |
379
+ | Excluded local link or `--no-workspaces` | No target traversal, named exclusions, and no fallback to another same-name instance |
380
+ | Workspace traversal | Links to workspaces point to one workspace node per project, workspace dependencies resolve from the workspace's own `node_modules` and then the root, and unreached workspaces are counted |
381
+ | Workspace development dependencies | `--include-dev` follows root and every workspace's development dependencies, including workspaces no declaration reaches, without synthetic root edges, and not those of published packages |
382
+ | `--workspace <name>` | The graph starts at the named workspace; an unknown name or combination with `--no-workspaces` is exit code `1` |
383
+ | Dependency-free project | Root-only diagram, empty dependency list, and exit code `0` |
384
+ | Escaping and reserved Mermaid tokens | Markdown stays structurally valid and the extracted Mermaid block passes the parser |
385
+ | Reordered JSON keys and repeated runs | Byte-identical documents for equivalent input objects and options |
386
+ | Windows and a non-Windows host | Equivalent graph identities and output bytes despite different filesystem path separators |
387
+ | Existing `node_modules` or unrelated workspace files | Same result as an input-only directory |
388
+ | Offline execution | Succeeds with outbound access blocked and no child process, cache modification, or input modification |
389
+ | Output protection and write failure | Exit code `1` preserves inputs and prior file output without leaked temporary files; stdout write failures may leave already-written bytes |
390
+ | Diagnostic file output | Exit code `2` writes the complete diagnostic report and may replace the explicitly selected existing output file |
391
+
392
+ Use small committed fixtures for these cases and parser-based tests for generated Mermaid.
393
+ Test Markdown output, including stderr separation and exit codes.
394
+ Pin the Mermaid test dependency rather than relying on an external rendering service.
395
+ Representative small diagrams must also be visually checked in a documented Mermaid-capable Markdown viewer.
396
+
397
+ ### npm/cli representative case
398
+
399
+ Prepare a fixture from the root `package.json` and `package-lock.json` at the same pinned npm/cli commit.
400
+ Record the commit SHA with the fixture; do not download the mutable `latest` branch during test execution.
401
+ Confirm the chosen revision uses a supported lockfile version.
402
+
403
+ Generate the default production graph and a focused graph for a package present in the pinned input, such as `glob`.
404
+ Verify a known root dependency and a known transitive dependency against their exact lockfile records.
405
+ Assert that workspaces linked by root dependencies are traversed by default, and that with `--no-workspaces` workspace projects and links are excluded with clear warnings while independently reachable root dependencies remain present.
406
+ Manually audit expected node/edge counts for the pinned fixture rather than deriving the test oracle using the production graph builder.
407
+ Require deterministic generation and no implicit size-based truncation.
408
+
409
+ The full npm/cli diagram is a generation and correctness test, not a promise that every Markdown host can lay out a graph of that size.
410
+ Document the tested host and use depth or focus filter mode to demonstrate a readable view if the full diagram exceeds that host's renderer limits.
411
+
412
+ ### Delivery sequence
413
+
414
+ 1. Implement validated v2/v3 input reading and location-aware graph construction, with resolution fixtures.
415
+ 2. Add deterministic Markdown/Mermaid writers and parser-based output tests.
416
+ 3. Add development inclusion, depth/focus filtering, and omission diagnostics.
417
+ 4. Validate the pinned npm/cli root case and document CLI usage and rendering limitations.
418
+
419
+ ### Future work
420
+
421
+ Selecting several workspaces at once and traversing non-workspace local-directory links can extend workspace support.
422
+ An interactive HTML or website view can reuse the graph model for search, expansion, and reverse-dependency exploration.
423
+ GitHub input loading and optional registry access can be separate adapters rather than prerequisites for local visualization.
424
+
425
+ Upgrade analysis is a separate capability.
426
+ For a request such as moving a package from `13.0.4` to `14.0.3`, distinguish showing current parent chains from finding parent releases that permit the target version.
427
+ The latter requires additional release metadata and npm constraint analysis; the current lockfile alone does not establish a valid upgrade plan.
428
+ Do not claim that every ancestor needs updating, or that satisfying one declared range proves the entire proposed installation is valid.
429
+ If registry-backed planning is added, make network use explicit and keep the original offline graph workflow unchanged.
430
+
431
+ ### Research references
432
+
433
+ - Inspiration: `https://github.com/nkolev92/DependencyVisualizer`
434
+ - Representative root manifest: `https://github.com/npm/cli/blob/latest/package.json`
435
+ - Matching lockfile: `https://github.com/npm/cli/blob/latest/package-lock.json`
436
+ - Lockfile format: `https://docs.npmjs.com/cli/v11/configuring-npm/package-lock-json/`
437
+ - Dependency declarations and overrides: `https://docs.npmjs.com/cli/v11/configuring-npm/package-json/`
438
+ - npm dependency graph model: `https://github.com/npm/cli/blob/latest/workspaces/arborist/README.md`
439
+ - Mermaid flowchart syntax: `https://mermaid.js.org/syntax/flowchart.html`