-
Notifications
You must be signed in to change notification settings - Fork 196
Expand file tree
/
Copy pathdispatch.rs
More file actions
1850 lines (1620 loc) · 68.9 KB
/
dispatch.rs
File metadata and controls
1850 lines (1620 loc) · 68.9 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
//! Main dispatch logic for shim operations.
//!
//! This module handles the core shim functionality:
//! 1. Version resolution (with caching)
//! 2. Node.js installation (if needed)
//! 3. Tool execution (core tools and package binaries)
use vite_path::{AbsolutePath, AbsolutePathBuf, current_dir};
use vite_shared::{PrependOptions, env_vars, output, prepend_to_path_env};
use super::{
cache::{self, ResolveCache, ResolveCacheEntry},
exec, is_core_shim_tool,
};
use crate::commands::env::{
bin_config::{BinConfig, BinSource},
config::{self, ShimMode},
global_install::CORE_SHIMS,
package_metadata::PackageMetadata,
};
/// Environment variable used to prevent infinite recursion in shim dispatch.
///
/// When set, the shim will skip version resolution and execute the tool
/// directly using the current PATH (passthrough mode).
const RECURSION_ENV_VAR: &str = env_vars::VITE_PLUS_TOOL_RECURSION;
/// Package manager tools that should resolve Node.js version from the project context
/// rather than using the install-time version.
const PACKAGE_MANAGER_TOOLS: &[&str] = &["pnpm", "yarn", "bun"];
fn is_package_manager_tool(tool: &str) -> bool {
PACKAGE_MANAGER_TOOLS.contains(&tool)
}
/// Parsed npm global command (install or uninstall).
struct NpmGlobalCommand {
/// Package names/specs extracted from args (e.g., ["codex", "typescript@5"])
packages: Vec<String>,
/// Explicit `--prefix <dir>` from the CLI args, if present.
explicit_prefix: Option<String>,
}
/// Value-bearing npm flags whose next arg should be skipped during package extraction.
/// Note: `--prefix` is handled separately to capture its value.
const NPM_VALUE_FLAGS: &[&str] = &["--registry", "--tag", "--cache", "--tmp"];
/// Install subcommands recognized by npm.
const NPM_INSTALL_SUBCOMMANDS: &[&str] = &["install", "i", "add"];
/// Uninstall subcommands recognized by npm.
const NPM_UNINSTALL_SUBCOMMANDS: &[&str] = &["uninstall", "un", "remove", "rm"];
/// Parse npm args to detect a global command (`npm <subcommand> -g <packages>`).
/// Returns None if the args don't match the expected pattern.
fn parse_npm_global_command(args: &[String], subcommands: &[&str]) -> Option<NpmGlobalCommand> {
let mut has_global = false;
let mut has_subcommand = false;
let mut packages = Vec::new();
let mut skip_next = false;
let mut prefix_next = false;
let mut explicit_prefix = None;
// The npm subcommand must be the first positional (non-flag) arg.
// Once we see a positional that isn't a recognized subcommand, no later
// positional can be the subcommand (e.g. `npm run install -g` → not install).
let mut seen_positional = false;
for arg in args {
// Capture the value after --prefix
if prefix_next {
prefix_next = false;
explicit_prefix = Some(arg.clone());
continue;
}
if skip_next {
skip_next = false;
continue;
}
if arg == "-g" || arg == "--global" {
has_global = true;
continue;
}
// Capture --prefix specially (its value is needed for prefix resolution)
if arg == "--prefix" {
prefix_next = true;
continue;
}
if let Some(value) = arg.strip_prefix("--prefix=") {
explicit_prefix = Some(value.to_string());
continue;
}
// Check for value-bearing flags (skip their values)
if NPM_VALUE_FLAGS.contains(&arg.as_str()) {
skip_next = true;
continue;
}
// Skip flags
if arg.starts_with('-') {
continue;
}
// Subcommand must be the first positional arg
if !seen_positional && subcommands.contains(&arg.as_str()) && !has_subcommand {
has_subcommand = true;
seen_positional = true;
continue;
}
seen_positional = true;
// This is a positional arg (package spec)
packages.push(arg.clone());
}
if !has_global || !has_subcommand || packages.is_empty() {
return None;
}
Some(NpmGlobalCommand { packages, explicit_prefix })
}
/// Parse npm args to detect `npm install -g <packages>`.
fn parse_npm_global_install(args: &[String]) -> Option<NpmGlobalCommand> {
let mut parsed = parse_npm_global_command(args, NPM_INSTALL_SUBCOMMANDS)?;
// Filter out URLs and git+ prefixes (too complex to resolve package names)
parsed.packages.retain(|pkg| !pkg.contains("://") && !pkg.starts_with("git+"));
if parsed.packages.is_empty() { None } else { Some(parsed) }
}
/// Parse npm args to detect `npm uninstall -g <packages>`.
fn parse_npm_global_uninstall(args: &[String]) -> Option<NpmGlobalCommand> {
parse_npm_global_command(args, NPM_UNINSTALL_SUBCOMMANDS)
}
/// Resolve package name from a spec string.
///
/// Handles:
/// - Regular specs: "codex" → "codex", "typescript@5" → "typescript"
/// - Scoped specs: "@scope/pkg" → "@scope/pkg", "@scope/pkg@1.0" → "@scope/pkg"
/// - Local paths: "./foo" → reads foo/package.json → name field
fn is_local_path(spec: &str) -> bool {
spec == "."
|| spec == ".."
|| spec.starts_with("./")
|| spec.starts_with("../")
|| spec.starts_with('/')
|| (cfg!(windows)
&& spec.len() >= 3
&& spec.as_bytes()[1] == b':'
&& (spec.as_bytes()[2] == b'\\' || spec.as_bytes()[2] == b'/'))
}
fn resolve_package_name(spec: &str) -> Option<String> {
// Local path — read package.json to get the actual name
if is_local_path(spec) {
let pkg_json_path = current_dir().ok()?.join(spec).join("package.json");
let content = std::fs::read_to_string(pkg_json_path.as_path()).ok()?;
let json: serde_json::Value = serde_json::from_str(&content).ok()?;
return json.get("name").and_then(|n| n.as_str()).map(str::to_string);
}
// Scoped package: @scope/name or @scope/name@version
if let Some(rest) = spec.strip_prefix('@') {
if let Some(idx) = rest.find('@') {
return Some(spec[..=idx].to_string());
}
return Some(spec.to_string());
}
// Regular package: name or name@version
if let Some(idx) = spec.find('@') {
return Some(spec[..idx].to_string());
}
Some(spec.to_string())
}
/// Get the actual npm global prefix directory.
///
/// Runs `npm config get prefix` to determine the global prefix, which respects
/// `NPM_CONFIG_PREFIX` env var and `.npmrc` settings. Falls back to `node_dir`.
#[allow(clippy::disallowed_types)]
fn get_npm_global_prefix(npm_path: &AbsolutePath, node_dir: &AbsolutePathBuf) -> AbsolutePathBuf {
// `npm config get prefix` respects NPM_CONFIG_PREFIX, .npmrc, and other
// npm config mechanisms.
if let Ok(output) =
std::process::Command::new(npm_path.as_path()).args(["config", "get", "prefix"]).output()
{
if output.status.success() {
if let Ok(prefix) = std::str::from_utf8(&output.stdout) {
let prefix = prefix.trim();
if let Some(prefix_path) = AbsolutePathBuf::new(prefix.into()) {
return prefix_path;
}
}
}
}
// Fallback: default npm prefix is the Node install dir
node_dir.clone()
}
/// After npm install -g completes, check if installed binaries are on PATH.
///
/// First determines the actual npm global bin directory (which may differ from the
/// default if the user has set a custom prefix). If that directory is already on the
/// user's original PATH, binaries are reachable and no action is needed.
///
/// Otherwise, in interactive mode, prompt user to create bin links.
/// In non-interactive mode, create links automatically.
/// Always print a tip suggesting `vp install -g`.
#[allow(clippy::disallowed_macros, clippy::disallowed_types)]
fn check_npm_global_install_result(
packages: &[String],
original_path: Option<&std::ffi::OsStr>,
npm_prefix: &AbsolutePath,
node_dir: &AbsolutePath,
node_version: &str,
) {
use std::io::IsTerminal;
let Ok(bin_dir) = config::get_bin_dir() else { return };
// Derive bin dir from prefix (Unix: prefix/bin, Windows: prefix itself)
#[cfg(unix)]
let npm_bin_dir = npm_prefix.join("bin");
#[cfg(windows)]
let npm_bin_dir = npm_prefix.to_absolute_path_buf();
// If the npm global bin dir is already on the user's original PATH,
// binaries are reachable without shims — no action needed.
if let Some(orig) = original_path {
if std::env::split_paths(orig).any(|p| p == npm_bin_dir.as_path()) {
return;
}
}
let is_interactive = std::io::stdin().is_terminal();
// (bin_name, source_path, package_name)
let mut missing_bins: Vec<(String, AbsolutePathBuf, String)> = Vec::new();
let mut managed_conflicts: Vec<(String, String)> = Vec::new();
for spec in packages {
let Some(package_name) = resolve_package_name(spec) else { continue };
let Some(content) = read_npm_package_json(npm_prefix, node_dir, &package_name) else {
continue;
};
let Ok(package_json) = serde_json::from_str::<serde_json::Value>(&content) else {
continue;
};
let bin_names = extract_bin_names(&package_json);
for bin_name in bin_names {
// Skip core shims
if CORE_SHIMS.contains(&bin_name.as_str()) {
continue;
}
// Check if binary already exists in bin_dir (vite-plus bin)
// On Unix: symlinks (bin/tsc)
// On Windows: trampoline .exe (bin/tsc.exe) or legacy .cmd (bin/tsc.cmd)
let shim_path = bin_dir.join(&bin_name);
let shim_exists = std::fs::symlink_metadata(shim_path.as_path()).is_ok() || {
#[cfg(windows)]
{
let exe_path = bin_dir.join(vite_str::format!("{bin_name}.exe"));
std::fs::symlink_metadata(exe_path.as_path()).is_ok()
}
#[cfg(not(windows))]
false
};
if shim_exists {
if let Ok(Some(config)) = BinConfig::load_sync(&bin_name) {
if config.source == BinSource::Vp {
// Managed by vp install -g — warn about the conflict
managed_conflicts.push((bin_name, config.package.clone()));
} else if config.source == BinSource::Npm && config.package != package_name {
// Link exists from a different npm package — recreate link for new owner.
// The old symlink points at the previous package's binary; we must
// replace it so it resolves to the new package's binary in npm's bin dir.
#[cfg(unix)]
let source_path = npm_bin_dir.join(&bin_name);
#[cfg(windows)]
let source_path = npm_bin_dir.join(vite_str::format!("{bin_name}.cmd"));
if source_path.as_path().exists() {
let _ = std::fs::remove_file(shim_path.as_path());
create_bin_link(
&bin_dir,
&bin_name,
&source_path,
&package_name,
node_version,
);
}
}
}
continue;
}
// Also check .cmd on Windows
#[cfg(windows)]
{
let cmd_path = bin_dir.join(format!("{bin_name}.cmd"));
if cmd_path.as_path().exists() {
continue;
}
}
// Binary source in actual npm global bin dir
#[cfg(unix)]
let source_path = npm_bin_dir.join(&bin_name);
#[cfg(windows)]
let source_path = npm_bin_dir.join(format!("{bin_name}.cmd"));
if source_path.as_path().exists() {
missing_bins.push((bin_name, source_path, package_name.clone()));
}
}
}
// Deduplicate by bin_name so that when two packages declare the same binary,
// only the last one is linked (matching npm's "last writer wins" behavior).
let missing_bins = dedup_missing_bins(missing_bins);
if !managed_conflicts.is_empty() {
for (bin_name, pkg) in &managed_conflicts {
output::raw(&vite_str::format!(
"Skipped '{bin_name}': managed by `vp install -g {pkg}`. Run `vp uninstall -g {pkg}` to remove it first."
));
}
}
if missing_bins.is_empty() {
return;
}
let should_link = if is_interactive {
// Prompt user
let bin_list: Vec<&str> = missing_bins.iter().map(|(name, _, _)| name.as_str()).collect();
let bin_display = bin_list.join(", ");
output::raw(&vite_str::format!("'{bin_display}' is not available on your PATH."));
output::raw_inline("Create a link in ~/.vite-plus/bin/ to make it available? [Y/n] ");
let _ = std::io::Write::flush(&mut std::io::stdout());
let mut input = String::new();
let confirmed = std::io::stdin().read_line(&mut input).is_ok();
let trimmed = input.trim();
confirmed
&& (trimmed.is_empty()
|| trimmed.eq_ignore_ascii_case("y")
|| trimmed.eq_ignore_ascii_case("yes"))
} else {
// Non-interactive: auto-link
true
};
if should_link {
for (bin_name, source_path, package_name) in &missing_bins {
create_bin_link(&bin_dir, bin_name, source_path, package_name, node_version);
}
}
// Always print the tip
let pkg_names: Vec<&str> = packages.iter().map(String::as_str).collect();
let pkg_display = pkg_names.join(" ");
output::raw(&vite_str::format!(
"\ntip: Use `vp install -g {pkg_display}` for managed shims that persist across Node.js version changes."
));
}
/// Extract binary names from a package.json value.
fn extract_bin_names(package_json: &serde_json::Value) -> Vec<String> {
let mut bins = Vec::new();
if let Some(bin) = package_json.get("bin") {
match bin {
serde_json::Value::String(_) => {
// Single binary with package name
if let Some(name) = package_json["name"].as_str() {
let bin_name = name.split('/').last().unwrap_or(name);
bins.push(bin_name.to_string());
}
}
serde_json::Value::Object(map) => {
for name in map.keys() {
bins.push(name.clone());
}
}
_ => {}
}
}
bins
}
/// Extract the relative path for a specific bin name from a package.json "bin" field.
fn extract_bin_path(package_json: &serde_json::Value, bin_name: &str) -> Option<String> {
match package_json.get("bin")? {
serde_json::Value::String(path) => {
// Single binary — matches if the package name's last segment equals bin_name
let pkg_name = package_json["name"].as_str()?;
let expected = pkg_name.split('/').last().unwrap_or(pkg_name);
if expected == bin_name { Some(path.clone()) } else { None }
}
serde_json::Value::Object(map) => {
map.get(bin_name).and_then(|v| v.as_str()).map(str::to_string)
}
_ => None,
}
}
/// Create a bin link for a binary and record it via BinConfig.
fn create_bin_link(
bin_dir: &AbsolutePath,
bin_name: &str,
source_path: &AbsolutePath,
package_name: &str,
node_version: &str,
) {
let mut linked = false;
#[cfg(unix)]
{
let link_path = bin_dir.join(bin_name);
if std::os::unix::fs::symlink(source_path.as_path(), link_path.as_path()).is_ok() {
output::raw(&vite_str::format!(
"Linked '{bin_name}' to {}",
link_path.as_path().display()
));
linked = true;
} else {
output::error(&vite_str::format!("Failed to create link for '{bin_name}'"));
}
}
#[cfg(windows)]
{
// npm-installed packages use .cmd wrappers pointing to npm's generated script.
// Unlike vp-installed packages, these don't have PackageMetadata, so the
// trampoline approach won't work (dispatch_package_binary would fail).
let cmd_path = bin_dir.join(vite_str::format!("{bin_name}.cmd"));
let wrapper_content = vite_str::format!(
"@echo off\r\n\"{source}\" %*\r\nexit /b %ERRORLEVEL%\r\n",
source = source_path.as_path().display()
);
if std::fs::write(cmd_path.as_path(), &*wrapper_content).is_ok() {
output::raw(&vite_str::format!(
"Linked '{bin_name}' to {}",
cmd_path.as_path().display()
));
linked = true;
} else {
output::error(&vite_str::format!("Failed to create link for '{bin_name}'"));
}
// Also create shell script for Git Bash
let sh_path = bin_dir.join(bin_name);
let sh_content =
format!("#!/bin/sh\nexec \"{}\" \"$@\"\n", source_path.as_path().display());
let _ = std::fs::write(sh_path.as_path(), sh_content);
}
// Record the link in BinConfig so we can identify it during uninstall
if linked {
let _ = BinConfig::new_npm(
bin_name.to_string(),
package_name.to_string(),
node_version.to_string(),
)
.save_sync();
}
}
/// Deduplicate missing_bins by bin_name, keeping the last entry (npm's "last writer wins").
///
/// When `npm install -g pkg-a pkg-b` and both declare the same binary name, we get
/// duplicate entries. Without dedup, `create_bin_link` would fail on the second entry
/// because the symlink already exists, leaving stale BinConfig for the first package.
#[allow(clippy::disallowed_types)]
fn dedup_missing_bins(
missing_bins: Vec<(String, AbsolutePathBuf, String)>,
) -> Vec<(String, AbsolutePathBuf, String)> {
let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut deduped = Vec::new();
for entry in missing_bins.into_iter().rev() {
if seen.insert(entry.0.clone()) {
deduped.push(entry);
}
}
deduped.reverse();
deduped
}
/// After npm uninstall -g completes, remove bin links that were created during install.
///
/// Each entry is `(bin_name, package_name)`. We only remove a link if its BinConfig
/// has `source: Npm` AND `package` matches the package being uninstalled. This prevents
/// removing a link that was overwritten by a later install of a different package.
///
/// When a bin is owned by a **different** npm package (not being uninstalled), npm may
/// still delete its binary from `npm_bin_dir`, leaving our symlink dangling. In that
/// case we repair the link by pointing directly at the surviving package's binary.
#[allow(clippy::disallowed_types)]
fn remove_npm_global_uninstall_links(bin_entries: &[(String, String)], npm_prefix: &AbsolutePath) {
let Ok(bin_dir) = config::get_bin_dir() else { return };
for (bin_name, package_name) in bin_entries {
// Skip core shims
if CORE_SHIMS.contains(&bin_name.as_str()) {
continue;
}
let config = match BinConfig::load_sync(bin_name) {
Ok(Some(c)) if c.source == BinSource::Npm => c,
_ => continue,
};
if config.package == *package_name {
// Owned by the package being uninstalled — remove the link
let link_path = bin_dir.join(bin_name);
if std::fs::symlink_metadata(link_path.as_path()).is_ok() {
if std::fs::remove_file(link_path.as_path()).is_ok() {
output::raw(&vite_str::format!(
"Removed link '{bin_name}' from {}",
link_path.as_path().display()
));
}
}
// Clean up the BinConfig
let _ = BinConfig::delete_sync(bin_name);
// Also remove .cmd and .exe on Windows
#[cfg(windows)]
{
let cmd_path = bin_dir.join(vite_str::format!("{bin_name}.cmd"));
let _ = std::fs::remove_file(cmd_path.as_path());
let exe_path = bin_dir.join(vite_str::format!("{bin_name}.exe"));
let _ = std::fs::remove_file(exe_path.as_path());
}
} else {
// Owned by a different npm package — check if our link target is now broken
// (npm may have deleted the binary from npm_bin_dir when uninstalling)
let link_path = bin_dir.join(bin_name);
// On Unix, exists() follows the symlink — if target is gone, it returns false.
// On Windows, the shim files are regular files that always "exist",
// so we always fall through to the repair check below.
#[cfg(unix)]
if link_path.as_path().exists() {
// Target still accessible — nothing to repair
continue;
}
// Target is broken — repair by pointing to the surviving package's binary
let surviving_pkg = &config.package;
let node_modules_dir = config::get_node_modules_dir(npm_prefix, surviving_pkg);
let pkg_json_path = node_modules_dir.join("package.json");
let content = match std::fs::read_to_string(pkg_json_path.as_path()) {
Ok(c) => c,
Err(_) => continue,
};
let package_json = match serde_json::from_str::<serde_json::Value>(&content) {
Ok(v) => v,
Err(_) => continue,
};
let Some(bin_rel_path) = extract_bin_path(&package_json, bin_name) else {
continue;
};
let source_path = node_modules_dir.join(&bin_rel_path);
if source_path.as_path().exists() {
let _ = std::fs::remove_file(link_path.as_path());
#[cfg(windows)]
{
let cmd_path = bin_dir.join(vite_str::format!("{bin_name}.cmd"));
let _ = std::fs::remove_file(cmd_path.as_path());
}
create_bin_link(
&bin_dir,
bin_name,
&source_path,
surviving_pkg,
&config.node_version,
);
}
}
}
}
/// Read the installed package.json from npm's node_modules directory.
/// Tries the npm prefix first (handles custom prefix), then falls back to node_dir.
#[allow(clippy::disallowed_types)]
fn read_npm_package_json(
npm_prefix: &AbsolutePath,
node_dir: &AbsolutePath,
package_name: &str,
) -> Option<String> {
std::fs::read_to_string(
config::get_node_modules_dir(npm_prefix, package_name).join("package.json").as_path(),
)
.ok()
.or_else(|| {
let dir = config::get_node_modules_dir(node_dir, package_name);
std::fs::read_to_string(dir.join("package.json").as_path()).ok()
})
}
/// Collect (bin_name, package_name) pairs from packages by reading their installed package.json files.
#[allow(clippy::disallowed_types)]
fn collect_bin_names_from_npm(
packages: &[String],
npm_prefix: &AbsolutePath,
node_dir: &AbsolutePath,
) -> Vec<(String, String)> {
let mut all_bins = Vec::new();
for spec in packages {
let Some(package_name) = resolve_package_name(spec) else { continue };
let Some(content) = read_npm_package_json(npm_prefix, node_dir, &package_name) else {
continue;
};
let Ok(package_json) = serde_json::from_str::<serde_json::Value>(&content) else {
continue;
};
for bin_name in extract_bin_names(&package_json) {
all_bins.push((bin_name, package_name.clone()));
}
}
all_bins
}
/// Resolve the npm prefix, preferring an explicit `--prefix` from CLI args.
///
/// Handles both absolute and relative `--prefix` values by resolving against cwd.
/// `AbsolutePathBuf::join` replaces the base when the argument is absolute (like
/// `PathBuf::join`), so `cwd.join("/abs")` → `/abs` and `cwd.join("./rel")` → `/cwd/./rel`.
fn resolve_npm_prefix(
parsed: &NpmGlobalCommand,
npm_path: &AbsolutePath,
node_dir: &AbsolutePathBuf,
) -> AbsolutePathBuf {
if let Some(ref prefix) = parsed.explicit_prefix {
if let Ok(cwd) = current_dir() {
return cwd.join(prefix);
}
}
get_npm_global_prefix(npm_path, node_dir)
}
/// Main shim dispatch entry point.
///
/// Called when the binary is invoked as node, npm, npx, or a package binary.
/// Returns an exit code to be used with std::process::exit.
pub async fn dispatch(tool: &str, args: &[String]) -> i32 {
tracing::debug!("dispatch: tool: {tool}, args: {:?}", args);
// Handle vpx — standalone command, doesn't need recursion/bypass/shim-mode checks
if tool == "vpx" {
let cwd = match current_dir() {
Ok(path) => path,
Err(e) => {
eprintln!("vp: Failed to get current directory: {e}");
return 1;
}
};
return crate::commands::vpx::execute_vpx(args, &cwd).await;
}
// Check recursion prevention - if already in a shim context, passthrough directly
// Only applies to core tools (node/npm/npx) whose bin dir is prepended to PATH.
// Package binaries are always resolved via metadata lookup, so they can't loop.
if std::env::var(RECURSION_ENV_VAR).is_ok() && is_core_shim_tool(tool) {
tracing::debug!("recursion prevention enabled for core tool");
return passthrough_to_system(tool, args);
}
// Check bypass mode (explicit environment variable)
if std::env::var(env_vars::VITE_PLUS_BYPASS).is_ok() {
tracing::debug!("bypass mode enabled");
return bypass_to_system(tool, args);
}
// Check shim mode from config
let shim_mode = load_shim_mode().await;
if shim_mode == ShimMode::SystemFirst {
tracing::debug!("system-first mode enabled");
// In system-first mode, try to find system tool first
if let Some(system_path) = find_system_tool(tool) {
// Append current bin_dir to VITE_PLUS_BYPASS to prevent infinite loops
// when multiple vite-plus installations exist in PATH.
// The next installation will filter all accumulated paths.
if let Ok(bin_dir) = config::get_bin_dir() {
let bypass_val = match std::env::var_os(env_vars::VITE_PLUS_BYPASS) {
Some(existing) => {
let mut paths: Vec<_> = std::env::split_paths(&existing).collect();
paths.push(bin_dir.as_path().to_path_buf());
std::env::join_paths(paths).unwrap_or(existing)
}
None => std::ffi::OsString::from(bin_dir.as_path()),
};
// SAFETY: Setting env vars before exec (which replaces the process) is safe
unsafe {
std::env::set_var(env_vars::VITE_PLUS_BYPASS, bypass_val);
}
}
return exec::exec_tool(&system_path, args);
}
// Fall through to managed if system not found
}
// Check if this is a package binary (not node/npm/npx)
if !is_core_shim_tool(tool) {
return dispatch_package_binary(tool, args).await;
}
// Get current working directory
let cwd = match current_dir() {
Ok(path) => path,
Err(e) => {
eprintln!("vp: Failed to get current directory: {e}");
return 1;
}
};
// Resolve version (with caching)
let resolution = match resolve_with_cache(&cwd).await {
Ok(r) => r,
Err(e) => {
eprintln!("vp: Failed to resolve Node version: {e}");
eprintln!("vp: Run 'vp env doctor' for diagnostics");
return 1;
}
};
// Ensure Node.js is installed
if let Err(e) = ensure_installed(&resolution.version).await {
eprintln!("vp: Failed to install Node {}: {e}", resolution.version);
return 1;
}
// Locate tool binary
let tool_path = match locate_tool(&resolution.version, tool) {
Ok(p) => p,
Err(e) => {
eprintln!("vp: Tool '{tool}' not found: {e}");
return 1;
}
};
// Save original PATH before we modify it — needed for npm global install check.
// Only captured for npm to avoid unnecessary work on node/npx hot path.
let original_path = if tool == "npm" { std::env::var_os("PATH") } else { None };
// Prepare environment for recursive invocations
// Prepend real node bin dir to PATH so child processes use the correct version
let node_bin_dir = tool_path.parent().expect("Tool has no parent directory");
// Use dedupe_anywhere=false to only check if it's first in PATH (original behavior)
prepend_to_path_env(node_bin_dir, PrependOptions::default());
// Optional debug env vars
if std::env::var(env_vars::VITE_PLUS_DEBUG_SHIM).is_ok() {
// SAFETY: Setting env vars at this point before exec is safe
unsafe {
std::env::set_var(env_vars::VITE_PLUS_ACTIVE_NODE, &resolution.version);
std::env::set_var(env_vars::VITE_PLUS_RESOLVE_SOURCE, &resolution.source);
}
}
// Set recursion prevention marker before executing
// This prevents infinite loops when the executed tool invokes another shim
// SAFETY: Setting env vars at this point before exec is safe
unsafe {
std::env::set_var(RECURSION_ENV_VAR, "1");
}
// For npm install/uninstall -g, use spawn+wait so we can post-check/cleanup binaries
if tool == "npm" {
if let Some(parsed) = parse_npm_global_install(args) {
let exit_code = exec::spawn_tool(&tool_path, args);
if exit_code == 0 {
if let Ok(home_dir) = vite_shared::get_vite_plus_home() {
let node_dir =
home_dir.join("js_runtime").join("node").join(&*resolution.version);
let npm_prefix = resolve_npm_prefix(&parsed, &tool_path, &node_dir);
check_npm_global_install_result(
&parsed.packages,
original_path.as_deref(),
&npm_prefix,
&node_dir,
&resolution.version,
);
}
}
return exit_code;
}
if let Some(parsed) = parse_npm_global_uninstall(args) {
// Collect bin names before uninstall (package.json will be gone after)
let context = if let Ok(home_dir) = vite_shared::get_vite_plus_home() {
let node_dir = home_dir.join("js_runtime").join("node").join(&*resolution.version);
let npm_prefix = resolve_npm_prefix(&parsed, &tool_path, &node_dir);
let bins = collect_bin_names_from_npm(&parsed.packages, &npm_prefix, &node_dir);
Some((bins, npm_prefix))
} else {
None
};
let exit_code = exec::spawn_tool(&tool_path, args);
if exit_code == 0 {
if let Some((bin_names, npm_prefix)) = context {
remove_npm_global_uninstall_links(&bin_names, &npm_prefix);
}
}
return exit_code;
}
}
// Execute the tool (normal path — exec replaces process on Unix)
exec::exec_tool(&tool_path, args)
}
/// Dispatch a package binary shim.
///
/// Finds the package that provides this binary and executes it with the
/// Node.js version that was used to install the package.
async fn dispatch_package_binary(tool: &str, args: &[String]) -> i32 {
// Find which package provides this binary
let package_metadata = match find_package_for_binary(tool).await {
Ok(Some(metadata)) => metadata,
Ok(None) => {
eprintln!("vp: Binary '{tool}' not found in any installed package");
eprintln!("vp: Run 'vp install -g <package>' to install");
return 1;
}
Err(e) => {
eprintln!("vp: Failed to find package for '{tool}': {e}");
return 1;
}
};
// Determine Node.js version to use:
// - Package managers (pnpm, yarn): resolve from project context so they respect
// the project's engines.node / .node-version, falling back to install-time version
// - Other package binaries: use the install-time version (original behavior)
let node_version = if is_package_manager_tool(tool) {
let cwd = match current_dir() {
Ok(path) => path,
Err(e) => {
eprintln!("vp: Failed to get current directory: {e}");
return 1;
}
};
match resolve_with_cache(&cwd).await {
Ok(resolution) => resolution.version,
Err(_) => {
// Fall back to install-time version if project resolution fails
package_metadata.platform.node.clone()
}
}
} else {
package_metadata.platform.node.clone()
};
// Ensure Node.js is installed
if let Err(e) = ensure_installed(&node_version).await {
eprintln!("vp: Failed to install Node {}: {e}", node_version);
return 1;
}
// Locate the actual binary in the package directory
let binary_path = match locate_package_binary(&package_metadata.name, tool) {
Ok(p) => p,
Err(e) => {
eprintln!("vp: Binary '{tool}' not found: {e}");
return 1;
}
};
// Locate node binary for this version
let node_path = match locate_tool(&node_version, "node") {
Ok(p) => p,
Err(e) => {
eprintln!("vp: Node not found: {e}");
return 1;
}
};
// Prepare environment for recursive invocations
let node_bin_dir = node_path.parent().expect("Node has no parent directory");
prepend_to_path_env(node_bin_dir, PrependOptions::default());
// Check if the binary is a JavaScript file that needs Node.js
// This info was determined at install time and stored in metadata
if package_metadata.is_js_binary(tool) {
// Execute: node <binary_path> <args>
let mut full_args = vec![binary_path.as_path().display().to_string()];
full_args.extend(args.iter().cloned());
exec::exec_tool(&node_path, &full_args)
} else {
// Execute the binary directly (native executable or non-Node script)
exec::exec_tool(&binary_path, args)
}
}
/// Find the package that provides a given binary.
///
/// Uses BinConfig for deterministic O(1) lookup instead of scanning all packages.
pub(crate) async fn find_package_for_binary(
binary_name: &str,
) -> Result<Option<PackageMetadata>, String> {
// Use BinConfig for deterministic lookup
if let Some(bin_config) = BinConfig::load(binary_name).await.map_err(|e| format!("{e}"))? {
return PackageMetadata::load(&bin_config.package).await.map_err(|e| format!("{e}"));
}
// Binary not installed
Ok(None)
}
/// Locate a binary within a package's installation directory.
pub(crate) fn locate_package_binary(
package_name: &str,
binary_name: &str,
) -> Result<AbsolutePathBuf, String> {
let packages_dir = config::get_packages_dir().map_err(|e| format!("{e}"))?;
let package_dir = packages_dir.join(package_name);
// The binary is referenced in package.json's bin field
// npm uses different layouts: Unix=lib/node_modules, Windows=node_modules
let node_modules_dir = config::get_node_modules_dir(&package_dir, package_name);
let package_json_path = node_modules_dir.join("package.json");
if !package_json_path.as_path().exists() {
return Err(format!("Package {} not found", package_name));
}
// Read package.json to find the binary path
let content = std::fs::read_to_string(package_json_path.as_path())
.map_err(|e| format!("Failed to read package.json: {e}"))?;
let package_json: serde_json::Value =
serde_json::from_str(&content).map_err(|e| format!("Failed to parse package.json: {e}"))?;
let binary_path = match package_json.get("bin") {
Some(serde_json::Value::String(path)) => {
// Single binary - check if it matches the name
let pkg_name = package_json["name"].as_str().unwrap_or("");
let expected_name = pkg_name.split('/').last().unwrap_or(pkg_name);
if expected_name == binary_name {
node_modules_dir.join(path)
} else {
return Err(format!("Binary {} not found in package", binary_name));
}
}
Some(serde_json::Value::Object(map)) => {
// Multiple binaries - find the one we need
if let Some(serde_json::Value::String(path)) = map.get(binary_name) {
node_modules_dir.join(path)
} else {
return Err(format!("Binary {} not found in package", binary_name));
}
}
_ => {
return Err(format!("No bin field in package.json for {}", package_name));
}
};
if !binary_path.as_path().exists() {
return Err(format!(
"Binary {} not found at {}",
binary_name,
binary_path.as_path().display()
));
}
Ok(binary_path)
}
/// Bypass shim and use system tool.
fn bypass_to_system(tool: &str, args: &[String]) -> i32 {
match find_system_tool(tool) {
Some(system_path) => exec::exec_tool(&system_path, args),
None => {
eprintln!("vp: VITE_PLUS_BYPASS is set but no system '{tool}' found in PATH");
1
}
}
}
/// Passthrough mode for recursion prevention.
///
/// When VITE_PLUS_TOOL_RECURSION is set, we skip version resolution
/// and execute the tool directly using the current PATH.
/// This prevents infinite loops when a managed tool invokes another shim.
fn passthrough_to_system(tool: &str, args: &[String]) -> i32 {