-
Notifications
You must be signed in to change notification settings - Fork 232
Expand file tree
/
Copy pathnode.rs
More file actions
1512 lines (1289 loc) · 58.3 KB
/
Copy pathnode.rs
File metadata and controls
1512 lines (1289 loc) · 58.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Node.js runtime provider implementation.
use std::time::{SystemTime, UNIX_EPOCH};
use async_trait::async_trait;
use node_semver::{Range, Version};
use serde::{Deserialize, Serialize};
use vite_path::{AbsolutePath, AbsolutePathBuf};
use vite_str::Str;
// Only referenced on non-musl builds, where official releases are signed.
#[cfg(not(target_env = "musl"))]
use crate::provider::ShasumsSignature;
use crate::{
Error, Platform,
download::fetch_json_with_cache_headers,
platform::Os,
provider::{ArchiveFormat, DownloadInfo, HashVerification, JsRuntimeProvider},
};
/// Default Node.js distribution base URL
#[cfg(not(target_env = "musl"))]
const DEFAULT_NODE_DIST_URL: &str = "https://nodejs.org/dist";
/// Unofficial builds URL for musl (official nodejs.org only provides glibc binaries)
#[cfg(target_env = "musl")]
const DEFAULT_NODE_DIST_URL: &str = "https://unofficial-builds.nodejs.org/download/release";
/// Environment variable to override the Node.js distribution URL
/// Default cache TTL in seconds (1 hour)
const DEFAULT_CACHE_TTL_SECS: u64 = 3600;
/// A single entry from the Node.js version index
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct NodeVersionEntry {
/// Version string (e.g., "v25.5.0")
pub version: Str,
/// LTS information
#[serde(default)]
pub lts: LtsInfo,
}
impl NodeVersionEntry {
/// Check if this version is an LTS release.
#[must_use]
pub const fn is_lts(&self) -> bool {
matches!(self.lts, LtsInfo::Codename(_))
}
}
/// LTS field can be false or a codename string
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
#[serde(untagged)]
pub enum LtsInfo {
/// Not an LTS release
#[default]
NotLts,
/// Boolean false (not LTS)
Boolean(bool),
/// LTS codename (e.g., "Jod")
Codename(Str),
}
/// Cached version index with expiration
#[derive(Deserialize, Serialize, Debug)]
struct VersionIndexCache {
/// Unix timestamp when cache expires
expires_at: u64,
/// `ETag` from HTTP response (for conditional requests)
#[serde(default)]
etag: Option<Str>,
/// Cached version entries
versions: Vec<NodeVersionEntry>,
}
/// Node.js runtime provider
#[derive(Debug, Default)]
pub struct NodeProvider;
impl NodeProvider {
/// Create a new `NodeProvider`
#[must_use]
pub const fn new() -> Self {
Self
}
/// Check if a version string is an exact version (not a range).
///
/// Returns `true` for exact versions like "20.18.0", "22.13.1".
/// Returns `false` for ranges like "^20.18.0", "~20.18.0", ">=20 <22", "20.x".
#[must_use]
pub fn is_exact_version(version_str: &str) -> bool {
Version::parse(version_str).is_ok()
}
/// Find a locally cached version that satisfies the version requirement.
///
/// This checks the local cache directory for installed Node.js versions
/// and returns a version that satisfies the semver range. Prefers LTS
/// versions over non-LTS versions.
///
/// # Arguments
/// * `version_req` - A semver range requirement (e.g., "^20.18.0")
/// * `cache_dir` - The cache directory path (e.g., `~/.cache/vite-plus/js_runtime`)
///
/// # Returns
/// The highest LTS cached version that satisfies the requirement, or the
/// highest non-LTS version if no LTS version matches, or `None` if no
/// cached version matches.
///
/// # Errors
/// Returns an error if the version requirement is invalid.
pub async fn find_cached_version(
&self,
version_req: &str,
cache_dir: &AbsolutePath,
) -> Result<Option<Str>, Error> {
let node_cache = cache_dir.join("node");
// List directories in cache
let mut entries = match tokio::fs::read_dir(&node_cache).await {
Ok(entries) => entries,
Err(_) => return Ok(None), // Cache dir doesn't exist
};
let range = Range::parse(version_req)?;
let mut matching_versions: Vec<Version> = Vec::new();
let platform = Platform::current();
while let Some(entry) = entries.next_entry().await? {
let name = entry.file_name().to_string_lossy().to_string();
// Skip non-version entries (index_cache.json, .lock files)
if let Ok(version) = Version::parse(&name) {
// Check if binary exists (valid installation)
let binary_path = node_cache.join(&name).join(self.binary_relative_path(platform));
if tokio::fs::try_exists(&binary_path).await.unwrap_or(false)
&& range.satisfies(&version)
{
matching_versions.push(version);
}
}
}
if matching_versions.is_empty() {
return Ok(None);
}
// Fetch version index to check LTS status
let version_index = self.fetch_version_index().await?;
// Build a set of LTS versions for fast lookup
let lts_versions: std::collections::HashSet<String> = version_index
.iter()
.filter(|e| e.is_lts())
.map(|e| e.version.strip_prefix('v').unwrap_or(&e.version).to_string())
.collect();
// Prefer LTS: find highest LTS cached version first
let lts_max =
matching_versions.iter().filter(|v| lts_versions.contains(&v.to_string())).max();
if let Some(version) = lts_max {
return Ok(Some(version.to_string().into()));
}
// Fallback to highest non-LTS
Ok(matching_versions.into_iter().max().map(|v| v.to_string().into()))
}
/// Get the archive format for a platform
const fn archive_format(platform: Platform) -> ArchiveFormat {
match platform.os {
Os::Windows => ArchiveFormat::Zip,
Os::Linux | Os::Darwin => ArchiveFormat::TarGz,
}
}
/// Fetch the version index from nodejs.org/dist/index.json with HTTP caching.
///
/// Uses ETag-based conditional requests to minimize bandwidth when cache expires.
/// If a network error occurs and a local cache exists (even if expired), returns
/// the cached version with a warning log instead of failing.
///
/// # Errors
///
/// Returns an error only if the download fails and no local cache exists.
pub async fn fetch_version_index(&self) -> Result<Vec<NodeVersionEntry>, Error> {
let cache_dir = crate::cache::get_cache_dir()?;
let cache_path = cache_dir.join("node/index_cache.json");
// Try to load from cache
let Some(cache) = load_cache(&cache_path).await else {
// No cache - must fetch
return self.fetch_and_cache(&cache_path).await;
};
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
// If cache is still fresh, use it
if now < cache.expires_at {
tracing::debug!("Using cached version index (expires in {}s)", cache.expires_at - now);
return Ok(cache.versions);
}
// Cache expired - try conditional request with ETag if available
if let Some(ref etag) = cache.etag {
tracing::debug!("Cache expired, trying conditional request with ETag");
match self.fetch_with_etag(etag, &cache, &cache_path).await {
Ok(versions) => return Ok(versions),
Err(e) => {
// Network error with ETag request - return cached version
tracing::warn!("Conditional request failed: {e}, using expired cache");
return Ok(cache.versions);
}
}
}
// No ETag - try full fetch, fallback to cache
tracing::debug!("Cache expired, no ETag available for conditional request");
match self.fetch_and_cache(&cache_path).await {
Ok(versions) => Ok(versions),
Err(e) => {
tracing::warn!("Failed to fetch version index: {e}, using expired cache");
Ok(cache.versions)
}
}
}
/// Try conditional fetch with `ETag`, returns cached versions if 304
async fn fetch_with_etag(
&self,
etag: &str,
cache: &VersionIndexCache,
cache_path: &AbsolutePathBuf,
) -> Result<Vec<NodeVersionEntry>, Error> {
let base_url = get_dist_url();
let index_url = vite_str::format!("{base_url}/index.json");
let response =
fetch_json_with_cache_headers::<Vec<NodeVersionEntry>>(&index_url, Some(etag)).await?;
if response.not_modified {
// Server confirmed data hasn't changed, refresh TTL
tracing::debug!("Server returned 304 Not Modified, refreshing cache TTL");
let new_cache = VersionIndexCache {
expires_at: calculate_expires_at(response.max_age),
etag: cache.etag.clone(),
versions: cache.versions.clone(),
};
save_cache(cache_path, &new_cache).await;
return Ok(cache.versions.clone());
}
// Got new data
let versions = response.body.ok_or_else(|| Error::VersionIndexParseFailed {
reason: "Empty response body".into(),
})?;
let new_cache = VersionIndexCache {
expires_at: calculate_expires_at(response.max_age),
etag: response.etag,
versions: versions.clone(),
};
save_cache(cache_path, &new_cache).await;
Ok(versions)
}
/// Fetch the version index and cache it.
async fn fetch_and_cache(
&self,
cache_path: &AbsolutePathBuf,
) -> Result<Vec<NodeVersionEntry>, Error> {
let base_url = get_dist_url();
let index_url = vite_str::format!("{base_url}/index.json");
tracing::debug!("Fetching version index from {index_url}");
let response =
fetch_json_with_cache_headers::<Vec<NodeVersionEntry>>(&index_url, None).await?;
let versions = response.body.ok_or_else(|| Error::VersionIndexParseFailed {
reason: "Empty response body".into(),
})?;
let cache = VersionIndexCache {
expires_at: calculate_expires_at(response.max_age),
etag: response.etag,
versions: versions.clone(),
};
save_cache(cache_path, &cache).await;
Ok(versions)
}
/// Resolve a version requirement (e.g., "^24.4.0") to an exact version.
///
/// Returns the highest version that satisfies the semver range.
/// Uses npm-compatible semver range parsing.
///
/// # Errors
///
/// Returns an error if no matching version is found or if the version requirement is invalid.
pub async fn resolve_version(&self, version_req: &str) -> Result<Str, Error> {
let versions = self.fetch_version_index().await?;
resolve_version_from_list(version_req, &versions)
}
/// Get the latest LTS version with the highest version number.
///
/// # Errors
///
/// Returns an error if no LTS version is found or the version index cannot be fetched.
pub async fn resolve_latest_version(&self) -> Result<Str, Error> {
let versions = self.fetch_version_index().await?;
find_latest_lts_version(&versions)
}
/// Get the absolute latest version, including non-LTS.
///
/// # Errors
///
/// Returns an error if no version is found or the version index cannot be fetched.
pub async fn resolve_absolute_latest_version(&self) -> Result<Str, Error> {
let versions = self.fetch_version_index().await?;
find_absolute_latest_version(&versions)
}
/// Check if a version string is an LTS alias (e.g., `lts/*`, `lts/iron`, `lts/-1`).
///
/// Returns `true` for LTS alias formats:
/// - `lts/*` - Latest LTS version
/// - `lts/<codename>` - Specific LTS line (e.g., `lts/iron`, `lts/jod`)
/// - `lts/-n` - Nth-highest LTS line (e.g., `lts/-1` for second highest)
#[must_use]
pub fn is_lts_alias(version: &str) -> bool {
version.starts_with("lts/")
}
/// Check if a version string is a "latest" alias.
///
/// Returns `true` for:
/// - `latest` - The absolute latest Node.js version (including non-LTS)
#[must_use]
pub const fn is_latest_alias(version: &str) -> bool {
version.eq_ignore_ascii_case("latest")
}
/// Check if a version string is any kind of alias (lts/* or latest).
#[must_use]
pub fn is_version_alias(version: &str) -> bool {
Self::is_lts_alias(version) || Self::is_latest_alias(version)
}
/// Resolve an LTS alias to an exact version.
///
/// # Supported Formats
///
/// - `lts/*` - Returns the latest LTS version
/// - `lts/<codename>` - Returns the highest version for that LTS line (e.g., `lts/iron` → 20.x)
/// - `lts/-n` - Returns the nth-highest LTS line (e.g., `lts/-1` → second highest)
///
/// # Errors
///
/// Returns an error if:
/// - The alias format is invalid
/// - The codename is not recognized
/// - The offset is too large (not enough LTS lines)
pub async fn resolve_lts_alias(&self, alias: &str) -> Result<Str, Error> {
let suffix = alias
.strip_prefix("lts/")
.ok_or_else(|| Error::InvalidLtsAlias { alias: alias.into() })?;
// lts/* - latest LTS
if suffix == "*" {
return self.resolve_latest_version().await;
}
// lts/-n - nth-highest LTS (e.g., lts/-1 = second highest)
if suffix.starts_with('-')
&& let Ok(n) = suffix.parse::<i32>()
&& n < 0
{
return self.resolve_lts_by_offset(n).await;
}
// lts/<codename> - specific LTS line
self.resolve_lts_by_codename(suffix).await
}
/// Resolve LTS by codename (e.g., "iron" → 20.x, "jod" → 22.x).
async fn resolve_lts_by_codename(&self, codename: &str) -> Result<Str, Error> {
let versions = self.fetch_version_index().await?;
let target = codename.to_lowercase();
// Find all versions matching the codename
let matching: Vec<_> = versions
.iter()
.filter(|v| matches!(&v.lts, LtsInfo::Codename(name) if name.to_lowercase() == target))
.collect();
if matching.is_empty() {
return Err(Error::UnknownLtsCodename { codename: codename.into() });
}
// Find the highest matching version
let highest = matching
.into_iter()
.filter_map(|entry| {
let version_str = entry.version.strip_prefix('v').unwrap_or(&entry.version);
Version::parse(version_str).ok().map(|v| (v, version_str))
})
.max_by(|(a, _), (b, _)| a.cmp(b));
highest
.map(|(_, version_str)| version_str.into())
.ok_or_else(|| Error::UnknownLtsCodename { codename: codename.into() })
}
/// Resolve LTS by offset (e.g., -1 = second highest LTS line).
///
/// The offset is negative: lts/-1 means "one below the latest LTS line".
async fn resolve_lts_by_offset(&self, offset: i32) -> Result<Str, Error> {
let versions = self.fetch_version_index().await?;
// Get unique LTS codenames ordered by highest version in each line
let mut lts_lines: Vec<(String, u64)> = Vec::new();
for entry in &versions {
if let LtsInfo::Codename(name) = &entry.lts {
let version_str = entry.version.strip_prefix('v').unwrap_or(&entry.version);
if let Ok(ver) = Version::parse(version_str) {
let key = name.to_lowercase();
// Only add if we haven't seen this codename yet (keeping highest version)
if !lts_lines.iter().any(|(n, _)| n == &key) {
lts_lines.push((key, ver.major));
}
}
}
}
// Sort by major version descending (highest first)
lts_lines.sort_by_key(|b| std::cmp::Reverse(b.1));
// offset is negative, so lts/-1 = index 1 (second highest)
let index = (-offset) as usize;
let (codename, _) = lts_lines
.get(index)
.ok_or_else(|| Error::InvalidLtsOffset { offset, available: lts_lines.len() })?;
self.resolve_lts_by_codename(codename).await
}
}
/// Find the LTS version with the highest version number from a list of versions.
///
/// # Errors
///
/// Returns an error if no LTS version is found in the list.
fn find_latest_lts_version(versions: &[NodeVersionEntry]) -> Result<Str, Error> {
let latest_lts = versions
.iter()
.filter(|entry| entry.is_lts())
.filter_map(|entry| {
let version_str = entry.version.strip_prefix('v').unwrap_or(&entry.version);
Version::parse(version_str).ok().map(|v| (v, version_str))
})
.max_by(|(a, _), (b, _)| a.cmp(b));
latest_lts.map(|(_, version_str)| version_str.into()).ok_or_else(|| {
Error::VersionIndexParseFailed { reason: "No LTS version found in version index".into() }
})
}
/// Find the absolute latest version, regardless of LTS status.
///
/// The version index is sorted newest-first, so we take the first entry.
fn find_absolute_latest_version(versions: &[NodeVersionEntry]) -> Result<Str, Error> {
versions
.first()
.map(|entry| {
let version_str = entry.version.strip_prefix('v').unwrap_or(&entry.version);
version_str.into()
})
.ok_or_else(|| Error::VersionIndexParseFailed {
reason: "No version found in version index".into(),
})
}
/// Resolve a version requirement to a matching version from a list.
///
/// Prefers LTS versions over non-LTS versions. Returns the highest LTS version
/// that satisfies the range, or falls back to the highest non-LTS version if
/// no LTS version matches.
///
/// # Errors
///
/// Returns an error if no matching version is found or if the version requirement is invalid.
fn resolve_version_from_list(
version_req: &str,
versions: &[NodeVersionEntry],
) -> Result<Str, Error> {
let range = Range::parse(version_req)?;
// Collect all matching versions with their LTS status
let matching_versions: Vec<(Version, &str, bool)> = versions
.iter()
.filter_map(|entry| {
let version_str = entry.version.strip_prefix('v').unwrap_or(&entry.version);
Version::parse(version_str)
.ok()
.filter(|v| range.satisfies(v))
.map(|v| (v, version_str, entry.is_lts()))
})
.collect();
// Prefer LTS versions: find highest LTS first
let lts_max = matching_versions
.iter()
.filter(|(_, _, is_lts)| *is_lts)
.max_by(|(a, _, _), (b, _, _)| a.cmp(b));
if let Some((_, version_str, _)) = lts_max {
return Ok((*version_str).into());
}
// Fallback to highest non-LTS version
matching_versions
.into_iter()
.max_by(|(a, _, _), (b, _, _)| a.cmp(b))
.map(|(_, version_str, _)| version_str.into())
.ok_or_else(|| Error::NoMatchingVersion { version_req: version_req.into() })
}
/// Load cache from file.
async fn load_cache(cache_path: &AbsolutePathBuf) -> Option<VersionIndexCache> {
let content = tokio::fs::read_to_string(cache_path).await.ok()?;
serde_json::from_str(&content).ok()
}
/// Save cache to file.
async fn save_cache(cache_path: &AbsolutePathBuf, cache: &VersionIndexCache) {
// Ensure cache directory exists
if let Some(parent) = cache_path.parent() {
tokio::fs::create_dir_all(parent).await.ok();
}
// Write cache file (ignore errors)
if let Ok(cache_json) = serde_json::to_string(cache) {
tokio::fs::write(cache_path, cache_json).await.ok();
}
}
/// Calculate expiration timestamp from `max_age` or default TTL.
fn calculate_expires_at(max_age: Option<u64>) -> u64 {
let ttl = max_age.unwrap_or(DEFAULT_CACHE_TTL_SECS);
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() + ttl
}
/// Get the Node.js distribution base URL
///
/// Returns the value of `VP_NODE_DIST_MIRROR` environment variable if set,
/// otherwise returns the default `https://nodejs.org/dist`.
fn get_dist_url() -> Str {
vite_shared::EnvConfig::get().node_dist_mirror.map_or_else(
|| DEFAULT_NODE_DIST_URL.into(),
|url| Str::from(url.trim_end_matches('/').to_string()),
)
}
/// Whether `base_url` points at the official `nodejs.org` distribution, which
/// always publishes the clearsigned `SHASUMS256.txt.asc`. Signature
/// verification is required for the official host (even when reached through
/// `VP_NODE_DIST_MIRROR`) and best-effort for any other mirror.
#[cfg(not(target_env = "musl"))]
fn is_official_dist_host(base_url: &str) -> bool {
let authority =
base_url.split_once("://").map_or(base_url, |(_, rest)| rest).split(['/', '?', '#']).next();
let host = authority
.unwrap_or_default()
// Drop any `userinfo@` prefix and `:port` suffix, then a trailing dot.
.rsplit('@')
.next()
.unwrap_or_default()
.split(':')
.next()
.unwrap_or_default()
.trim_end_matches('.');
host.eq_ignore_ascii_case("nodejs.org")
}
#[async_trait]
impl JsRuntimeProvider for NodeProvider {
fn name(&self) -> &'static str {
"node"
}
fn platform_string(&self, platform: Platform) -> Str {
let os = match platform.os {
Os::Linux => "linux",
Os::Darwin => "darwin",
Os::Windows => "win",
};
let arch = match platform.arch {
crate::platform::Arch::X64 => "x64",
crate::platform::Arch::Arm64 => "arm64",
};
// On musl targets, append "-musl" to match unofficial-builds filename pattern
// e.g. "linux-x64-musl" instead of "linux-x64"
#[cfg(target_env = "musl")]
if platform.os == Os::Linux {
return vite_str::format!("{os}-{arch}-musl");
}
vite_str::format!("{os}-{arch}")
}
fn get_download_info(&self, version: &str, platform: Platform) -> DownloadInfo {
let base_url = get_dist_url();
let platform_str = self.platform_string(platform);
let format = Self::archive_format(platform);
let ext = format.extension();
let archive_filename: Str = vite_str::format!("node-v{version}-{platform_str}.{ext}");
let archive_url = vite_str::format!("{base_url}/v{version}/{archive_filename}");
let shasums_url = vite_str::format!("{base_url}/v{version}/SHASUMS256.txt");
let extracted_dir_name = vite_str::format!("node-v{version}-{platform_str}");
// Official nodejs.org releases publish a clearsigned SHASUMS256.txt.asc
// signed by a Node.js releaser; verify it. The unofficial musl builds
// (unofficial-builds.nodejs.org) publish no signature, so fall back to
// the plain SHASUMS256.txt there.
#[cfg(not(target_env = "musl"))]
let signature = Some(ShasumsSignature {
url: vite_str::format!("{base_url}/v{version}/SHASUMS256.txt.asc"),
// Require the signature based on the resolved host: official
// nodejs.org always ships it (including when VP_NODE_DIST_MIRROR
// points back at nodejs.org). A custom mirror (e.g. an internal
// Artifactory) may publish only the archives and SHASUMS256.txt, so
// there the signature is best-effort.
required: is_official_dist_host(&base_url),
});
#[cfg(target_env = "musl")]
let signature = None;
DownloadInfo {
archive_url,
archive_filename,
archive_format: format,
hash_verification: HashVerification::ShasumsFile { url: shasums_url, signature },
extracted_dir_name,
}
}
fn binary_relative_path(&self, platform: Platform) -> Str {
match platform.os {
Os::Windows => "node.exe".into(),
Os::Linux | Os::Darwin => "bin/node".into(),
}
}
fn bin_dir_relative_path(&self, platform: Platform) -> Str {
match platform.os {
Os::Windows => "".into(),
Os::Linux | Os::Darwin => "bin".into(),
}
}
fn parse_shasums(&self, shasums_content: &str, filename: &str) -> Result<Str, Error> {
// Node.js SHASUMS256.txt format: "<hash> <filename>" (two spaces between)
for line in shasums_content.lines() {
let parts: Vec<&str> = line.splitn(2, " ").collect();
if parts.len() == 2 {
let hash = parts[0].trim();
let file = parts[1].trim();
if file == filename {
return Ok(hash.into());
}
}
}
Err(Error::HashNotFound { filename: filename.into() })
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::platform::{Arch, Os};
#[test]
fn test_platform_string() {
let provider = NodeProvider::new();
#[cfg(not(target_env = "musl"))]
let cases = [
(Platform { os: Os::Linux, arch: Arch::X64 }, "linux-x64"),
(Platform { os: Os::Linux, arch: Arch::Arm64 }, "linux-arm64"),
(Platform { os: Os::Darwin, arch: Arch::X64 }, "darwin-x64"),
(Platform { os: Os::Darwin, arch: Arch::Arm64 }, "darwin-arm64"),
(Platform { os: Os::Windows, arch: Arch::X64 }, "win-x64"),
(Platform { os: Os::Windows, arch: Arch::Arm64 }, "win-arm64"),
];
#[cfg(target_env = "musl")]
let cases = [
(Platform { os: Os::Linux, arch: Arch::X64 }, "linux-x64-musl"),
(Platform { os: Os::Linux, arch: Arch::Arm64 }, "linux-arm64-musl"),
(Platform { os: Os::Darwin, arch: Arch::X64 }, "darwin-x64"),
(Platform { os: Os::Darwin, arch: Arch::Arm64 }, "darwin-arm64"),
(Platform { os: Os::Windows, arch: Arch::X64 }, "win-x64"),
(Platform { os: Os::Windows, arch: Arch::Arm64 }, "win-arm64"),
];
for (platform, expected) in cases {
assert_eq!(provider.platform_string(platform), expected);
}
}
#[test]
fn test_get_download_info() {
let provider = NodeProvider::new();
let platform = Platform { os: Os::Linux, arch: Arch::X64 };
// for_test() leaves node_dist_mirror unset, so this exercises the
// official (default) source where signature verification is required.
let info = vite_shared::EnvConfig::test_scope(vite_shared::EnvConfig::for_test(), || {
provider.get_download_info("22.13.1", platform)
});
#[cfg(not(target_env = "musl"))]
{
assert_eq!(info.archive_filename, "node-v22.13.1-linux-x64.tar.gz");
assert_eq!(
info.archive_url,
"https://nodejs.org/dist/v22.13.1/node-v22.13.1-linux-x64.tar.gz"
);
assert_eq!(info.extracted_dir_name, "node-v22.13.1-linux-x64");
if let HashVerification::ShasumsFile { url, signature } = &info.hash_verification {
assert_eq!(url, "https://nodejs.org/dist/v22.13.1/SHASUMS256.txt");
let signature = signature.as_ref().expect("official builds are signature-verified");
assert_eq!(signature.url, "https://nodejs.org/dist/v22.13.1/SHASUMS256.txt.asc");
assert!(signature.required, "official builds must require signature verification");
} else {
panic!("Expected ShasumsFile verification");
}
}
#[cfg(target_env = "musl")]
{
assert_eq!(info.archive_filename, "node-v22.13.1-linux-x64-musl.tar.gz");
assert_eq!(
info.archive_url,
"https://unofficial-builds.nodejs.org/download/release/v22.13.1/node-v22.13.1-linux-x64-musl.tar.gz"
);
assert_eq!(info.extracted_dir_name, "node-v22.13.1-linux-x64-musl");
if let HashVerification::ShasumsFile { url, signature } = &info.hash_verification {
assert_eq!(
url,
"https://unofficial-builds.nodejs.org/download/release/v22.13.1/SHASUMS256.txt"
);
// Unofficial musl builds publish no PGP signature.
assert!(signature.is_none(), "musl builds have no signature to verify");
} else {
panic!("Expected ShasumsFile verification");
}
}
assert_eq!(info.archive_format, ArchiveFormat::TarGz);
}
// A custom mirror (VP_NODE_DIST_MIRROR) may publish only the archives and
// plain SHASUMS256.txt, so signature verification there is best-effort.
#[cfg(not(target_env = "musl"))]
#[test]
fn test_get_download_info_custom_mirror_signature_optional() {
let provider = NodeProvider::new();
let platform = Platform { os: Os::Linux, arch: Arch::X64 };
let info = vite_shared::EnvConfig::test_scope(
vite_shared::EnvConfig {
node_dist_mirror: Some("https://mirror.example/node".into()),
..vite_shared::EnvConfig::for_test()
},
|| provider.get_download_info("22.13.1", platform),
);
if let HashVerification::ShasumsFile { url, signature } = &info.hash_verification {
assert_eq!(url, "https://mirror.example/node/v22.13.1/SHASUMS256.txt");
let signature =
signature.as_ref().expect("signature URL is still provided for mirrors");
assert_eq!(signature.url, "https://mirror.example/node/v22.13.1/SHASUMS256.txt.asc");
assert!(!signature.required, "custom mirror signature must be best-effort");
} else {
panic!("Expected ShasumsFile verification");
}
}
// A mirror pointed back at the official nodejs.org host must still require
// the signature (required is based on the resolved host, not merely whether
// VP_NODE_DIST_MIRROR is set).
#[cfg(not(target_env = "musl"))]
#[test]
fn test_get_download_info_official_mirror_requires_signature() {
let provider = NodeProvider::new();
let platform = Platform { os: Os::Linux, arch: Arch::X64 };
let info = vite_shared::EnvConfig::test_scope(
vite_shared::EnvConfig {
node_dist_mirror: Some("https://nodejs.org/download/release".into()),
..vite_shared::EnvConfig::for_test()
},
|| provider.get_download_info("22.13.1", platform),
);
if let HashVerification::ShasumsFile { signature, .. } = &info.hash_verification {
let signature = signature.as_ref().expect("official host is signature-verified");
assert!(
signature.required,
"an official nodejs.org mirror URL must still require the signature"
);
} else {
panic!("Expected ShasumsFile verification");
}
}
#[cfg(not(target_env = "musl"))]
#[test]
fn test_is_official_dist_host() {
assert!(is_official_dist_host("https://nodejs.org/dist"));
assert!(is_official_dist_host("https://nodejs.org/download/release"));
assert!(is_official_dist_host("https://NODEJS.ORG/dist"));
// Official host reached via userinfo, port, or a trailing dot still counts.
assert!(is_official_dist_host("https://user@nodejs.org/dist"));
assert!(is_official_dist_host("https://nodejs.org:443/dist"));
assert!(is_official_dist_host("https://nodejs.org./dist"));
assert!(!is_official_dist_host("https://npmmirror.com/mirrors/node"));
assert!(!is_official_dist_host("https://unofficial-builds.nodejs.org/download/release"));
assert!(!is_official_dist_host("https://artifactory.internal/node"));
// A look-alike host must not be mistaken for the official one.
assert!(!is_official_dist_host("https://nodejs.org.evil.com/dist"));
assert!(!is_official_dist_host("https://evil.com/nodejs.org"));
}
#[test]
fn test_get_download_info_windows() {
let provider = NodeProvider::new();
let platform = Platform { os: Os::Windows, arch: Arch::X64 };
let info = provider.get_download_info("22.13.1", platform);
assert_eq!(info.archive_filename, "node-v22.13.1-win-x64.zip");
assert_eq!(info.archive_format, ArchiveFormat::Zip);
}
#[test]
fn test_binary_relative_path() {
let provider = NodeProvider::new();
assert_eq!(
provider.binary_relative_path(Platform { os: Os::Linux, arch: Arch::X64 }),
"bin/node"
);
assert_eq!(
provider.binary_relative_path(Platform { os: Os::Darwin, arch: Arch::Arm64 }),
"bin/node"
);
assert_eq!(
provider.binary_relative_path(Platform { os: Os::Windows, arch: Arch::X64 }),
"node.exe"
);
}
#[test]
fn test_bin_dir_relative_path() {
let provider = NodeProvider::new();
assert_eq!(
provider.bin_dir_relative_path(Platform { os: Os::Linux, arch: Arch::X64 }),
"bin"
);
assert_eq!(
provider.bin_dir_relative_path(Platform { os: Os::Windows, arch: Arch::X64 }),
""
);
}
#[test]
fn test_parse_shasums() {
let provider = NodeProvider::new();
let content = r"abc123def456 node-v22.13.1-linux-x64.tar.gz
789xyz000111 node-v22.13.1-darwin-arm64.tar.gz
fedcba987654 node-v22.13.1-win-x64.zip";
assert_eq!(
provider.parse_shasums(content, "node-v22.13.1-linux-x64.tar.gz").unwrap(),
"abc123def456"
);
assert_eq!(
provider.parse_shasums(content, "node-v22.13.1-darwin-arm64.tar.gz").unwrap(),
"789xyz000111"
);
assert_eq!(
provider.parse_shasums(content, "node-v22.13.1-win-x64.zip").unwrap(),
"fedcba987654"
);
// Test missing filename
let result = provider.parse_shasums(content, "nonexistent.tar.gz");
assert!(result.is_err());
}
#[test]
fn test_get_dist_url_default() {
vite_shared::EnvConfig::test_scope(vite_shared::EnvConfig::for_test(), || {
assert_eq!(get_dist_url(), DEFAULT_NODE_DIST_URL);
});
}
#[test]
fn test_get_dist_url_with_mirror() {
vite_shared::EnvConfig::test_scope(
vite_shared::EnvConfig {
node_dist_mirror: Some("https://nodejs.org/dist".into()),
..vite_shared::EnvConfig::for_test()
},
|| {
assert_eq!(get_dist_url(), "https://nodejs.org/dist");
},
);
}
#[test]
fn test_get_dist_url_trims_trailing_slash() {
vite_shared::EnvConfig::test_scope(
vite_shared::EnvConfig {
node_dist_mirror: Some("https://nodejs.org/dist/".into()),
..vite_shared::EnvConfig::for_test()
},
|| {
assert_eq!(get_dist_url(), "https://nodejs.org/dist");
},
);
}
#[test]
fn test_parse_lts_info() {
// Test parsing different LTS formats
let json_not_lts = r#"{"version": "v23.0.0", "lts": false}"#;
let entry: NodeVersionEntry = serde_json::from_str(json_not_lts).unwrap();
assert!(matches!(entry.lts, LtsInfo::Boolean(false)));
let json_lts_codename = r#"{"version": "v22.12.0", "lts": "Jod"}"#;
let entry: NodeVersionEntry = serde_json::from_str(json_lts_codename).unwrap();
assert!(matches!(entry.lts, LtsInfo::Codename(_)));
let json_no_lts = r#"{"version": "v23.0.0"}"#;
let entry: NodeVersionEntry = serde_json::from_str(json_no_lts).unwrap();
assert!(matches!(entry.lts, LtsInfo::NotLts));
}
#[tokio::test]
async fn test_fetch_version_index() {
let provider = NodeProvider::new();
let versions = provider.fetch_version_index().await.unwrap();
// Should have at least some versions
assert!(!versions.is_empty());
// First entry should be the latest version
let first = &versions[0];
assert!(first.version.starts_with('v'));
// Should contain some known versions
let has_v20 = versions.iter().any(|v| v.version.starts_with("v20."));
assert!(has_v20, "Should contain Node.js v20.x versions");
}
#[test]
fn test_resolve_version_from_list_caret() {
use super::resolve_version_from_list;
// Mock version data in random order
let versions = vec![
NodeVersionEntry { version: "v20.17.0".into(), lts: LtsInfo::Codename("Iron".into()) },
NodeVersionEntry { version: "v20.19.0".into(), lts: LtsInfo::Codename("Iron".into()) },
NodeVersionEntry { version: "v20.18.0".into(), lts: LtsInfo::Codename("Iron".into()) },
NodeVersionEntry { version: "v21.0.0".into(), lts: LtsInfo::Boolean(false) },
NodeVersionEntry { version: "v20.20.0".into(), lts: LtsInfo::Codename("Iron".into()) },
];
// ^20.18.0 should match highest 20.x.x >= 20.18.0
let result = resolve_version_from_list("^20.18.0", &versions).unwrap();
assert_eq!(result, "20.20.0");
}
#[test]
fn test_resolve_version_from_list_tilde() {
use super::resolve_version_from_list;
let versions = vec![
NodeVersionEntry { version: "v20.18.0".into(), lts: LtsInfo::Codename("Iron".into()) },