dev-prune 1.22.0

Universal, lockfile-safe workspace pruner and background dependency cleaner
Documentation
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
// Copyright 2026 VKrishna04
// SPDX-License-Identifier: Apache-2.0

// NPM adapter implementation.

use super::{
    BloatDir, EnforcePolicy, PackageManager, dir_size, enforce_two_tier, run_command_with_timeout,
};
use crate::declared::{Gap, RebuildCheck, label_of, path_of, relative_parts};
use anyhow::Result;
use std::fs;
use std::path::Path;

/// NPM package manager adapter.
pub struct Npm;

/// Refuse when `node_modules` holds packages `package-lock.json` never recorded.
///
/// `npm install --no-save` puts a package in the tree without touching the lockfile,
/// and `npm link` plants a symlink to a package that lives outside the project. Both
/// survive `npm ci --dry-run` — it checks the lockfile against `package.json`, not
/// against the tree — and neither comes back after deletion. npm writes its own record
/// of what it actually installed to `node_modules/.package-lock.json`; comparing that
/// against the real lockfile catches the `--no-save` case, and a scan for symlinked
/// entries catches `npm link`.
fn check_unrecorded_installs(project_dir: &Path) -> Result<()> {
    let node_modules = project_dir.join("node_modules");

    // `npm link` first: a symlinked package is outside the tree entirely, so the
    // hidden lockfile comparison below would not see it. Dot-entries are skipped —
    // `.bin` is symlinks by design.
    let mut linked: Vec<String> = Vec::new();
    if let Ok(entries) = fs::read_dir(&node_modules) {
        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().into_owned();
            if name.starts_with('.') {
                continue;
            }
            let is_link = |p: &Path| {
                fs::symlink_metadata(p)
                    .map(|m| m.file_type().is_symlink())
                    .unwrap_or(false)
            };
            if is_link(&entry.path()) {
                linked.push(name);
            } else if name.starts_with('@') {
                // Scoped packages sit one level down: `@scope/pkg`.
                if let Ok(scoped) = fs::read_dir(entry.path()) {
                    for pkg in scoped.flatten() {
                        if is_link(&pkg.path()) {
                            linked.push(format!("{name}/{}", pkg.file_name().to_string_lossy()));
                        }
                    }
                }
            }
        }
    }
    if !linked.is_empty() {
        linked.sort();
        anyhow::bail!(
            "`{}` contains npm-linked package(s) ({}) — symlinks to code that lives \
             outside this project. `npm ci` after deletion would not re-link them. \
             Run `npm unlink` for each, or install them normally, then retry.",
            node_modules.display(),
            linked.join(", ")
        );
    }

    let extras = no_save_extras(project_dir);
    if extras.is_empty() {
        return Ok(());
    }
    let shown = extras
        .iter()
        .take(10)
        .map(|s| s.as_str())
        .collect::<Vec<_>>()
        .join(", ");
    let suffix = if extras.len() > 10 {
        format!(", … and {} more", extras.len() - 10)
    } else {
        String::new()
    };
    anyhow::bail!(
        "`node_modules` holds {} package(s) that package-lock.json does not record \
         ({shown}{suffix}) — likely installed with `npm install --no-save`. `npm ci` \
         after deletion would not bring them back. Run `npm install <pkg>` to save \
         them (or `npm install` to sync), then retry.",
        extras.len()
    );
}

/// The `--no-save` case, as data: entries npm's own install record
/// (`node_modules/.package-lock.json`) knows about that the committed lockfile does
/// not, sorted. Either file missing or unparseable means there is nothing to compare —
/// not evidence of drift — and answers empty.
fn no_save_extras(project_dir: &Path) -> Vec<String> {
    let package_names = |path: &Path| -> Option<std::collections::HashSet<String>> {
        let json: serde_json::Value = serde_json::from_str(&fs::read_to_string(path).ok()?).ok()?;
        Some(
            json.get("packages")?
                .as_object()?
                .keys()
                .filter(|k| !k.is_empty())
                .cloned()
                .collect(),
        )
    };
    let (Some(installed), Some(recorded)) = (
        package_names(&project_dir.join("node_modules").join(".package-lock.json")),
        package_names(&project_dir.join("package-lock.json")),
    ) else {
        return Vec::new();
    };
    let mut extras: Vec<String> = installed.difference(&recorded).cloned().collect();
    extras.sort();
    extras
}

impl PackageManager for Npm {
    /// Returns the name of the package manager.
    fn name(&self) -> &'static str {
        "npm"
    }

    /// Detects if the project uses npm by checking for `package-lock.json`.
    fn detect(&self, project_dir: &Path) -> bool {
        project_dir.join("package-lock.json").exists()
    }

    /// Returns the bloat directories for npm (node_modules).
    fn bloat_dirs(&self, project_dir: &Path) -> Vec<BloatDir> {
        let node_modules = project_dir.join("node_modules");
        if node_modules.exists() {
            let size = dir_size(&node_modules);
            vec![BloatDir {
                name: "node_modules".to_string(),
                path: node_modules,
                size_bytes: size,
                shared_bytes: 0,
            }]
        } else {
            vec![]
        }
    }

    /// Enforces the lockfile without running install scripts, and without writing.
    ///
    /// `npm ci --dry-run` is the read-only check: it builds the tree the lockfile
    /// describes, fails outright when `package-lock.json` and `package.json` disagree,
    /// and — with `--dry-run` — neither installs nor writes. `--package-lock-only` is
    /// the writing form, kept for the no-lockfile case where there is nothing to
    /// preserve, and for the user who opted into rewriting.
    fn enforce_lockfile(&self, project_dir: &Path, policy: EnforcePolicy) -> Result<()> {
        check_unrecorded_installs(project_dir)?;
        let lockfile = project_dir.join("package-lock.json");
        enforce_two_tier(
            &lockfile,
            "npm",
            &["ci", "--dry-run", "--ignore-scripts"],
            &["install", "--package-lock-only", "--ignore-scripts"],
            project_dir,
            policy,
        )
    }

    /// Restores the dependencies using the lockfile.
    fn restore(&self, project_dir: &Path, timeout: std::time::Duration) -> Result<()> {
        run_command_with_timeout("npm", &["ci"], project_dir, timeout)
    }

    fn lockfiles(&self) -> &'static [&'static str] {
        &["package-lock.json"]
    }

    /// The `--no-save` comparison `enforce_lockfile` refuses on, as data. npm-linked
    /// packages are deliberately not listed here: a symlink to code outside the project
    /// is not something any lockfile edit can record, so it stays a prune-time refusal.
    fn drift(&self, project_dir: &Path) -> Vec<super::DriftReport> {
        let extras = no_save_extras(project_dir);
        if extras.is_empty() {
            return Vec::new();
        }
        vec![super::DriftReport {
            directory: "node_modules".to_string(),
            unrecorded: extras,
            record_command: "npm install <pkg> (or `npm install` to sync the lockfile)",
        }]
    }
}

/// The rebuild check for `npm`, `pnpm` and `yarn` declarations.
///
/// One check for three tools because all three resolve a script the same way, against
/// the same manifest: `package.json` in the directory the command names. The check
/// lives here rather than in `crate::declared` so everything this crate knows about
/// node package managers stays in one file.
pub(crate) struct NodeScripts;

impl RebuildCheck for NodeScripts {
    fn tools(&self) -> &'static [&'static str] {
        &["npm", "pnpm", "yarn"]
    }

    fn gap(&self, repo_path: &Path, tool: &str, args: &[&str]) -> Option<Gap> {
        node_script_gap(repo_path, tool, args)
    }
}

/// Subcommands of `pnpm` and `yarn`, which both also run a script from a bare word.
///
/// `pnpm build` runs the `build` script, but `pnpm install` does not — so the bare form
/// can only be resolved against a list of the tool's own verbs. Deliberately generous,
/// and shared between the two tools: a word wrongly on this list is a script this
/// check declines to look up, which is the failure this file prefers.
const NODE_SUBCOMMANDS: &[&str] = &[
    "add",
    "audit",
    "bin",
    "cache",
    "config",
    "create",
    "dedupe",
    "deploy",
    "dlx",
    "doctor",
    "env",
    "exec",
    "fetch",
    "get",
    "global",
    "help",
    "i",
    "import",
    "info",
    "init",
    "install",
    "licenses",
    "link",
    "list",
    "login",
    "logout",
    "ls",
    "node",
    "outdated",
    "pack",
    "patch",
    "policies",
    "prune",
    "publish",
    "rebuild",
    "remove",
    "restart",
    "rm",
    "root",
    "server",
    "set",
    "setup",
    "start",
    "stop",
    "store",
    "test",
    "un",
    "uninstall",
    "unlink",
    "up",
    "update",
    "upgrade",
    "version",
    "whoami",
    "why",
    "workspace",
    "workspaces",
];

/// A `package.json` script the command names and the file does not define.
fn node_script_gap(repo_path: &Path, tool: &str, args: &[&str]) -> Option<Gap> {
    let (script, prefix) = node_script_and_prefix(tool, args)?;
    let parts = relative_parts(prefix.as_deref())?;
    let manifest = label_of(&parts, "package.json");
    let content = fs::read_to_string(path_of(repo_path, &parts, "package.json")).ok()?;
    let json: serde_json::Value = serde_json::from_str(&content).ok()?;
    let defined = match json.get("scripts") {
        // No `scripts` table at all: there is nothing `run` could resolve against.
        None => false,
        // Present but not a table — a shape this cannot read.
        Some(value) => value.as_object()?.contains_key(script.as_str()),
    };
    if defined {
        return None;
    }
    Some(Gap {
        what: format!("`{manifest}` defines no `{script}` script"),
        fix: format!("Add a `{script}` script to `{manifest}`, or fix the command."),
    })
}

/// The script an `npm`/`pnpm`/`yarn` command runs, and the directory it runs it in.
///
/// The prefix flags matter because `crate::declared`'s shell-builtin refusal actively
/// recommends `npm --prefix docs run build`: following that advice must not then land
/// on the wrong `package.json`. Resolution stops at the named directory rather than
/// walking upward the way npm does — a parent manifest could be outside the repository,
/// and "somewhere above here" is not an answer this check is willing to refuse on.
fn node_script_and_prefix(tool: &str, args: &[&str]) -> Option<(String, Option<String>)> {
    let mut prefix = None;
    let mut saw_run = false;
    let mut i = 0;
    while i < args.len() {
        let arg = args[i];
        if arg == "--" {
            return None;
        }
        if let Some(value) = arg
            .strip_prefix("--prefix=")
            .or_else(|| arg.strip_prefix("--dir="))
            .or_else(|| arg.strip_prefix("--cwd="))
        {
            prefix = Some(value.to_string());
        } else if matches!(arg, "--prefix" | "--dir" | "-C" | "--cwd") {
            prefix = Some((*args.get(i + 1)?).to_string());
            i += 1;
        } else if arg == "run" || arg == "run-script" {
            saw_run = true;
        } else if arg.starts_with('-') {
            // A flag this does not model. Whatever follows it might be its argument, and
            // reading that as the script name is exactly the guess to avoid.
            return None;
        } else if saw_run {
            return Some((arg.to_string(), prefix));
        } else if tool == "npm" || NODE_SUBCOMMANDS.contains(&arg) {
            // npm has no bare-script shorthand, and the pnpm/yarn one does not apply to
            // the tool's own verbs.
            return None;
        } else {
            return Some((arg.to_string(), prefix));
        }
        i += 1;
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn test_name() {
        assert_eq!(Npm.name(), "npm");
    }

    /// npm used to run `npm install --package-lock-only` here, which *fixes* a lockfile
    /// that has drifted from `package.json` by rewriting it — during a pass that may
    /// have been started by the scheduler. Verification must now refuse instead.
    ///
    /// Skipped rather than failed when `npm` is absent from `PATH`.
    #[test]
    fn a_default_pass_never_rewrites_a_stale_lockfile() {
        if !super::super::binary_available("npm") {
            return;
        }
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("package.json"),
            r#"{"name":"stale","version":"1.0.0","dependencies":{"left-pad":"^1.3.0"}}"#,
        )
        .unwrap();

        // A lockfile that never heard of `left-pad`, so it cannot rebuild the tree.
        let stale = r#"{"name":"stale","version":"1.0.0","lockfileVersion":3,"requires":true,"packages":{"":{"name":"stale","version":"1.0.0"}}}"#;
        fs::write(dir.path().join("package-lock.json"), stale).unwrap();

        let result = Npm.enforce_lockfile(dir.path(), EnforcePolicy::default());

        assert!(
            result.is_err(),
            "a lockfile out of sync with package.json must not pass verification"
        );
        assert_eq!(
            fs::read_to_string(dir.path().join("package-lock.json")).unwrap(),
            stale,
            "the read-only verification rewrote package-lock.json"
        );
    }

    #[test]
    fn test_detect_positive() {
        let dir = tempdir().unwrap();
        fs::File::create(dir.path().join("package-lock.json")).unwrap();
        assert!(Npm.detect(dir.path()));
    }

    #[test]
    fn test_detect_negative() {
        let dir = tempdir().unwrap();
        assert!(!Npm.detect(dir.path()));
    }

    #[test]
    fn test_bloat_dirs_present() {
        let dir = tempdir().unwrap();
        fs::create_dir(dir.path().join("node_modules")).unwrap();
        let bloat = Npm.bloat_dirs(dir.path());
        assert_eq!(bloat.len(), 1);
        assert_eq!(bloat[0].path, dir.path().join("node_modules"));
    }

    #[test]
    fn test_bloat_dirs_absent() {
        let dir = tempdir().unwrap();
        let bloat = Npm.bloat_dirs(dir.path());
        assert!(bloat.is_empty());
    }

    #[test]
    fn drift_reports_the_no_save_install_as_data() {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("package-lock.json"),
            r#"{"packages":{"":{},"node_modules/left-pad":{}}}"#,
        )
        .unwrap();
        let nm = dir.path().join("node_modules");
        fs::create_dir(&nm).unwrap();
        fs::write(
            nm.join(".package-lock.json"),
            r#"{"packages":{"":{},"node_modules/left-pad":{},"node_modules/sneaky":{}}}"#,
        )
        .unwrap();

        let reports = Npm.drift(dir.path());
        assert_eq!(reports.len(), 1);
        assert_eq!(reports[0].directory, "node_modules");
        assert_eq!(reports[0].unrecorded, vec!["node_modules/sneaky"]);
    }

    /// A missing hidden lockfile means npm never recorded what it installed — that is
    /// "nothing to compare", not drift.
    #[test]
    fn drift_is_silent_without_npms_own_install_record() {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("package-lock.json"),
            r#"{"packages":{"":{}}}"#,
        )
        .unwrap();
        fs::create_dir(dir.path().join("node_modules")).unwrap();

        assert!(Npm.drift(dir.path()).is_empty());
    }
}