1use anyhow::{anyhow, bail, Context, Result};
2use async_compression::futures::bufread::GzipDecoder;
3use async_tar::Archive;
4use futures::lock::Mutex;
5use futures::{future::Shared, FutureExt};
6use gpui::{executor::Background, Task};
7use serde::Deserialize;
8use smol::{fs, io::BufReader, process::Command};
9use std::process::{Output, Stdio};
10use std::{
11 env::consts,
12 path::{Path, PathBuf},
13 sync::{Arc, OnceLock},
14};
15use util::http::HttpClient;
16
17const VERSION: &str = "v18.15.0";
18
19static RUNTIME_INSTANCE: OnceLock<Arc<NodeRuntime>> = OnceLock::new();
20
21#[derive(Debug, Deserialize)]
22#[serde(rename_all = "kebab-case")]
23pub struct NpmInfo {
24 #[serde(default)]
25 dist_tags: NpmInfoDistTags,
26 versions: Vec<String>,
27}
28
29#[derive(Debug, Deserialize, Default)]
30pub struct NpmInfoDistTags {
31 latest: Option<String>,
32}
33
34pub struct NodeRuntime {
35 http: Arc<dyn HttpClient>,
36 background: Arc<Background>,
37 installation_path: Mutex<Option<Shared<Task<Result<PathBuf, Arc<anyhow::Error>>>>>>,
38}
39
40impl NodeRuntime {
41 pub fn instance(http: Arc<dyn HttpClient>, background: Arc<Background>) -> Arc<NodeRuntime> {
42 RUNTIME_INSTANCE
43 .get_or_init(|| {
44 Arc::new(NodeRuntime {
45 http,
46 background,
47 installation_path: Mutex::new(None),
48 })
49 })
50 .clone()
51 }
52
53 pub async fn binary_path(&self) -> Result<PathBuf> {
54 let installation_path = self.install_if_needed().await?;
55 Ok(installation_path.join("bin/node"))
56 }
57
58 pub async fn run_npm_subcommand(
59 &self,
60 directory: Option<&Path>,
61 subcommand: &str,
62 args: &[&str],
63 ) -> Result<Output> {
64 let attempt = |installation_path: PathBuf| async move {
65 let node_binary = installation_path.join("bin/node");
66 let npm_file = installation_path.join("bin/npm");
67
68 if smol::fs::metadata(&node_binary).await.is_err() {
69 return Err(anyhow!("missing node binary file"));
70 }
71
72 if smol::fs::metadata(&npm_file).await.is_err() {
73 return Err(anyhow!("missing npm file"));
74 }
75
76 let mut command = Command::new(node_binary);
77 command.arg(npm_file).arg(subcommand).args(args);
78
79 if let Some(directory) = directory {
80 command.current_dir(directory);
81 }
82
83 command.output().await.map_err(|e| anyhow!("{e}"))
84 };
85
86 let installation_path = self.install_if_needed().await?;
87 let mut output = attempt(installation_path.clone()).await;
88 if output.is_err() {
89 output = attempt(installation_path).await;
90 if output.is_err() {
91 return Err(anyhow!(
92 "failed to launch npm subcommand {subcommand} subcommand"
93 ));
94 }
95 }
96
97 if let Ok(output) = &output {
98 if !output.status.success() {
99 return Err(anyhow!(
100 "failed to execute npm {subcommand} subcommand:\nstdout: {:?}\nstderr: {:?}",
101 String::from_utf8_lossy(&output.stdout),
102 String::from_utf8_lossy(&output.stderr)
103 ));
104 }
105 }
106
107 output.map_err(|e| anyhow!("{e}"))
108 }
109
110 pub async fn npm_package_latest_version(&self, name: &str) -> Result<String> {
111 let output = self
112 .run_npm_subcommand(
113 None,
114 "info",
115 &[
116 name,
117 "--json",
118 "-fetch-retry-mintimeout",
119 "2000",
120 "-fetch-retry-maxtimeout",
121 "5000",
122 "-fetch-timeout",
123 "5000",
124 ],
125 )
126 .await?;
127
128 let mut info: NpmInfo = serde_json::from_slice(&output.stdout)?;
129 info.dist_tags
130 .latest
131 .or_else(|| info.versions.pop())
132 .ok_or_else(|| anyhow!("no version found for npm package {}", name))
133 }
134
135 pub async fn npm_install_packages(
136 &self,
137 directory: &Path,
138 packages: impl IntoIterator<Item = (&str, &str)>,
139 ) -> Result<()> {
140 let packages: Vec<_> = packages
141 .into_iter()
142 .map(|(name, version)| format!("{name}@{version}"))
143 .collect();
144
145 let mut arguments: Vec<_> = packages.iter().map(|p| p.as_str()).collect();
146 arguments.extend_from_slice(&[
147 "-fetch-retry-mintimeout",
148 "2000",
149 "-fetch-retry-maxtimeout",
150 "5000",
151 "-fetch-timeout",
152 "5000",
153 ]);
154
155 self.run_npm_subcommand(Some(directory), "install", &arguments)
156 .await?;
157 Ok(())
158 }
159
160 async fn install_if_needed(&self) -> Result<PathBuf> {
161 let task = self
162 .installation_path
163 .lock()
164 .await
165 .get_or_insert_with(|| {
166 let http = self.http.clone();
167 self.background
168 .spawn(async move { Self::install(http).await.map_err(Arc::new) })
169 .shared()
170 })
171 .clone();
172
173 task.await.map_err(|e| anyhow!("{}", e))
174 }
175
176 async fn install(http: Arc<dyn HttpClient>) -> Result<PathBuf> {
177 log::info!("installing Node runtime");
178 let arch = match consts::ARCH {
179 "x86_64" => "x64",
180 "aarch64" => "arm64",
181 other => bail!("Running on unsupported platform: {other}"),
182 };
183
184 let folder_name = format!("node-{VERSION}-darwin-{arch}");
185 let node_containing_dir = util::paths::SUPPORT_DIR.join("node");
186 let node_dir = node_containing_dir.join(folder_name);
187 let node_binary = node_dir.join("bin/node");
188 let npm_file = node_dir.join("bin/npm");
189
190 let result = Command::new(&node_binary)
191 .arg(npm_file)
192 .arg("--version")
193 .stdin(Stdio::null())
194 .stdout(Stdio::null())
195 .stderr(Stdio::null())
196 .status()
197 .await;
198 let valid = matches!(result, Ok(status) if status.success());
199
200 if !valid {
201 _ = fs::remove_dir_all(&node_containing_dir).await;
202 fs::create_dir(&node_containing_dir)
203 .await
204 .context("error creating node containing dir")?;
205
206 let file_name = format!("node-{VERSION}-darwin-{arch}.tar.gz");
207 let url = format!("https://nodejs.org/dist/{VERSION}/{file_name}");
208 let mut response = http
209 .get(&url, Default::default(), true)
210 .await
211 .context("error downloading Node binary tarball")?;
212
213 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
214 let archive = Archive::new(decompressed_bytes);
215 archive.unpack(&node_containing_dir).await?;
216 }
217
218 anyhow::Ok(node_dir)
219 }
220}