1use anyhow::{anyhow, bail, Context, Result};
2use async_compression::futures::bufread::GzipDecoder;
3use async_tar::Archive;
4use serde::Deserialize;
5use smol::{fs, io::BufReader, lock::Mutex, process::Command};
6use std::process::{Output, Stdio};
7use std::{
8 env::consts,
9 path::{Path, PathBuf},
10 sync::Arc,
11};
12use util::http::HttpClient;
13
14const VERSION: &str = "v18.15.0";
15
16#[derive(Debug, Deserialize)]
17#[serde(rename_all = "kebab-case")]
18pub struct NpmInfo {
19 #[serde(default)]
20 dist_tags: NpmInfoDistTags,
21 versions: Vec<String>,
22}
23
24#[derive(Debug, Deserialize, Default)]
25pub struct NpmInfoDistTags {
26 latest: Option<String>,
27}
28
29#[async_trait::async_trait]
30pub trait NodeRuntime: Send + Sync {
31 async fn binary_path(&self) -> Result<PathBuf>;
32
33 async fn run_npm_subcommand(
34 &self,
35 directory: Option<&Path>,
36 subcommand: &str,
37 args: &[&str],
38 ) -> Result<Output>;
39
40 async fn npm_package_latest_version(&self, name: &str) -> Result<String>;
41
42 async fn npm_install_packages(&self, directory: &Path, packages: &[(&str, &str)])
43 -> Result<()>;
44}
45
46pub struct RealNodeRuntime {
47 http: Arc<dyn HttpClient>,
48 installation_lock: Mutex<()>,
49}
50
51impl RealNodeRuntime {
52 pub fn new(http: Arc<dyn HttpClient>) -> Arc<dyn NodeRuntime> {
53 Arc::new(RealNodeRuntime {
54 http,
55 installation_lock: Mutex::new(()),
56 })
57 }
58
59 async fn install_if_needed(&self) -> Result<PathBuf> {
60 let _lock = self.installation_lock.lock().await;
61 log::info!("Node runtime install_if_needed");
62
63 let arch = match consts::ARCH {
64 "x86_64" => "x64",
65 "aarch64" => "arm64",
66 other => bail!("Running on unsupported platform: {other}"),
67 };
68
69 let folder_name = format!("node-{VERSION}-darwin-{arch}");
70 let node_containing_dir = util::paths::SUPPORT_DIR.join("node");
71 let node_dir = node_containing_dir.join(folder_name);
72 let node_binary = node_dir.join("bin/node");
73 let npm_file = node_dir.join("bin/npm");
74
75 let result = Command::new(&node_binary)
76 .env_clear()
77 .arg(npm_file)
78 .arg("--version")
79 .stdin(Stdio::null())
80 .stdout(Stdio::null())
81 .stderr(Stdio::null())
82 .args(["--cache".into(), node_dir.join("cache")])
83 .args(["--userconfig".into(), node_dir.join("blank_user_npmrc")])
84 .args(["--globalconfig".into(), node_dir.join("blank_global_npmrc")])
85 .status()
86 .await;
87 let valid = matches!(result, Ok(status) if status.success());
88
89 if !valid {
90 _ = fs::remove_dir_all(&node_containing_dir).await;
91 fs::create_dir(&node_containing_dir)
92 .await
93 .context("error creating node containing dir")?;
94
95 let file_name = format!("node-{VERSION}-darwin-{arch}.tar.gz");
96 let url = format!("https://nodejs.org/dist/{VERSION}/{file_name}");
97 let mut response = self
98 .http
99 .get(&url, Default::default(), true)
100 .await
101 .context("error downloading Node binary tarball")?;
102
103 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
104 let archive = Archive::new(decompressed_bytes);
105 archive.unpack(&node_containing_dir).await?;
106 }
107
108 // Note: Not in the `if !valid {}` so we can populate these for existing installations
109 _ = fs::create_dir(node_dir.join("cache")).await;
110 _ = fs::write(node_dir.join("blank_user_npmrc"), []).await;
111 _ = fs::write(node_dir.join("blank_global_npmrc"), []).await;
112
113 anyhow::Ok(node_dir)
114 }
115}
116
117#[async_trait::async_trait]
118impl NodeRuntime for RealNodeRuntime {
119 async fn binary_path(&self) -> Result<PathBuf> {
120 let installation_path = self.install_if_needed().await?;
121 Ok(installation_path.join("bin/node"))
122 }
123
124 async fn run_npm_subcommand(
125 &self,
126 directory: Option<&Path>,
127 subcommand: &str,
128 args: &[&str],
129 ) -> Result<Output> {
130 let attempt = || async move {
131 let installation_path = self.install_if_needed().await?;
132
133 let mut env_path = installation_path.join("bin").into_os_string();
134 if let Some(existing_path) = std::env::var_os("PATH") {
135 if !existing_path.is_empty() {
136 env_path.push(":");
137 env_path.push(&existing_path);
138 }
139 }
140
141 let node_binary = installation_path.join("bin/node");
142 let npm_file = installation_path.join("bin/npm");
143
144 if smol::fs::metadata(&node_binary).await.is_err() {
145 return Err(anyhow!("missing node binary file"));
146 }
147
148 if smol::fs::metadata(&npm_file).await.is_err() {
149 return Err(anyhow!("missing npm file"));
150 }
151
152 let mut command = Command::new(node_binary);
153 command.env_clear();
154 command.env("PATH", env_path);
155 command.arg(npm_file).arg(subcommand);
156 command.args(["--cache".into(), installation_path.join("cache")]);
157 command.args([
158 "--userconfig".into(),
159 installation_path.join("blank_user_npmrc"),
160 ]);
161 command.args([
162 "--globalconfig".into(),
163 installation_path.join("blank_global_npmrc"),
164 ]);
165 command.args(args);
166
167 if let Some(directory) = directory {
168 command.current_dir(directory);
169 }
170
171 command.output().await.map_err(|e| anyhow!("{e}"))
172 };
173
174 let mut output = attempt().await;
175 if output.is_err() {
176 output = attempt().await;
177 if output.is_err() {
178 return Err(anyhow!(
179 "failed to launch npm subcommand {subcommand} subcommand"
180 ));
181 }
182 }
183
184 if let Ok(output) = &output {
185 if !output.status.success() {
186 return Err(anyhow!(
187 "failed to execute npm {subcommand} subcommand:\nstdout: {:?}\nstderr: {:?}",
188 String::from_utf8_lossy(&output.stdout),
189 String::from_utf8_lossy(&output.stderr)
190 ));
191 }
192 }
193
194 output.map_err(|e| anyhow!("{e}"))
195 }
196
197 async fn npm_package_latest_version(&self, name: &str) -> Result<String> {
198 let output = self
199 .run_npm_subcommand(
200 None,
201 "info",
202 &[
203 name,
204 "--json",
205 "--fetch-retry-mintimeout",
206 "2000",
207 "--fetch-retry-maxtimeout",
208 "5000",
209 "--fetch-timeout",
210 "5000",
211 ],
212 )
213 .await?;
214
215 let mut info: NpmInfo = serde_json::from_slice(&output.stdout)?;
216 info.dist_tags
217 .latest
218 .or_else(|| info.versions.pop())
219 .ok_or_else(|| anyhow!("no version found for npm package {}", name))
220 }
221
222 async fn npm_install_packages(
223 &self,
224 directory: &Path,
225 packages: &[(&str, &str)],
226 ) -> Result<()> {
227 let packages: Vec<_> = packages
228 .into_iter()
229 .map(|(name, version)| format!("{name}@{version}"))
230 .collect();
231
232 let mut arguments: Vec<_> = packages.iter().map(|p| p.as_str()).collect();
233 arguments.extend_from_slice(&[
234 "--fetch-retry-mintimeout",
235 "2000",
236 "--fetch-retry-maxtimeout",
237 "5000",
238 "--fetch-timeout",
239 "5000",
240 ]);
241
242 self.run_npm_subcommand(Some(directory), "install", &arguments)
243 .await?;
244 Ok(())
245 }
246}
247
248pub struct FakeNodeRuntime;
249
250impl FakeNodeRuntime {
251 pub fn new() -> Arc<dyn NodeRuntime> {
252 Arc::new(Self)
253 }
254}
255
256#[async_trait::async_trait]
257impl NodeRuntime for FakeNodeRuntime {
258 async fn binary_path(&self) -> anyhow::Result<PathBuf> {
259 unreachable!()
260 }
261
262 async fn run_npm_subcommand(
263 &self,
264 _: Option<&Path>,
265 subcommand: &str,
266 args: &[&str],
267 ) -> anyhow::Result<Output> {
268 unreachable!("Should not run npm subcommand '{subcommand}' with args {args:?}")
269 }
270
271 async fn npm_package_latest_version(&self, name: &str) -> anyhow::Result<String> {
272 unreachable!("Should not query npm package '{name}' for latest version")
273 }
274
275 async fn npm_install_packages(
276 &self,
277 _: &Path,
278 packages: &[(&str, &str)],
279 ) -> anyhow::Result<()> {
280 unreachable!("Should not install packages {packages:?}")
281 }
282}