node_runtime.rs

  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 str),
 38    /// Install if current version is older than latest version
 39    Latest(&'a str),
 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<String>> {
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<String> {
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 mut arguments: Vec<_> = packages.iter().map(|p| p.as_str()).collect();
284        arguments.extend_from_slice(&[
285            "--save-exact",
286            "--fetch-retry-mintimeout",
287            "2000",
288            "--fetch-retry-maxtimeout",
289            "5000",
290            "--fetch-timeout",
291            "5000",
292        ]);
293
294        // This is also wrong because the directory is wrong.
295        self.run_npm_subcommand(Some(directory), "install", &arguments)
296            .await?;
297        Ok(())
298    }
299
300    pub async fn should_install_npm_package(
301        &self,
302        package_name: &str,
303        local_executable_path: &Path,
304        local_package_directory: &Path,
305        version_strategy: VersionStrategy<'_>,
306    ) -> bool {
307        // In the case of the local system not having the package installed,
308        // or in the instances where we fail to parse package.json data,
309        // we attempt to install the package.
310        if fs::metadata(local_executable_path).await.is_err() {
311            return true;
312        }
313
314        let Some(installed_version) = self
315            .npm_package_installed_version(local_package_directory, package_name)
316            .await
317            .log_err()
318            .flatten()
319        else {
320            return true;
321        };
322
323        let Some(installed_version) = Version::parse(&installed_version).log_err() else {
324            return true;
325        };
326
327        match version_strategy {
328            VersionStrategy::Pin(pinned_version) => {
329                let Some(pinned_version) = Version::parse(pinned_version).log_err() else {
330                    return true;
331                };
332                installed_version != pinned_version
333            }
334            VersionStrategy::Latest(latest_version) => {
335                let Some(latest_version) = Version::parse(latest_version).log_err() else {
336                    return true;
337                };
338                installed_version < latest_version
339            }
340        }
341    }
342}
343
344enum ArchiveType {
345    TarGz,
346    Zip,
347}
348
349#[derive(Debug, Deserialize)]
350#[serde(rename_all = "kebab-case")]
351pub struct NpmInfo {
352    #[serde(default)]
353    dist_tags: NpmInfoDistTags,
354    versions: Vec<String>,
355}
356
357#[derive(Debug, Deserialize, Default)]
358pub struct NpmInfoDistTags {
359    latest: Option<String>,
360}
361
362#[async_trait::async_trait]
363trait NodeRuntimeTrait: Send + Sync {
364    fn boxed_clone(&self) -> Box<dyn NodeRuntimeTrait>;
365    fn binary_path(&self) -> Result<PathBuf>;
366
367    async fn run_npm_subcommand(
368        &self,
369        directory: Option<&Path>,
370        proxy: Option<&Url>,
371        subcommand: &str,
372        args: &[&str],
373    ) -> Result<Output>;
374
375    async fn npm_package_installed_version(
376        &self,
377        local_package_directory: &Path,
378        name: &str,
379    ) -> Result<Option<String>>;
380}
381
382#[derive(Clone)]
383struct ManagedNodeRuntime {
384    installation_path: PathBuf,
385}
386
387impl ManagedNodeRuntime {
388    const VERSION: &str = "v24.11.0";
389
390    #[cfg(not(windows))]
391    const NODE_PATH: &str = "bin/node";
392    #[cfg(windows)]
393    const NODE_PATH: &str = "node.exe";
394
395    #[cfg(not(windows))]
396    const NPM_PATH: &str = "bin/npm";
397    #[cfg(windows)]
398    const NPM_PATH: &str = "node_modules/npm/bin/npm-cli.js";
399
400    async fn install_if_needed(http: &Arc<dyn HttpClient>) -> Result<Self> {
401        log::info!("Node runtime install_if_needed");
402
403        let os = match consts::OS {
404            "macos" => "darwin",
405            "linux" => "linux",
406            "windows" => "win",
407            other => bail!("Running on unsupported os: {other}"),
408        };
409
410        let arch = match consts::ARCH {
411            "x86_64" => "x64",
412            "aarch64" => "arm64",
413            other => bail!("Running on unsupported architecture: {other}"),
414        };
415
416        let version = Self::VERSION;
417        let folder_name = format!("node-{version}-{os}-{arch}");
418        let node_containing_dir = paths::data_dir().join("node");
419        let node_dir = node_containing_dir.join(folder_name);
420        let node_binary = node_dir.join(Self::NODE_PATH);
421        let npm_file = node_dir.join(Self::NPM_PATH);
422        let node_ca_certs = env::var(NODE_CA_CERTS_ENV_VAR).unwrap_or_else(|_| String::new());
423
424        let valid = if fs::metadata(&node_binary).await.is_ok() {
425            let result = util::command::new_smol_command(&node_binary)
426                .env(NODE_CA_CERTS_ENV_VAR, node_ca_certs)
427                .arg(npm_file)
428                .arg("--version")
429                .args(["--cache".into(), node_dir.join("cache")])
430                .args(["--userconfig".into(), node_dir.join("blank_user_npmrc")])
431                .args(["--globalconfig".into(), node_dir.join("blank_global_npmrc")])
432                .output()
433                .await;
434            match result {
435                Ok(output) => {
436                    if output.status.success() {
437                        true
438                    } else {
439                        log::warn!(
440                            "Zed managed Node.js binary at {} failed check with output: {:?}",
441                            node_binary.display(),
442                            output
443                        );
444                        false
445                    }
446                }
447                Err(err) => {
448                    log::warn!(
449                        "Zed managed Node.js binary at {} failed check, so re-downloading it. \
450                        Error: {}",
451                        node_binary.display(),
452                        err
453                    );
454                    false
455                }
456            }
457        } else {
458            false
459        };
460
461        if !valid {
462            _ = fs::remove_dir_all(&node_containing_dir).await;
463            fs::create_dir(&node_containing_dir)
464                .await
465                .context("error creating node containing dir")?;
466
467            let archive_type = match consts::OS {
468                "macos" | "linux" => ArchiveType::TarGz,
469                "windows" => ArchiveType::Zip,
470                other => bail!("Running on unsupported os: {other}"),
471            };
472
473            let version = Self::VERSION;
474            let file_name = format!(
475                "node-{version}-{os}-{arch}.{extension}",
476                extension = match archive_type {
477                    ArchiveType::TarGz => "tar.gz",
478                    ArchiveType::Zip => "zip",
479                }
480            );
481
482            let url = format!("https://nodejs.org/dist/{version}/{file_name}");
483            log::info!("Downloading Node.js binary from {url}");
484            let mut response = http
485                .get(&url, Default::default(), true)
486                .await
487                .context("error downloading Node binary tarball")?;
488            log::info!("Download of Node.js complete, extracting...");
489
490            let body = response.body_mut();
491            match archive_type {
492                ArchiveType::TarGz => {
493                    let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
494                    let archive = Archive::new(decompressed_bytes);
495                    archive.unpack(&node_containing_dir).await?;
496                }
497                ArchiveType::Zip => extract_zip(&node_containing_dir, body).await?,
498            }
499            log::info!("Extracted Node.js to {}", node_containing_dir.display())
500        }
501
502        // Note: Not in the `if !valid {}` so we can populate these for existing installations
503        _ = fs::create_dir(node_dir.join("cache")).await;
504        _ = fs::write(node_dir.join("blank_user_npmrc"), []).await;
505        _ = fs::write(node_dir.join("blank_global_npmrc"), []).await;
506
507        anyhow::Ok(ManagedNodeRuntime {
508            installation_path: node_dir,
509        })
510    }
511}
512
513fn path_with_node_binary_prepended(node_binary: &Path) -> Option<OsString> {
514    let existing_path = env::var_os("PATH");
515    let node_bin_dir = node_binary.parent().map(|dir| dir.as_os_str());
516    match (existing_path, node_bin_dir) {
517        (Some(existing_path), Some(node_bin_dir)) => {
518            if let Ok(joined) = env::join_paths(
519                [PathBuf::from(node_bin_dir)]
520                    .into_iter()
521                    .chain(env::split_paths(&existing_path)),
522            ) {
523                Some(joined)
524            } else {
525                Some(existing_path)
526            }
527        }
528        (Some(existing_path), None) => Some(existing_path),
529        (None, Some(node_bin_dir)) => Some(node_bin_dir.to_owned()),
530        _ => None,
531    }
532}
533
534#[async_trait::async_trait]
535impl NodeRuntimeTrait for ManagedNodeRuntime {
536    fn boxed_clone(&self) -> Box<dyn NodeRuntimeTrait> {
537        Box::new(self.clone())
538    }
539
540    fn binary_path(&self) -> Result<PathBuf> {
541        Ok(self.installation_path.join(Self::NODE_PATH))
542    }
543
544    async fn run_npm_subcommand(
545        &self,
546        directory: Option<&Path>,
547        proxy: Option<&Url>,
548        subcommand: &str,
549        args: &[&str],
550    ) -> Result<Output> {
551        let attempt = || async move {
552            let node_binary = self.installation_path.join(Self::NODE_PATH);
553            let npm_file = self.installation_path.join(Self::NPM_PATH);
554            let env_path = path_with_node_binary_prepended(&node_binary).unwrap_or_default();
555
556            anyhow::ensure!(
557                smol::fs::metadata(&node_binary).await.is_ok(),
558                "missing node binary file"
559            );
560            anyhow::ensure!(
561                smol::fs::metadata(&npm_file).await.is_ok(),
562                "missing npm file"
563            );
564
565            let node_ca_certs = env::var(NODE_CA_CERTS_ENV_VAR).unwrap_or_else(|_| String::new());
566
567            let mut command = util::command::new_smol_command(node_binary);
568            command.env("PATH", env_path);
569            command.env(NODE_CA_CERTS_ENV_VAR, node_ca_certs);
570            command.arg(npm_file).arg(subcommand);
571            command.arg(format!(
572                "--cache={}",
573                self.installation_path.join("cache").display()
574            ));
575            command.args([
576                "--userconfig".into(),
577                self.installation_path.join("blank_user_npmrc"),
578            ]);
579            command.args([
580                "--globalconfig".into(),
581                self.installation_path.join("blank_global_npmrc"),
582            ]);
583            command.args(args);
584            configure_npm_command(&mut command, directory, proxy);
585            command.output().await.map_err(|e| anyhow!("{e}"))
586        };
587
588        let mut output = attempt().await;
589        if output.is_err() {
590            output = attempt().await;
591            anyhow::ensure!(
592                output.is_ok(),
593                "failed to launch npm subcommand {subcommand} subcommand\nerr: {:?}",
594                output.err()
595            );
596        }
597
598        if let Ok(output) = &output {
599            anyhow::ensure!(
600                output.status.success(),
601                "failed to execute npm {subcommand} subcommand:\nstdout: {:?}\nstderr: {:?}",
602                String::from_utf8_lossy(&output.stdout),
603                String::from_utf8_lossy(&output.stderr)
604            );
605        }
606
607        output.map_err(|e| anyhow!("{e}"))
608    }
609    async fn npm_package_installed_version(
610        &self,
611        local_package_directory: &Path,
612        name: &str,
613    ) -> Result<Option<String>> {
614        read_package_installed_version(local_package_directory.join("node_modules"), name).await
615    }
616}
617
618#[derive(Debug, Clone)]
619pub struct SystemNodeRuntime {
620    node: PathBuf,
621    npm: PathBuf,
622    global_node_modules: PathBuf,
623    scratch_dir: PathBuf,
624}
625
626impl SystemNodeRuntime {
627    const MIN_VERSION: semver::Version = Version::new(22, 0, 0);
628    async fn new(node: PathBuf, npm: PathBuf) -> Result<Self> {
629        let output = util::command::new_smol_command(&node)
630            .arg("--version")
631            .output()
632            .await
633            .with_context(|| format!("running node from {:?}", node))?;
634        if !output.status.success() {
635            anyhow::bail!(
636                "failed to run node --version. stdout: {}, stderr: {}",
637                String::from_utf8_lossy(&output.stdout),
638                String::from_utf8_lossy(&output.stderr),
639            );
640        }
641        let version_str = String::from_utf8_lossy(&output.stdout);
642        let version = semver::Version::parse(version_str.trim().trim_start_matches('v'))?;
643        if version < Self::MIN_VERSION {
644            anyhow::bail!(
645                "node at {} is too old. want: {}, got: {}",
646                node.to_string_lossy(),
647                Self::MIN_VERSION,
648                version
649            )
650        }
651
652        let scratch_dir = paths::data_dir().join("node");
653        fs::create_dir(&scratch_dir).await.ok();
654        fs::create_dir(scratch_dir.join("cache")).await.ok();
655
656        let mut this = Self {
657            node,
658            npm,
659            global_node_modules: PathBuf::default(),
660            scratch_dir,
661        };
662        let output = this.run_npm_subcommand(None, None, "root", &["-g"]).await?;
663        this.global_node_modules =
664            PathBuf::from(String::from_utf8_lossy(&output.stdout).to_string());
665
666        Ok(this)
667    }
668
669    async fn detect() -> std::result::Result<Self, DetectError> {
670        let node = which::which("node").map_err(DetectError::NotInPath)?;
671        let npm = which::which("npm").map_err(DetectError::NotInPath)?;
672        Self::new(node, npm).await.map_err(DetectError::Other)
673    }
674}
675
676enum DetectError {
677    NotInPath(which::Error),
678    Other(anyhow::Error),
679}
680
681impl Display for DetectError {
682    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
683        match self {
684            DetectError::NotInPath(err) => {
685                write!(f, "system Node.js wasn't found on PATH: {}", err)
686            }
687            DetectError::Other(err) => {
688                write!(f, "checking system Node.js failed with error: {}", err)
689            }
690        }
691    }
692}
693
694#[async_trait::async_trait]
695impl NodeRuntimeTrait for SystemNodeRuntime {
696    fn boxed_clone(&self) -> Box<dyn NodeRuntimeTrait> {
697        Box::new(self.clone())
698    }
699
700    fn binary_path(&self) -> Result<PathBuf> {
701        Ok(self.node.clone())
702    }
703
704    async fn run_npm_subcommand(
705        &self,
706        directory: Option<&Path>,
707        proxy: Option<&Url>,
708        subcommand: &str,
709        args: &[&str],
710    ) -> anyhow::Result<Output> {
711        let node_ca_certs = env::var(NODE_CA_CERTS_ENV_VAR).unwrap_or_else(|_| String::new());
712        let mut command = util::command::new_smol_command(self.npm.clone());
713        let path = path_with_node_binary_prepended(&self.node).unwrap_or_default();
714        command
715            .env("PATH", path)
716            .env(NODE_CA_CERTS_ENV_VAR, node_ca_certs)
717            .arg(subcommand)
718            .arg(format!(
719                "--cache={}",
720                self.scratch_dir.join("cache").display()
721            ))
722            .args(args);
723        configure_npm_command(&mut command, directory, proxy);
724        let output = command.output().await?;
725        anyhow::ensure!(
726            output.status.success(),
727            "failed to execute npm {subcommand} subcommand:\nstdout: {:?}\nstderr: {:?}",
728            String::from_utf8_lossy(&output.stdout),
729            String::from_utf8_lossy(&output.stderr)
730        );
731        Ok(output)
732    }
733
734    async fn npm_package_installed_version(
735        &self,
736        local_package_directory: &Path,
737        name: &str,
738    ) -> Result<Option<String>> {
739        read_package_installed_version(local_package_directory.join("node_modules"), name).await
740        // todo: allow returning a globally installed version (requires callers not to hard-code the path)
741    }
742}
743
744pub async fn read_package_installed_version(
745    node_module_directory: PathBuf,
746    name: &str,
747) -> Result<Option<String>> {
748    let package_json_path = node_module_directory.join(name).join("package.json");
749
750    let mut file = match fs::File::open(package_json_path).await {
751        Ok(file) => file,
752        Err(err) => {
753            if err.kind() == io::ErrorKind::NotFound {
754                return Ok(None);
755            }
756
757            Err(err)?
758        }
759    };
760
761    #[derive(Deserialize)]
762    struct PackageJson {
763        version: String,
764    }
765
766    let mut contents = String::new();
767    file.read_to_string(&mut contents).await?;
768    let package_json: PackageJson = serde_json::from_str(&contents)?;
769    Ok(Some(package_json.version))
770}
771
772#[derive(Clone)]
773pub struct UnavailableNodeRuntime {
774    error_message: Arc<String>,
775}
776
777#[async_trait::async_trait]
778impl NodeRuntimeTrait for UnavailableNodeRuntime {
779    fn boxed_clone(&self) -> Box<dyn NodeRuntimeTrait> {
780        Box::new(self.clone())
781    }
782    fn binary_path(&self) -> Result<PathBuf> {
783        bail!("{}", self.error_message)
784    }
785
786    async fn run_npm_subcommand(
787        &self,
788        _: Option<&Path>,
789        _: Option<&Url>,
790        _: &str,
791        _: &[&str],
792    ) -> anyhow::Result<Output> {
793        bail!("{}", self.error_message)
794    }
795
796    async fn npm_package_installed_version(
797        &self,
798        _local_package_directory: &Path,
799        _: &str,
800    ) -> Result<Option<String>> {
801        bail!("{}", self.error_message)
802    }
803}
804
805fn configure_npm_command(
806    command: &mut smol::process::Command,
807    directory: Option<&Path>,
808    proxy: Option<&Url>,
809) {
810    if let Some(directory) = directory {
811        command.current_dir(directory);
812        command.args(["--prefix".into(), directory.to_path_buf()]);
813    }
814
815    if let Some(mut proxy) = proxy.cloned() {
816        // Map proxy settings from `http://localhost:10809` to `http://127.0.0.1:10809`
817        // NodeRuntime without environment information can not parse `localhost`
818        // correctly.
819        // TODO: map to `[::1]` if we are using ipv6
820        if matches!(proxy.host(), Some(Host::Domain(domain)) if domain.eq_ignore_ascii_case("localhost"))
821        {
822            // When localhost is a valid Host, so is `127.0.0.1`
823            let _ = proxy.set_ip_host(IpAddr::V4(Ipv4Addr::LOCALHOST));
824        }
825
826        command.args(["--proxy", proxy.as_str()]);
827    }
828
829    #[cfg(windows)]
830    {
831        // SYSTEMROOT is a critical environment variables for Windows.
832        if let Some(val) = env::var("SYSTEMROOT")
833            .context("Missing environment variable: SYSTEMROOT!")
834            .log_err()
835        {
836            command.env("SYSTEMROOT", val);
837        }
838        // Without ComSpec, the post-install will always fail.
839        if let Some(val) = env::var("ComSpec")
840            .context("Missing environment variable: ComSpec!")
841            .log_err()
842        {
843            command.env("ComSpec", val);
844        }
845    }
846}
847
848#[cfg(test)]
849mod tests {
850    use http_client::Url;
851
852    use super::configure_npm_command;
853
854    // Map localhost to 127.0.0.1
855    // NodeRuntime without environment information can not parse `localhost` correctly.
856    #[test]
857    fn test_configure_npm_command_map_localhost_proxy() {
858        const CASES: [(&str, &str); 4] = [
859            // Map localhost to 127.0.0.1
860            ("http://localhost:9090/", "http://127.0.0.1:9090/"),
861            ("https://google.com/", "https://google.com/"),
862            (
863                "http://username:password@proxy.thing.com:8080/",
864                "http://username:password@proxy.thing.com:8080/",
865            ),
866            // Test when localhost is contained within a different part of the URL
867            (
868                "http://username:localhost@localhost:8080/",
869                "http://username:localhost@127.0.0.1:8080/",
870            ),
871        ];
872
873        for (proxy, mapped_proxy) in CASES {
874            let mut dummy = smol::process::Command::new("");
875            let proxy = Url::parse(proxy).unwrap();
876            configure_npm_command(&mut dummy, None, Some(&proxy));
877            let proxy = dummy
878                .get_args()
879                .skip_while(|&arg| arg != "--proxy")
880                .skip(1)
881                .next();
882            let proxy = proxy.expect("Proxy was not passed to Command correctly");
883            assert_eq!(
884                proxy, mapped_proxy,
885                "Incorrectly mapped localhost to 127.0.0.1"
886            );
887        }
888    }
889}