Skip to main content

brrrty_node/
find.rs

1//! Which Node runs the data: `BRRRTY_NODE` when set, else `node` on `PATH`.
2
3use std::ffi::{OsStr, OsString};
4use std::io::Read;
5use std::path::{Path, PathBuf};
6use std::process::{Command, Stdio};
7use std::time::{Duration, Instant};
8
9/// 11ty 3's own floor.
10pub const MIN_NODE: (u32, u32, u32) = (18, 0, 0);
11
12/// How long `node -p` may take to say what it is.
13const PROBE_LIMIT: Duration = Duration::from_secs(5);
14
15/// A Node that can run the worker.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct NodeInfo {
18    /// As given (`BRRRTY_NODE`) or found on `PATH`.
19    pub path: PathBuf,
20    pub version: (u32, u32, u32),
21    /// `process.versions.tz`, the time zone data it formats dates with.
22    pub tz: String,
23    /// `process.versions.icu`.
24    pub icu: String,
25    /// `module.registerHooks` exists (22.15 and later), so the worker can
26    /// record every module it loads.
27    pub load_hooks: bool,
28}
29
30impl NodeInfo {
31    /// `v24.22.3`.
32    pub fn version_text(&self) -> String {
33        let (a, b, c) = self.version;
34        format!("v{a}.{b}.{c}")
35    }
36}
37
38/// Why there is no Node to run the data with.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub enum NodeMissing {
41    /// Nothing ran: each place tried, as shown to the user.
42    NotFound { tried: Vec<String> },
43    /// Older than 18.0.0.
44    TooOld { path: PathBuf, version: String },
45    /// It ran, but didn't answer as Node does.
46    Broken { path: PathBuf, stderr: String },
47}
48
49impl std::fmt::Display for NodeMissing {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        match self {
52            NodeMissing::NotFound { tried } => {
53                write!(f, "Node not found (tried {})", tried.join(", "))
54            }
55            NodeMissing::TooOld { path, version } => write!(
56                f,
57                "Node {version} at {} is too old: JavaScript data needs Node 18 or later",
58                path.display()
59            ),
60            NodeMissing::Broken { path, stderr } => {
61                write!(
62                    f,
63                    "{} didn't run as Node: {}",
64                    path.display(),
65                    stderr.trim()
66                )
67            }
68        }
69    }
70}
71
72/// Find Node: `env_override` (the value of `BRRRTY_NODE`) when set, else
73/// `node` on `PATH`.
74pub fn find_node(env_override: Option<&OsStr>) -> Result<NodeInfo, NodeMissing> {
75    let (program, tried): (OsString, Vec<String>) = match env_override {
76        Some(p) if !p.is_empty() => (
77            p.to_os_string(),
78            vec![format!("BRRRTY_NODE={}", p.to_string_lossy())],
79        ),
80        _ => ("node".into(), vec!["node on PATH".to_string()]),
81    };
82    // The last item names the runtime: Bun and Deno answer like Node, but
83    // load modules and read files their own way.
84    let script = r#"process.stdout.write(JSON.stringify([process.version, process.versions.tz || "", process.versions.icu || "", typeof require("node:module").registerHooks, process.versions.bun ? "Bun" : process.versions.deno ? "Deno" : (process.release && process.release.name) || ""]))"#;
85    let mut child = match Command::new(&program)
86        .args(["-e", script])
87        .stdin(Stdio::null())
88        .stdout(Stdio::piped())
89        .stderr(Stdio::piped())
90        .spawn()
91    {
92        Ok(c) => c,
93        Err(_) => return Err(NodeMissing::NotFound { tried }),
94    };
95    let path = PathBuf::from(&program);
96    let start = Instant::now();
97    let status = loop {
98        match child.try_wait() {
99            Ok(Some(s)) => break s,
100            Ok(None) if start.elapsed() < PROBE_LIMIT => {
101                std::thread::sleep(Duration::from_millis(10))
102            }
103            _ => {
104                let _ = child.kill();
105                let _ = child.wait();
106                return Err(NodeMissing::Broken {
107                    path,
108                    stderr: format!("no answer within {} s", PROBE_LIMIT.as_secs()),
109                });
110            }
111        }
112    };
113    let mut stdout = String::new();
114    let mut stderr = String::new();
115    if let Some(mut s) = child.stdout.take() {
116        let _ = s.read_to_string(&mut stdout);
117    }
118    if let Some(mut s) = child.stderr.take() {
119        let _ = s.read_to_string(&mut stderr);
120    }
121    if !status.success() {
122        return Err(NodeMissing::Broken { path, stderr });
123    }
124    parse_probe(&path, &stdout).ok_or(NodeMissing::Broken {
125        path: path.clone(),
126        stderr: format!("unexpected answer: {}", stdout.trim()),
127    })?
128}
129
130fn parse_probe(path: &Path, stdout: &str) -> Option<Result<NodeInfo, NodeMissing>> {
131    let v: serde_json::Value = serde_json::from_str(stdout.trim()).ok()?;
132    let a = v.as_array()?;
133    let runtime = a.get(4)?.as_str()?;
134    if runtime != "node" {
135        return Some(Err(NodeMissing::Broken {
136            path: path.to_path_buf(),
137            stderr: format!("it is {runtime}, which runs JavaScript differently from Node"),
138        }));
139    }
140    let version_text = a.first()?.as_str()?;
141    let version = parse_version(version_text)?;
142    if version < MIN_NODE {
143        return Some(Err(NodeMissing::TooOld {
144            path: path.to_path_buf(),
145            version: version_text.to_string(),
146        }));
147    }
148    Some(Ok(NodeInfo {
149        path: path.to_path_buf(),
150        version,
151        tz: a.get(1)?.as_str()?.to_string(),
152        icu: a.get(2)?.as_str()?.to_string(),
153        load_hooks: a.get(3)?.as_str()? == "function",
154    }))
155}
156
157/// `v24.22.3` (or `24.22.3`) as numbers.
158pub fn parse_version(text: &str) -> Option<(u32, u32, u32)> {
159    let t = text.trim().strip_prefix('v').unwrap_or(text.trim());
160    let mut parts = t.split(['.', '-']);
161    Some((
162        parts.next()?.parse().ok()?,
163        parts.next()?.parse().ok()?,
164        parts.next()?.parse().ok()?,
165    ))
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    #[test]
173    fn versions_parse() {
174        assert_eq!(parse_version("v24.22.3"), Some((24, 22, 3)));
175        assert_eq!(parse_version("18.0.0"), Some((18, 0, 0)));
176        assert_eq!(parse_version("v26.0.0-nightly"), Some((26, 0, 0)));
177        assert_eq!(parse_version("x"), None);
178    }
179
180    #[test]
181    fn an_old_node_is_too_old() {
182        let r = parse_probe(
183            Path::new("n"),
184            r#"["v16.20.2","2023c","73.1","undefined","node"]"#,
185        );
186        assert!(matches!(r, Some(Err(NodeMissing::TooOld { .. }))));
187        let r = parse_probe(
188            Path::new("n"),
189            r#"["v22.15.0","2025a","76.1","function","node"]"#,
190        );
191        assert!(matches!(
192            r,
193            Some(Ok(NodeInfo {
194                load_hooks: true,
195                ..
196            }))
197        ));
198    }
199
200    #[test]
201    fn a_runtime_that_only_answers_like_node_is_not_node() {
202        let r = parse_probe(
203            Path::new("bun"),
204            r#"["v24.3.0","2025b","77.1","function","Bun"]"#,
205        );
206        match r {
207            Some(Err(NodeMissing::Broken { stderr, .. })) => assert!(stderr.contains("Bun")),
208            other => panic!("{other:?}"),
209        }
210    }
211}