1use anyhow::{Context as _, Result, anyhow, bail};
2use async_compression::futures::bufread::GzipDecoder;
3use async_tar::Archive;
4use futures::{AsyncReadExt, FutureExt as _, channel::oneshot, future::Shared};
5use http_client::{Host, HttpClient, Url};
6use log::Level;
7use semver::Version;
8use serde::Deserialize;
9use smol::io::BufReader;
10use smol::{fs, lock::Mutex};
11use std::fmt::Display;
12use std::future::Future;
13use std::pin::Pin;
14use std::{
15 env::{self, consts},
16 ffi::OsString,
17 io,
18 net::{IpAddr, Ipv4Addr},
19 path::{Path, PathBuf},
20 process::Output,
21 sync::Arc,
22};
23use util::ResultExt;
24use util::archive::extract_zip;
25
26const NODE_CA_CERTS_ENV_VAR: &str = "NODE_EXTRA_CA_CERTS";
27
28#[derive(Clone, Debug, Default, Eq, PartialEq)]
29pub struct NodeBinaryOptions {
30 pub allow_path_lookup: bool,
31 pub allow_binary_download: bool,
32 pub use_paths: Option<(PathBuf, PathBuf)>,
33}
34
35pub enum VersionStrategy<'a> {
36 /// Install if current version doesn't match pinned version
37 Pin(&'a Version),
38 /// Install if current version is older than latest version
39 Latest(&'a Version),
40}
41
42#[derive(Clone)]
43pub struct NodeRuntime(Arc<Mutex<NodeRuntimeState>>);
44
45struct NodeRuntimeState {
46 http: Arc<dyn HttpClient>,
47 instance: Option<Box<dyn NodeRuntimeTrait>>,
48 last_options: Option<NodeBinaryOptions>,
49 options: watch::Receiver<Option<NodeBinaryOptions>>,
50 shell_env_loaded: Shared<oneshot::Receiver<()>>,
51 trust_task: Option<Pin<Box<dyn Future<Output = ()> + Send>>>,
52}
53
54impl NodeRuntime {
55 pub fn new(
56 http: Arc<dyn HttpClient>,
57 shell_env_loaded: Option<oneshot::Receiver<()>>,
58 options: watch::Receiver<Option<NodeBinaryOptions>>,
59 trust_task: Option<Pin<Box<dyn Future<Output = ()> + Send>>>,
60 ) -> Self {
61 NodeRuntime(Arc::new(Mutex::new(NodeRuntimeState {
62 http,
63 trust_task,
64 instance: None,
65 last_options: None,
66 options,
67 shell_env_loaded: shell_env_loaded.unwrap_or(oneshot::channel().1).shared(),
68 })))
69 }
70
71 pub fn unavailable() -> Self {
72 NodeRuntime(Arc::new(Mutex::new(NodeRuntimeState {
73 http: Arc::new(http_client::BlockedHttpClient),
74 instance: None,
75 last_options: None,
76 options: watch::channel(Some(NodeBinaryOptions::default())).1,
77 shell_env_loaded: oneshot::channel().1.shared(),
78 trust_task: None,
79 })))
80 }
81
82 async fn instance(&self) -> Box<dyn NodeRuntimeTrait> {
83 let mut state = self.0.lock().await;
84 if let Some(trust_task) = state.trust_task.take() {
85 trust_task.await;
86 }
87
88 let options = loop {
89 if let Some(options) = state.options.borrow().as_ref() {
90 break options.clone();
91 }
92 match state.options.changed().await {
93 Ok(()) => {}
94 // failure case not cached
95 Err(err) => {
96 return Box::new(UnavailableNodeRuntime {
97 error_message: err.to_string().into(),
98 });
99 }
100 }
101 };
102
103 if state.last_options.as_ref() != Some(&options) {
104 state.instance.take();
105 }
106 if let Some(instance) = state.instance.as_ref() {
107 return instance.boxed_clone();
108 }
109
110 if let Some((node, npm)) = options.use_paths.as_ref() {
111 let instance = match SystemNodeRuntime::new(node.clone(), npm.clone()).await {
112 Ok(instance) => {
113 log::info!("using Node.js from `node.path` in settings: {:?}", instance);
114 Box::new(instance)
115 }
116 Err(err) => {
117 // failure case not cached, since it's cheap to check again
118 return Box::new(UnavailableNodeRuntime {
119 error_message: format!(
120 "failure checking Node.js from `node.path` in settings ({}): {:?}",
121 node.display(),
122 err
123 )
124 .into(),
125 });
126 }
127 };
128 state.instance = Some(instance.boxed_clone());
129 state.last_options = Some(options);
130 return instance;
131 }
132
133 let system_node_error = if options.allow_path_lookup {
134 state.shell_env_loaded.clone().await.ok();
135 match SystemNodeRuntime::detect().await {
136 Ok(instance) => {
137 log::info!("using Node.js found on PATH: {:?}", instance);
138 state.instance = Some(instance.boxed_clone());
139 state.last_options = Some(options);
140 return Box::new(instance);
141 }
142 Err(err) => Some(err),
143 }
144 } else {
145 None
146 };
147
148 let instance = if options.allow_binary_download {
149 let (log_level, why_using_managed) = match system_node_error {
150 Some(err @ DetectError::Other(_)) => (Level::Warn, err.to_string()),
151 Some(err @ DetectError::NotInPath(_)) => (Level::Info, err.to_string()),
152 None => (
153 Level::Info,
154 "`node.ignore_system_version` is `true` in settings".to_string(),
155 ),
156 };
157 match ManagedNodeRuntime::install_if_needed(&state.http).await {
158 Ok(instance) => {
159 log::log!(
160 log_level,
161 "using Zed managed Node.js at {} since {}",
162 instance.installation_path.display(),
163 why_using_managed
164 );
165 Box::new(instance) as Box<dyn NodeRuntimeTrait>
166 }
167 Err(err) => {
168 // failure case is cached, since downloading + installing may be expensive. The
169 // downside of this is that it may fail due to an intermittent network issue.
170 //
171 // TODO: Have `install_if_needed` indicate which failure cases are retryable
172 // and/or have shared tracking of when internet is available.
173 Box::new(UnavailableNodeRuntime {
174 error_message: format!(
175 "failure while downloading and/or installing Zed managed Node.js, \
176 restart Zed to retry: {}",
177 err
178 )
179 .into(),
180 }) as Box<dyn NodeRuntimeTrait>
181 }
182 }
183 } else if let Some(system_node_error) = system_node_error {
184 // failure case not cached, since it's cheap to check again
185 //
186 // TODO: When support is added for setting `options.allow_binary_download`, update this
187 // error message.
188 return Box::new(UnavailableNodeRuntime {
189 error_message: format!(
190 "failure while checking system Node.js from PATH: {}",
191 system_node_error
192 )
193 .into(),
194 });
195 } else {
196 // failure case is cached because it will always happen with these options
197 //
198 // TODO: When support is added for setting `options.allow_binary_download`, update this
199 // error message.
200 Box::new(UnavailableNodeRuntime {
201 error_message: "`node` settings do not allow any way to use Node.js"
202 .to_string()
203 .into(),
204 })
205 };
206
207 state.instance = Some(instance.boxed_clone());
208 state.last_options = Some(options);
209 instance
210 }
211
212 pub async fn binary_path(&self) -> Result<PathBuf> {
213 self.instance().await.binary_path()
214 }
215
216 pub async fn run_npm_subcommand(
217 &self,
218 directory: Option<&Path>,
219 subcommand: &str,
220 args: &[&str],
221 ) -> Result<Output> {
222 let http = self.0.lock().await.http.clone();
223 self.instance()
224 .await
225 .run_npm_subcommand(directory, http.proxy(), subcommand, args)
226 .await
227 }
228
229 pub async fn npm_package_installed_version(
230 &self,
231 local_package_directory: &Path,
232 name: &str,
233 ) -> Result<Option<Version>> {
234 self.instance()
235 .await
236 .npm_package_installed_version(local_package_directory, name)
237 .await
238 }
239
240 pub async fn npm_package_latest_version(&self, name: &str) -> Result<Version> {
241 let http = self.0.lock().await.http.clone();
242 let output = self
243 .instance()
244 .await
245 .run_npm_subcommand(
246 None,
247 http.proxy(),
248 "info",
249 &[
250 name,
251 "--json",
252 "--fetch-retry-mintimeout",
253 "2000",
254 "--fetch-retry-maxtimeout",
255 "5000",
256 "--fetch-timeout",
257 "5000",
258 ],
259 )
260 .await?;
261
262 let mut info: NpmInfo = serde_json::from_slice(&output.stdout)?;
263 info.dist_tags
264 .latest
265 .or_else(|| info.versions.pop())
266 .with_context(|| format!("no version found for npm package {name}"))
267 }
268
269 pub async fn npm_install_packages(
270 &self,
271 directory: &Path,
272 packages: &[(&str, &str)],
273 ) -> Result<()> {
274 if packages.is_empty() {
275 return Ok(());
276 }
277
278 let packages: Vec<_> = packages
279 .iter()
280 .map(|(name, version)| format!("{name}@{version}"))
281 .collect();
282
283 let arguments: Vec<_> = packages
284 .iter()
285 .map(|p| p.as_str())
286 .chain([
287 "--save-exact",
288 "--fetch-retry-mintimeout",
289 "2000",
290 "--fetch-retry-maxtimeout",
291 "5000",
292 "--fetch-timeout",
293 "5000",
294 ])
295 .collect();
296
297 // This is also wrong because the directory is wrong.
298 self.run_npm_subcommand(Some(directory), "install", &arguments)
299 .await?;
300 Ok(())
301 }
302
303 pub async fn should_install_npm_package(
304 &self,
305 package_name: &str,
306 local_executable_path: &Path,
307 local_package_directory: &Path,
308 version_strategy: VersionStrategy<'_>,
309 ) -> bool {
310 // In the case of the local system not having the package installed,
311 // or in the instances where we fail to parse package.json data,
312 // we attempt to install the package.
313 if fs::metadata(local_executable_path).await.is_err() {
314 return true;
315 }
316
317 let Some(installed_version) = self
318 .npm_package_installed_version(local_package_directory, package_name)
319 .await
320 .log_err()
321 .flatten()
322 else {
323 return true;
324 };
325
326 match version_strategy {
327 VersionStrategy::Pin(pinned_version) => &installed_version != pinned_version,
328 VersionStrategy::Latest(latest_version) => &installed_version < latest_version,
329 }
330 }
331}
332
333enum ArchiveType {
334 TarGz,
335 Zip,
336}
337
338#[derive(Debug, Deserialize)]
339#[serde(rename_all = "kebab-case")]
340pub struct NpmInfo {
341 #[serde(default)]
342 dist_tags: NpmInfoDistTags,
343 versions: Vec<Version>,
344}
345
346#[derive(Debug, Deserialize, Default)]
347pub struct NpmInfoDistTags {
348 latest: Option<Version>,
349}
350
351#[async_trait::async_trait]
352trait NodeRuntimeTrait: Send + Sync {
353 fn boxed_clone(&self) -> Box<dyn NodeRuntimeTrait>;
354 fn binary_path(&self) -> Result<PathBuf>;
355
356 async fn run_npm_subcommand(
357 &self,
358 directory: Option<&Path>,
359 proxy: Option<&Url>,
360 subcommand: &str,
361 args: &[&str],
362 ) -> Result<Output>;
363
364 async fn npm_package_installed_version(
365 &self,
366 local_package_directory: &Path,
367 name: &str,
368 ) -> Result<Option<Version>>;
369}
370
371#[derive(Clone)]
372struct ManagedNodeRuntime {
373 installation_path: PathBuf,
374}
375
376impl ManagedNodeRuntime {
377 const VERSION: &str = "v24.11.0";
378
379 #[cfg(not(windows))]
380 const NODE_PATH: &str = "bin/node";
381 #[cfg(windows)]
382 const NODE_PATH: &str = "node.exe";
383
384 #[cfg(not(windows))]
385 const NPM_PATH: &str = "bin/npm";
386 #[cfg(windows)]
387 const NPM_PATH: &str = "node_modules/npm/bin/npm-cli.js";
388
389 async fn install_if_needed(http: &Arc<dyn HttpClient>) -> Result<Self> {
390 log::info!("Node runtime install_if_needed");
391
392 let os = match consts::OS {
393 "macos" => "darwin",
394 "linux" => "linux",
395 "windows" => "win",
396 other => bail!("Running on unsupported os: {other}"),
397 };
398
399 let arch = match consts::ARCH {
400 "x86_64" => "x64",
401 "aarch64" => "arm64",
402 other => bail!("Running on unsupported architecture: {other}"),
403 };
404
405 let version = Self::VERSION;
406 let folder_name = format!("node-{version}-{os}-{arch}");
407 let node_containing_dir = paths::data_dir().join("node");
408 let node_dir = node_containing_dir.join(folder_name);
409 let node_binary = node_dir.join(Self::NODE_PATH);
410 let npm_file = node_dir.join(Self::NPM_PATH);
411 let node_ca_certs = env::var(NODE_CA_CERTS_ENV_VAR).unwrap_or_else(|_| String::new());
412
413 let valid = if fs::metadata(&node_binary).await.is_ok() {
414 let result = util::command::new_smol_command(&node_binary)
415 .env(NODE_CA_CERTS_ENV_VAR, node_ca_certs)
416 .arg(npm_file)
417 .arg("--version")
418 .args(["--cache".into(), node_dir.join("cache")])
419 .args(["--userconfig".into(), node_dir.join("blank_user_npmrc")])
420 .args(["--globalconfig".into(), node_dir.join("blank_global_npmrc")])
421 .output()
422 .await;
423 match result {
424 Ok(output) => {
425 if output.status.success() {
426 true
427 } else {
428 log::warn!(
429 "Zed managed Node.js binary at {} failed check with output: {:?}",
430 node_binary.display(),
431 output
432 );
433 false
434 }
435 }
436 Err(err) => {
437 log::warn!(
438 "Zed managed Node.js binary at {} failed check, so re-downloading it. \
439 Error: {}",
440 node_binary.display(),
441 err
442 );
443 false
444 }
445 }
446 } else {
447 false
448 };
449
450 if !valid {
451 _ = fs::remove_dir_all(&node_containing_dir).await;
452 fs::create_dir(&node_containing_dir)
453 .await
454 .context("error creating node containing dir")?;
455
456 let archive_type = match consts::OS {
457 "macos" | "linux" => ArchiveType::TarGz,
458 "windows" => ArchiveType::Zip,
459 other => bail!("Running on unsupported os: {other}"),
460 };
461
462 let version = Self::VERSION;
463 let file_name = format!(
464 "node-{version}-{os}-{arch}.{extension}",
465 extension = match archive_type {
466 ArchiveType::TarGz => "tar.gz",
467 ArchiveType::Zip => "zip",
468 }
469 );
470
471 let url = format!("https://nodejs.org/dist/{version}/{file_name}");
472 log::info!("Downloading Node.js binary from {url}");
473 let mut response = http
474 .get(&url, Default::default(), true)
475 .await
476 .context("error downloading Node binary tarball")?;
477 log::info!("Download of Node.js complete, extracting...");
478
479 let body = response.body_mut();
480 match archive_type {
481 ArchiveType::TarGz => {
482 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
483 let archive = Archive::new(decompressed_bytes);
484 archive.unpack(&node_containing_dir).await?;
485 }
486 ArchiveType::Zip => extract_zip(&node_containing_dir, body).await?,
487 }
488 log::info!("Extracted Node.js to {}", node_containing_dir.display())
489 }
490
491 // Note: Not in the `if !valid {}` so we can populate these for existing installations
492 _ = fs::create_dir(node_dir.join("cache")).await;
493 _ = fs::write(node_dir.join("blank_user_npmrc"), []).await;
494 _ = fs::write(node_dir.join("blank_global_npmrc"), []).await;
495
496 anyhow::Ok(ManagedNodeRuntime {
497 installation_path: node_dir,
498 })
499 }
500}
501
502fn path_with_node_binary_prepended(node_binary: &Path) -> Option<OsString> {
503 let existing_path = env::var_os("PATH");
504 let node_bin_dir = node_binary.parent().map(|dir| dir.as_os_str());
505 match (existing_path, node_bin_dir) {
506 (Some(existing_path), Some(node_bin_dir)) => {
507 if let Ok(joined) = env::join_paths(
508 [PathBuf::from(node_bin_dir)]
509 .into_iter()
510 .chain(env::split_paths(&existing_path)),
511 ) {
512 Some(joined)
513 } else {
514 Some(existing_path)
515 }
516 }
517 (Some(existing_path), None) => Some(existing_path),
518 (None, Some(node_bin_dir)) => Some(node_bin_dir.to_owned()),
519 _ => None,
520 }
521}
522
523#[async_trait::async_trait]
524impl NodeRuntimeTrait for ManagedNodeRuntime {
525 fn boxed_clone(&self) -> Box<dyn NodeRuntimeTrait> {
526 Box::new(self.clone())
527 }
528
529 fn binary_path(&self) -> Result<PathBuf> {
530 Ok(self.installation_path.join(Self::NODE_PATH))
531 }
532
533 async fn run_npm_subcommand(
534 &self,
535 directory: Option<&Path>,
536 proxy: Option<&Url>,
537 subcommand: &str,
538 args: &[&str],
539 ) -> Result<Output> {
540 let attempt = || async move {
541 let node_binary = self.installation_path.join(Self::NODE_PATH);
542 let npm_file = self.installation_path.join(Self::NPM_PATH);
543 let env_path = path_with_node_binary_prepended(&node_binary).unwrap_or_default();
544
545 anyhow::ensure!(
546 smol::fs::metadata(&node_binary).await.is_ok(),
547 "missing node binary file"
548 );
549 anyhow::ensure!(
550 smol::fs::metadata(&npm_file).await.is_ok(),
551 "missing npm file"
552 );
553
554 let node_ca_certs = env::var(NODE_CA_CERTS_ENV_VAR).unwrap_or_else(|_| String::new());
555
556 let mut command = util::command::new_smol_command(node_binary);
557 command.env("PATH", env_path);
558 command.env(NODE_CA_CERTS_ENV_VAR, node_ca_certs);
559 command.arg(npm_file).arg(subcommand);
560 command.arg(format!(
561 "--cache={}",
562 self.installation_path.join("cache").display()
563 ));
564 command.args([
565 "--userconfig".into(),
566 self.installation_path.join("blank_user_npmrc"),
567 ]);
568 command.args([
569 "--globalconfig".into(),
570 self.installation_path.join("blank_global_npmrc"),
571 ]);
572 command.args(args);
573 configure_npm_command(&mut command, directory, proxy);
574 command.output().await.map_err(|e| anyhow!("{e}"))
575 };
576
577 let mut output = attempt().await;
578 if output.is_err() {
579 output = attempt().await;
580 anyhow::ensure!(
581 output.is_ok(),
582 "failed to launch npm subcommand {subcommand} subcommand\nerr: {:?}",
583 output.err()
584 );
585 }
586
587 if let Ok(output) = &output {
588 anyhow::ensure!(
589 output.status.success(),
590 "failed to execute npm {subcommand} subcommand:\nstdout: {:?}\nstderr: {:?}",
591 String::from_utf8_lossy(&output.stdout),
592 String::from_utf8_lossy(&output.stderr)
593 );
594 }
595
596 output.map_err(|e| anyhow!("{e}"))
597 }
598 async fn npm_package_installed_version(
599 &self,
600 local_package_directory: &Path,
601 name: &str,
602 ) -> Result<Option<Version>> {
603 read_package_installed_version(local_package_directory.join("node_modules"), name).await
604 }
605}
606
607#[derive(Debug, Clone)]
608pub struct SystemNodeRuntime {
609 node: PathBuf,
610 npm: PathBuf,
611 global_node_modules: PathBuf,
612 scratch_dir: PathBuf,
613}
614
615impl SystemNodeRuntime {
616 const MIN_VERSION: semver::Version = Version::new(22, 0, 0);
617 async fn new(node: PathBuf, npm: PathBuf) -> Result<Self> {
618 let output = util::command::new_smol_command(&node)
619 .arg("--version")
620 .output()
621 .await
622 .with_context(|| format!("running node from {:?}", node))?;
623 if !output.status.success() {
624 anyhow::bail!(
625 "failed to run node --version. stdout: {}, stderr: {}",
626 String::from_utf8_lossy(&output.stdout),
627 String::from_utf8_lossy(&output.stderr),
628 );
629 }
630 let version_str = String::from_utf8_lossy(&output.stdout);
631 let version = semver::Version::parse(version_str.trim().trim_start_matches('v'))?;
632 if version < Self::MIN_VERSION {
633 anyhow::bail!(
634 "node at {} is too old. want: {}, got: {}",
635 node.to_string_lossy(),
636 Self::MIN_VERSION,
637 version
638 )
639 }
640
641 let scratch_dir = paths::data_dir().join("node");
642 fs::create_dir(&scratch_dir).await.ok();
643 fs::create_dir(scratch_dir.join("cache")).await.ok();
644
645 let mut this = Self {
646 node,
647 npm,
648 global_node_modules: PathBuf::default(),
649 scratch_dir,
650 };
651 let output = this.run_npm_subcommand(None, None, "root", &["-g"]).await?;
652 this.global_node_modules =
653 PathBuf::from(String::from_utf8_lossy(&output.stdout).to_string());
654
655 Ok(this)
656 }
657
658 async fn detect() -> std::result::Result<Self, DetectError> {
659 let node = which::which("node").map_err(DetectError::NotInPath)?;
660 let npm = which::which("npm").map_err(DetectError::NotInPath)?;
661 Self::new(node, npm).await.map_err(DetectError::Other)
662 }
663}
664
665enum DetectError {
666 NotInPath(which::Error),
667 Other(anyhow::Error),
668}
669
670impl Display for DetectError {
671 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
672 match self {
673 DetectError::NotInPath(err) => {
674 write!(f, "system Node.js wasn't found on PATH: {}", err)
675 }
676 DetectError::Other(err) => {
677 write!(f, "checking system Node.js failed with error: {}", err)
678 }
679 }
680 }
681}
682
683#[async_trait::async_trait]
684impl NodeRuntimeTrait for SystemNodeRuntime {
685 fn boxed_clone(&self) -> Box<dyn NodeRuntimeTrait> {
686 Box::new(self.clone())
687 }
688
689 fn binary_path(&self) -> Result<PathBuf> {
690 Ok(self.node.clone())
691 }
692
693 async fn run_npm_subcommand(
694 &self,
695 directory: Option<&Path>,
696 proxy: Option<&Url>,
697 subcommand: &str,
698 args: &[&str],
699 ) -> anyhow::Result<Output> {
700 let node_ca_certs = env::var(NODE_CA_CERTS_ENV_VAR).unwrap_or_else(|_| String::new());
701 let mut command = util::command::new_smol_command(self.npm.clone());
702 let path = path_with_node_binary_prepended(&self.node).unwrap_or_default();
703 command
704 .env("PATH", path)
705 .env(NODE_CA_CERTS_ENV_VAR, node_ca_certs)
706 .arg(subcommand)
707 .arg(format!(
708 "--cache={}",
709 self.scratch_dir.join("cache").display()
710 ))
711 .args(args);
712 configure_npm_command(&mut command, directory, proxy);
713 let output = command.output().await?;
714 anyhow::ensure!(
715 output.status.success(),
716 "failed to execute npm {subcommand} subcommand:\nstdout: {:?}\nstderr: {:?}",
717 String::from_utf8_lossy(&output.stdout),
718 String::from_utf8_lossy(&output.stderr)
719 );
720 Ok(output)
721 }
722
723 async fn npm_package_installed_version(
724 &self,
725 local_package_directory: &Path,
726 name: &str,
727 ) -> Result<Option<Version>> {
728 read_package_installed_version(local_package_directory.join("node_modules"), name).await
729 // todo: allow returning a globally installed version (requires callers not to hard-code the path)
730 }
731}
732
733pub async fn read_package_installed_version(
734 node_module_directory: PathBuf,
735 name: &str,
736) -> Result<Option<Version>> {
737 let package_json_path = node_module_directory.join(name).join("package.json");
738
739 let mut file = match fs::File::open(package_json_path).await {
740 Ok(file) => file,
741 Err(err) => {
742 if err.kind() == io::ErrorKind::NotFound {
743 return Ok(None);
744 }
745
746 Err(err)?
747 }
748 };
749
750 #[derive(Deserialize)]
751 struct PackageJson {
752 version: Version,
753 }
754
755 let mut contents = String::new();
756 file.read_to_string(&mut contents).await?;
757 let package_json: PackageJson = serde_json::from_str(&contents)?;
758 Ok(Some(package_json.version))
759}
760
761#[derive(Clone)]
762pub struct UnavailableNodeRuntime {
763 error_message: Arc<String>,
764}
765
766#[async_trait::async_trait]
767impl NodeRuntimeTrait for UnavailableNodeRuntime {
768 fn boxed_clone(&self) -> Box<dyn NodeRuntimeTrait> {
769 Box::new(self.clone())
770 }
771 fn binary_path(&self) -> Result<PathBuf> {
772 bail!("{}", self.error_message)
773 }
774
775 async fn run_npm_subcommand(
776 &self,
777 _: Option<&Path>,
778 _: Option<&Url>,
779 _: &str,
780 _: &[&str],
781 ) -> anyhow::Result<Output> {
782 bail!("{}", self.error_message)
783 }
784
785 async fn npm_package_installed_version(
786 &self,
787 _local_package_directory: &Path,
788 _: &str,
789 ) -> Result<Option<Version>> {
790 bail!("{}", self.error_message)
791 }
792}
793
794fn configure_npm_command(
795 command: &mut smol::process::Command,
796 directory: Option<&Path>,
797 proxy: Option<&Url>,
798) {
799 if let Some(directory) = directory {
800 command.current_dir(directory);
801 command.args(["--prefix".into(), directory.to_path_buf()]);
802 }
803
804 if let Some(mut proxy) = proxy.cloned() {
805 // Map proxy settings from `http://localhost:10809` to `http://127.0.0.1:10809`
806 // NodeRuntime without environment information can not parse `localhost`
807 // correctly.
808 // TODO: map to `[::1]` if we are using ipv6
809 if matches!(proxy.host(), Some(Host::Domain(domain)) if domain.eq_ignore_ascii_case("localhost"))
810 {
811 // When localhost is a valid Host, so is `127.0.0.1`
812 let _ = proxy.set_ip_host(IpAddr::V4(Ipv4Addr::LOCALHOST));
813 }
814
815 command.args(["--proxy", proxy.as_str()]);
816 }
817
818 #[cfg(windows)]
819 {
820 // SYSTEMROOT is a critical environment variables for Windows.
821 if let Some(val) = env::var("SYSTEMROOT")
822 .context("Missing environment variable: SYSTEMROOT!")
823 .log_err()
824 {
825 command.env("SYSTEMROOT", val);
826 }
827 // Without ComSpec, the post-install will always fail.
828 if let Some(val) = env::var("ComSpec")
829 .context("Missing environment variable: ComSpec!")
830 .log_err()
831 {
832 command.env("ComSpec", val);
833 }
834 }
835}
836
837#[cfg(test)]
838mod tests {
839 use http_client::Url;
840
841 use super::configure_npm_command;
842
843 // Map localhost to 127.0.0.1
844 // NodeRuntime without environment information can not parse `localhost` correctly.
845 #[test]
846 fn test_configure_npm_command_map_localhost_proxy() {
847 const CASES: [(&str, &str); 4] = [
848 // Map localhost to 127.0.0.1
849 ("http://localhost:9090/", "http://127.0.0.1:9090/"),
850 ("https://google.com/", "https://google.com/"),
851 (
852 "http://username:password@proxy.thing.com:8080/",
853 "http://username:password@proxy.thing.com:8080/",
854 ),
855 // Test when localhost is contained within a different part of the URL
856 (
857 "http://username:localhost@localhost:8080/",
858 "http://username:localhost@127.0.0.1:8080/",
859 ),
860 ];
861
862 for (proxy, mapped_proxy) in CASES {
863 let mut dummy = smol::process::Command::new("");
864 let proxy = Url::parse(proxy).unwrap();
865 configure_npm_command(&mut dummy, None, Some(&proxy));
866 let proxy = dummy
867 .get_args()
868 .skip_while(|&arg| arg != "--proxy")
869 .skip(1)
870 .next();
871 let proxy = proxy.expect("Proxy was not passed to Command correctly");
872 assert_eq!(
873 proxy, mapped_proxy,
874 "Incorrectly mapped localhost to 127.0.0.1"
875 );
876 }
877 }
878}