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