Skip to main content

bynk_driver/
npm_install.rs

1//! Installing the npm packages a generated build directory lists, with the
2//! package manager the user already has (#3350).
3//!
4//! `bynk test`, `bynk dev` and `bynk deploy` all build into a directory bynk
5//! generates (`out/`, `.bynk/dev`, `.bynk/deploy`) whose `package.json` pins the
6//! toolchain's own npm packages (`postal-mime` for inbound email, ADR 0799 C)
7//! and any adapter's approved ones. This module is the one routine that makes
8//! those packages present, and it runs a tool only when a listed package is
9//! missing, so a warm re-run needs no network.
10//!
11//! Which tool downloads the packages is decided by [`detect`], a pure function
12//! over an injected [`Project`] view (files and environment) and a
13//! [`Toolbox`] (PATH), so every rule is unit-tested without a real tool. The
14//! install runs through a [`Runner`] for the same reason.
15//!
16//! Lifecycle scripts are always off. The approval of a fetched adapter's npm
17//! packages (ADR 0575) is enforced when the project compiles, before the build
18//! directory exists, so nothing here can install an unapproved package: the
19//! `package.json` this reads only lists approved ones and the toolchain's own.
20
21use std::path::{Path, PathBuf};
22
23use crate::probe::{SystemToolbox, Toolbox};
24
25/// The environment variable that overrides `bynk.toml`'s `[build] package_manager`.
26pub const PACKAGE_MANAGER_ENV: &str = "BYNK_PACKAGE_MANAGER";
27
28/// The environment form of `--no-install` (for `bynk dev` and `bynk deploy`).
29pub const NO_INSTALL_ENV: &str = "BYNK_NO_INSTALL";
30
31/// Whether `BYNK_NO_INSTALL` asks for `--no-install`: set, and not `0`,
32/// `false`, `no` or `off`.
33pub fn no_install_from_env() -> bool {
34    std::env::var(NO_INSTALL_ENV).is_ok_and(|v| {
35        let v = v.trim().to_ascii_lowercase();
36        !matches!(v.as_str(), "" | "0" | "false" | "no" | "off")
37    })
38}
39
40/// A package manager bynk can install with.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum PackageManager {
43    Npm,
44    Pnpm,
45    Bun,
46    /// Yarn classic (v1) only; Yarn Berry is refused (its Plug'n'Play layout leaves no `node_modules`).
47    Yarn,
48}
49
50impl PackageManager {
51    /// Every manager a setting may name.
52    pub const ALL: [PackageManager; 4] = [Self::Npm, Self::Pnpm, Self::Bun, Self::Yarn];
53
54    /// The executable's name, which is also the setting's value.
55    pub fn name(self) -> &'static str {
56        match self {
57            Self::Npm => "npm",
58            Self::Pnpm => "pnpm",
59            Self::Bun => "bun",
60            Self::Yarn => "yarn",
61        }
62    }
63
64    /// Parse a setting or a `packageManager` name (no version).
65    pub fn parse(name: &str) -> Option<Self> {
66        Self::ALL.into_iter().find(|m| m.name() == name.trim())
67    }
68
69    /// The arguments of the install. Lifecycle scripts are always off.
70    pub fn install_args(self) -> &'static [&'static str] {
71        match self {
72            Self::Npm => &["install", "--no-audit", "--no-fund", "--ignore-scripts"],
73            // Without `--ignore-workspace`, a `pnpm-workspace.yaml` above the
74            // generated directory would pull it into the user's workspace.
75            Self::Pnpm => &["install", "--ignore-scripts", "--ignore-workspace"],
76            Self::Bun => &["install", "--ignore-scripts"],
77            Self::Yarn => &["install", "--ignore-scripts", "--non-interactive"],
78        }
79    }
80
81    /// The command as a user would type it, for messages (`pnpm install`).
82    pub fn command_line(self) -> String {
83        format!("{} {}", self.name(), self.install_args().join(" "))
84    }
85}
86
87impl PackageManager {
88    /// The program that runs a package's binary without installing it first:
89    /// `npx`, `pnpm` (as `pnpm dlx`) or `bunx`. Yarn classic has none.
90    pub fn runner_program(self) -> Option<&'static str> {
91        match self {
92            Self::Npm => Some("npx"),
93            Self::Pnpm => Some("pnpm"),
94            Self::Bun => Some("bunx"),
95            Self::Yarn => None,
96        }
97    }
98
99    /// The runner as a user would say it, for messages and `bynk doctor`:
100    /// `npx`, `pnpm dlx` or `bunx`.
101    pub fn runner_label(self) -> Option<&'static str> {
102        match self {
103            Self::Npm => Some("npx"),
104            Self::Pnpm => Some("pnpm dlx"),
105            Self::Bun => Some("bunx"),
106            Self::Yarn => None,
107        }
108    }
109
110    /// The arguments after [`Self::runner_program`] that run `bin` from the
111    /// package `package` (which may be pinned, as [`crate::tools::pins::typescript_spec`]
112    /// is), downloading it
113    /// on first use. `npx` needs `--yes` to skip its prompt; `pnpm dlx` and
114    /// `bunx` do not prompt.
115    pub fn runner_args(self, package: &str, bin: &str) -> Vec<String> {
116        let own = |parts: &[&str]| parts.iter().map(|p| (*p).to_string()).collect::<Vec<_>>();
117        match self {
118            Self::Npm => own(&["--yes", "-p", package, bin]),
119            Self::Pnpm => own(&["dlx", "--package", package, bin]),
120            Self::Bun => own(&["--package", package, bin]),
121            Self::Yarn => Vec::new(),
122        }
123    }
124
125    /// The command that installs `package` globally.
126    pub fn global_install(self, package: &str) -> String {
127        match self {
128            Self::Npm => format!("npm install -g {package}"),
129            Self::Pnpm => format!("pnpm add -g {package}"),
130            Self::Bun => format!("bun add -g {package}"),
131            Self::Yarn => format!("yarn global add {package}"),
132        }
133    }
134
135    /// The command that adds `package` to the project as a dev dependency.
136    pub fn dev_install(self, package: &str) -> String {
137        match self {
138            Self::Npm => format!("npm install --save-dev {package}"),
139            Self::Pnpm => format!("pnpm add -D {package}"),
140            Self::Bun => format!("bun add -d {package}"),
141            Self::Yarn => format!("yarn add -D {package}"),
142        }
143    }
144
145    /// The runner this tool gives a user, given what is on PATH: its own when
146    /// it has one and it is found, else `npx` when found (a Yarn classic user,
147    /// who has no runner, or a detected tool that is not installed), else none.
148    pub fn runner(self, tb: &dyn Toolbox) -> Option<PackageManager> {
149        let found = |m: PackageManager| match m {
150            PackageManager::Npm => tb.npx_available(),
151            other => other
152                .runner_program()
153                .is_some_and(|program| tb.on_path(program).is_some()),
154        };
155        [self, PackageManager::Npm]
156            .into_iter()
157            .find(|m| m.runner_program().is_some() && found(*m))
158    }
159}
160
161/// The package manager the toolchain's own tool fallbacks and install hints
162/// follow: the detected one, or npm (today's behaviour) when detection finds
163/// none or names an unknown tool.
164pub fn tool_manager(
165    project: &dyn Project,
166    setting: Option<&str>,
167    tb: &dyn Toolbox,
168) -> PackageManager {
169    detect(project, setting, tb)
170        .map(|d| d.manager)
171        .unwrap_or(PackageManager::Npm)
172}
173
174/// [`tool_manager`] over the project's real files and the process environment,
175/// reading `[build] package_manager` from its `bynk.toml`, with PATH seen
176/// through `tb`.
177pub fn manager_in(project_root: &Path, tb: &dyn Toolbox) -> PackageManager {
178    tool_manager(
179        &RealProject(project_root),
180        configured_manager(project_root).as_deref(),
181        tb,
182    )
183}
184
185/// [`manager_in`] over the real PATH.
186pub fn system_tool_manager(project_root: &Path) -> PackageManager {
187    manager_in(project_root, &SystemToolbox)
188}
189
190/// The rule that chose the package manager, for `bynk doctor` and messages.
191#[derive(Debug, Clone, PartialEq, Eq)]
192pub enum Rule {
193    /// `BYNK_PACKAGE_MANAGER`.
194    Env,
195    /// `bynk.toml`'s `[build] package_manager`.
196    Setting,
197    /// The project root `package.json`'s `packageManager` field.
198    PackageJson,
199    /// A lockfile at the project root, by file name.
200    Lockfile(&'static str),
201    /// `npm_config_user_agent`.
202    UserAgent,
203    /// The first of npm, pnpm and bun found on PATH.
204    Path,
205}
206
207impl Rule {
208    /// A short phrase for the reader: why this tool.
209    pub fn describe(&self) -> String {
210        match self {
211            Rule::Env => format!("`{PACKAGE_MANAGER_ENV}` is set"),
212            Rule::Setting => "`bynk.toml` sets `[build] package_manager`".to_string(),
213            Rule::PackageJson => "`package.json` names it in `packageManager`".to_string(),
214            Rule::Lockfile(file) => format!("`{file}` is at the project root"),
215            Rule::UserAgent => "bynk was started by it (`npm_config_user_agent`)".to_string(),
216            Rule::Path => "the first of npm, pnpm and bun on PATH".to_string(),
217        }
218    }
219}
220
221/// The detected package manager and the rule that chose it.
222#[derive(Debug, Clone, PartialEq, Eq)]
223pub struct Detection {
224    pub manager: PackageManager,
225    pub rule: Rule,
226}
227
228/// Why detection chose nothing usable.
229#[derive(Debug, Clone, PartialEq, Eq)]
230pub enum DetectError {
231    /// An explicit setting names a manager bynk does not know.
232    UnknownManager { source: &'static str, value: String },
233    /// No explicit choice, and none of npm, pnpm or bun is on PATH.
234    NoneAvailable,
235}
236
237impl std::fmt::Display for DetectError {
238    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239        match self {
240            DetectError::UnknownManager { source, value } => write!(
241                f,
242                "{source} names the package manager `{value}`, which bynk cannot install with (npm, pnpm, bun or yarn)"
243            ),
244            DetectError::NoneAvailable => f.write_str(
245                "none of npm, pnpm or bun is on PATH to install the generated project's npm packages; install Node.js (which ships npm), or set `[build] package_manager`",
246            ),
247        }
248    }
249}
250
251/// The files and environment of the project, as a view detection reads.
252pub trait Project {
253    /// The text of a file at the project root, if it exists.
254    fn read(&self, name: &str) -> Option<String>;
255    /// Whether a file exists at the project root.
256    fn exists(&self, name: &str) -> bool;
257    /// An environment variable.
258    fn env(&self, key: &str) -> Option<String>;
259}
260
261/// [`Project`] over the real file system and process environment.
262pub struct RealProject<'a>(pub &'a Path);
263
264impl Project for RealProject<'_> {
265    fn read(&self, name: &str) -> Option<String> {
266        std::fs::read_to_string(self.0.join(name)).ok()
267    }
268
269    fn exists(&self, name: &str) -> bool {
270        self.0.join(name).is_file()
271    }
272
273    fn env(&self, key: &str) -> Option<String> {
274        std::env::var(key).ok().filter(|v| !v.trim().is_empty())
275    }
276}
277
278/// Lockfiles in the order they are tried.
279const LOCKFILES: [(&str, PackageManager); 5] = [
280    ("pnpm-lock.yaml", PackageManager::Pnpm),
281    ("bun.lock", PackageManager::Bun),
282    ("bun.lockb", PackageManager::Bun),
283    ("yarn.lock", PackageManager::Yarn),
284    ("package-lock.json", PackageManager::Npm),
285];
286
287/// The managers tried against PATH, in order. npm first: it ships with Node.
288const PATH_ORDER: [PackageManager; 3] = [
289    PackageManager::Npm,
290    PackageManager::Pnpm,
291    PackageManager::Bun,
292];
293
294/// Choose the package manager, first match wins:
295///
296/// 1. an explicit setting, `BYNK_PACKAGE_MANAGER` over `bynk.toml`'s
297///    `[build] package_manager` (`setting`);
298/// 2. the `packageManager` field of the project root's `package.json`;
299/// 3. a lockfile at the project root;
300/// 4. `npm_config_user_agent`;
301/// 5. the first of npm, pnpm and bun on PATH.
302///
303/// A `packageManager` or user agent naming a tool bynk does not install with
304/// is skipped, since neither is a setting bynk owns; an explicit setting
305/// naming one is an error.
306pub fn detect(
307    project: &dyn Project,
308    setting: Option<&str>,
309    tb: &dyn Toolbox,
310) -> Result<Detection, DetectError> {
311    if let Some(found) = explicit(project, setting)? {
312        return Ok(found);
313    }
314    if let Some(found) = from_package_json(project)
315        .or_else(|| from_lockfile(project))
316        .or_else(|| from_user_agent(project))
317    {
318        return Ok(found);
319    }
320    PATH_ORDER
321        .into_iter()
322        .find(|m| tb.on_path(m.name()).is_some())
323        .map(|manager| Detection {
324            manager,
325            rule: Rule::Path,
326        })
327        .ok_or(DetectError::NoneAvailable)
328}
329
330fn explicit(
331    project: &dyn Project,
332    setting: Option<&str>,
333) -> Result<Option<Detection>, DetectError> {
334    let candidates = [
335        (
336            Rule::Env,
337            "`BYNK_PACKAGE_MANAGER`",
338            project.env(PACKAGE_MANAGER_ENV),
339        ),
340        (
341            Rule::Setting,
342            "`bynk.toml`'s `[build] package_manager`",
343            setting.map(str::to_string),
344        ),
345    ];
346    for (rule, source, value) in candidates {
347        let Some(value) = value else { continue };
348        let manager = PackageManager::parse(&value).ok_or(DetectError::UnknownManager {
349            source,
350            value: value.clone(),
351        })?;
352        return Ok(Some(Detection { manager, rule }));
353    }
354    Ok(None)
355}
356
357fn from_package_json(project: &dyn Project) -> Option<Detection> {
358    let text = project.read("package.json")?;
359    let doc: serde_json::Value = serde_json::from_str(&text).ok()?;
360    let field = doc.get("packageManager")?.as_str()?;
361    let manager = PackageManager::parse(field.split('@').next()?)?;
362    Some(Detection {
363        manager,
364        rule: Rule::PackageJson,
365    })
366}
367
368fn from_lockfile(project: &dyn Project) -> Option<Detection> {
369    LOCKFILES
370        .into_iter()
371        .find(|(file, _)| project.exists(file))
372        .map(|(file, manager)| Detection {
373            manager,
374            rule: Rule::Lockfile(file),
375        })
376}
377
378fn from_user_agent(project: &dyn Project) -> Option<Detection> {
379    let agent = project.env("npm_config_user_agent")?;
380    // `pnpm/9.1.0 npm/? node/v22 linux x64`: the first token names the tool.
381    let tool = agent.split(['/', ' ']).next()?;
382    let manager = PackageManager::parse(tool)?;
383    Some(Detection {
384        manager,
385        rule: Rule::UserAgent,
386    })
387}
388
389/// The npm packages the emitted `package.json` lists (an adapter's, and the
390/// toolchain's own, ADR 0799 C) that `node_modules` beside it does not hold,
391/// sorted.
392pub fn missing_npm_dependencies(build_dir: &Path) -> Vec<String> {
393    missing_npm_dependencies_in(build_dir, build_dir)
394}
395
396/// [`missing_npm_dependencies`], reading `package.json` from `build_dir` and
397/// looking for the packages under `modules_root`'s `node_modules`. #3796: a
398/// deploy dry run builds in a scratch directory, but the packages a real deploy
399/// installed are in `.bynk/deploy`.
400fn missing_npm_dependencies_in(build_dir: &Path, modules_root: &Path) -> Vec<String> {
401    let Ok(text) = std::fs::read_to_string(build_dir.join("package.json")) else {
402        return Vec::new();
403    };
404    let Ok(manifest) = serde_json::from_str::<serde_json::Value>(&text) else {
405        return Vec::new();
406    };
407    let mut missing: Vec<String> = manifest["dependencies"]
408        .as_object()
409        .into_iter()
410        .flatten()
411        .map(|(name, _)| name.clone())
412        .filter(|name| {
413            !modules_root
414                .join("node_modules")
415                .join(name)
416                .join("package.json")
417                .is_file()
418        })
419        .collect();
420    missing.sort();
421    missing
422}
423
424/// What an install request is allowed to do.
425#[derive(Debug, Clone, Copy, PartialEq, Eq)]
426pub enum Mode {
427    /// Install what is missing.
428    Install,
429    /// `--no-install`: stop, naming the command, instead of installing.
430    NoInstall,
431    /// `--dry-run`: report what would be installed, and run nothing.
432    DryRun,
433}
434
435impl Mode {
436    /// The mode of a `bynk dev` / `bynk deploy` run. A dry run never installs,
437    /// so it outranks `--no-install`.
438    pub fn of(dry_run: bool, no_install: bool) -> Mode {
439        if dry_run {
440            Mode::DryRun
441        } else if no_install {
442            Mode::NoInstall
443        } else {
444            Mode::Install
445        }
446    }
447}
448
449/// What [`ensure_installed`] did.
450#[derive(Debug, Clone, PartialEq, Eq)]
451pub enum Outcome {
452    /// Every listed package was present (or none is listed): nothing ran.
453    Present,
454    /// The packages were installed.
455    Installed(Detection),
456    /// A dry run: these would be installed, with this tool.
457    /// A dry run: these would be installed, with this tool (or, when none can
458    /// be chosen, why not). Detection failing never fails a dry run.
459    WouldInstall(Vec<String>, Result<Detection, DetectError>),
460}
461
462/// Why the packages are not installed.
463#[derive(Debug, Clone, PartialEq, Eq)]
464pub enum InstallError {
465    Detect(DetectError),
466    /// `--no-install`: today's preflight stop.
467    Declined {
468        missing: Vec<String>,
469        /// The detected install command, if a package manager could be chosen.
470        command: Option<String>,
471        dir: PathBuf,
472    },
473    /// The chosen tool is not on PATH.
474    ToolMissing {
475        detection: Detection,
476    },
477    /// Yarn Berry, which bynk does not install with.
478    YarnBerry {
479        version: String,
480    },
481    /// The tool ran and failed, or could not be started.
482    Failed {
483        command: String,
484        dir: PathBuf,
485        detail: String,
486    },
487}
488
489impl std::fmt::Display for InstallError {
490    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
491        match self {
492            InstallError::Detect(e) => write!(f, "{e}"),
493            InstallError::Declined {
494                missing,
495                command,
496                dir,
497            } => {
498                let run = command.as_ref().map_or_else(
499                    || "Install them with your package manager".to_string(),
500                    |c| format!("Run `{c}`"),
501                );
502                write!(
503                    f,
504                    "the build needs npm packages that are not installed: {}. {run} in `{}`, then try again",
505                    missing.join(", "),
506                    dir.display()
507                )
508            }
509            InstallError::ToolMissing { detection } => write!(
510                f,
511                "`{}` is not on PATH to install the generated project's npm packages ({}); install it, or choose another with `[build] package_manager` or `{PACKAGE_MANAGER_ENV}`",
512                detection.manager.name(),
513                detection.rule.describe()
514            ),
515            InstallError::YarnBerry { version } => write!(
516                f,
517                "yarn {version} is Yarn Berry, which bynk does not install with (its Plug'n'Play layout leaves no `node_modules`); use Yarn classic, or choose npm, pnpm or bun with `[build] package_manager` or `{PACKAGE_MANAGER_ENV}`"
518            ),
519            InstallError::Failed {
520                command,
521                dir,
522                detail,
523            } => write!(
524                f,
525                "`{command}` failed in `{}`:\n{}",
526                dir.display(),
527                detail.trim_end()
528            ),
529        }
530    }
531}
532
533impl std::error::Error for InstallError {}
534
535/// Runs a tool to completion. The seam for tests; [`SystemRunner`] is the real one.
536pub trait Runner {
537    /// Run `program args` in `dir`; `Ok((success, output))` with the combined
538    /// stdout and stderr, `Err` when the tool could not be started.
539    fn run(&self, program: &Path, args: &[&str], dir: &Path) -> Result<(bool, String), String>;
540}
541
542/// [`Runner`] over the real tools ([`crate::tools::run_to_completion`]).
543pub struct SystemRunner;
544
545impl Runner for SystemRunner {
546    fn run(&self, program: &Path, args: &[&str], dir: &Path) -> Result<(bool, String), String> {
547        crate::tools::run_to_completion(program, args, dir)
548    }
549}
550
551/// Everything [`ensure_installed`] reads: the project, its `bynk.toml`
552/// setting, the toolbox and the runner.
553pub struct Install<'a> {
554    pub project: &'a dyn Project,
555    /// `bynk.toml`'s `[build] package_manager`.
556    pub setting: Option<&'a str>,
557    pub toolbox: &'a dyn Toolbox,
558    pub runner: &'a dyn Runner,
559}
560
561/// Make the packages `build_dir/package.json` lists present in its
562/// `node_modules`. Nothing runs when none is missing.
563pub fn ensure_installed(
564    install: &Install<'_>,
565    build_dir: &Path,
566    mode: Mode,
567) -> Result<Outcome, InstallError> {
568    ensure_installed_in(install, build_dir, build_dir, mode)
569}
570
571/// [`ensure_installed`], with the installed packages looked for under
572/// `modules_root` ([`missing_npm_dependencies_in`]).
573fn ensure_installed_in(
574    install: &Install<'_>,
575    build_dir: &Path,
576    modules_root: &Path,
577    mode: Mode,
578) -> Result<Outcome, InstallError> {
579    let missing = missing_npm_dependencies_in(build_dir, modules_root);
580    if missing.is_empty() {
581        return Ok(Outcome::Present);
582    }
583    let detection = detect(install.project, install.setting, install.toolbox);
584    match (mode, detection) {
585        // Neither a dry run nor `--no-install` installs, so neither fails for
586        // want of a package manager: both still name the missing packages.
587        (Mode::DryRun, detection) => Ok(Outcome::WouldInstall(missing, detection)),
588        (Mode::NoInstall, detection) => Err(InstallError::Declined {
589            command: detection.ok().map(|d| d.manager.command_line()),
590            missing,
591            dir: build_dir.to_path_buf(),
592        }),
593        (Mode::Install, Err(e)) => Err(InstallError::Detect(e)),
594        (Mode::Install, Ok(detection)) => run_install(install, build_dir, detection),
595    }
596}
597
598fn run_install(
599    install: &Install<'_>,
600    build_dir: &Path,
601    detection: Detection,
602) -> Result<Outcome, InstallError> {
603    let manager = detection.manager;
604    let Some(program) = install.toolbox.on_path(manager.name()) else {
605        return Err(InstallError::ToolMissing { detection });
606    };
607    if manager == PackageManager::Yarn {
608        check_yarn_classic(install.runner, &program, build_dir)?;
609    }
610    let failed = |detail: String| InstallError::Failed {
611        command: manager.command_line(),
612        dir: build_dir.to_path_buf(),
613        detail,
614    };
615    match install
616        .runner
617        .run(&program, manager.install_args(), build_dir)
618    {
619        Ok((true, _)) => Ok(Outcome::Installed(detection)),
620        Ok((false, output)) => Err(failed(output)),
621        Err(e) => Err(failed(e)),
622    }
623}
624
625/// Yarn Berry defaults to Plug'n'Play, which leaves no `node_modules` for
626/// wrangler's bundler or the test link, so only Yarn classic installs here.
627fn check_yarn_classic(runner: &dyn Runner, yarn: &Path, dir: &Path) -> Result<(), InstallError> {
628    let Ok((true, text)) = runner.run(yarn, &["--version"], dir) else {
629        return Ok(());
630    };
631    let version = text.trim().to_string();
632    match version
633        .split('.')
634        .next()
635        .and_then(|major| major.parse::<u32>().ok())
636    {
637        Some(major) if major >= 2 => Err(InstallError::YarnBerry { version }),
638        _ => Ok(()),
639    }
640}
641
642/// The tool `bynk dev`/`bynk deploy`/`bynk test` print before a real install,
643/// so a slow download does not read as a hang.
644pub fn announce(detection: &Detection, build_dir: &Path) -> String {
645    format!(
646        "bynk: installing npm packages with {} in `{}`",
647        detection.manager.name(),
648        build_dir.display()
649    )
650}
651
652/// The dry-run line: what would be installed, and with which tool.
653pub fn dry_run_message(
654    missing: &[String],
655    detection: &Result<Detection, DetectError>,
656    build_dir: &Path,
657) -> String {
658    let how = match detection {
659        Ok(found) => format!(
660            "A real run would install them with `{}` in `{}` ({})",
661            found.manager.command_line(),
662            build_dir.display(),
663            found.rule.describe()
664        ),
665        Err(e) => format!("A real run could not install them: {e}"),
666    };
667    format!(
668        "bynk: the build needs npm packages that are not installed: {}. {how}",
669        missing.join(", ")
670    )
671}
672
673/// The whole step for a caller with the real file system, tools and process
674/// environment: detect, install, and print the announcements. `Err` is the
675/// message to print (without the `bynk: ` prefix).
676pub fn install_for_project(
677    project_root: &Path,
678    build_dir: &Path,
679    setting: Option<&str>,
680    mode: Mode,
681) -> Result<(), String> {
682    install_for_project_shown_as(project_root, build_dir, build_dir, setting, mode)
683}
684
685/// [`install_for_project`], with a dry run's report naming `shown_dir`: where a
686/// real run would install. #3796: a deploy dry run builds in a scratch
687/// directory, but a real deploy installs in `.bynk/deploy`.
688pub fn install_for_project_shown_as(
689    project_root: &Path,
690    build_dir: &Path,
691    shown_dir: &Path,
692    setting: Option<&str>,
693    mode: Mode,
694) -> Result<(), String> {
695    let project = RealProject(project_root);
696    let toolbox = SystemToolbox;
697    let install = Install {
698        project: &project,
699        setting,
700        toolbox: &toolbox,
701        runner: &SystemRunner,
702    };
703    // Announce before running: a download with no output reads as a hang.
704    if mode == Mode::Install
705        && !missing_npm_dependencies(build_dir).is_empty()
706        && let Ok(found) = detect(&project, setting, &toolbox)
707    {
708        crate::colour::eprintln(&announce(&found, build_dir));
709    }
710    // A dry run installs nothing, so what is missing is judged where a real run
711    // would install: `shown_dir`.
712    let modules_root = if mode == Mode::DryRun {
713        shown_dir
714    } else {
715        build_dir
716    };
717    match ensure_installed_in(&install, build_dir, modules_root, mode).map_err(|e| e.to_string())? {
718        Outcome::WouldInstall(missing, found) => {
719            crate::colour::eprintln(&dry_run_message(&missing, &found, shown_dir));
720            Ok(())
721        }
722        Outcome::Present | Outcome::Installed(_) => Ok(()),
723    }
724}
725
726/// `bynk.toml`'s `[build] package_manager`, if it sets one and the manifest
727/// reads. A malformed manifest is reported by the build, not here.
728pub fn configured_manager(project_root: &Path) -> Option<String> {
729    bynk_project::try_read_build_config(project_root)
730        .ok()
731        .and_then(|c| c.package_manager)
732}
733
734#[cfg(test)]
735mod tests {
736    use super::*;
737    use crate::probe::Version;
738    use std::cell::RefCell;
739    use std::collections::{BTreeMap, BTreeSet};
740    use std::process::Command;
741
742    #[derive(Default)]
743    struct Fake {
744        files: BTreeMap<&'static str, String>,
745        env: BTreeMap<&'static str, &'static str>,
746        path: BTreeSet<&'static str>,
747    }
748
749    impl Project for Fake {
750        fn read(&self, name: &str) -> Option<String> {
751            self.files.get(name).cloned()
752        }
753        fn exists(&self, name: &str) -> bool {
754            self.files.contains_key(name)
755        }
756        fn env(&self, key: &str) -> Option<String> {
757            self.env.get(key).map(|v| v.to_string())
758        }
759    }
760
761    impl Toolbox for Fake {
762        fn on_path(&self, tool: &str) -> Option<PathBuf> {
763            self.path
764                .contains(tool)
765                .then(|| PathBuf::from(format!("/bin/{tool}")))
766        }
767        fn in_dir(&self, _: &Path, _: &str) -> Option<PathBuf> {
768            None
769        }
770        fn version(&self, _: &Path) -> Option<Version> {
771            None
772        }
773        fn npx_available(&self) -> bool {
774            false
775        }
776    }
777
778    fn pick(fake: &Fake, setting: Option<&str>) -> Result<Detection, DetectError> {
779        detect(fake, setting, fake)
780    }
781
782    fn chose(fake: &Fake, setting: Option<&str>) -> (PackageManager, Rule) {
783        let d = pick(fake, setting).unwrap();
784        (d.manager, d.rule)
785    }
786
787    #[test]
788    fn the_environment_overrides_the_setting() {
789        let mut f = Fake::default();
790        f.env.insert(PACKAGE_MANAGER_ENV, "bun");
791        assert_eq!(chose(&f, Some("pnpm")), (PackageManager::Bun, Rule::Env));
792    }
793
794    #[test]
795    fn the_setting_beats_package_json_and_lockfiles() {
796        let mut f = Fake::default();
797        f.files
798            .insert("package.json", r#"{"packageManager":"[email protected]"}"#.into());
799        f.files.insert("yarn.lock", String::new());
800        assert_eq!(chose(&f, Some("bun")), (PackageManager::Bun, Rule::Setting));
801    }
802
803    #[test]
804    fn an_unknown_explicit_setting_is_an_error_naming_where_it_came_from() {
805        let f = Fake::default();
806        let e = pick(&f, Some("deno")).unwrap_err();
807        assert!(
808            e.to_string().contains("`bynk.toml`") && e.to_string().contains("`deno`"),
809            "{e}"
810        );
811        let mut f = Fake::default();
812        f.env.insert(PACKAGE_MANAGER_ENV, "nope");
813        assert!(
814            pick(&f, None)
815                .unwrap_err()
816                .to_string()
817                .contains("BYNK_PACKAGE_MANAGER")
818        );
819    }
820
821    #[test]
822    fn package_json_names_the_manager_before_any_version() {
823        for (field, want) in [
824            ("[email protected]+sha512.abc", PackageManager::Pnpm),
825            ("[email protected]", PackageManager::Yarn),
826            ("[email protected]", PackageManager::Bun),
827            ("[email protected]", PackageManager::Npm),
828        ] {
829            let mut f = Fake::default();
830            f.files
831                .insert("package.json", format!(r#"{{"packageManager":"{field}"}}"#));
832            f.files.insert("package-lock.json", String::new());
833            assert_eq!(chose(&f, None), (want, Rule::PackageJson), "{field}");
834        }
835    }
836
837    #[test]
838    fn an_unknown_or_absent_package_manager_field_falls_through() {
839        let mut f = Fake::default();
840        f.files
841            .insert("package.json", r#"{"packageManager":"deno@2"}"#.into());
842        f.files.insert("pnpm-lock.yaml", String::new());
843        assert_eq!(
844            chose(&f, None),
845            (PackageManager::Pnpm, Rule::Lockfile("pnpm-lock.yaml"))
846        );
847        let mut f = Fake::default();
848        f.files.insert("package.json", "{ not json".into());
849        f.files.insert("yarn.lock", String::new());
850        assert_eq!(
851            chose(&f, None),
852            (PackageManager::Yarn, Rule::Lockfile("yarn.lock"))
853        );
854    }
855
856    #[test]
857    fn each_lockfile_names_its_manager() {
858        for (file, want) in [
859            ("pnpm-lock.yaml", PackageManager::Pnpm),
860            ("bun.lock", PackageManager::Bun),
861            ("bun.lockb", PackageManager::Bun),
862            ("yarn.lock", PackageManager::Yarn),
863            ("package-lock.json", PackageManager::Npm),
864        ] {
865            let mut f = Fake::default();
866            f.files.insert(file, String::new());
867            assert_eq!(chose(&f, None), (want, Rule::Lockfile(file)), "{file}");
868        }
869    }
870
871    #[test]
872    fn a_lockfile_beats_the_user_agent_and_the_user_agent_beats_path() {
873        let mut f = Fake::default();
874        f.files.insert("yarn.lock", String::new());
875        f.env
876            .insert("npm_config_user_agent", "pnpm/9.0.0 npm/? node/v22");
877        assert_eq!(chose(&f, None).0, PackageManager::Yarn);
878
879        let mut f = Fake::default();
880        f.env
881            .insert("npm_config_user_agent", "pnpm/9.0.0 npm/? node/v22");
882        f.path.insert("npm");
883        assert_eq!(chose(&f, None), (PackageManager::Pnpm, Rule::UserAgent));
884        for (agent, want) in [
885            ("bun/1.1.0 npm/? node/v22", PackageManager::Bun),
886            ("yarn/1.22.0 npm/? node/v22", PackageManager::Yarn),
887            ("npm/10.0.0 node/v22 linux x64", PackageManager::Npm),
888        ] {
889            let mut f = Fake::default();
890            f.env.insert("npm_config_user_agent", agent);
891            assert_eq!(chose(&f, None), (want, Rule::UserAgent), "{agent}");
892        }
893    }
894
895    #[test]
896    fn an_unrecognised_user_agent_falls_through_to_path() {
897        let mut f = Fake::default();
898        f.env.insert("npm_config_user_agent", "deno/2.0");
899        f.path.insert("bun");
900        assert_eq!(chose(&f, None), (PackageManager::Bun, Rule::Path));
901    }
902
903    #[test]
904    fn path_prefers_npm_then_pnpm_then_bun() {
905        let mut f = Fake::default();
906        f.path.extend(["bun", "pnpm", "npm"]);
907        assert_eq!(chose(&f, None), (PackageManager::Npm, Rule::Path));
908        f.path.remove("npm");
909        assert_eq!(chose(&f, None).0, PackageManager::Pnpm);
910        f.path.remove("pnpm");
911        assert_eq!(chose(&f, None).0, PackageManager::Bun);
912        f.path.remove("bun");
913        assert_eq!(pick(&f, None), Err(DetectError::NoneAvailable));
914    }
915
916    #[test]
917    fn each_tools_arguments_turn_lifecycle_scripts_off() {
918        assert_eq!(
919            PackageManager::Npm.install_args(),
920            ["install", "--no-audit", "--no-fund", "--ignore-scripts"]
921        );
922        assert_eq!(
923            PackageManager::Pnpm.install_args(),
924            ["install", "--ignore-scripts", "--ignore-workspace"]
925        );
926        assert_eq!(
927            PackageManager::Bun.install_args(),
928            ["install", "--ignore-scripts"]
929        );
930        assert_eq!(
931            PackageManager::Yarn.install_args(),
932            ["install", "--ignore-scripts", "--non-interactive"]
933        );
934        for m in PackageManager::ALL {
935            assert!(m.install_args().contains(&"--ignore-scripts"), "{m:?}");
936        }
937    }
938
939    // -- ensure_installed ---------------------------------------------------
940
941    #[derive(Default)]
942    struct Spy {
943        calls: RefCell<Vec<(PathBuf, Vec<String>, PathBuf)>>,
944        yarn_version: &'static str,
945        fail: bool,
946    }
947
948    impl Runner for Spy {
949        fn run(&self, program: &Path, args: &[&str], dir: &Path) -> Result<(bool, String), String> {
950            if args == ["--version"] {
951                return Ok((true, self.yarn_version.to_string()));
952            }
953            self.calls.borrow_mut().push((
954                program.to_path_buf(),
955                args.iter().map(|a| a.to_string()).collect(),
956                dir.to_path_buf(),
957            ));
958            if self.fail {
959                Ok((false, "ERR network unreachable\n".to_string()))
960            } else {
961                Ok((true, String::new()))
962            }
963        }
964    }
965
966    fn build_dir(name: &str, listed: &[&str], installed: &[&str]) -> PathBuf {
967        let d =
968            std::env::temp_dir().join(format!("bynk-npm-install-{name}-{}", std::process::id()));
969        let _ = std::fs::remove_dir_all(&d);
970        std::fs::create_dir_all(&d).unwrap();
971        let deps: Vec<String> = listed
972            .iter()
973            .map(|n| format!("\"{n}\": \"1.0.0\""))
974            .collect();
975        std::fs::write(
976            d.join("package.json"),
977            format!("{{\"dependencies\": {{{}}}}}", deps.join(", ")),
978        )
979        .unwrap();
980        for n in installed {
981            let p = d.join("node_modules").join(n);
982            std::fs::create_dir_all(&p).unwrap();
983            std::fs::write(p.join("package.json"), "{}").unwrap();
984        }
985        d
986    }
987
988    fn with_pnpm() -> Fake {
989        let mut f = Fake::default();
990        f.files.insert("pnpm-lock.yaml", String::new());
991        f.path.insert("pnpm");
992        f
993    }
994
995    fn run_mode(fake: &Fake, spy: &Spy, dir: &Path, mode: Mode) -> Result<Outcome, InstallError> {
996        let install = Install {
997            project: fake,
998            setting: None,
999            toolbox: fake,
1000            runner: spy,
1001        };
1002        ensure_installed(&install, dir, mode)
1003    }
1004
1005    #[test]
1006    fn a_missing_package_runs_the_detected_tool_in_the_build_directory() {
1007        let d = build_dir("run", &["postal-mime"], &[]);
1008        let spy = Spy::default();
1009        let got = run_mode(&with_pnpm(), &spy, &d, Mode::Install).unwrap();
1010        assert!(matches!(got, Outcome::Installed(ref det) if det.manager == PackageManager::Pnpm));
1011        let calls = spy.calls.borrow();
1012        assert_eq!(calls.len(), 1);
1013        assert_eq!(calls[0].0, PathBuf::from("/bin/pnpm"));
1014        assert_eq!(
1015            calls[0].1,
1016            ["install", "--ignore-scripts", "--ignore-workspace"]
1017        );
1018        assert_eq!(calls[0].2, d);
1019    }
1020
1021    #[test]
1022    fn a_warm_directory_runs_nothing_and_needs_no_tool() {
1023        let d = build_dir("warm", &["postal-mime", "jose"], &["postal-mime", "jose"]);
1024        let spy = Spy::default();
1025        // Not even a detectable manager: nothing is looked up.
1026        let got = run_mode(&Fake::default(), &spy, &d, Mode::Install).unwrap();
1027        assert_eq!(got, Outcome::Present);
1028        assert!(spy.calls.borrow().is_empty());
1029        let none = build_dir("none", &[], &[]);
1030        assert_eq!(
1031            run_mode(&Fake::default(), &spy, &none, Mode::Install).unwrap(),
1032            Outcome::Present
1033        );
1034    }
1035
1036    #[test]
1037    fn a_partly_installed_directory_installs_again() {
1038        let d = build_dir("partial", &["postal-mime", "jose"], &["jose"]);
1039        let spy = Spy::default();
1040        run_mode(&with_pnpm(), &spy, &d, Mode::Install).unwrap();
1041        assert_eq!(spy.calls.borrow().len(), 1);
1042    }
1043
1044    #[test]
1045    fn no_install_stops_naming_the_detected_command_and_directory() {
1046        let d = build_dir("declined", &["postal-mime"], &[]);
1047        let spy = Spy::default();
1048        let e = run_mode(&with_pnpm(), &spy, &d, Mode::NoInstall).unwrap_err();
1049        let text = e.to_string();
1050        assert!(
1051            text.contains("postal-mime")
1052                && text.contains("Run `pnpm install --ignore-scripts --ignore-workspace`")
1053                && text.contains(&d.display().to_string())
1054                && !text.contains("`npm install"),
1055            "{text}"
1056        );
1057        assert!(spy.calls.borrow().is_empty());
1058    }
1059
1060    #[test]
1061    fn a_dry_run_reports_what_it_would_install_and_runs_nothing() {
1062        let d = build_dir("dry", &["postal-mime"], &[]);
1063        let spy = Spy::default();
1064        let got = run_mode(&with_pnpm(), &spy, &d, Mode::DryRun).unwrap();
1065        let Outcome::WouldInstall(missing, det) = got else {
1066            panic!("{got:?}")
1067        };
1068        assert_eq!(missing, ["postal-mime"]);
1069        assert_eq!(det.as_ref().unwrap().manager, PackageManager::Pnpm);
1070        let msg = dry_run_message(&missing, &det, &d);
1071        assert!(
1072            msg.contains("pnpm install") && msg.contains("pnpm-lock.yaml"),
1073            "{msg}"
1074        );
1075        assert!(spy.calls.borrow().is_empty());
1076        // A dry run outranks `--no-install`.
1077        assert_eq!(Mode::of(true, true), Mode::DryRun);
1078        assert_eq!(Mode::of(false, true), Mode::NoInstall);
1079        assert_eq!(Mode::of(false, false), Mode::Install);
1080    }
1081
1082    #[test]
1083    fn a_dry_run_and_no_install_still_name_the_packages_when_no_tool_is_found() {
1084        let d = build_dir("no-tool", &["postal-mime"], &[]);
1085        let spy = Spy::default();
1086        // No manager on PATH and nothing pointing at one.
1087        let got = run_mode(&Fake::default(), &spy, &d, Mode::DryRun).unwrap();
1088        let Outcome::WouldInstall(missing, det) = got else {
1089            panic!("{got:?}")
1090        };
1091        assert_eq!(det, Err(DetectError::NoneAvailable));
1092        let msg = dry_run_message(&missing, &det, &d);
1093        assert!(
1094            msg.contains("postal-mime") && msg.contains("could not install"),
1095            "{msg}"
1096        );
1097        let text = run_mode(&Fake::default(), &spy, &d, Mode::NoInstall)
1098            .unwrap_err()
1099            .to_string();
1100        assert!(
1101            text.contains("postal-mime")
1102                && text.contains("Install them with your package manager")
1103                && text.contains(&d.display().to_string()),
1104            "{text}"
1105        );
1106        // An unknown explicit setting does not fail either, and a real run does.
1107        let install = Install {
1108            project: &Fake::default(),
1109            setting: Some("deno"),
1110            toolbox: &Fake::default(),
1111            runner: &spy,
1112        };
1113        assert!(ensure_installed(&install, &d, Mode::DryRun).is_ok());
1114        assert!(matches!(
1115            ensure_installed(&install, &d, Mode::Install),
1116            Err(InstallError::Detect(_))
1117        ));
1118        assert!(spy.calls.borrow().is_empty());
1119    }
1120
1121    #[test]
1122    fn a_failed_install_names_the_command_the_directory_and_the_tools_error() {
1123        let d = build_dir("failed", &["postal-mime"], &[]);
1124        let spy = Spy {
1125            fail: true,
1126            ..Spy::default()
1127        };
1128        let text = run_mode(&with_pnpm(), &spy, &d, Mode::Install)
1129            .unwrap_err()
1130            .to_string();
1131        assert!(
1132            text.contains("pnpm install")
1133                && text.contains(&d.display().to_string())
1134                && text.contains("network unreachable"),
1135            "{text}"
1136        );
1137    }
1138
1139    #[test]
1140    fn a_chosen_tool_that_is_not_installed_says_why_it_was_chosen() {
1141        let d = build_dir("toolless", &["postal-mime"], &[]);
1142        let mut f = Fake::default();
1143        f.files.insert("bun.lock", String::new());
1144        let text = run_mode(&f, &Spy::default(), &d, Mode::Install)
1145            .unwrap_err()
1146            .to_string();
1147        assert!(
1148            text.contains("`bun`") && text.contains("bun.lock"),
1149            "{text}"
1150        );
1151    }
1152
1153    #[test]
1154    fn the_npm_fallback_installs_with_npm_when_nothing_else_points_anywhere() {
1155        let d = build_dir("npm", &["postal-mime"], &[]);
1156        let mut f = Fake::default();
1157        f.path.insert("npm");
1158        let spy = Spy::default();
1159        run_mode(&f, &spy, &d, Mode::Install).unwrap();
1160        assert_eq!(
1161            spy.calls.borrow()[0].1,
1162            ["install", "--no-audit", "--no-fund", "--ignore-scripts"]
1163        );
1164    }
1165
1166    #[test]
1167    fn yarn_classic_installs_and_berry_is_refused() {
1168        let mut f = Fake::default();
1169        f.files.insert("yarn.lock", String::new());
1170        f.path.insert("yarn");
1171        let d = build_dir("yarn", &["postal-mime"], &[]);
1172        let classic = Spy {
1173            yarn_version: "1.22.22\n",
1174            ..Spy::default()
1175        };
1176        run_mode(&f, &classic, &d, Mode::Install).unwrap();
1177        assert_eq!(classic.calls.borrow().len(), 1);
1178        let berry = Spy {
1179            yarn_version: "4.5.0\n",
1180            ..Spy::default()
1181        };
1182        let e = run_mode(&f, &berry, &d, Mode::Install).unwrap_err();
1183        assert!(matches!(e, InstallError::YarnBerry { .. }), "{e}");
1184        assert!(berry.calls.borrow().is_empty());
1185        assert!(e.to_string().contains("Berry"));
1186    }
1187
1188    // -- real tools ----------------------------------------------------------
1189
1190    /// Install `postal-mime` with the real `tool` into a directory below a
1191    /// `pnpm-workspace.yaml`, then run again. Skips when the tool is absent.
1192    fn real_install(tool: &str) {
1193        let Ok(path) = which::which(tool) else {
1194            eprintln!("skipping: `{tool}` is not installed");
1195            return;
1196        };
1197        let up = std::env::temp_dir().join(format!("bynk-npm-real-{tool}-{}", std::process::id()));
1198        let _ = std::fs::remove_dir_all(&up);
1199        // A workspace file above the generated directory: `pnpm install` would
1200        // adopt the directory as a member without `--ignore-workspace`.
1201        std::fs::create_dir_all(&up).unwrap();
1202        std::fs::write(
1203            up.join("pnpm-workspace.yaml"),
1204            "packages:\n  - 'elsewhere'\n",
1205        )
1206        .unwrap();
1207        let dir = up.join(".bynk").join("deploy");
1208        std::fs::create_dir_all(&dir).unwrap();
1209        std::fs::write(
1210            dir.join("package.json"),
1211            r#"{"type":"module","dependencies":{"postal-mime":"4.1.4"}}"#,
1212        )
1213        .unwrap();
1214        let mut fake = Fake::default();
1215        fake.path.insert(match tool {
1216            "npm" => "npm",
1217            "pnpm" => "pnpm",
1218            "bun" => "bun",
1219            _ => "yarn",
1220        });
1221        // The fake toolbox resolves the name to `/bin/<tool>`; the real runner
1222        // needs the real path.
1223        struct At(PathBuf);
1224        impl Runner for At {
1225            fn run(&self, _: &Path, args: &[&str], dir: &Path) -> Result<(bool, String), String> {
1226                SystemRunner.run(&self.0, args, dir)
1227            }
1228        }
1229        let runner = At(path);
1230        let install = Install {
1231            project: &fake,
1232            setting: Some(tool),
1233            toolbox: &fake,
1234            runner: &runner,
1235        };
1236        let first = ensure_installed(&install, &dir, Mode::Install);
1237        assert!(
1238            matches!(first, Ok(Outcome::Installed(_))),
1239            "{tool}: {first:?}"
1240        );
1241        assert!(
1242            dir.join("node_modules/postal-mime/package.json").is_file(),
1243            "{tool}: installed into the generated directory"
1244        );
1245        assert!(
1246            !up.join("node_modules").exists(),
1247            "{tool}: nothing was installed at the workspace root"
1248        );
1249        // Lifecycle scripts stay off, and a warm re-run runs nothing.
1250        assert_eq!(
1251            ensure_installed(&install, &dir, Mode::Install),
1252            Ok(Outcome::Present),
1253            "{tool}"
1254        );
1255        let _ = std::fs::remove_dir_all(&up);
1256    }
1257
1258    #[test]
1259    fn npm_installs_for_real() {
1260        real_install("npm");
1261    }
1262
1263    #[test]
1264    fn pnpm_installs_for_real_beside_a_workspace_file() {
1265        real_install("pnpm");
1266    }
1267
1268    #[test]
1269    fn bun_installs_for_real() {
1270        real_install("bun");
1271    }
1272
1273    #[test]
1274    fn yarn_classic_installs_for_real() {
1275        let classic = which::which("yarn").ok().is_some_and(|y| {
1276            Command::new(y)
1277                .arg("--version")
1278                .output()
1279                .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).starts_with("1."))
1280        });
1281        if classic {
1282            real_install("yarn");
1283        } else {
1284            eprintln!("skipping: Yarn classic is not installed");
1285        }
1286    }
1287
1288    /// A toolbox with chosen programs on PATH and `npx` present or not.
1289    struct Tools {
1290        path: &'static [&'static str],
1291        npx: bool,
1292    }
1293
1294    impl Toolbox for Tools {
1295        fn on_path(&self, tool: &str) -> Option<PathBuf> {
1296            self.path
1297                .contains(&tool)
1298                .then(|| PathBuf::from(format!("/bin/{tool}")))
1299        }
1300        fn in_dir(&self, _: &Path, _: &str) -> Option<PathBuf> {
1301            None
1302        }
1303        fn version(&self, _: &Path) -> Option<Version> {
1304            None
1305        }
1306        fn npx_available(&self) -> bool {
1307            self.npx
1308        }
1309    }
1310
1311    #[test]
1312    fn each_manager_runs_a_pinned_package_binary_its_own_way() {
1313        let typescript = crate::tools::pins::typescript_spec();
1314        let args = |m: PackageManager| m.runner_args(&typescript, "tsc");
1315        assert_eq!(
1316            args(PackageManager::Npm),
1317            ["--yes", "-p", typescript.as_str(), "tsc"]
1318        );
1319        assert_eq!(
1320            args(PackageManager::Pnpm),
1321            ["dlx", "--package", typescript.as_str(), "tsc"]
1322        );
1323        assert_eq!(
1324            args(PackageManager::Bun),
1325            ["--package", typescript.as_str(), "tsc"]
1326        );
1327        assert!(args(PackageManager::Yarn).is_empty());
1328        let programs = PackageManager::ALL.map(PackageManager::runner_program);
1329        assert_eq!(programs, [Some("npx"), Some("pnpm"), Some("bunx"), None]);
1330        let labels = PackageManager::ALL.map(PackageManager::runner_label);
1331        assert_eq!(labels, [Some("npx"), Some("pnpm dlx"), Some("bunx"), None]);
1332    }
1333
1334    #[test]
1335    fn each_manager_has_its_own_install_commands() {
1336        let global = PackageManager::ALL.map(|m| m.global_install("wrangler@4"));
1337        assert_eq!(
1338            global,
1339            [
1340                "npm install -g wrangler@4",
1341                "pnpm add -g wrangler@4",
1342                "bun add -g wrangler@4",
1343                "yarn global add wrangler@4"
1344            ]
1345        );
1346        let dev = PackageManager::ALL.map(|m| m.dev_install("wrangler@4"));
1347        assert_eq!(
1348            dev,
1349            [
1350                "npm install --save-dev wrangler@4",
1351                "pnpm add -D wrangler@4",
1352                "bun add -d wrangler@4",
1353                "yarn add -D wrangler@4"
1354            ]
1355        );
1356    }
1357
1358    #[test]
1359    fn the_runner_is_the_managers_own_else_npx_else_none() {
1360        let all = Tools {
1361            path: &["pnpm", "bunx"],
1362            npx: true,
1363        };
1364        assert_eq!(
1365            PackageManager::Pnpm.runner(&all),
1366            Some(PackageManager::Pnpm)
1367        );
1368        assert_eq!(PackageManager::Bun.runner(&all), Some(PackageManager::Bun));
1369        assert_eq!(PackageManager::Npm.runner(&all), Some(PackageManager::Npm));
1370        // Yarn classic has no runner: `npx` when it is there (decision A) ...
1371        assert_eq!(PackageManager::Yarn.runner(&all), Some(PackageManager::Npm));
1372        // ... and the plain message (no runner) when it is not.
1373        let none = Tools {
1374            path: &["yarn"],
1375            npx: false,
1376        };
1377        assert_eq!(PackageManager::Yarn.runner(&none), None);
1378        // A detected tool that is not installed falls back to `npx` too.
1379        let npx_only = Tools {
1380            path: &[],
1381            npx: true,
1382        };
1383        assert_eq!(
1384            PackageManager::Pnpm.runner(&npx_only),
1385            Some(PackageManager::Npm)
1386        );
1387        assert_eq!(PackageManager::Bun.runner(&none), None);
1388    }
1389
1390    #[test]
1391    fn tool_manager_reuses_detection_and_defaults_to_npm() {
1392        let pnpm = Fake {
1393            files: BTreeMap::from([("pnpm-lock.yaml", String::new())]),
1394            ..Fake::default()
1395        };
1396        assert_eq!(tool_manager(&pnpm, None, &pnpm), PackageManager::Pnpm);
1397        // Nothing detected, or an unknown setting: today's npm behaviour.
1398        let empty = Fake::default();
1399        assert_eq!(tool_manager(&empty, None, &empty), PackageManager::Npm);
1400        assert_eq!(
1401            tool_manager(&empty, Some("nope"), &empty),
1402            PackageManager::Npm
1403        );
1404    }
1405
1406    /// The real tools, where installed: the flags in the issue run the pinned
1407    /// TypeScript ([`crate::tools::pins::typescript_spec`]) for real. Skips
1408    /// cleanly when the tool is absent.
1409    #[test]
1410    fn real_runners_run_a_pinned_tsc() {
1411        if std::env::var_os("BYNK_REAL_RUNNERS").is_none() {
1412            eprintln!("skipping: set BYNK_REAL_RUNNERS=1 to download and run each tool");
1413            return;
1414        }
1415        for manager in [
1416            PackageManager::Pnpm,
1417            PackageManager::Bun,
1418            PackageManager::Npm,
1419        ] {
1420            let program = manager.runner_program().expect("a runner");
1421            let Ok(path) = which::which(program) else {
1422                eprintln!("skipping {}: not installed", manager.name());
1423                continue;
1424            };
1425            let out = Command::new(path)
1426                .args(manager.runner_args(&crate::tools::pins::typescript_spec(), "tsc"))
1427                .arg("--version")
1428                .output()
1429                .expect("runs");
1430            let text = String::from_utf8_lossy(&out.stdout);
1431            let version = format!("Version {}.", bynk_emit::TYPESCRIPT_MAJOR_TESTED);
1432            assert!(
1433                out.status.success() && text.contains(&version),
1434                "{}: {text}",
1435                manager.name()
1436            );
1437        }
1438    }
1439}