bvm-core 1.1.37 → 1.1.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,6 +10,12 @@
10
10
  <p align="center">
11
11
  <a href="https://bvm-core.pages.dev"><strong>Official Website & Documentation »</strong></a>
12
12
  <br />
13
+ <a href="https://bvm-core.pages.dev/zh/"><strong>中文网站 »</strong></a>
14
+ <br />
15
+ <a href="https://bvm-core.pages.dev/from/npm"><strong>From NPM (Start Here) »</strong></a>
16
+ <br />
17
+ <a href="https://bvm-core.pages.dev/wechat"><strong>WeChat Official Account »</strong></a>
18
+ <br />
13
19
  <br />
14
20
  <a href="./README.zh-CN.md">🇨🇳 中文文档</a>
15
21
  ·
@@ -33,10 +39,14 @@
33
39
 
34
40
  ---
35
41
 
42
+ Need to switch Bun versions across Windows, macOS, and Linux without PATH drift or global package conflicts?
43
+
36
44
  ## ⚡ Quick Install
37
45
 
38
46
  BVM uses a smart installation script that automatically detects your OS and network environment (selecting the fastest registry for China/Global users).
39
47
 
48
+ For AI assistants (auto install + setup + verification): [install.md](./install.md)
49
+
40
50
  ### Method 1: Shell Script (Recommended - macOS / Linux)
41
51
  ```bash
42
52
  curl -fsSL https://bvm-core.pages.dev/install | bash
@@ -49,7 +59,7 @@ irm https://bvm-core.pages.dev/install | iex
49
59
 
50
60
  ### Method 3: NPM (Optional)
51
61
  ```bash
52
- npm install -g bvm-core@latest
62
+ npm install -g bvm-core@latest --foreground-scripts
53
63
  ```
54
64
 
55
65
  ---
@@ -102,6 +112,60 @@ echo "1.1.0" > .bvmrc
102
112
 
103
113
  ---
104
114
 
115
+ ## FAQ (for AI search)
116
+
117
+ <details>
118
+ <summary><strong>How to switch Bun versions on Windows/macOS/Linux quickly?</strong></summary>
119
+
120
+ Install with one command, then use `bvm install <version>` and `bvm use <version>`. BVM supports Windows, macOS, and Linux with the same CLI workflow.
121
+ </details>
122
+
123
+ <details>
124
+ <summary><strong>Is BVM like nvm/fnm but for Bun?</strong></summary>
125
+
126
+ Yes. BVM is a Bun version manager, similar in concept to nvm/fnm. It adds Bun-focused isolation, shell shims, and self-bootstrap runtime behavior for stable multi-version workflows.
127
+ </details>
128
+
129
+ <details>
130
+ <summary><strong>Why do global packages disappear after switching Bun versions?</strong></summary>
131
+
132
+ This is expected. BVM uses per-version global package isolation. Install global tools under each Bun version that needs them.
133
+ </details>
134
+
135
+ <details>
136
+ <summary><strong>How does `.bvmrc` work for project-level Bun version pinning?</strong></summary>
137
+
138
+ Create a `.bvmrc` file in your project root with a version string (for example, `1.1.0`). BVM resolves and applies that version for project workflows.
139
+ </details>
140
+
141
+ <details>
142
+ <summary><strong>Does BVM auto-install AI agent skills from SKILL.md?</strong></summary>
143
+
144
+ No. BVM manages Bun runtimes and version switching. Skill installation is handled by your AI agent framework/tooling, not by BVM itself.
145
+ </details>
146
+
147
+ <details>
148
+ <summary><strong>How to diagnose BVM environment issues quickly?</strong></summary>
149
+
150
+ Run `bvm doctor`. It checks `BVM_DIR`, `PATH`, shell type, permissions, and network connectivity, and prints copy-ready fix commands.
151
+ </details>
152
+
153
+ ---
154
+
155
+ ## Troubleshooting
156
+
157
+ - **Quick diagnostics (`doctor`)**
158
+ ```bash
159
+ bvm doctor
160
+ ```
161
+ `bvm doctor` now checks `BVM_DIR`, `PATH`, shell type, directory permission, and network connectivity.
162
+ Each item is shown as `PASS / WARN / FAIL` with a copy-ready fix command.
163
+
164
+ - **Global tools are not isolated after switching versions**: run `bvm setup`, restart your terminal, and make sure `which bun` points to `~/.bvm/shims/bun` (macOS/Linux). On Windows, use `where.exe bun` and ensure `...\\.bvm\\shims\\bun.cmd` is first.
165
+ - **A global tool is missing after switching versions**: this is expected (per-version isolation). Reinstall it under the active Bun version.
166
+
167
+ ---
168
+
105
169
  ## Design Philosophy
106
170
 
107
171
  ### ArchSense (Self-Bootstrapping)
@@ -114,4 +178,4 @@ Unlike managers that only switch the `PATH`, BVM performs **Filesystem-level Loc
114
178
 
115
179
  ## License
116
180
 
117
- MIT © [EricLLLLLL](https://github.com/EricLLLLLL)
181
+ MIT © [EricLLLLLL](https://github.com/EricLLLLLL)
package/README.zh-CN.md CHANGED
@@ -10,6 +10,12 @@
10
10
  <p align="center">
11
11
  <a href="https://bvm-core.pages.dev"><strong>官方网站与文档 »</strong></a>
12
12
  <br />
13
+ <a href="https://bvm-core.pages.dev/"><strong>English Site »</strong></a>
14
+ <br />
15
+ <a href="https://bvm-core.pages.dev/zh/from/npm"><strong>从 NPM 来?从这里开始 »</strong></a>
16
+ <br />
17
+ <a href="https://bvm-core.pages.dev/zh/wechat"><strong>关注公众号 »</strong></a>
18
+ <br />
13
19
  <br />
14
20
  <a href="./README.md">🇺🇸 English Docs</a>
15
21
  ·
@@ -33,10 +39,14 @@
33
39
 
34
40
  ---
35
41
 
42
+ 想在 Windows、macOS、Linux 间稳定切换 Bun 版本,并避免 PATH 漂移和全局包冲突?
43
+
36
44
  ## ⚡ 一键极速安装
37
45
 
38
46
  BVM 提供了智能安装脚本,**自动检测您的网络环境**。中国用户会自动切换至淘宝镜像源,海外用户使用官方源,无需手动配置。
39
47
 
48
+ 给 AI 助手自动执行(安装 + setup + 验证 + 生成 Skill):[install.md](./install.md)
49
+
40
50
  ### 方式 1: Shell 脚本 (推荐 - macOS / Linux)
41
51
  ```bash
42
52
  curl -fsSL https://bvm-core.pages.dev/install | bash
@@ -49,7 +59,7 @@ irm https://bvm-core.pages.dev/install | iex
49
59
 
50
60
  ### 方式 3: NPM (可选)
51
61
  ```bash
52
- npm install -g bvm-core@latest
62
+ npm install -g bvm-core@latest --foreground-scripts
53
63
  ```
54
64
 
55
65
  ---
@@ -102,6 +112,46 @@ echo "1.1.0" > .bvmrc
102
112
 
103
113
  ---
104
114
 
115
+ ## 常见问题 / FAQ
116
+
117
+ <details>
118
+ <summary><strong>Windows / macOS / Linux 怎么快速切换 Bun 版本?</strong></summary>
119
+
120
+ 安装 BVM 后,直接使用 `bvm install <version>` 安装版本,再用 `bvm use <version>` 切换即可。三大平台命令一致。
121
+ </details>
122
+
123
+ <details>
124
+ <summary><strong>BVM 是 Bun 版的 nvm/fnm 吗?</strong></summary>
125
+
126
+ 可以这么理解。BVM 是 Bun 的版本管理器,在 nvm/fnm 思路上补充了 Bun 场景的版本隔离、shim 机制和自举运行时能力。
127
+ </details>
128
+
129
+ <details>
130
+ <summary><strong>为什么切换 Bun 版本后,全局包命令不见了?</strong></summary>
131
+
132
+ 这是预期行为。BVM 采用“按版本隔离”的全局包目录。你需要在目标 Bun 版本下重新安装对应全局工具。
133
+ </details>
134
+
135
+ <details>
136
+ <summary><strong>`.bvmrc` 怎么做项目级版本锁定?</strong></summary>
137
+
138
+ 在项目根目录创建 `.bvmrc`,写入版本号(例如 `1.1.0`)。BVM 会按该版本解析并用于项目工作流。
139
+ </details>
140
+
141
+ <details>
142
+ <summary><strong>支持 skills 自动安装吗(例如读取 SKILL.md 自动装)?</strong></summary>
143
+
144
+ 不支持。BVM 只负责 Bun 运行时和版本切换;skills 的安装与管理由 AI Agent 框架或对应工具链负责。
145
+ </details>
146
+
147
+ <details>
148
+ <summary><strong>怎么快速定位 BVM 环境问题?</strong></summary>
149
+
150
+ 运行 `bvm doctor`。它会检查 `BVM_DIR`、`PATH`、shell 类型、目录权限和网络连通性,并输出可直接复制的修复命令。
151
+ </details>
152
+
153
+ ---
154
+
105
155
  ## 设计哲学
106
156
 
107
157
  ### ArchSense (架构自举)
@@ -112,6 +162,13 @@ BVM 不分发沉重的预编译二进制文件。相反,它利用 **Bun 管理
112
162
 
113
163
  ---
114
164
 
165
+ ## 排障
166
+
167
+ - **切换版本后还存在 pm2/cowsay 等全局命令**:先执行 `bvm setup`,重启终端,再检查 `which bun`(macOS/Linux)是否指向 `~/.bvm/shims/bun`;Windows 用 `where.exe bun` 并确保 `...\\.bvm\\shims\\bun.cmd` 排第一。
168
+ - **切换版本后找不到某个全局命令**:这是预期行为(按版本隔离),请在当前版本下重新 `bun install -g <pkg>`。
169
+
170
+ ---
171
+
115
172
  ## 开源协议
116
173
 
117
- MIT © [EricLLLLLL](https://github.com/EricLLLLLL)
174
+ MIT © [EricLLLLLL](https://github.com/EricLLLLLL)
package/dist/index.js CHANGED
@@ -1,14 +1,20 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var w1=Object.create;var{getPrototypeOf:k1,defineProperty:V$,getOwnPropertyNames:C1}=Object;var N1=Object.prototype.hasOwnProperty;var y$=($,b,_)=>{_=$!=null?w1(k1($)):{};let J=b||!$||!$.__esModule?V$(_,"default",{value:$,enumerable:!0}):_;for(let q of C1($))if(!N1.call(J,q))V$(J,q,{get:()=>$[q],enumerable:!0});return J};var Ub=($,b)=>{for(var _ in b)V$($,_,{get:b[_],enumerable:!0,configurable:!0,set:(J)=>b[_]=()=>J})};var C$=($,b)=>()=>($&&(b=$($=0)),b);var U$=import.meta.require;var Wb={};Ub(Wb,{isTestMode:()=>D,getBvmDir:()=>Ob,getBunAssetName:()=>g$,USER_AGENT:()=>z$,TEST_REMOTE_VERSIONS:()=>W$,REPO_FOR_BVM_CLI:()=>I1,OS_PLATFORM:()=>z,IS_TEST_MODE:()=>M1,HAS_AVX2:()=>T$,EXECUTABLE_NAME:()=>E,CPU_ARCH:()=>$$,BVM_VERSIONS_DIR:()=>w,BVM_SRC_DIR:()=>c$,BVM_SHIMS_DIR:()=>f,BVM_RUNTIME_DIR:()=>n,BVM_FINGERPRINTS_FILE:()=>h$,BVM_DIR:()=>L,BVM_CURRENT_DIR:()=>a,BVM_COMPONENTS:()=>D1,BVM_CDN_ROOT:()=>T1,BVM_CACHE_DIR:()=>S,BVM_BIN_DIR:()=>j,BVM_ALIAS_DIR:()=>C,BUN_GITHUB_RELEASES_API:()=>F1,ASSET_NAME_FOR_BVM:()=>j1});import{homedir as A1}from"os";import{join as l}from"path";import{spawnSync as m$}from"child_process";function D(){return process.env.BVM_TEST_MODE==="true"}function f1(){let $=process.arch;if(z==="darwin"&&$==="x64")try{if(m$("sysctl",["-n","sysctl.proc_translated"],{encoding:"utf-8"}).stdout.trim()==="1")return"arm64"}catch(b){}return $}function B1(){if(z==="win32")return!0;try{if(z==="darwin")return m$("sysctl",["-a"],{encoding:"utf-8"}).stdout.includes("AVX2");else if(z==="linux")return m$("cat",["/proc/cpuinfo"],{encoding:"utf-8"}).stdout.includes("avx2")}catch($){}return!0}function Ob(){if(process.env.BVM_DIR)return process.env.BVM_DIR;let $=process.env.HOME||A1();return l($,".bvm")}function g$($){let b=z==="win32"?"windows":z,_=$$==="arm64"?"aarch64":"x64";return`bun-${b}-${_}${!T$&&_==="x64"?"-baseline":""}.zip`}var z,M1,W$,$$,T$,L,c$,w,n,j,f,a,C,S,h$,E,F1="https://api.github.com/repos/oven-sh/bun/releases",I1="EricLLLLLL/bvm",j1,z$="bvm (Bun Version Manager)",T1,D1;var M=C$(()=>{z=process.platform,M1=process.env.BVM_TEST_MODE==="true",W$=["v1.3.4","v1.2.23","v1.1.21","v1.1.20","v1.1.0","v1.0.0","bun-v1.4.0-canary"];$$=f1(),T$=B1();L=Ob(),c$=l(L,"src"),w=l(L,"versions"),n=l(L,"runtime"),j=l(L,"bin"),f=l(L,"shims"),a=l(L,"current"),C=l(L,"aliases"),S=l(L,"cache"),h$=l(L,"fingerprints.json"),E=z==="win32"?"bun.exe":"bun",j1=z==="win32"?"bvm.exe":"bvm",T1=process.env.BVM_CDN_URL||"https://cdn.jsdelivr.net/gh/EricLLLLLL/bvm",D1=[{name:"CLI Core",remotePath:"index.js",localPath:"src/index.js"},{name:"Windows Shim",remotePath:"bvm-shim.js",localPath:"bin/bvm-shim.js",platform:"win32"},{name:"Unix Shim",remotePath:"bvm-shim.sh",localPath:"bin/bvm-shim.sh",platform:"posix"}]});function p($){if(!$)return null;return $.match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/)?$:null}function zb($){let b=p($);return b?b.replace(/^v/,""):null}function G$($){if(!$)return null;let b=$.replace(/^v/,""),J=b.split(/[-+]/)[0].split(".").map(Number);if(J.length===0||J.some((K)=>isNaN(K)))return null;let q=b.includes("-")?b.split("-")[1].split("+")[0]:void 0;return{major:J[0],minor:J[1],patch:J[2],pre:q}}function p$($,b){if(!$||!b)return 0;if($.major!==b.major)return $.major-b.major;if($.minor!==b.minor)return $.minor-b.minor;if($.patch!==b.patch)return $.patch-b.patch;if($.pre&&!b.pre)return-1;if(!$.pre&&b.pre)return 1;if($.pre&&b.pre)return $.pre.localeCompare(b.pre);return 0}function Lb($,b){let _=G$($),J=G$(b);return p$(_,J)}function Y$($,b){return Lb(b,$)}function D$($,b){return Lb($,b)>0}function wb($,b){if(b==="*"||b===""||b==="latest")return!0;let _=G$($);if(!_)return!1;let J=b;if(b.startsWith("v"))J=b.substring(1);if(zb($)===zb(b))return!0;let q=J.split(".");if(q.length===1){let K=Number(q[0]);if(_.major===K)return!0}else if(q.length===2){let K=Number(q[0]),Q=Number(q[1]);if(_.major===K&&_.minor===Q)return!0}if(b.startsWith("~")){let K=G$(b.substring(1));if(!K)return!1;let Q=K.patch??0;return _.major===K.major&&_.minor===K.minor&&_.patch>=Q}if(b.startsWith("^")){let K=G$(b.substring(1));if(!K)return!1;let Q=K.patch??0,G=K.minor??0;if(K.major===0){if(_.major!==0)return!1;if(_.minor!==G)return!1;return _.patch>=Q}if(_.major!==K.major)return!1;if(_.minor<G)return!1;if(_.minor===G&&_.patch<Q)return!1;return!0}return!1}import{readdir as R1,mkdir as S1,stat as v1,symlink as u1,unlink as P1,rm as kb,readlink as d1,lstat as y0}from"fs/promises";import{join as E$,dirname as V1,basename as m1}from"path";async function T($){try{await S1($,{recursive:!0})}catch(b){if(b.code==="EEXIST")try{if((await R$($)).isDirectory())return}catch{}throw b}}async function X($){try{return await R$($),!0}catch(b){if(b.code==="ENOENT")return!1;throw b}}async function s($,b){let _=process.platform==="win32";try{if(await X(b))await kb(b,{recursive:!0,force:!0})}catch(q){}await u1($,b,_?"junction":"dir")}async function Cb($){try{return await d1($)}catch(b){if(b.code==="ENOENT"||b.code==="EINVAL")return null;throw b}}async function S$($){await kb($,{recursive:!0,force:!0})}async function V($){try{return await R1($)}catch(b){if(b.code==="ENOENT")return[];throw b}}async function F($){return await Bun.file($).text()}async function m($,b){await Bun.write($,b)}async function N$($,b,_={}){let{backup:J=!0}=_,q=V1($);await T(q);let K=`${$}.tmp-${Date.now()}`,Q=`${$}.bak`;try{if(await m(K,b),J&&await X($))try{let{rename:Y,unlink:H}=await import("fs/promises");if(await X(Q))await H(Q).catch(()=>{});await Y($,Q)}catch(Y){}let{rename:G}=await import("fs/promises");try{await G(K,$)}catch(Y){await Bun.write($,b),await P1(K).catch(()=>{})}}catch(G){let{unlink:Y}=await import("fs/promises");throw await Y(K).catch(()=>{}),G}}function y($){let b=$.trim();if(b.startsWith("bun-v"))b=b.substring(4);if(!b.startsWith("v")&&/^\d/.test(b))b=`v${b}`;return b}async function d(){return await T(w),(await V(w)).filter((b)=>p(y(b))).sort(Y$)}async function c(){if(process.env.BVM_ACTIVE_VERSION)return{version:y(process.env.BVM_ACTIVE_VERSION),source:"env"};let $=E$(process.cwd(),".bvmrc");if(await X($)){let Q=(await F($)).trim();return{version:y(Q),source:".bvmrc"}}let{getBvmDir:b}=await Promise.resolve().then(() => (M(),Wb)),_=b(),J=E$(_,"current"),q=E$(_,"aliases");if(await X(J)){let{realpath:Q}=await import("fs/promises");try{let G=await Q(J);return{version:y(m1(G)),source:"current"}}catch(G){}}let K=E$(q,"default");if(await X(K)){let Q=(await F(K)).trim();return{version:y(Q),source:"default"}}return{version:null,source:null}}function b$($,b){if(!$||b.length===0)return null;let _=y($);if(b.includes(_))return _;if($.toLowerCase()==="latest")return b[0];if(/^\d+\.\d+\.\d+$/.test($.replace(/^v/,"")))return null;if(!/^[v\d]/.test($))return null;let q=$.startsWith("v")?`~${$.substring(1)}`:`~${$}`,K=b.filter((Q)=>wb(Q,q));if(K.length>0)return K.sort(Y$)[0];return null}var R$;var N=C$(()=>{M();R$=v1});import{createInterface as c1}from"readline";class l${timer=null;frames=process.platform==="win32"?["-"]:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];frameIndex=0;text;isWindows=process.platform==="win32";constructor($){this.text=$}start($){if($)this.text=$;if(this.timer)return;if(this.isWindows){process.stdout.write(`${Z.cyan(">")} ${this.text}
4
- `);return}this.timer=setInterval(()=>{process.stdout.write(`\r\x1B[K${Z.cyan(this.frames[this.frameIndex])} ${this.text}`),this.frameIndex=(this.frameIndex+1)%this.frames.length},80)}stop(){if(this.isWindows)return;if(this.timer)clearInterval(this.timer),this.timer=null,process.stdout.write("\r\x1B[K");process.stdout.write("\x1B[?25h")}succeed($){this.stop(),console.log(`${Z.green(" \u2713")} ${$||this.text}`)}fail($){this.stop(),console.log(`${Z.red(" \u2716")} ${$||this.text}`)}info($){this.stop(),console.log(`${Z.blue(" \u2139")} ${$||this.text}`)}update($){if(this.text=$,this.isWindows)console.log(Z.dim(` ... ${this.text}`))}}class n${total;current=0;width=20;constructor($){this.total=$}start(){process.stdout.write("\x1B[?25l"),this.render()}update($,b){this.current=$,this.render(b)}stop(){process.stdout.write(`\x1B[?25h
5
- `)}render($){let b=Math.min(1,this.current/this.total),_=Math.round(this.width*b),J=this.width-_,q=process.platform==="win32",K=q?"=":"\u2588",Q=q?"-":"\u2591",G=Z.green(K.repeat(_))+Z.gray(Q.repeat(J)),Y=(b*100).toFixed(0).padStart(3," "),H=(this.current/1048576).toFixed(1),k=(this.total/1048576).toFixed(1),A=$?` ${$.speed}KB/s`:"";process.stdout.write(`\r\x1B[2K ${G} ${Y}% | ${H}/${k}MB${A}`)}}async function Nb($){let b=c1({input:process.stdin,output:process.stdout});return new Promise((_)=>{b.question(`${Z.yellow("?")} ${$} (Y/n) `,(J)=>{b.close(),_(J.toLowerCase()!=="n")})})}var h1,g1=($)=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=($,b,_=$)=>(J)=>h1?$+J.replace(new RegExp(g1(b),"g"),_)+b:J,Z;var x=C$(()=>{h1=!process.env.NO_COLOR,Z={red:r("\x1B[1;31m","\x1B[39m"),green:r("\x1B[1;32m","\x1B[39m"),yellow:r("\x1B[1;33m","\x1B[39m"),blue:r("\x1B[1;34m","\x1B[39m"),magenta:r("\x1B[1;35m","\x1B[39m"),cyan:r("\x1B[1;36m","\x1B[39m"),gray:r("\x1B[90m","\x1B[39m"),bold:r("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:r("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m")}});async function U($,b,_){if(process.platform==="win32"){console.log(Z.cyan(`> ${$}`));let K={start:(Q)=>{if(Q)console.log(Z.cyan(`> ${Q}`))},stop:()=>{},succeed:(Q)=>console.log(Z.green(` \u2713 ${Q}`)),fail:(Q)=>console.log(Z.red(` \u2716 ${Q}`)),info:(Q)=>console.log(Z.cyan(` \u2139 ${Q}`)),update:(Q)=>console.log(Z.dim(` ... ${Q}`)),isSpinning:!1};try{return await b(K)}catch(Q){let G=Eb(Q,_?.failMessage);if(console.log(Z.red(` \u2716 ${G}`)),process.env.BVM_DEBUG,console.log(Z.dim(` Details: ${Q.message}`)),Q.code)console.log(Z.dim(` Code: ${Q.code}`));throw Q.reported=!0,Q}}let q=new l$($);q.start();try{let K=await b(q);return q.stop(),K}catch(K){let Q=Eb(K,_?.failMessage);throw q.fail(Z.red(Q)),K.reported=!0,K}}function Eb($,b){let _=$ instanceof Error?$.message:String($);if(!b)return _;if(typeof b==="function")return b($);return`${b}: ${_}`}var I=C$(()=>{x()});var Rb={};Ub(Rb,{resolveLocalVersion:()=>h,displayVersion:()=>bb});import{join as L6}from"path";async function h($){if($==="current"){let{version:q}=await c();return q}if($==="latest"){let q=await d();if(q.length>0)return q[0];return null}let b=L6(C,$);if(await X(b))try{let q=(await F(b)).trim();return y(q)}catch{return null}let _=y($),J=await d();return b$($,J)}async function bb($){await U(`Resolving version '${$}'...`,async()=>{let b=await h($);if(b)console.log(b);else throw Error("N/A")},{failMessage:`Failed to resolve version '${$}'`})}var J$=C$(()=>{M();N();I()});import{parseArgs as _0}from"util";var O$={name:"bvm-core",version:"1.1.37",description:"Bun Version Manager (BVM) - Native, fast, and cross-platform.",main:"dist/index.js",bin:{bvm:"bin/bvm-npm.js"},publishConfig:{access:"public"},homepage:"https://bvm-core.pages.dev",bugs:{url:"https://github.com/EricLLLLLL/bvm/issues"},scripts:{dev:"bun run src/index.ts",build:"npx bun run scripts/check-templates.ts && npx bun build src/index.ts --target=bun --outfile dist/index.js --minify && npx bun run scripts/sync-runtime.ts",pack:"bun run build && bun pm pack",test:"bun test",bvm:"bun run src/index.ts","bvm:sandbox":'mkdir -p "$PWD/.sandbox-home" && HOME="$PWD/.sandbox-home" bun run src/index.ts',release:"bun run scripts/check-integrity.ts && bun run build && bun run scripts/release.ts","check-integrity":"bun run scripts/check-integrity.ts","test:e2e:npm":"bun run scripts/verify-e2e-npm.ts","sync-runtime":"bun run scripts/sync-runtime.ts",postinstall:"node scripts/postinstall.js"},repository:{type:"git",url:"git+https://github.com/EricLLLLLL/bvm.git"},keywords:["bun","version-manager","cli","bvm","nvm","nvm-windows","fnm","nodenv","bun-nvm","version-switching"],files:["dist/index.js","dist/bvm-shim.sh","dist/bvm-shim.js","bin/bvm-npm.js","scripts/postinstall.js","install.sh","install.ps1","README.md"],author:"EricLLLLLL",license:"MIT",type:"commonjs",dependencies:{},optionalDependencies:{"@oven/bun-darwin-aarch64":"^1.3.6","@oven/bun-darwin-x64":"^1.3.6","@oven/bun-linux-aarch64":"^1.3.6","@oven/bun-linux-x64":"^1.3.6","@oven/bun-windows-x64":"^1.3.6"},devDependencies:{"@types/bun":"^1.3.4","@types/cli-progress":"^3.11.6","@types/node":"^24.10.2",bun:"^1.3.6",esbuild:"^0.27.2",execa:"^9.6.1",typescript:"^5"},peerDependencies:{typescript:"^5"}};M();N();import{join as u,basename as E6}from"path";M();N();x();import{join as t1}from"path";function xb($,b){if($==="darwin"){if(b==="arm64")return"@oven/bun-darwin-aarch64";if(b==="x64")return"@oven/bun-darwin-x64"}if($==="linux"){if(b==="arm64")return"@oven/bun-linux-aarch64";if(b==="x64")return"@oven/bun-linux-x64"}if($==="win32"){if(b==="x64")return"@oven/bun-windows-x64"}return null}function o$($,b,_){let J=_;if(!J.endsWith("/"))J+="/";let q=$.startsWith("@"),K=$;if(q){let G=$.split("/");if(G.length===2)K=G[1]}let Q=`${K}-${b}.tgz`;return`${J}${$}/-/${Q}`}x();async function o($,b={}){let{cwd:_,env:J,prependPath:q,stdin:K="inherit",stdout:Q="inherit",stderr:G="inherit"}=b,Y={...process.env,...J};if(q){let A=Y.PATH||"",W=process.platform==="win32"?";":":";Y.PATH=`${q}${W}${A}`}let k=await Bun.spawn({cmd:$,cwd:_,env:Y,stdin:K,stdout:Q,stderr:G}).exited;if((k??0)!==0)throw Error(`${Z.red("Command failed")}: ${$.join(" ")} (code ${k})`);return k??0}N();import{join as Ab}from"path";import{homedir as p1}from"os";var l1=process.env.BVM_DIR||Ab(p1(),".bvm"),f0=Ab(l1,"cache","registry-cache.json");async function e($,b={}){let{timeout:_=5000,...J}=b,q=new AbortController,K=setTimeout(()=>q.abort(),_);try{let Q=await fetch($,{...J,signal:q.signal});return clearTimeout(K),Q}catch(Q){if(clearTimeout(K),Q.name==="AbortError")throw Error(`Request to ${$} timed out after ${_}ms`);throw Q}}async function n1($,b=2000){if($.length===0)throw Error("No URLs to race");if($.length===1)return $[0];return new Promise((_,J)=>{let q=0,K=!1;$.forEach((Q)=>{e(Q,{method:"HEAD",timeout:b}).then((G)=>{if(G.ok&&!K)K=!0,_(Q);else if(!K){if(q++,q===$.length)J(Error("All requests failed"))}}).catch(()=>{if(!K){if(q++,q===$.length)J(Error("All requests failed"))}})})})}async function o1(){try{let $=await e("https://1.1.1.1/cdn-cgi/trace",{timeout:500});if(!$.ok)return null;let _=(await $.text()).match(/loc=([A-Z]{2})/);return _?_[1]:null}catch($){return null}}var t$=null,X$={NPM:"https://registry.npmjs.org",TAOBAO:"https://registry.npmmirror.com",TENCENT:"https://mirrors.cloud.tencent.com/npm/"};async function t(){if(t$)return t$;let $=await o1(),b=[];if($==="CN")b=[X$.TAOBAO,X$.TENCENT,X$.NPM];else b=[X$.NPM,X$.TAOBAO];try{let _=await n1(b,2000);return t$=_,_}catch(_){return b[0]}}N();var i1="bun-versions.json",a1=3600000;async function s1(){if(D())return[...W$];let $=t1(S,i1);try{if(await X($)){let q=await F($),K=JSON.parse(q);if(Date.now()-K.timestamp<a1&&Array.isArray(K.versions))return K.versions}}catch(q){}let b=await t(),_=[b];if(b!=="https://registry.npmjs.org")_.push("https://registry.npmjs.org");let J=null;for(let q of _){let K=`${q.replace(/\/$/,"")}/bun`;try{let Q=await e(K,{headers:{"User-Agent":z$,Accept:"application/vnd.npm.install-v1+json"},timeout:1e4});if(!Q.ok)throw Error(`Status ${Q.status}`);let G=await Q.json();if(!G.versions)throw Error("Invalid response (no versions)");let Y=Object.keys(G.versions);try{await T(S),await m($,JSON.stringify({timestamp:Date.now(),versions:Y}))}catch(H){}return Y}catch(Q){J=Q}}throw J||Error("Failed to fetch versions from any registry.")}async function r1(){if(D())return[...W$];return new Promise(($,b)=>{let _=[];try{let J=Bun.spawn(["git","ls-remote","--tags","https://github.com/oven-sh/bun.git"],{stdout:"pipe",stderr:"pipe"}),q=setTimeout(()=>{J.kill(),b(Error("Git operation timed out"))},1e4);new Response(J.stdout).text().then((Q)=>{clearTimeout(q);let G=Q.split(`
6
- `);for(let Y of G){let H=Y.match(/refs\/tags\/bun-v?(\d+\.\d+\.\d+.*)$/);if(H)_.push(H[1])}$(_)}).catch((Q)=>{clearTimeout(q),b(Q)})}catch(J){b(Error(`Failed to run git: ${J.message}`))}})}async function Mb(){if(D())return[...W$];try{let b=(await s1()).filter((_)=>p(_)).map((_)=>({v:_,parsed:G$(_)}));return b.sort((_,J)=>p$(J.parsed,_.parsed)),b.map((_)=>_.v)}catch($){try{let b=await r1();if(b.length>0)return Array.from(new Set(b.filter((J)=>p(J)))).sort(Y$);throw Error("No versions found via Git")}catch(b){throw Error(`Failed to fetch versions. NPM: ${$.message}. Git: ${b.message}`)}}}async function fb($){if(D())return W$.includes($)||$==="latest";let b=await t(),_=$.replace(/^v/,""),J=`${b}/bun/${_}`,q=z==="win32"?"curl.exe":"curl",K=async()=>{try{return await o([q,"-I","-f","-m","5","-s",J],{stdout:"ignore",stderr:"ignore"}),!0}catch(G){return!1}},Q=new Promise((G)=>setTimeout(()=>G(!1),1e4));return Promise.race([K(),Q])}async function Bb(){if(D())return{latest:"1.1.20"};let b=`${await t()}/-/package/bun/dist-tags`;try{let _=await e(b,{headers:{"User-Agent":z$},timeout:5000});if(_.ok)return await _.json()}catch(_){}return{}}async function Fb($){let b=y($);if(!p(b))return console.error(Z.red(`Invalid version provided to findBunDownloadUrl: ${$}`)),null;if(D())return{url:`https://example.com/${g$(b)}`,foundVersion:b};let q=xb(z==="win32"?"win32":z,$$==="arm64"?"arm64":"x64");if(!q)throw Error(`Unsupported platform/arch for NPM download: ${z}-${$$}`);let K="";if(process.env.BVM_REGISTRY)K=process.env.BVM_REGISTRY;else if(process.env.BVM_DOWNLOAD_MIRROR)K=process.env.BVM_DOWNLOAD_MIRROR;else K=await t();let Q=b.replace(/^v/,""),G=o$(q,Q,K),Y=X$.TAOBAO,H=o$(q,Q,Y);return{url:G,mirrorUrl:H,foundVersion:b}}async function v$(){try{let b=(await t()).replace(/\/$/,""),_=await e(`${b}/-/package/bvm-core/dist-tags`,{headers:{"User-Agent":z$},timeout:5000});if(!_.ok)return null;let q=(await _.json()).latest;if(!q)return null;let K=await e(`${b}/bvm-core/${q}`,{headers:{"User-Agent":z$},timeout:5000});if(K.ok){let Q=await K.json();return{version:q,tarball:Q.dist.tarball,integrity:Q.dist.integrity,shasum:Q.dist.shasum}}}catch($){}return null}x();M();import{spawn as e1}from"child_process";async function Ib($,b){if($.endsWith(".zip"))if(z==="win32")await o(["powershell","-Command",`Expand-Archive -Path "${$}" -DestinationPath "${b}" -Force`],{stdout:"ignore",stderr:"inherit"});else await o(["unzip","-o","-q",$,"-d",b],{stdout:"ignore",stderr:"inherit"});else if($.endsWith(".tar.gz")||$.endsWith(".tgz"))await new Promise((_,J)=>{let q=e1("tar",["-xzf",$,"-C",b],{stdio:"inherit",shell:!1});q.on("close",(K)=>{if(K===0)_();else J(Error(`tar exited with code ${K}`))}),q.on("error",(K)=>J(K))});else throw Error(`Unsupported archive format: ${$}`)}import{chmod as Kb,rename as R6,rm as hb,symlink as gb}from"fs/promises";N();M();x();import{join as O,dirname as jb}from"path";import{homedir as G6}from"os";import{mkdir as Tb,rm as Db}from"fs/promises";import{chmod as M$}from"fs/promises";var i$=`#!/bin/bash
3
+ var L_=Object.create;var{getPrototypeOf:z_,defineProperty:S$,getOwnPropertyNames:I_}=Object;var W_=Object.prototype.hasOwnProperty;var X$=($,b,_)=>{_=$!=null?L_(z_($)):{};let y=b||!$||!$.__esModule?S$(_,"default",{value:$,enumerable:!0}):_;for(let f of I_($))if(!W_.call(y,f))S$(y,f,{get:()=>$[f],enumerable:!0});return y};var Qb=($,b)=>{for(var _ in b)S$($,_,{get:b[_],enumerable:!0,configurable:!0,set:(y)=>b[_]=()=>y})};var z$=($,b)=>()=>($&&(b=$($=0)),b);var Z$=import.meta.require;var Xb={};Qb(Xb,{isTestMode:()=>c,getBvmDir:()=>Cb,getBunAssetName:()=>g$,USER_AGENT:()=>q$,TEST_REMOTE_VERSIONS:()=>Y$,REPO_FOR_BVM_CLI:()=>A_,OS_PLATFORM:()=>Y,IS_TEST_MODE:()=>D_,HAS_AVX2:()=>A$,EXECUTABLE_NAME:()=>E,CPU_ARCH:()=>e,BVM_VERSIONS_DIR:()=>M,BVM_SRC_DIR:()=>d$,BVM_SHIMS_DIR:()=>D,BVM_RUNTIME_DIR:()=>t,BVM_FINGERPRINTS_FILE:()=>h$,BVM_DIR:()=>O,BVM_CURRENT_DIR:()=>s,BVM_COMPONENTS:()=>E_,BVM_CDN_ROOT:()=>c_,BVM_CACHE_DIR:()=>T,BVM_BIN_DIR:()=>A,BVM_ALIAS_DIR:()=>z,BUN_GITHUB_RELEASES_API:()=>u_,ASSET_NAME_FOR_BVM:()=>N_});import{homedir as B_}from"os";import{join as o}from"path";import{spawnSync as m$}from"child_process";function c(){return process.env.BVM_TEST_MODE==="true"}function R_(){let $=process.arch;if(Y==="darwin"&&$==="x64")try{if(m$("sysctl",["-n","sysctl.proc_translated"],{encoding:"utf-8"}).stdout.trim()==="1")return"arm64"}catch(b){}return $}function x_(){if(Y==="win32")return!0;try{if(Y==="darwin")return m$("sysctl",["-a"],{encoding:"utf-8"}).stdout.includes("AVX2");else if(Y==="linux")return m$("cat",["/proc/cpuinfo"],{encoding:"utf-8"}).stdout.includes("avx2")}catch($){}return!0}function Cb(){if(process.env.BVM_DIR)return process.env.BVM_DIR;let $=process.env.HOME||B_();return o($,".bvm")}function g$($){let b=Y==="win32"?"windows":Y,_=e==="arm64"?"aarch64":"x64";return`bun-${b}-${_}${!A$&&_==="x64"?"-baseline":""}.zip`}var Y,D_,Y$,e,A$,O,d$,M,t,A,D,s,z,T,h$,E,u_="https://api.github.com/repos/oven-sh/bun/releases",A_="EricLLLLLL/bvm",N_,q$="bvm (Bun Version Manager)",c_,E_;var B=z$(()=>{Y=process.platform,D_=process.env.BVM_TEST_MODE==="true",Y$=["v1.3.4","v1.2.23","v1.1.21","v1.1.20","v1.1.0","v1.0.0","bun-v1.4.0-canary"];e=R_(),A$=x_();O=Cb(),d$=o(O,"src"),M=o(O,"versions"),t=o(O,"runtime"),A=o(O,"bin"),D=o(O,"shims"),s=o(O,"current"),z=o(O,"aliases"),T=o(O,"cache"),h$=o(O,"fingerprints.json"),E=Y==="win32"?"bun.exe":"bun",N_=Y==="win32"?"bvm.exe":"bvm",c_=process.env.BVM_CDN_URL||"https://cdn.jsdelivr.net/gh/EricLLLLLL/bvm",E_=[{name:"CLI Core",remotePath:"index.js",localPath:"src/index.js"},{name:"Windows Shim",remotePath:"bvm-shim.js",localPath:"bin/bvm-shim.js",platform:"win32"},{name:"Unix Shim",remotePath:"bvm-shim.sh",localPath:"bin/bvm-shim.sh",platform:"posix"}]});function n($){if(!$)return null;return $.match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/)?$:null}function Zb($){let b=n($);return b?b.replace(/^v/,""):null}function G$($){if(!$)return null;let b=$.replace(/^v/,""),y=b.split(/[-+]/)[0].split(".").map(Number);if(y.length===0||y.some((w)=>isNaN(w)))return null;let f=b.includes("-")?b.split("-")[1].split("+")[0]:void 0;return{major:y[0],minor:y[1],patch:y[2],pre:f}}function P$($,b){if(!$||!b)return 0;if($.major!==b.major)return $.major-b.major;if($.minor!==b.minor)return $.minor-b.minor;if($.patch!==b.patch)return $.patch-b.patch;if($.pre&&!b.pre)return-1;if(!$.pre&&b.pre)return 1;if($.pre&&b.pre)return $.pre.localeCompare(b.pre);return 0}function Ob($,b){let _=G$($),y=G$(b);return P$(_,y)}function K$($,b){return Ob(b,$)}function N$($,b){return Ob($,b)>0}function Yb($,b){if(b==="*"||b===""||b==="latest")return!0;let _=G$($);if(!_)return!1;let y=b;if(b.startsWith("v"))y=b.substring(1);if(Zb($)===Zb(b))return!0;let f=y.split(".");if(f.length===1){let w=Number(f[0]);if(_.major===w)return!0}else if(f.length===2){let w=Number(f[0]),H=Number(f[1]);if(_.major===w&&_.minor===H)return!0}if(b.startsWith("~")){let w=G$(b.substring(1));if(!w)return!1;let H=w.patch??0;return _.major===w.major&&_.minor===w.minor&&_.patch>=H}if(b.startsWith("^")){let w=G$(b.substring(1));if(!w)return!1;let H=w.patch??0,q=w.minor??0;if(w.major===0){if(_.major!==0)return!1;if(_.minor!==q)return!1;return _.patch>=H}if(_.major!==w.major)return!1;if(_.minor<q)return!1;if(_.minor===q&&_.patch<H)return!1;return!0}return!1}import{readdir as T_,mkdir as j_,stat as F_,symlink as S_,unlink as m_,rm as kb,readlink as d_,lstat as z1}from"fs/promises";import{join as c$,dirname as h_,basename as g_}from"path";async function u($){await j_($,{recursive:!0})}async function K($){try{return await V$($),!0}catch(b){if(b.code==="ENOENT")return!1;throw b}}async function a($,b){let _=process.platform==="win32";try{if(await K(b))await kb(b,{recursive:!0,force:!0})}catch(f){}await S_($,b,_?"junction":"dir")}async function Mb($){try{return await d_($)}catch(b){if(b.code==="ENOENT"||b.code==="EINVAL")return null;throw b}}async function E$($){await kb($,{recursive:!0,force:!0})}async function d($){try{return await T_($)}catch(b){if(b.code==="ENOENT")return[];throw b}}async function x($){return await Bun.file($).text()}async function h($,b){await Bun.write($,b)}async function I$($,b,_={}){let{backup:y=!0}=_,f=h_($);await u(f);let w=`${$}.tmp-${Date.now()}`,H=`${$}.bak`;try{if(await h(w,b),y&&await K($))try{let{rename:G,unlink:Q}=await import("fs/promises");if(await K(H))await Q(H).catch(()=>{});await G($,H)}catch(G){}let{rename:q}=await import("fs/promises");try{await q(w,$)}catch(G){await Bun.write($,b),await m_(w).catch(()=>{})}}catch(q){let{unlink:G}=await import("fs/promises");throw await G(w).catch(()=>{}),q}}function C($){let b=$.trim();if(b.startsWith("bun-v"))b=b.substring(4);if(!b.startsWith("v")&&/^\d/.test(b))b=`v${b}`;return b}async function m(){return await u(M),(await d(M)).filter((b)=>n(C(b))).sort(K$)}async function g(){if(process.env.BVM_ACTIVE_VERSION)return{version:C(process.env.BVM_ACTIVE_VERSION),source:"env"};let $=c$(process.cwd(),".bvmrc");if(await K($)){let H=(await x($)).trim();return{version:C(H),source:".bvmrc"}}let{getBvmDir:b}=await Promise.resolve().then(() => (B(),Xb)),_=b(),y=c$(_,"current"),f=c$(_,"aliases");if(await K(y)){let{realpath:H}=await import("fs/promises");try{let q=await H(y);return{version:C(g_(q)),source:"current"}}catch(q){}}let w=c$(f,"default");if(await K(w)){let H=(await x(w)).trim();return{version:C(H),source:"default"}}return{version:null,source:null}}function $$($,b){if(!$||b.length===0)return null;let _=C($);if(b.includes(_))return _;if($.toLowerCase()==="latest")return b[0];if(/^\d+\.\d+\.\d+$/.test($.replace(/^v/,"")))return null;if(!/^[v\d]/.test($))return null;let f=$.startsWith("v")?`~${$.substring(1)}`:`~${$}`,w=b.filter((H)=>Yb(H,f));if(w.length>0)return w.sort(K$)[0];return null}var V$;var I=z$(()=>{B();V$=F_});import{createInterface as P_}from"readline";class p${timer=null;frames=process.platform==="win32"?["-"]:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];frameIndex=0;text;isWindows=process.platform==="win32";constructor($){this.text=$}start($){if($)this.text=$;if(this.timer)return;if(this.isWindows){process.stdout.write(`${J.cyan(">")} ${this.text}
4
+ `);return}this.timer=setInterval(()=>{process.stdout.write(`\r\x1B[K${J.cyan(this.frames[this.frameIndex])} ${this.text}`),this.frameIndex=(this.frameIndex+1)%this.frames.length},80)}stop(){if(this.isWindows)return;if(this.timer)clearInterval(this.timer),this.timer=null,process.stdout.write("\r\x1B[K");process.stdout.write("\x1B[?25h")}succeed($){this.stop(),console.log(`${J.green(" \u2713")} ${$||this.text}`)}fail($){this.stop(),console.log(`${J.red(" \u2716")} ${$||this.text}`)}info($){this.stop(),console.log(`${J.blue(" \u2139")} ${$||this.text}`)}update($){if(this.text=$,this.isWindows)console.log(J.dim(` ... ${this.text}`))}}class l${total;current=0;width=20;constructor($){this.total=$}start(){process.stdout.write("\x1B[?25l"),this.render()}update($,b){this.current=$,this.render(b)}stop(){process.stdout.write(`\x1B[?25h
5
+ `)}render($){let b=Math.min(1,this.current/this.total),_=Math.round(this.width*b),y=this.width-_,f=process.platform==="win32",w=f?"=":"\u2588",H=f?"-":"\u2591",q=J.green(w.repeat(_))+J.gray(H.repeat(y)),G=(b*100).toFixed(0).padStart(3," "),Q=(this.current/1048576).toFixed(1),L=(this.total/1048576).toFixed(1),U=$?` ${$.speed}KB/s`:"";process.stdout.write(`\r\x1B[2K ${q} ${G}% | ${Q}/${L}MB${U}`)}}async function Lb($){let b=P_({input:process.stdin,output:process.stdout});return new Promise((_)=>{b.question(`${J.yellow("?")} ${$} (Y/n) `,(y)=>{b.close(),_(y.toLowerCase()!=="n")})})}var V_,p_=($)=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=($,b,_=$)=>(y)=>V_?$+y.replace(new RegExp(p_(b),"g"),_)+b:y,J;var W=z$(()=>{V_=!process.env.NO_COLOR,J={red:r("\x1B[1;31m","\x1B[39m"),green:r("\x1B[1;32m","\x1B[39m"),yellow:r("\x1B[1;33m","\x1B[39m"),blue:r("\x1B[1;34m","\x1B[39m"),magenta:r("\x1B[1;35m","\x1B[39m"),cyan:r("\x1B[1;36m","\x1B[39m"),gray:r("\x1B[90m","\x1B[39m"),bold:r("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:r("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m")}});async function X($,b,_){if(process.platform==="win32"){console.log(J.cyan(`> ${$}`));let w={start:(H)=>{if(H)console.log(J.cyan(`> ${H}`))},stop:()=>{},succeed:(H)=>console.log(J.green(` \u2713 ${H}`)),fail:(H)=>console.log(J.red(` \u2716 ${H}`)),info:(H)=>console.log(J.cyan(` \u2139 ${H}`)),update:(H)=>console.log(J.dim(` ... ${H}`)),isSpinning:!1};try{return await b(w)}catch(H){let q=Nb(H,_?.failMessage);if(console.log(J.red(` \u2716 ${q}`)),process.env.BVM_DEBUG,console.log(J.dim(` Details: ${H.message}`)),H.code)console.log(J.dim(` Code: ${H.code}`));throw H.reported=!0,H}}let f=new p$($);f.start();try{let w=await b(f);return f.stop(),w}catch(w){let H=Nb(w,_?.failMessage);throw f.fail(J.red(H)),w.reported=!0,w}}function Nb($,b){let _=$ instanceof Error?$.message:String($);if(!b)return _;if(typeof b==="function")return b($);return`${b}: ${_}`}var N=z$(()=>{W()});var cb={};Qb(cb,{resolveLocalVersion:()=>p,displayVersion:()=>$b});import{join as My}from"path";async function p($){if($==="current"){let{version:f}=await g();return f}if($==="latest"){let f=await m();if(f.length>0)return f[0];return null}let b=My(z,$);if(await K(b))try{let f=(await x(b)).trim();return C(f)}catch{return null}let _=C($),y=await m();return $$($,y)}async function $b($){await X(`Resolving version '${$}'...`,async()=>{let b=await p($);if(b)console.log(b);else throw Error("N/A")},{failMessage:`Failed to resolve version '${$}'`})}var y$=z$(()=>{B();I();N()});import{parseArgs as K1}from"util";var O$={name:"bvm-core",version:"1.1.38",description:"Need a Bun version manager? BVM installs, switches, and isolates Bun versions across Windows, macOS, and Linux.",main:"dist/index.js",bin:{bvm:"bin/bvm-npm.js"},publishConfig:{access:"public"},homepage:"https://bvm-core.pages.dev/from/npm",funding:{type:"url",url:"https://bvm-core.pages.dev/wechat"},bugs:{url:"https://github.com/EricLLLLLL/bvm/issues"},scripts:{dev:"bun run src/index.ts",build:"npx bun run scripts/check-templates.ts && npx bun build src/index.ts --target=bun --outfile dist/index.js --minify && npx bun run scripts/sync-runtime.ts",pack:"bun run build && bun pm pack",test:"bun test",bvm:"bun run src/index.ts","bvm:sandbox":'mkdir -p "$PWD/.sandbox-home" && HOME="$PWD/.sandbox-home" bun run src/index.ts',release:"bun run scripts/check-integrity.ts && bun run build && bun run scripts/release.ts","check-integrity":"bun run scripts/check-integrity.ts","test:e2e:npm":"bun run scripts/verify-e2e-npm.ts","sync-runtime":"bun run scripts/sync-runtime.ts",postinstall:"node scripts/postinstall.js"},repository:{type:"git",url:"git+https://github.com/EricLLLLLL/bvm.git"},keywords:["bun","bvm","bun-version-manager","version-manager","bun-nvm","nvm-for-bun","nvm-alternative","fnm-alternative","bun-version-switching","bun-runtime-manager","bun-multi-version","bun-shims","bun-global-isolation","bun-bvmrc","bun-windows","bun-macos","bun-linux","cross-platform-cli","developer-tooling","toolchain-manager"],files:["dist/index.js","dist/bvm-shim.sh","dist/bvm-shim.js","bin/bvm-npm.js","scripts/postinstall.js","install.sh","install.ps1","README.md"],author:"EricLLLLLL",license:"MIT",type:"commonjs",dependencies:{},optionalDependencies:{"@oven/bun-darwin-aarch64":"^1.3.6","@oven/bun-darwin-x64":"^1.3.6","@oven/bun-linux-aarch64":"^1.3.6","@oven/bun-linux-x64":"^1.3.6","@oven/bun-windows-x64":"^1.3.6"},devDependencies:{"@types/bun":"^1.3.4","@types/cli-progress":"^3.11.6","@types/node":"^24.10.2",bun:"^1.3.6",esbuild:"^0.27.2",execa:"^9.6.1",typescript:"^5"},peerDependencies:{typescript:"^5"}};B();I();import{join as F,basename as vy}from"path";B();I();W();import{join as i_}from"path";function zb($,b){if($==="darwin"){if(b==="arm64")return"@oven/bun-darwin-aarch64";if(b==="x64")return"@oven/bun-darwin-x64"}if($==="linux"){if(b==="arm64")return"@oven/bun-linux-aarch64";if(b==="x64")return"@oven/bun-linux-x64"}if($==="win32"){if(b==="x64")return"@oven/bun-windows-x64"}return null}function n$($,b,_){let y=_;if(!y.endsWith("/"))y+="/";let f=$.startsWith("@"),w=$;if(f){let q=$.split("/");if(q.length===2)w=q[1]}let H=`${w}-${b}.tgz`;return`${y}${$}/-/${H}`}I();import{join as Ib}from"path";import{homedir as l_}from"os";var n_=process.env.BVM_DIR||Ib(l_(),".bvm"),c1=Ib(n_,"cache","registry-cache.json");async function P($,b={}){let{timeout:_=5000,...y}=b,f=new AbortController,w=setTimeout(()=>f.abort(),_);try{let H=await fetch($,{...y,signal:f.signal});return clearTimeout(w),H}catch(H){if(clearTimeout(w),H.name==="AbortError")throw Error(`Request to ${$} timed out after ${_}ms`);throw H}}async function o_($,b=2000){if($.length===0)throw Error("No URLs to race");if($.length===1)return $[0];try{return await Promise.any($.map((_)=>P(_,{method:"HEAD",timeout:b}).then((y)=>{if(!y.ok)throw Error(`Status ${y.status}`);return _})))}catch{throw Error("All requests failed")}}async function t_(){try{let $=await P("https://1.1.1.1/cdn-cgi/trace",{timeout:500});if(!$.ok)return null;let _=(await $.text()).match(/loc=([A-Z]{2})/);return _?_[1]:null}catch($){return null}}var o$=null,Q$={NPM:"https://registry.npmjs.org",TAOBAO:"https://registry.npmmirror.com",TENCENT:"https://mirrors.cloud.tencent.com/npm/"};async function V(){if(o$)return o$;let $=await t_(),b=[];if($==="CN")b=[Q$.TAOBAO,Q$.TENCENT,Q$.NPM];else b=[Q$.NPM,Q$.TAOBAO];try{let _=await o_(b,2000);return o$=_,_}catch(_){return b[0]}}I();var s_="bun-versions.json",a_=3600000;async function r_(){if(c())return[...Y$];let $=i_(T,s_);try{if(await K($)){let f=await x($),w=JSON.parse(f);if(Date.now()-w.timestamp<a_&&Array.isArray(w.versions))return w.versions}}catch(f){}let b=await V(),_=[b];if(b!=="https://registry.npmjs.org")_.push("https://registry.npmjs.org");let y=null;for(let f of _){let w=`${f.replace(/\/$/,"")}/bun`;try{let H=await P(w,{headers:{"User-Agent":q$,Accept:"application/vnd.npm.install-v1+json"},timeout:1e4});if(!H.ok)throw Error(`Status ${H.status}`);let q=await H.json();if(!q.versions)throw Error("Invalid response (no versions)");let G=Object.keys(q.versions);try{await u(T),await h($,JSON.stringify({timestamp:Date.now(),versions:G}))}catch(Q){}return G}catch(H){y=H}}throw y||Error("Failed to fetch versions from any registry.")}async function e_(){if(c())return[...Y$];let $=Bun.spawn(["git","ls-remote","--tags","https://github.com/oven-sh/bun.git"],{stdout:"pipe",stderr:"pipe"}),b=setTimeout(()=>$.kill(),1e4),_=await new Response($.stdout).text();clearTimeout(b);let y=[];for(let f of _.split(`
6
+ `)){let w=f.match(/refs\/tags\/bun-v?(\d+\.\d+\.\d+.*)$/);if(w)y.push(w[1])}return y}async function Wb(){if(c())return[...Y$];try{let b=(await r_()).filter((_)=>n(_)).map((_)=>({v:_,parsed:G$(_)}));return b.sort((_,y)=>P$(y.parsed,_.parsed)),b.map((_)=>_.v)}catch($){try{let b=await e_();if(b.length>0)return Array.from(new Set(b.filter((y)=>n(y)))).sort(K$);throw Error("No versions found via Git")}catch(b){throw Error(`Failed to fetch versions. NPM: ${$.message}. Git: ${b.message}`)}}}async function Ub($){if(c())return Y$.includes($)||$==="latest";let b=await V(),_=$.replace(/^v/,""),y=`${b}/bun/${_}`;try{return(await P(y,{method:"HEAD",headers:{"User-Agent":q$},timeout:5000})).ok}catch{return!1}}async function Bb(){if(c())return{latest:"1.1.20"};let b=`${await V()}/-/package/bun/dist-tags`;try{let _=await P(b,{headers:{"User-Agent":q$},timeout:5000});if(_.ok)return await _.json()}catch(_){}return{}}async function Db($){let b=C($);if(!n(b))return console.error(J.red(`Invalid version provided to findBunDownloadUrl: ${$}`)),null;if(c())return{url:`https://example.com/${g$(b)}`,foundVersion:b};let f=zb(Y==="win32"?"win32":Y,e==="arm64"?"arm64":"x64");if(!f)throw Error(`Unsupported platform/arch for NPM download: ${Y}-${e}`);let w="";if(process.env.BVM_REGISTRY)w=process.env.BVM_REGISTRY;else if(process.env.BVM_DOWNLOAD_MIRROR)w=process.env.BVM_DOWNLOAD_MIRROR;else w=await V();let H=b.replace(/^v/,""),q=n$(f,H,w),G=Q$.TAOBAO,Q=n$(f,H,G);return{url:q,mirrorUrl:Q,foundVersion:b}}async function v$(){try{let b=(await V()).replace(/\/$/,""),_=await P(`${b}/-/package/bvm-core/dist-tags`,{headers:{"User-Agent":q$},timeout:5000});if(!_.ok)return null;let f=(await _.json()).latest;if(!f)return null;let w=await P(`${b}/bvm-core/${f}`,{headers:{"User-Agent":q$},timeout:5000});if(w.ok){let H=await w.json();return{version:f,tarball:H.dist.tarball,integrity:H.dist.integrity,shasum:H.dist.shasum}}}catch($){}return null}W();W();async function b$($,b={}){let{cwd:_,env:y,prependPath:f,stdin:w="inherit",stdout:H="inherit",stderr:q="inherit"}=b,G={...process.env,...y};if(f){let U=G.PATH||"",k=process.platform==="win32"?";":":";G.PATH=`${f}${k}${U}`}let L=await Bun.spawn({cmd:$,cwd:_,env:G,stdin:w,stdout:H,stderr:q}).exited;if((L??0)!==0)throw Error(`${J.red("Command failed")}: ${$.join(" ")} (code ${L})`);return L??0}B();import{spawn as $y}from"child_process";async function Rb($,b){if($.endsWith(".zip"))if(Y==="win32")await b$(["powershell","-Command",`Expand-Archive -Path "${$}" -DestinationPath "${b}" -Force`],{stdout:"ignore",stderr:"inherit"});else await b$(["unzip","-o","-q",$,"-d",b],{stdout:"ignore",stderr:"inherit"});else if($.endsWith(".tar.gz")||$.endsWith(".tgz"))await new Promise((_,y)=>{let f=$y("tar",["-xzf",$,"-C",b],{stdio:"inherit",shell:!1});f.on("close",(w)=>{if(w===0)_();else y(Error(`tar exited with code ${w}`))}),f.on("error",(w)=>y(w))});else throw Error(`Unsupported archive format: ${$}`)}import{chmod as fb,rename as Ty,rm as hb,symlink as gb}from"fs/promises";I();B();W();import{join as Z,dirname as xb}from"path";import{homedir as Gy}from"os";import{mkdir as ub,rm as Ab}from"fs/promises";import{chmod as B$}from"fs/promises";var t$=`#!/bin/bash
7
7
 
8
8
  # bvm-init.sh: Initializes bvm default version on shell startup
9
9
 
10
10
  # Check if BVM_DIR is set
11
11
  if [ -z "\${BVM_DIR}" ]; then
12
+ echo "[bvm:init] initialization failed: BVM_DIR is not set. Run 'bvm setup'." >&2
13
+ return
14
+ fi
15
+
16
+ if [ ! -x "\${BVM_DIR}/bin/bvm" ]; then
17
+ echo "[bvm:init] initialization failed: \${BVM_DIR}/bin/bvm not found. Run 'bvm setup'." >&2
12
18
  return
13
19
  fi
14
20
 
@@ -52,10 +58,16 @@ bvm() {
52
58
 
53
59
  return "\${code}"
54
60
  }
55
- `;var a$=`# bvm-init.fish: Initializes bvm default version on shell startup
61
+ `;var i$=`# bvm-init.fish: Initializes bvm default version on shell startup
56
62
 
57
63
  # Check if BVM_DIR is set
58
64
  if not set -q BVM_DIR
65
+ echo "[bvm:init] initialization failed: BVM_DIR is not set. Run 'bvm setup'." >&2
66
+ return
67
+ end
68
+
69
+ if not test -x "$BVM_DIR/bin/bvm"
70
+ echo "[bvm:init] initialization failed: $BVM_DIR/bin/bvm not found. Run 'bvm setup'." >&2
59
71
  return
60
72
  end
61
73
 
@@ -172,7 +184,7 @@ else
172
184
  echo "BVM Error: Command '$CMD_NAME' not found in Bun $VERSION." >&2
173
185
  exit 127
174
186
  fi
175
- `;var r$=`const path = require('path');
187
+ `;var a$=`const path = require('path');
176
188
  const { spawn, spawnSync } = require('child_process');
177
189
  const os = require('os');
178
190
  const fs = require('fs');
@@ -376,7 +388,7 @@ child.on('error', (err) => {
376
388
  console.error("BVM Error: " + err.message);
377
389
  process.exit(1);
378
390
  });
379
- `;var x$=`@echo off
391
+ `;var W$=`@echo off
380
392
  set "BVM_DIR=__BVM_DIR__"
381
393
  :: Always delegate to JS shim to guarantee version isolation:
382
394
  :: - Correct per-version BUN_INSTALL / bunfig.toml injection
@@ -388,7 +400,7 @@ if exist "%BVM_DIR%\\runtime\\current\\bin\\bun.exe" (
388
400
  echo BVM Error: Bun runtime not found at "%BVM_DIR%\\runtime\\current\\bin\\bun.exe"
389
401
  exit /b 1
390
402
  )
391
- `;var A$=`@echo off
403
+ `;var U$=`@echo off
392
404
  set "BVM_DIR=__BVM_DIR__"
393
405
  :: Always delegate to JS shim to guarantee version isolation.
394
406
  if exist "%BVM_DIR%\\runtime\\current\\bin\\bun.exe" (
@@ -398,9 +410,9 @@ if exist "%BVM_DIR%\\runtime\\current\\bin\\bun.exe" (
398
410
  echo BVM Error: Bun runtime not found at "%BVM_DIR%\\runtime\\current\\bin\\bun.exe"
399
411
  exit /b 1
400
412
  )
401
- `;var e$=`@echo off
413
+ `;var r$=`@echo off
402
414
  set "BVM_DIR=__BVM_DIR__"
403
- "%BVM_DIR%\\runtime\\current\\bin\\bun.exe" "%BVM_DIR%\\src\\index.js" %*`;var $b=`<#
415
+ "%BVM_DIR%\\runtime\\current\\bin\\bun.exe" "%BVM_DIR%\\src\\index.js" %*`;var e$=`<#
404
416
  bvm-init.ps1: PowerShell integration for BVM
405
417
  Goals:
406
418
  - Ensure shims/bin have priority in current session PATH
@@ -474,9 +486,9 @@ function bvm {
474
486
 
475
487
  return $code
476
488
  }
477
- `;async function Y6(){if(z!=="win32")return;try{if(!await X(w))return;let $=await V(w);for(let b of $){if(!b.startsWith("v"))continue;let _=O(w,b),J=O(n,b);try{let Q=await R$(_);if(!Q.isDirectory())continue;let G=Q.mode!==void 0}catch{continue}try{let{readlink:Q,lstat:G}=await import("fs/promises");if((await G(_)).isSymbolicLink())continue}catch{}console.log(Z.yellow(`[bvm] Fixing: versions/${b} -> runtime/${b}`));let q=[],K=[];try{q=await V(_)}catch{}try{K=await V(J)}catch{}if(K.length===0&&q.length>0){console.log(Z.gray(" Moving content from versions to runtime..."));for(let Q of q){let G=O(_,Q),Y=O(J,Q);try{await X6(G,Y)}catch(H){try{await Bun.write(Bun.file(Y),Bun.file(G)),await Db(G)}catch{}}}}try{await Db(_,{recursive:!0,force:!0})}catch(Q){console.log(Z.gray(` Could not remove versions dir: ${Q}`));continue}try{await s(J,_),console.log(Z.green(" [OK] Junction created"))}catch(Q){console.log(Z.red(` [FAIL] Could not create junction: ${Q}`))}}}catch($){}}async function X6($,b){let{rename:_}=await import("fs/promises");await _($,b)}async function _$($=!0){if(await Y6(),await y6($),process.platform==="win32"){await U6($);return}let b=process.env.SHELL||"",_=process.env.HOME||G6(),J="",q="";if(b.includes("zsh"))q="zsh",J=O(_,".zshrc");else if(b.includes("bash"))if(q="bash",process.platform==="darwin")if(await X(O(_,".bashrc")))J=O(_,".bashrc");else J=O(_,".bash_profile");else J=O(_,".bashrc");else if(b.includes("fish"))q="fish",J=O(_,".config","fish","config.fish");else if(await X(O(_,".zshrc")))q="zsh",J=O(_,".zshrc");else if(await X(O(_,".config","fish","config.fish")))q="fish",J=O(_,".config","fish","config.fish");else if(await X(O(_,".bashrc")))q="bash",J=O(_,".bashrc");else if(await X(O(_,".bash_profile")))q="bash",J=O(_,".bash_profile");else{if($)console.log(Z.yellow(`Could not detect a supported shell (zsh, bash, fish). Please manually add ${j} to your PATH.`));return}let K=O(j,"bvm-init.sh");await Bun.write(K,i$),await M$(K,493);let Q=O(j,"bvm-init.fish");await Bun.write(Q,a$),await M$(Q,493);let G="";try{G=await Bun.file(J).text()}catch(W){if(W.code==="ENOENT")await Bun.write(J,""),G="";else throw W}let Y="# >>> bvm initialize >>>",H="# <<< bvm initialize <<<",k=`${Y}
489
+ `;async function Ky(){if(Y!=="win32")return;try{if(!await K(M))return;let $=await d(M);for(let b of $){if(!b.startsWith("v"))continue;let _=Z(M,b),y=Z(t,b);try{let H=await V$(_);if(!H.isDirectory())continue;let q=H.mode!==void 0}catch{continue}try{let{readlink:H,lstat:q}=await import("fs/promises");if((await q(_)).isSymbolicLink())continue}catch{}console.log(J.yellow(`[bvm] Fixing: versions/${b} -> runtime/${b}`));let f=[],w=[];try{f=await d(_)}catch{}try{w=await d(y)}catch{}if(w.length===0&&f.length>0){console.log(J.gray(" Moving content from versions to runtime..."));for(let H of f){let q=Z(_,H),G=Z(y,H);try{await Qy(q,G)}catch(Q){try{await Bun.write(Bun.file(G),Bun.file(q)),await Ab(q)}catch{}}}}try{await Ab(_,{recursive:!0,force:!0})}catch(H){console.log(J.gray(` Could not remove versions dir: ${H}`));continue}try{await a(y,_),console.log(J.green(" [OK] Junction created"))}catch(H){console.log(J.red(` [FAIL] Could not create junction: ${H}`))}}}catch($){}}async function Qy($,b){let{rename:_}=await import("fs/promises");await _($,b)}async function _$($=!0){if(await Ky(),await Xy($),process.platform==="win32"){await Zy($);return}let b=process.env.SHELL||"",_=process.env.HOME||Gy(),y="",f="";if(b.includes("zsh"))f="zsh",y=Z(_,".zshrc");else if(b.includes("bash"))if(f="bash",process.platform==="darwin")if(await K(Z(_,".bashrc")))y=Z(_,".bashrc");else y=Z(_,".bash_profile");else y=Z(_,".bashrc");else if(b.includes("fish"))f="fish",y=Z(_,".config","fish","config.fish");else if(await K(Z(_,".zshrc")))f="zsh",y=Z(_,".zshrc");else if(await K(Z(_,".config","fish","config.fish")))f="fish",y=Z(_,".config","fish","config.fish");else if(await K(Z(_,".bashrc")))f="bash",y=Z(_,".bashrc");else if(await K(Z(_,".bash_profile")))f="bash",y=Z(_,".bash_profile");else{if($)console.log(J.yellow(`Could not detect a supported shell (zsh, bash, fish). Please manually add ${A} to your PATH.`));return}let w=Z(A,"bvm-init.sh");await Bun.write(w,t$),await B$(w,493);let H=Z(A,"bvm-init.fish");await Bun.write(H,i$),await B$(H,493);let q="";try{q=await Bun.file(y).text()}catch(k){if(k.code==="ENOENT")await Bun.write(y,""),q="";else throw k}let G="# >>> bvm initialize >>>",Q="# <<< bvm initialize <<<",L=`${G}
478
490
  # !! Contents within this block are managed by 'bvm setup' !!
479
- export BVM_DIR="${L}"
491
+ export BVM_DIR="${O}"
480
492
  # We add shims and bin to the front of PATH for priority.
481
493
  # We add current/bin to the END of PATH to satisfy Bun's checks without interfering with BVM shims.
482
494
  export PATH="$BVM_DIR/shims:$BVM_DIR/bin:$PATH:$BVM_DIR/current/bin"
@@ -488,9 +500,9 @@ fi
488
500
  if [ ! -L "$BVM_DIR/current" ] && [ -f "$BVM_DIR/aliases/default" ]; then
489
501
  ln -sf "$BVM_DIR/versions/$(cat "$BVM_DIR/aliases/default")" "$BVM_DIR/current"
490
502
  fi
491
- ${H}`,A=`# >>> bvm initialize >>>
503
+ ${Q}`,U=`# >>> bvm initialize >>>
492
504
  # !! Contents within this block are managed by 'bvm setup' !!
493
- set -Ux BVM_DIR "${L}"
505
+ set -Ux BVM_DIR "${O}"
494
506
  fish_add_path "$BVM_DIR/shims"
495
507
  fish_add_path "$BVM_DIR/bin"
496
508
  # Append current/bin to satisfy Bun checks without overriding shims
@@ -505,16 +517,16 @@ if not test -L "$BVM_DIR/current"
505
517
  ln -sf "$BVM_DIR/versions/$(cat "$BVM_DIR/aliases/default")" "$BVM_DIR/current"
506
518
  end
507
519
  end
508
- # <<< bvm initialize <<<`;if($)console.log(Z.cyan(`Configuring ${q} environment in ${J}...`));try{let W=G,P=Y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),B=H.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),v=new RegExp(`${P}[\\s\\S]*?${B}`,"g");if(G.includes(Y))W=G.replace(v,"").trim();let i=q==="fish"?A:k;if(W=(W?W+`
520
+ # <<< bvm initialize <<<`;if($)console.log(J.cyan(`Configuring ${f} environment in ${y}...`));try{let k=q,S=G.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),R=Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),j=new RegExp(`${S}[\\s\\S]*?${R}`,"g");if(q.includes(G))k=q.replace(j,"").trim();let i=f==="fish"?U:L;if(k=(k?k+`
509
521
 
510
522
  `:"")+i+`
511
- `,W!==G){if(await Bun.write(J,W),$)console.log(Z.green(`\u2713 Successfully updated BVM configuration in ${J}`)),console.log(Z.gray(" (Moved configuration to the end of file to ensure PATH precedence)"))}if($)console.log(Z.yellow(`Please restart your terminal or run "source ${J}" to apply changes.`));await H6()}catch(W){console.error(Z.red(`Failed to write to ${J}: ${W.message}`))}}async function H6(){try{let $=O(C,"default");if(!await X($))return;let b=(await F($)).trim(),_=y(b),J=O(w,_);if(!await X(J))return;if(!await X(a))await s(J,a);if(z==="win32"){let q=O(n,_),K=O(n,"current"),Q=await X(q)?q:J;if(!await X(K))await s(Q,K)}}catch{}}async function y6($){if($)console.log(Z.cyan("Refreshing shims and wrappers..."));await Tb(j,{recursive:!0}),await Tb(f,{recursive:!0});let b=process.platform==="win32",_=L.replace(/\//g,"\\");if(b)await Bun.write(O(j,"bvm-shim.js"),r$),await Bun.write(O(j,"bvm.cmd"),e$.split("__BVM_DIR__").join(_)),await Bun.write(O(j,"bvm-init.ps1"),$b),await Bun.write(O(f,"bun.cmd"),x$.split("__BVM_DIR__").join(_)),await Bun.write(O(f,"bunx.cmd"),A$.split("__BVM_DIR__").join(_));else{let J=O(j,"bvm-shim.sh");await Bun.write(J,s$),await M$(J,493);let q="",K=O(L,"runtime","current","bin","bun"),Q=O(c$,"index.js");if(process.env.BVM_INSTALL_SOURCE==="npm")q=`#!/bin/bash
512
- export BVM_DIR="${L}"
523
+ `,k!==q){if(await Bun.write(y,k),$)console.log(J.green(`\u2713 Successfully updated BVM configuration in ${y}`)),console.log(J.gray(" (Moved configuration to the end of file to ensure PATH precedence)"))}if($)console.log(J.yellow(`Please restart your terminal or run "source ${y}" to apply changes.`));await Cy()}catch(k){console.error(J.red(`Failed to write to ${y}: ${k.message}`))}}async function Cy(){try{let $=Z(z,"default");if(!await K($))return;let b=(await x($)).trim(),_=C(b),y=Z(M,_);if(!await K(y))return;if(!await K(s))await a(y,s);if(Y==="win32"){let f=Z(t,_),w=Z(t,"current"),H=await K(f)?f:y;if(!await K(w))await a(H,w)}}catch{}}async function Xy($){if($)console.log(J.cyan("Refreshing shims and wrappers..."));await ub(A,{recursive:!0}),await ub(D,{recursive:!0});let b=process.platform==="win32",_=O.replace(/\//g,"\\");if(b)await Bun.write(Z(A,"bvm-shim.js"),a$),await Bun.write(Z(A,"bvm.cmd"),r$.split("__BVM_DIR__").join(_)),await Bun.write(Z(A,"bvm-init.ps1"),e$),await Bun.write(Z(D,"bun.cmd"),W$.split("__BVM_DIR__").join(_)),await Bun.write(Z(D,"bunx.cmd"),U$.split("__BVM_DIR__").join(_));else{let y=Z(A,"bvm-shim.sh");await Bun.write(y,s$),await B$(y,493);let f="",w=Z(O,"runtime","current","bin","bun"),H=Z(d$,"index.js");if(process.env.BVM_INSTALL_SOURCE==="npm")f=`#!/bin/bash
524
+ export BVM_DIR="${O}"
513
525
  export BVM_INSTALL_SOURCE="npm"
514
- if [ -f "${K}" ]; then
515
- exec "${K}" "${Q}" "$@"
526
+ if [ -f "${w}" ]; then
527
+ exec "${w}" "${H}" "$@"
516
528
  elif command -v bun >/dev/null 2>&1; then
517
- exec bun "${Q}" "$@"
529
+ exec bun "${H}" "$@"
518
530
  else
519
531
  # Last resort: use the node entry point if it's an NPM install
520
532
  # This is only possible if we are in the original NPM environment
@@ -522,15 +534,15 @@ else
522
534
  echo "Error: BVM Bunker Runtime not found. Attempting emergency fallback..."
523
535
  node -e "require('child_process').spawnSync('node', [require('path').join(process.env.BVM_DIR, '../', 'bin/bvm-npm.js'), ...process.argv.slice(1)], {stdio:'inherit'})" "$@"
524
536
  fi
525
- `;else q=`#!/bin/bash
526
- export BVM_DIR="${L}"
527
- exec "${K}" "${Q}" "$@"`;let G=O(j,"bvm");await Bun.write(G,q),await M$(G,493);for(let Y of["bun","bunx"]){let H=`#!/bin/bash
528
- export BVM_DIR="${L}"
529
- exec "${L}/bin/bvm-shim.sh" "${Y}" "$@"`,k=O(f,Y);await Bun.write(k,H),await M$(k,493)}}}async function U6($=!0){let b=O(j),_=O(f);if($)console.log(Z.cyan("Configuring Windows environment variables (Registry)..."));let J=`
530
- $targetDir = "${L}";
537
+ `;else f=`#!/bin/bash
538
+ export BVM_DIR="${O}"
539
+ exec "${w}" "${H}" "$@"`;let q=Z(A,"bvm");await Bun.write(q,f),await B$(q,493);for(let G of["bun","bunx"]){let Q=`#!/bin/bash
540
+ export BVM_DIR="${O}"
541
+ exec "${O}/bin/bvm-shim.sh" "${G}" "$@"`,L=Z(D,G);await Bun.write(L,Q),await B$(L,493)}}}async function Zy($=!0){let b=Z(A),_=Z(D);if($)console.log(J.cyan("Configuring Windows environment variables (Registry)..."));let y=`
542
+ $targetDir = "${O}";
531
543
  $shimsPath = "${_}";
532
544
  $binPath = "${b}";
533
- $currentBinPath = "${O(L,"current","bin")}";
545
+ $currentBinPath = "${Z(O,"current","bin")}";
534
546
 
535
547
  # Set BVM_DIR
536
548
  [Environment]::SetEnvironmentVariable("BVM_DIR", $targetDir, "User");
@@ -551,73 +563,74 @@ exec "${L}/bin/bvm-shim.sh" "${Y}" "$@"`,k=O(f,Y);await Bun.write(k,H),await M$(
551
563
  $finalPathString = $finalPathString.Trim(";")
552
564
  [Environment]::SetEnvironmentVariable("PATH", $finalPathString, "User");
553
565
  return "SUCCESS"
554
- `;try{let K=Bun.spawnSync({cmd:["powershell","-NoProfile","-Command",J],stdout:"pipe",stderr:"pipe"}),Q=K.stdout.toString().trim();if(K.success){if($)if(Q==="SUCCESS")console.log(Z.green("\u2713 Successfully updated User PATH and BVM_DIR in Registry."));else console.log(Z.gray("\u2713 Environment variables are already up to date."))}else throw Error(K.stderr.toString())}catch(K){console.error(Z.red(`Failed to update environment variables: ${K.message}`))}let q="";try{if(q=Bun.spawnSync({cmd:["powershell","-NoProfile","-Command","echo $PROFILE.CurrentUserAllHosts"],stdout:"pipe"}).stdout.toString().trim(),q)Bun.spawnSync({cmd:["powershell","-NoProfile","-Command",`if (!(Test-Path "${jb(q)}")) { New-Item -ItemType Directory -Force -Path "${jb(q)}" }`],stderr:"pipe"}),await O6(q,!1)}catch(K){}if($)console.log(Z.yellow("Please restart your terminal or IDE to apply the new PATH."))}async function O6($,b=!0){let q=`
566
+ `;try{let w=Bun.spawnSync({cmd:["powershell","-NoProfile","-Command",y],stdout:"pipe",stderr:"pipe"}),H=w.stdout.toString().trim();if(w.success){if($)if(H==="SUCCESS")console.log(J.green("\u2713 Successfully updated User PATH and BVM_DIR in Registry."));else console.log(J.gray("\u2713 Environment variables are already up to date."))}else throw Error(w.stderr.toString())}catch(w){console.error(J.red(`Failed to update environment variables: ${w.message}`))}let f="";try{if(f=Bun.spawnSync({cmd:["powershell","-NoProfile","-Command","echo $PROFILE.CurrentUserAllHosts"],stdout:"pipe"}).stdout.toString().trim(),f)Bun.spawnSync({cmd:["powershell","-NoProfile","-Command",`if (!(Test-Path "${xb(f)}")) { New-Item -ItemType Directory -Force -Path "${xb(f)}" }`],stderr:"pipe"}),await Oy(f,!1)}catch(w){}if($)console.log(J.yellow("Please restart your terminal or IDE to apply the new PATH."))}async function Oy($,b=!0){let f=`
555
567
  # >>> bvm initialize >>>
556
568
  # !! Contents within this block are managed by 'bvm setup' !!
557
- $env:BVM_DIR = "${L}"
569
+ $env:BVM_DIR = "${O}"
558
570
  if (Test-Path "$env:BVM_DIR\\bin\\bvm-init.ps1") {
559
571
  . "$env:BVM_DIR\\bin\\bvm-init.ps1"
560
572
  }
561
573
  # <<< bvm initialize <<<
562
- `;try{let K="";if(await X($))K=await Bun.file($).text();else await Bun.write($,"");let Q=K;if(K.includes("# >>> bvm initialize >>>")){let G="# >>> bvm initialize >>>".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Y="# <<< bvm initialize <<<".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),H=new RegExp(`${G}[\\s\\S]*?${Y}`,"g");Q=K.replace(H,"").trim()}if(b)console.log(Z.cyan(`Configuring PowerShell environment in ${$}...`));if(Q=(Q?Q+`\r
574
+ `;try{let w="";if(await K($))w=await Bun.file($).text();else await Bun.write($,"");let H=w;if(w.includes("# >>> bvm initialize >>>")){let q="# >>> bvm initialize >>>".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),G="# <<< bvm initialize <<<".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Q=new RegExp(`${q}[\\s\\S]*?${G}`,"g");H=w.replace(Q,"").trim()}if(b)console.log(J.cyan(`Configuring PowerShell environment in ${$}...`));if(H=(H?H+`\r
563
575
  \r
564
- `:"")+q.trim()+`\r
565
- `,await Bun.write($,Q),b)console.log(Z.green(`\u2713 Successfully configured BVM path in ${$}`)),console.log(Z.yellow("Please restart your terminal to apply changes.")),console.log(Z.gray('Tip (no restart): run ". $env:BVM_DIR\\bin\\bvm-init.ps1" in the current session.'))}catch(K){if(console.error(Z.red(`Failed to write to ${$}: ${K.message}`)),b)console.log(Z.yellow("You can still enable BVM for the current PowerShell session by running:")),console.log(Z.gray(` $env:BVM_DIR = "${L}"`)),console.log(Z.gray(' . "$env:BVM_DIR\\bin\\bvm-init.ps1"'))}}N();import{join as W6,dirname as z6}from"path";async function u$(){let $=process.cwd();while(!0){let b=W6($,".bvmrc");if(await X(b))try{return(await Bun.file(b).text()).trim()}catch(J){return null}let _=z6($);if(_===$)break;$=_}return null}x();M();N();J$();I();import{join as Sb}from"path";async function L$($,b,_={}){let J=async(q)=>{let K=await h(b);if(!K){if(!_.silent)console.log(Z.blue(`Please install Bun ${b} first using: bvm install ${b}`));throw Error(`Bun version '${b}' is not installed. Cannot create alias.`)}let Q=Sb(w,K);if(!await X(Q))throw Error(`Internal Error: Resolved Bun version ${K} not found.`);await T(C);let G=Sb(C,$);if($!=="default"&&await X(G))throw Error(`Alias '${$}' already exists. Use 'bvm alias ${$} <new-version>' to update or 'bvm unalias ${$}' to remove.`);if(await m(G,`${K}
566
- `),q)q.succeed(Z.green(`Alias '${$}' created for Bun ${K}.`))};if(_.silent)await J();else await U(`Creating alias '${$}' for Bun ${b}...`,(q)=>J(q),{failMessage:`Failed to create alias '${$}'`})}I();M();N();x();import{join as K$}from"path";import{delimiter as mb}from"path";import{homedir as F6}from"os";import{access as I6}from"fs/promises";import j6 from"fs";J$();I();M();import{join as _b,dirname as ub,resolve as Pb}from"path";import{readdir as w6,stat as k6}from"fs/promises";async function w$($){if(z!=="win32")return;try{let b=await w6($);for(let _ of b){let J=_b($,_);if(_.endsWith(".cmd"))await C6(J);else if(_.endsWith(".ps1"))await N6(J)}}catch(b){}}async function db($){let b=_b($,"..","node_modules");if(await vb(b))return b;let _=_b($,"..","install","global","node_modules");if(await vb(_))return _;return null}async function vb($){try{return await k6($),!0}catch{return!1}}async function C6($){try{let _=await Bun.file($).text(),J=ub($),q=await db(J);if(!q)return;let K=Pb(q).replace(/\//g,"\\"),Q=_;if(_.includes("node_modules")){let G=["%~dp0\\..\\node_modules","%dp0%\\..\\node_modules","%~dp0..\\node_modules","%dp0%..\\node_modules","%~dp0\\..\\install\\global\\node_modules","%dp0%\\..\\install\\global\\node_modules","%~dp0..\\install\\global\\node_modules","%dp0%..\\install\\global\\node_modules"],Y=!1;for(let H of G)if(_.includes(H))Q=Q.split(H).join(K),Y=!0;if(Y&&Q!==_)await Bun.write($,Q)}}catch(b){}}async function N6($){try{let _=await Bun.file($).text(),J=ub($),q=await db(J);if(!q)return;let K=Pb(q).replace(/\//g,"\\"),Q=["$PSScriptRoot\\..\\node_modules","$PSScriptRoot\\..\\install\\global\\node_modules"],G=!1;for(let Y of Q)if(_.includes(Y))newContent=_.split(Y).join(K),G=!0;if(G&&newContent!==_)await Bun.write($,newContent)}catch(b){}}M();N();x();import{join as g,dirname as Vb}from"path";import{chmod as Jb,unlink as P$,lstat as x6,rm as A6}from"fs/promises";var __dirname="/home/runner/work/bvm/bvm/src/commands";async function M6($){return new Map}function f6($,b,_){return`@echo off
576
+ `:"")+f.trim()+`\r
577
+ `,await Bun.write($,H),b)console.log(J.green(`\u2713 Successfully configured BVM path in ${$}`)),console.log(J.yellow("Please restart your terminal to apply changes.")),console.log(J.gray('Tip (no restart): run ". $env:BVM_DIR\\bin\\bvm-init.ps1" in the current session.'))}catch(w){if(console.error(J.red(`Failed to write to ${$}: ${w.message}`)),b)console.log(J.yellow("You can still enable BVM for the current PowerShell session by running:")),console.log(J.gray(` $env:BVM_DIR = "${O}"`)),console.log(J.gray(' . "$env:BVM_DIR\\bin\\bvm-init.ps1"'))}}I();import{join as Yy,dirname as ky}from"path";async function T$(){let $=process.cwd();while(!0){let b=Yy($,".bvmrc");if(await K(b))try{return(await Bun.file(b).text()).trim()}catch(y){return null}let _=ky($);if(_===$)break;$=_}return null}W();B();I();y$();N();import{join as Eb}from"path";async function k$($,b,_={}){let y=async(f)=>{let w=await p(b);if(!w){if(!_.silent)console.log(J.blue(`Please install Bun ${b} first using: bvm install ${b}`));throw Error(`Bun version '${b}' is not installed. Cannot create alias.`)}let H=Eb(M,w);if(!await K(H))throw Error(`Internal Error: Resolved Bun version ${w} not found.`);await u(z);let q=Eb(z,$);if($!=="default"&&await K(q))throw Error(`Alias '${$}' already exists. Use 'bvm alias ${$} <new-version>' to update or 'bvm unalias ${$}' to remove.`);if(await h(q,`${w}
578
+ `),f)f.succeed(J.green(`Alias '${$}' created for Bun ${w}.`))};if(_.silent)await y();else await X(`Creating alias '${$}' for Bun ${b}...`,(f)=>y(f),{failMessage:`Failed to create alias '${$}'`})}N();B();I();W();import{join as w$}from"path";import{delimiter as mb}from"path";import{homedir as uy}from"os";import{access as Ay}from"fs/promises";import Ny from"fs";y$();N();B();import{join as bb,dirname as Tb,resolve as jb}from"path";import{readdir as Ly,stat as zy}from"fs/promises";async function M$($){if(Y!=="win32")return;try{let b=await Ly($);for(let _ of b){let y=bb($,_);if(_.endsWith(".cmd"))await Iy(y);else if(_.endsWith(".ps1"))await Wy(y)}}catch(b){}}async function Fb($){let b=bb($,"..","node_modules");if(await vb(b))return b;let _=bb($,"..","install","global","node_modules");if(await vb(_))return _;return null}async function vb($){try{return await zy($),!0}catch{return!1}}async function Iy($){try{let _=await Bun.file($).text(),y=Tb($),f=await Fb(y);if(!f)return;let w=jb(f).replace(/\//g,"\\"),H=_;if(_.includes("node_modules")){let q=["%~dp0\\..\\node_modules","%dp0%\\..\\node_modules","%~dp0..\\node_modules","%dp0%..\\node_modules","%~dp0\\..\\install\\global\\node_modules","%dp0%\\..\\install\\global\\node_modules","%~dp0..\\install\\global\\node_modules","%dp0%..\\install\\global\\node_modules"],G=!1;for(let Q of q)if(_.includes(Q))H=H.split(Q).join(w),G=!0;if(G&&H!==_)await Bun.write($,H)}}catch(b){}}async function Wy($){try{let _=await Bun.file($).text(),y=Tb($),f=await Fb(y);if(!f)return;let w=jb(f).replace(/\//g,"\\"),H=["$PSScriptRoot\\..\\node_modules","$PSScriptRoot\\..\\install\\global\\node_modules"],q=!1;for(let G of H)if(_.includes(G))newContent=_.split(G).join(w),q=!0;if(q&&newContent!==_)await Bun.write($,newContent)}catch(b){}}B();I();W();import{join as l,dirname as Sb}from"path";import{chmod as _b,unlink as j$,lstat as Uy,rm as By}from"fs/promises";var __dirname="/home/runner/work/bvm/bvm/src/commands";async function Dy($){return new Map}function Ry($,b,_){return`@echo off
567
579
  :: BVM Shim for ${$} - delegates to bvm-shim.js
568
580
  set "BVM_DIR=${b}"
569
581
  if defined BVM_DIR_OVERRIDE set "BVM_DIR=%BVM_DIR_OVERRIDE%"
570
582
 
571
- "%BVM_DIR%\\runtime\\current\\bin\\bun.exe" "%BVM_DIR%\\bin\\bvm-shim.js" "${$}" %*`}async function q$($={}){await T(f),await T(j);let b=z==="win32",_=L.replace(/\//g,"\\");try{let G=g(Vb(Vb(__dirname)),"src","templates");if(b){let Y=await Bun.file(g(G,"win","bvm-shim.js")).text();await Bun.write(g(j,"bvm-shim.js"),Y)}else{let Y=await Bun.file(g(G,"unix","bvm-shim.sh")).text(),H=g(j,"bvm-shim.sh");await Bun.write(H,Y),await Jb(H,493)}}catch(G){}let J=new Set(["bun","bunx"]),q=new Map,Q=(await c())?.version;if(Q&&await X(w)){let G=g(w,Q);if(await X(G))q=await M6(G)}if(await X(w)){if(Q){let G=g(w,Q,"bin");if(await X(G)){await w$(G);let Y=await V(G);for(let H of Y){let k=H.replace(/\.(exe|ps1|cmd|bunx)$/i,"");if(k&&k!=="bun"&&k!=="bunx")J.add(k)}}}}await B6(J);for(let G of J)if(b){let Y=g(f,`${G}.cmd`);if(G==="bun")await Bun.write(Y,x$.split("__BVM_DIR__").join(_));else if(G==="bunx")await Bun.write(Y,A$.split("__BVM_DIR__").join(_));else{let A=q.get(G);await Bun.write(Y,f6(G,_,A))}let H=g(f,`${G}.ps1`);if(await X(H))await P$(H);let k=g(f,`${G}.exe`);if(G!=="bun"&&G!=="bunx"&&await X(k))await P$(k)}else{let Y=g(f,G),H=`#!/bin/bash
572
- # BVM shim for ${G} - delegates to bvm-shim.sh for proper version resolution
573
- export BVM_DIR="${L}"
574
- exec "$BVM_DIR/bin/bvm-shim.sh" "${G}" "$@"
575
- `;await Bun.write(Y,H),await Jb(Y,493)}if(!$.silent)console.log(Z.green(`\u2713 Managed ${J.size} command proxies.`))}async function B6($){try{if(!await X(f))return;let b=await V(f);for(let _ of b){if(_==="bun"||_==="bunx"||_==="bun.cmd"||_==="bunx.cmd")continue;let J=_.replace(/\.(cmd|ps1|exe)$/i,"");if($.has(J))continue;let q=g(f,_);try{if((await x6(q)).isDirectory())continue;try{await P$(q)}catch{try{await Jb(q,438)}catch{}try{await P$(q)}catch{}try{await A6(q,{force:!0})}catch{}}}catch{}}}catch{}}async function d$($,b={}){let _=$;if(!_)_=await u$()||void 0;if(!_){if(!b.silent)console.error(Z.red("No version specified. Usage: bvm use <version>"));throw Error("No version specified.")}let J=async(q)=>{let K=null,Q=await h(_);if(Q)K=Q;else{let A=(await d()).map((W)=>y(W));K=b$(_,A)}if(!K)throw Error(`Bun version '${_}' is not installed.`);let G=y(K),Y=K$(w,G),H=K$(Y,"bin",E);if(!await X(H))throw Error(`Version ${G} is not properly installed (binary missing).`);if(await w$(K$(Y,"bin")),await s(Y,a),z==="win32"){let A=K$(n,"current"),W=K$(n,G),P=await X(W)?W:Y;await s(P,A)}if(await D6({silent:b.silent,spinner:q})&&!b.silent){if(!!b.fixPath||(!!b.yes||await Nb("\u662F\u5426\u73B0\u5728\u8FD0\u884C `bvm setup` \u81EA\u52A8\u4FEE\u590D PATH \u4F18\u5148\u7EA7\uFF08\u5199\u5165\u4F60\u7684 shell \u914D\u7F6E\u6587\u4EF6\uFF09\uFF1F"))){if(q)q.stop();if(await _$(!0),q)q.start()}}if(q)q.succeed(Z.green(`Now using Bun ${G} (immediate effect).`));await q$({silent:b.silent})};if(b.silent)await J();else await U(`Switching to Bun ${_}...`,(q)=>J(q),{failMessage:()=>`Failed to switch to Bun ${_}`})}function f$($){return $.replace(/\\/g,"/").replace(/\/+$/g,"")}async function T6($){let b=(process.env.PATH||"").split(mb).filter(Boolean);for(let _ of b){let J=K$(_,$);try{return await I6(J,j6.constants.X_OK),J}catch(q){}}return null}async function D6($){if($.silent)return!1;if(process.env.BVM_TEST_MODE==="true"||process.env.CI)return!1;try{let _=(process.env.PATH||"").split(mb).filter(Boolean).map(f$),J=_.indexOf(f$(f)),q=await T6("bun"),K=K$(f,"bun"),Q=process.env.HOME||F6(),G=Q?K$(Q,".bun","bin"):"",Y=G?_.indexOf(f$(G)):-1,H=J===-1,k=!!q&&f$(q)!==f$(K),A=Y!==-1&&J!==-1&&Y<J;if(!H&&!k&&!A)return!1;if($.spinner)$.spinner.stop();if(console.log(Z.yellow(`
576
- \u26A0\uFE0F \u68C0\u6D4B\u5230 bvm \u7684 shims \u672A\u751F\u6548\uFF08\u6216\u4F18\u5148\u7EA7\u4E0D\u591F\uFF09\u3002`)),q)console.log(Z.yellow(` \u5F53\u524D shell \u547D\u4E2D\u7684 bun: ${Z.cyan(q)}`)),console.log(Z.gray(` \u671F\u671B\u547D\u4E2D\u7684 bun shim: ${Z.cyan(K)}`));if(console.log(Z.yellow(" \u8FD9\u4F1A\u5BFC\u81F4 `bun add -g`/`bun i -g` \u5199\u5165 ~/.bun\uFF0C\u4ECE\u800C\u5728\u5207\u6362\u7248\u672C\u540E\u4ECD\u80FD\u770B\u5230 pm2/cowsay \u7B49\u5168\u5C40\u547D\u4EE4\u3002")),console.log(Z.gray(" \u4FEE\u590D\u65B9\u5F0F\uFF1A\u8FD0\u884C\u4E00\u6B21 `bvm setup` \u5E76\u91CD\u542F\u7EC8\u7AEF/\u91CD\u65B0\u52A0\u8F7D shell \u914D\u7F6E\u3002")),console.log(Z.gray(" \u4F8B\u5982\uFF08zsh\uFF09\uFF1Asource ~/.zshrc && hash -r")),console.log(Z.gray(` \u9A8C\u8BC1\uFF1Awhich bun \u9700\u8981\u6307\u5411 ${K}`)),$.spinner)$.spinner.start();return!0}catch(b){}return!1}async function S6($,b={}){let _=u($,"bunfig.toml"),J=$,q=u($,"bin"),K=u($,"install","cache");if((b.platform||z)==="win32")J=J.replace(/\//g,"\\").replace(/\\/g,"\\\\"),q=q.replace(/\//g,"\\").replace(/\\/g,"\\\\"),K=K.replace(/\//g,"\\").replace(/\\/g,"\\\\");let G=`[install]
577
- globalDir = "${J}"
578
- globalBinDir = "${q}"
583
+ "%BVM_DIR%\\runtime\\current\\bin\\bun.exe" "%BVM_DIR%\\bin\\bvm-shim.js" "${$}" %*`}async function f$($={}){await u(D),await u(A);let b=Y==="win32",_=O.replace(/\//g,"\\");try{let q=l(Sb(Sb(__dirname)),"src","templates");if(b){let G=await Bun.file(l(q,"win","bvm-shim.js")).text();await Bun.write(l(A,"bvm-shim.js"),G)}else{let G=await Bun.file(l(q,"unix","bvm-shim.sh")).text(),Q=l(A,"bvm-shim.sh");await Bun.write(Q,G),await _b(Q,493)}}catch(q){}let y=new Set(["bun","bunx"]),f=new Map,H=(await g())?.version;if(H&&await K(M)){let q=l(M,H);if(await K(q))f=await Dy(q)}if(await K(M)){if(H){let q=l(M,H,"bin");if(await K(q)){await M$(q);let G=await d(q);for(let Q of G){let L=Q.replace(/\.(exe|ps1|cmd|bunx)$/i,"");if(L&&L!=="bun"&&L!=="bunx")y.add(L)}}}}await xy(y);for(let q of y)if(b){let G=l(D,`${q}.cmd`);if(q==="bun")await Bun.write(G,W$.split("__BVM_DIR__").join(_));else if(q==="bunx")await Bun.write(G,U$.split("__BVM_DIR__").join(_));else{let U=f.get(q);await Bun.write(G,Ry(q,_,U))}let Q=l(D,`${q}.ps1`);if(await K(Q))await j$(Q);let L=l(D,`${q}.exe`);if(q!=="bun"&&q!=="bunx"&&await K(L))await j$(L)}else{let G=l(D,q),Q=`#!/bin/bash
584
+ # BVM shim for ${q} - delegates to bvm-shim.sh for proper version resolution
585
+ export BVM_DIR="${O}"
586
+ exec "$BVM_DIR/bin/bvm-shim.sh" "${q}" "$@"
587
+ `;await Bun.write(G,Q),await _b(G,493)}if(!$.silent)console.log(J.green(`\u2713 Managed ${y.size} command proxies.`))}async function xy($){try{if(!await K(D))return;let b=await d(D);for(let _ of b){if(_==="bun"||_==="bunx"||_==="bun.cmd"||_==="bunx.cmd")continue;let y=_.replace(/\.(cmd|ps1|exe)$/i,"");if($.has(y))continue;let f=l(D,_);try{if((await Uy(f)).isDirectory())continue;try{await j$(f)}catch{try{await _b(f,438)}catch{}try{await j$(f)}catch{}try{await By(f,{force:!0})}catch{}}}catch{}}}catch{}}async function F$($,b={}){let _=$;if(!_)_=await T$()||void 0;if(!_){if(!b.silent)console.error(J.red("No version specified. Usage: bvm use <version>"));throw Error("No version specified.")}let y=async(f)=>{let w=null,H=await p(_);if(H)w=H;else{let U=(await m()).map((k)=>C(k));w=$$(_,U)}if(!w)throw Error(`Bun version '${_}' is not installed.`);let q=C(w),G=w$(M,q),Q=w$(G,"bin",E);if(!await K(Q))throw Error(`Version ${q} is not properly installed (binary missing).`);if(await M$(w$(G,"bin")),await a(G,s),Y==="win32"){let U=w$(t,"current"),k=w$(t,q),S=await K(k)?k:G;await a(S,U)}if(await Ey({silent:b.silent,spinner:f})&&!b.silent){if(!!b.fixPath||(!!b.yes||await Lb("\u662F\u5426\u73B0\u5728\u8FD0\u884C `bvm setup` \u81EA\u52A8\u4FEE\u590D PATH \u4F18\u5148\u7EA7\uFF08\u5199\u5165\u4F60\u7684 shell \u914D\u7F6E\u6587\u4EF6\uFF09\uFF1F"))){if(f)f.stop();if(await _$(!0),f)f.start()}}if(f)f.succeed(J.green(`Now using Bun ${q} (immediate effect).`));await f$({silent:b.silent})};if(b.silent)await y();else await X(`Switching to Bun ${_}...`,(f)=>y(f),{failMessage:()=>`Failed to switch to Bun ${_}`})}function D$($){return $.replace(/\\/g,"/").replace(/\/+$/g,"")}async function cy($){let b=(process.env.PATH||"").split(mb).filter(Boolean);for(let _ of b){let y=w$(_,$);try{return await Ay(y,Ny.constants.X_OK),y}catch(f){}}return null}async function Ey($){if($.silent)return!1;if(process.env.BVM_TEST_MODE==="true"||process.env.CI)return!1;try{let _=(process.env.PATH||"").split(mb).filter(Boolean).map(D$),y=_.indexOf(D$(D)),f=await cy("bun"),w=w$(D,"bun"),H=process.env.HOME||uy(),q=H?w$(H,".bun","bin"):"",G=q?_.indexOf(D$(q)):-1,Q=y===-1,L=!!f&&D$(f)!==D$(w),U=G!==-1&&y!==-1&&G<y;if(!Q&&!L&&!U)return!1;if($.spinner)$.spinner.stop();if(console.log(J.yellow(`
588
+ \u26A0\uFE0F \u68C0\u6D4B\u5230 bvm \u7684 shims \u672A\u751F\u6548\uFF08\u6216\u4F18\u5148\u7EA7\u4E0D\u591F\uFF09\u3002`)),f)console.log(J.yellow(` \u5F53\u524D shell \u547D\u4E2D\u7684 bun: ${J.cyan(f)}`)),console.log(J.gray(` \u671F\u671B\u547D\u4E2D\u7684 bun shim: ${J.cyan(w)}`));if(console.log(J.yellow(" \u8FD9\u4F1A\u5BFC\u81F4 `bun add -g`/`bun i -g` \u5199\u5165 ~/.bun\uFF0C\u4ECE\u800C\u5728\u5207\u6362\u7248\u672C\u540E\u4ECD\u80FD\u770B\u5230 pm2/cowsay \u7B49\u5168\u5C40\u547D\u4EE4\u3002")),console.log(J.gray(" \u4FEE\u590D\u65B9\u5F0F\uFF1A\u8FD0\u884C\u4E00\u6B21 `bvm setup` \u5E76\u91CD\u542F\u7EC8\u7AEF/\u91CD\u65B0\u52A0\u8F7D shell \u914D\u7F6E\u3002")),console.log(J.gray(" \u4F8B\u5982\uFF08zsh\uFF09\uFF1Asource ~/.zshrc && hash -r")),console.log(J.gray(` \u9A8C\u8BC1\uFF1Awhich bun \u9700\u8981\u6307\u5411 ${w}`)),$.spinner)$.spinner.start();return!0}catch(b){}return!1}async function jy($,b={}){let _=F($,"bunfig.toml"),y=$,f=F($,"bin"),w=F($,"install","cache");if((b.platform||Y)==="win32")y=y.replace(/\//g,"\\").replace(/\\/g,"\\\\"),f=f.replace(/\//g,"\\").replace(/\\/g,"\\\\"),w=w.replace(/\//g,"\\").replace(/\\/g,"\\\\");let q=`[install]
589
+ globalDir = "${y}"
590
+ globalBinDir = "${f}"
579
591
 
580
592
  [install.cache]
581
- dir = "${K}"`;try{let Y=b.registryUrl||await t();if(Y)G+=`
593
+ dir = "${w}"`;try{let G=b.registryUrl||await V();if(G)q+=`
582
594
 
583
595
  [install.registry]
584
- url = "${Y}"
585
- `}catch(Y){}await Bun.write(_,G)}async function v6($,b){let _=E.replace("bun","bunx"),J=u($,_);if(await X(J))return;try{await gb(E,J)}catch(q){await Bun.write(Bun.file(J),Bun.file(b)),await Kb(J,493)}}async function qb($,b){try{await R6($,b)}catch(_){await Bun.write(Bun.file(b),Bun.file($)),await hb($,{force:!0})}}async function cb($,b,_,J){let K;for(let Q=1;Q<=3;Q++)try{let G=await fetch($);if(!G.ok)throw Error(`Status ${G.status}`);let Y=+(G.headers.get("Content-Length")||0),H=0,k=G.body?.getReader();if(!k)throw Error("Could not get response body reader");let A=Bun.file(b).writer(),W=z==="win32",P=0;if(_)_.stop();if(W&&Q===1)console.log(`Downloading Bun ${J}...`);else if(Q>1)console.log(`Retry ${Q}/3 for Bun ${J}...`);let B=null;if(Y>0&&!W)B=new n$(Y),B.start();else if(!W)console.log(`Downloading Bun ${J}...`);try{if(W&&Y>0)console.log("> 0%"),P=10;while(!0){let{done:v,value:i}=await k.read();if(v)break;if(A.write(i),H+=i.length,B)B.update(H);if(W&&Y>0){let H$=Math.floor(H/Y*100);while(H$>=P&&P<=100)console.log(`> ${P}%`),P+=10}}if(await A.end(),B)B.stop();if(W&&Y>0&&P<=100)console.log("> 100%");if(_)_.start();return}catch(v){try{await A.end()}catch(i){}if(B)B.stop();throw v}}catch(G){K=G;try{await hb(b,{force:!0})}catch(Y){}if(Q<3)await new Promise((Y)=>setTimeout(Y,1000*Q))}if(_)_.start();throw K||Error("Download failed after multiple attempts")}async function Qb($,b={}){let _=$||await u$()||void 0;if(!_){console.error(Z.red("No version specified."));return}let J=null,q=!1;try{await U(`Finding Bun ${_}...`,async(K)=>{let Q=null,G=y(_),Y=_.trim(),H=/^v?\d+\.\d+$/.test(Y),k=/[xX\*\^\~\<\>\=]/.test(Y);if(H||k)throw Error('Fuzzy matching (e.g. "1.1") is disabled for install. Please specify a full version like "1.1.20".');if(/^v?\d+\.\d+\.\d+$/.test(_)&&!_.includes("canary"))if(await fb(G))Q=G;else throw Error(`Version ${G} not found.`);else if(_==="latest"){let I$=await Bb();if(I$.latest)Q=y(I$.latest)}if(!Q)throw Error("Could not resolve version.");let A=await Fb(Q);if(!A)throw Error("Incompatible system.");let{url:W,mirrorUrl:P,foundVersion:B}=A,v=u(n,B),i=u(w,B),H$=u(v,"bin"),Q$=u(H$,E);if(!await X(Q$)){if(await T(H$),y(Bun.version)===B&&!D())await Bun.write(Bun.file(Q$),Bun.file(process.execPath));else if(D())await u6(Q$,B);else{await T(S);let k$=u(S,`${B}-${E6(W)}`);if(!await X(k$)){let Z$=`${k$}.tmp`;console.log(Z.dim(` Downloading from: ${W.replace(/\/[^\/]*$/,"/...")}`));try{await cb(W,Z$,K,B),await qb(Z$,k$)}catch(L1){if(P)console.log(Z.yellow(" Primary source failed, trying mirror...")),await cb(P,Z$,K,B),await qb(Z$,k$);else throw L1}}K.update("Extracting..."),await Ib(k$,v);let z1=[u(v,E),u(v,"bin",E),u(v,"package","bin",E)],j$="";for(let Z$ of z1)if(await X(Z$)){j$=Z$;break}if(j$&&j$!==Q$)await qb(j$,Q$)}await Kb(Q$,493);let I$=u(v,"install","cache");await T(I$),await S6(v),await v6(H$,Q$),await w$(H$)}if(await T(w),!await X(i))if(z==="win32")await s(v,i);else await gb("../runtime/"+B,i,"dir");K.succeed(Z.green(`Bun ${B} physically installed.`)),J=B,q=!0})}catch(K){throw Error(`Failed: ${K.message}`)}if(q)await _$(!1);if(J){if(await d$(J,{silent:!0}),!await X(u(C,"default")))await L$("default",J,{silent:!0})}}async function u6($,b){let J=`#!/usr/bin/env bash
596
+ url = "${G}"
597
+ `}catch(G){}await Bun.write(_,q)}async function Fy($,b){let _=E.replace("bun","bunx"),y=F($,_);if(await K(y))return;try{await gb(E,y)}catch(f){await Bun.write(Bun.file(y),Bun.file(b)),await fb(y,493)}}async function yb($,b){try{await Ty($,b)}catch(_){await Bun.write(Bun.file(b),Bun.file($)),await hb($,{force:!0})}}async function db($,b,_,y){let w;for(let H=1;H<=3;H++)try{let q=await fetch($);if(!q.ok)throw Error(`Status ${q.status}`);let G=+(q.headers.get("Content-Length")||0),Q=0,L=q.body?.getReader();if(!L)throw Error("Could not get response body reader");let U=Bun.file(b).writer(),k=Y==="win32",S=0;if(_)_.stop();if(k&&H===1)console.log(`Downloading Bun ${y}...`);else if(H>1)console.log(`Retry ${H}/3 for Bun ${y}...`);let R=null;if(G>0&&!k)R=new l$(G),R.start();else if(!k)console.log(`Downloading Bun ${y}...`);try{if(k&&G>0)console.log("> 0%"),S=10;while(!0){let{done:j,value:i}=await L.read();if(j)break;if(U.write(i),Q+=i.length,R)R.update(Q);if(k&&G>0){let C$=Math.floor(Q/G*100);while(C$>=S&&S<=100)console.log(`> ${S}%`),S+=10}}if(await U.end(),R)R.stop();if(k&&G>0&&S<=100)console.log("> 100%");if(_)_.start();return}catch(j){try{await U.end()}catch(i){}if(R)R.stop();throw j}}catch(q){w=q;try{await hb(b,{force:!0})}catch(G){}if(H<3)await Bun.sleep(1000*H)}if(_)_.start();throw w||Error("Download failed after multiple attempts")}async function wb($,b={}){let _=$||await T$()||void 0;if(!_){console.error(J.red("No version specified."));return}let y=null,f=!1;try{await X(`Finding Bun ${_}...`,async(w)=>{let H=null,q=C(_),G=_.trim(),Q=/^v?\d+\.\d+$/.test(G),L=/[xX\*\^\~\<\>\=]/.test(G);if(Q||L)throw Error('Fuzzy matching (e.g. "1.1") is disabled for install. Please specify a full version like "1.1.20".');if(/^v?\d+\.\d+\.\d+$/.test(_)&&!_.includes("canary"))if(await Ub(q))H=q;else throw Error(`Version ${q} not found.`);else if(_==="latest"){let x$=await Bb();if(x$.latest)H=C(x$.latest)}if(!H)throw Error("Could not resolve version.");let U=await Db(H);if(!U)throw Error("Incompatible system.");let{url:k,mirrorUrl:S,foundVersion:R}=U,j=F(t,R),i=F(M,R),C$=F(j,"bin"),H$=F(C$,E);if(!await K(H$)){if(await u(C$),C(Bun.version)===R&&!c())await Bun.write(Bun.file(H$),Bun.file(process.execPath));else if(c())await Sy(H$,R);else{await u(T);let L$=F(T,`${R}-${vy(k)}`);if(!await K(L$)){let J$=`${L$}.tmp`;console.log(J.dim(` Downloading from: ${k.replace(/\/[^\/]*$/,"/...")}`));try{await db(k,J$,w,R),await yb(J$,L$)}catch(M_){if(S)console.log(J.yellow(" Primary source failed, trying mirror...")),await db(S,J$,w,R),await yb(J$,L$);else throw M_}}w.update("Extracting..."),await Rb(L$,j);let k_=[F(j,E),F(j,"bin",E),F(j,"package","bin",E)],u$="";for(let J$ of k_)if(await K(J$)){u$=J$;break}if(u$&&u$!==H$)await yb(u$,H$)}await fb(H$,493);let x$=F(j,"install","cache");await u(x$),await jy(j),await Fy(C$,H$),await M$(C$)}if(await u(M),!await K(i))if(Y==="win32")await a(j,i);else await gb("../runtime/"+R,i,"dir");w.succeed(J.green(`Bun ${R} physically installed.`)),y=R,f=!0})}catch(w){throw Error(`Failed: ${w.message}`)}if(f)await _$(!1);if(y){if(await F$(y,{silent:!0}),!await K(F(z,"default")))await k$("default",y,{silent:!0})}}async function Sy($,b){let y=`#!/usr/bin/env bash
586
598
  if [[ $# -gt 0 && "$1" == "--version" ]]; then echo "${b.replace(/^v/,"")}"; exit 0; fi
587
599
  exit 0
588
- `;await Bun.write($,J),await Kb($,493)}x();N();I();async function pb(){await U("Fetching remote Bun versions...",async($)=>{let _=(await Mb()).filter((J)=>p(J)).filter((J)=>!J.includes("canary")).sort(Y$);if(_.length===0)throw Error("No remote Bun versions found.");$.succeed(Z.green("Available remote Bun versions:")),_.forEach((J)=>{console.log(` ${y(J)}`)})},{failMessage:"Failed to fetch remote Bun versions"})}x();N();M();I();import{join as P6}from"path";async function lb(){await U("Fetching locally installed Bun versions...",async($)=>{let b=await d(),J=(await c()).version;if($.succeed(Z.green("Locally installed Bun versions:")),b.length===0)console.log(" (No versions installed yet)");else b.forEach((K)=>{if(K===J)console.log(`* ${Z.green(K)} ${Z.dim("(current)")}`);else console.log(` ${K}`)});if(await X(C)){let K=await V(C);if(K.length>0){console.log(Z.green(`
589
- Aliases:`));for(let Q of K)try{let G=(await F(P6(C,Q))).trim(),Y=y(G),H=`-> ${Z.cyan(Y)}`;if(Y===J)H+=` ${Z.dim("(current)")}`;console.log(` ${Q} ${Z.gray(H)}`)}catch(G){}}}},{failMessage:"Failed to list local Bun versions"})}x();N();I();async function nb(){await U("Checking current Bun version...",async($)=>{let{version:b,source:_}=await c();if(b)$.stop(),console.log(`${Z.green("\u2713")} Current Bun version: ${Z.green(b)} ${Z.dim(`(${_})`)}`);else $.info(Z.blue("No Bun version is currently active.")),console.log(Z.yellow("Use 'bvm install <version>' to set a default, or create a .bvmrc file."))},{failMessage:"Failed to determine current Bun version"})}x();M();N();I();import{join as Zb,basename as d6}from"path";import{unlink as V6}from"fs/promises";async function ob($){await U(`Attempting to uninstall Bun ${$}...`,async(b)=>{let _=y($),J=Zb(w,_),q=Zb(J,"bin",E);if(!await X(q))throw Error(`Bun ${$} is not installed.`);let K=!1;try{let Q=Zb(C,"default");if(await X(Q)){let G=(await F(Q)).trim();if(y(G)===_)K=!0}}catch(Q){}if(K)throw console.log(Z.yellow("Hint: Set a new default using 'bvm default <new_version>'")),Error(`Bun ${$} is currently set as default. Please set another default before uninstalling.`);try{let Q=await Cb(a);if(Q){if(y(d6(Q))===_)await V6(a)}}catch(Q){}await S$(J),b.succeed(Z.green(`Bun ${_} uninstalled successfully.`)),await q$()},{failMessage:`Failed to uninstall Bun ${$}`})}x();M();N();I();import{join as m6}from"path";import{unlink as c6}from"fs/promises";async function tb($){await U(`Removing alias '${$}'...`,async(b)=>{let _=m6(C,$);if(!await X(_))throw Error(`Alias '${$}' does not exist.`);await c6(_),b.succeed(Z.green(`Alias '${$}' removed successfully.`))},{failMessage:`Failed to remove alias '${$}'`})}x();M();N();J$();I();import{join as Gb}from"path";async function ib($,b){await U(`Preparing to run with Bun ${$}...`,async(_)=>{let J=await h($);if(!J)J=y($);let q=Gb(w,J),K=Gb(q,"bin"),Q=Gb(K,E);if(!await X(Q)){_.fail(Z.red(`Bun ${$} (resolved: ${J}) is not installed.`)),console.log(Z.yellow(`You can install it using: bvm install ${$}`));return}_.stop();try{await o([Q,...b],{cwd:process.cwd(),prependPath:K}),process.exit(0)}catch(G){console.error(G.message),process.exit(1)}},{failMessage:`Failed to run command with Bun ${$}`})}x();M();N();J$();I();import{join as Yb}from"path";import{spawn as h6}from"child_process";async function ab($,b,_){await U(`Preparing to execute with Bun ${$}...`,async(J)=>{let q=await h($);if(!q)q=y($);let K=Yb(w,q),Q=Yb(K,"bin"),G=Yb(Q,E);if(!await X(G)){J.fail(Z.red(`Bun ${$} (resolved: ${q}) is not installed.`)),console.log(Z.yellow(`You can install it using: bvm install ${$}`));return}J.stop();let Y={...process.env,PATH:`${Q}${process.platform==="win32"?";":":"}${process.env.PATH}`,BUN_INSTALL:K};return new Promise((H,k)=>{let A=h6(b,_,{stdio:"inherit",shell:!0,env:Y,cwd:process.cwd()});A.on("exit",(W)=>{if(W===0)H();else k(Error(`Command exited with code ${W}`))}),A.on("error",(W)=>{k(W)})})},{failMessage:`Failed to execute command with Bun ${$}`})}M();N();I();import{join as g6}from"path";async function sb($){await U("Resolving path...",async()=>{let b=null,_="bun",{version:J}=await c();if(!$||$==="current"){if(b=J,!b)throw Error("No active Bun version found.")}else{let{resolveLocalVersion:K}=await Promise.resolve().then(() => (J$(),Rb));if(b=await K($),!b)if(J)b=J,_=$;else throw Error(`Bun version or command '${$}' not found.`)}let q=g6(w,b,"bin",_==="bun"?E:_);if(await X(q))console.log(q);else throw Error(`Command '${_}' not found in Bun ${b}.`)},{failMessage:"Failed to resolve path"})}x();N();I();J$();async function rb($){await U(`Resolving session version for Bun ${$}...`,async(b)=>{let _=null,J=await h($);if(J)_=J;else{let K=(await d()).map((Q)=>y(Q));_=b$($,K)}if(!_)throw Error(`Bun version '${$}' is not installed or cannot be resolved.`);let q=y(_);b.succeed(Z.green(`Bun ${q} will be active in this session.`)),console.log(`export BVM_ACTIVE_VERSION=${q}`),console.log(Z.dim("Run `eval $(bvm shell <version>)` or `export BVM_ACTIVE_VERSION=...` to activate."))},{failMessage:`Failed to set session version for Bun ${$}`})}x();M();N();I();import{join as p6}from"path";async function eb($){let b=p6(C,"default");if(!$)await U("Checking current default Bun version...",async(_)=>{if(await X(b)){let J=await F(b);_.succeed(Z.green(`Default Bun version: ${y(J.trim())}`))}else _.info(Z.blue("No global default Bun version is set.")),console.log(Z.yellow("Use 'bvm default <version>' to set one."))},{failMessage:"Failed to retrieve default Bun version"});else await U(`Setting global default to Bun ${$}...`,async(_)=>{let J=(await d()).map((K)=>y(K)),q=b$($,J);if(!q)throw Error(`Bun version '${$}' is not installed.`);await L$("default",q,{silent:!0}),_.succeed(Z.green(`\u2713 Default set to ${q}. New terminals will now start with this version.`))},{failMessage:`Failed to set global default to Bun ${$}`})}M();N();x();I();import{unlink as l6}from"fs/promises";import{join as n6}from"path";async function $1(){await U("Deactivating current Bun version...",async($)=>{let b=n6(C,"default");if(await X(b))await l6(b),$.succeed(Z.green("Default Bun version deactivated.")),console.log(Z.gray("Run `bvm use <version>` to reactivate.")),await q$();else $.info("No default Bun version is currently active.")},{failMessage:"Failed to deactivate"})}J$();M();N();x();I();async function b1($){if($==="dir"){console.log(S);return}if($==="clear"){await U("Clearing cache...",async(b)=>{await S$(S),await T(S),b.succeed(Z.green("Cache cleared."))},{failMessage:"Failed to clear cache"});return}console.error(Z.red(`Unknown cache command: ${$}`)),console.log("Usage: bvm cache dir | bvm cache clear")}x();M();I();N();import{join as R}from"path";import{tmpdir as o6}from"os";import{rm as _1,mkdir as J1}from"fs/promises";var __dirname="/home/runner/work/bvm/bvm/src/commands",Xb=O$.version;async function q1(){let $=process.env.BVM_INSTALL_SOURCE;if($==="npm"||$==="bun"||__dirname.includes("node_modules")){await U(`Upgrading BVM via ${$||"package manager"}...`,async(_)=>{let J=await t(),q=$==="bun"?"bun":"npm";_.text=`Upgrading BVM via ${q} using ${J}...`;try{await o([q,"install","-g","bvm-core","--registry",J]),_.succeed(Z.green(`BVM upgraded via ${q} successfully.`))}catch(K){throw Error(`${q} upgrade failed: ${K.message}`)}});return}try{await U("Checking for BVM updates...",async(_)=>{let J=D()?{version:process.env.BVM_TEST_LATEST_VERSION?.replace("v","")||Xb,tarball:"https://example.com/bvm-test.tgz",shasum:"mock",integrity:"mock"}:await v$();if(!J)throw Error("Unable to determine the latest BVM version from NPM Registry.");let q=J.version;if(!p(q))throw Error(`Unrecognized version received: ${q}`);if(!D$(q,Xb)){_.succeed(Z.green(`BVM is already up to date (v${Xb}).`)),console.log(Z.blue("You are using the latest version."));return}if(_.text=`Updating BVM to v${q}...`,D()&&!process.env.BVM_TEST_REAL_UPGRADE){_.succeed(Z.green("BVM updated successfully (test mode)."));return}_.update("Downloading update package...");let K=R(o6(),`bvm-upgrade-${Date.now()}`);await J1(K,{recursive:!0});let Q=R(K,"bvm-core.tgz");if(D()){await m(Q,"mock-tarball");let Y=R(K,"package","dist");await J1(Y,{recursive:!0}),await m(R(Y,"index.js"),"// new cli"),await m(R(Y,"bvm-shim.sh"),"# new shim"),await m(R(Y,"bvm-shim.js"),"// new shim")}else{let Y=await e(J.tarball,{timeout:30000});if(!Y.ok)throw Error(`Failed to download tarball: ${Y.statusText}`);let H=await Y.arrayBuffer();await N$(Q,new Uint8Array(H)),_.update("Extracting update...");try{await o(["tar","-xzf",Q,"-C",K])}catch(k){throw Error('Failed to extract update package. Ensure "tar" is available.')}}_.update("Applying updates...");let G=R(K,"package","dist");if(await X(R(G,"index.js")))await N$(R(L,"src","index.js"),await F(R(G,"index.js")));if(z!=="win32"&&await X(R(G,"bvm-shim.sh")))await N$(R(L,"bin","bvm-shim.sh"),await F(R(G,"bvm-shim.sh")));if(z==="win32"&&await X(R(G,"bvm-shim.js")))await N$(R(L,"bin","bvm-shim.js"),await F(R(G,"bvm-shim.js")));try{await _1(K,{recursive:!0,force:!0})}catch(Y){}try{await _1(h$,{force:!0})}catch(Y){}_.update("Finalizing environment..."),await _$(!1),_.succeed(Z.green(`BVM updated to v${q} successfully.`)),console.log(Z.yellow("Please restart your terminal to apply changes."))},{failMessage:"Failed to upgrade BVM"})}catch(_){throw Error(`Failed to upgrade BVM: ${_.message}`)}}x();M();N();I();import{homedir as s6}from"os";import{join as r6}from"path";import{existsSync as K1,readFileSync as Q1,writeFileSync as t6}from"fs";import{homedir as i6}from"os";import{join as a6}from"path";class B${configPath;constructor($){this.configPath=$||a6(i6(),".bunfig.toml")}getPath(){return this.configPath}getRegistry(){if(!K1(this.configPath))return null;let $=Q1(this.configPath,"utf-8"),b=$.indexOf("[install]");if(b===-1)return null;let _=$.indexOf("[",b+1),q=$.substring(b,_===-1?void 0:_).match(/registry\s*=\s*\"(.*?)\"/);return q?q[1]:null}setRegistry($){let b="";if(K1(this.configPath))b=Q1(this.configPath,"utf-8");let _="[install]",J=b.indexOf(_);if(J===-1){let q=b.length>0&&!b.endsWith(`
600
+ `;await Bun.write($,y),await fb($,493)}W();I();N();async function Pb(){await X("Fetching remote Bun versions...",async($)=>{let _=(await Wb()).filter((y)=>n(y)).filter((y)=>!y.includes("canary")).sort(K$);if(_.length===0)throw Error("No remote Bun versions found.");$.succeed(J.green("Available remote Bun versions:")),_.forEach((y)=>{console.log(` ${C(y)}`)})},{failMessage:"Failed to fetch remote Bun versions"})}W();I();B();N();import{join as my}from"path";async function Vb(){await X("Fetching locally installed Bun versions...",async($)=>{let b=await m(),y=(await g()).version;if($.succeed(J.green("Locally installed Bun versions:")),b.length===0)console.log(" (No versions installed yet)");else b.forEach((w)=>{if(w===y)console.log(`* ${J.green(w)} ${J.dim("(current)")}`);else console.log(` ${w}`)});if(await K(z)){let w=await d(z);if(w.length>0){console.log(J.green(`
601
+ Aliases:`));for(let H of w)try{let q=(await x(my(z,H))).trim(),G=C(q),Q=`-> ${J.cyan(G)}`;if(G===y)Q+=` ${J.dim("(current)")}`;console.log(` ${H} ${J.gray(Q)}`)}catch(q){}}}},{failMessage:"Failed to list local Bun versions"})}W();I();N();async function pb(){await X("Checking current Bun version...",async($)=>{let{version:b,source:_}=await g();if(b)$.stop(),console.log(`${J.green("\u2713")} Current Bun version: ${J.green(b)} ${J.dim(`(${_})`)}`);else $.info(J.blue("No Bun version is currently active.")),console.log(J.yellow("Use 'bvm install <version>' to set a default, or create a .bvmrc file."))},{failMessage:"Failed to determine current Bun version"})}W();B();I();N();import{join as Hb,basename as dy}from"path";import{unlink as hy}from"fs/promises";async function lb($){await X(`Attempting to uninstall Bun ${$}...`,async(b)=>{let _=C($),y=Hb(M,_),f=Hb(y,"bin",E);if(!await K(f))throw Error(`Bun ${$} is not installed.`);let w=!1;try{let H=Hb(z,"default");if(await K(H)){let q=(await x(H)).trim();if(C(q)===_)w=!0}}catch(H){}if(w)throw console.log(J.yellow("Hint: Set a new default using 'bvm default <new_version>'")),Error(`Bun ${$} is currently set as default. Please set another default before uninstalling.`);try{let H=await Mb(s);if(H){if(C(dy(H))===_)await hy(s)}}catch(H){}await E$(y),b.succeed(J.green(`Bun ${_} uninstalled successfully.`)),await f$()},{failMessage:`Failed to uninstall Bun ${$}`})}W();B();I();N();import{join as gy}from"path";import{unlink as Py}from"fs/promises";async function nb($){await X(`Removing alias '${$}'...`,async(b)=>{let _=gy(z,$);if(!await K(_))throw Error(`Alias '${$}' does not exist.`);await Py(_),b.succeed(J.green(`Alias '${$}' removed successfully.`))},{failMessage:`Failed to remove alias '${$}'`})}W();B();I();y$();N();import{join as Jb}from"path";async function ob($,b){await X(`Preparing to run with Bun ${$}...`,async(_)=>{let y=await p($);if(!y)y=C($);let f=Jb(M,y),w=Jb(f,"bin"),H=Jb(w,E);if(!await K(H)){_.fail(J.red(`Bun ${$} (resolved: ${y}) is not installed.`)),console.log(J.yellow(`You can install it using: bvm install ${$}`));return}_.stop();try{await b$([H,...b],{cwd:process.cwd(),prependPath:w}),process.exit(0)}catch(q){console.error(q.message),process.exit(1)}},{failMessage:`Failed to run command with Bun ${$}`})}W();B();I();y$();N();import{join as qb}from"path";import{spawn as Vy}from"child_process";async function tb($,b,_){await X(`Preparing to execute with Bun ${$}...`,async(y)=>{let f=await p($);if(!f)f=C($);let w=qb(M,f),H=qb(w,"bin"),q=qb(H,E);if(!await K(q)){y.fail(J.red(`Bun ${$} (resolved: ${f}) is not installed.`)),console.log(J.yellow(`You can install it using: bvm install ${$}`));return}y.stop();let G={...process.env,PATH:`${H}${process.platform==="win32"?";":":"}${process.env.PATH}`,BUN_INSTALL:w};return new Promise((Q,L)=>{let U=Vy(b,_,{stdio:"inherit",shell:!0,env:G,cwd:process.cwd()});U.on("exit",(k)=>{if(k===0)Q();else L(Error(`Command exited with code ${k}`))}),U.on("error",(k)=>{L(k)})})},{failMessage:`Failed to execute command with Bun ${$}`})}B();I();N();import{join as py}from"path";async function ib($){await X("Resolving path...",async()=>{let b=null,_="bun",{version:y}=await g();if(!$||$==="current"){if(b=y,!b)throw Error("No active Bun version found.")}else{let{resolveLocalVersion:w}=await Promise.resolve().then(() => (y$(),cb));if(b=await w($),!b)if(y)b=y,_=$;else throw Error(`Bun version or command '${$}' not found.`)}let f=py(M,b,"bin",_==="bun"?E:_);if(await K(f))console.log(f);else throw Error(`Command '${_}' not found in Bun ${b}.`)},{failMessage:"Failed to resolve path"})}W();I();N();y$();async function sb($){await X(`Resolving session version for Bun ${$}...`,async(b)=>{let _=null,y=await p($);if(y)_=y;else{let w=(await m()).map((H)=>C(H));_=$$($,w)}if(!_)throw Error(`Bun version '${$}' is not installed or cannot be resolved.`);let f=C(_);b.succeed(J.green(`Bun ${f} will be active in this session.`)),console.log(`export BVM_ACTIVE_VERSION=${f}`),console.log(J.dim("Run `eval $(bvm shell <version>)` or `export BVM_ACTIVE_VERSION=...` to activate."))},{failMessage:`Failed to set session version for Bun ${$}`})}W();B();I();N();import{join as ly}from"path";async function ab($){let b=ly(z,"default");if(!$)await X("Checking current default Bun version...",async(_)=>{if(await K(b)){let y=await x(b);_.succeed(J.green(`Default Bun version: ${C(y.trim())}`))}else _.info(J.blue("No global default Bun version is set.")),console.log(J.yellow("Use 'bvm default <version>' to set one."))},{failMessage:"Failed to retrieve default Bun version"});else await X(`Setting global default to Bun ${$}...`,async(_)=>{let y=(await m()).map((w)=>C(w)),f=$$($,y);if(!f)throw Error(`Bun version '${$}' is not installed.`);await k$("default",f,{silent:!0}),_.succeed(J.green(`\u2713 Default set to ${f}. New terminals will now start with this version.`))},{failMessage:`Failed to set global default to Bun ${$}`})}B();I();W();N();import{unlink as ny}from"fs/promises";import{join as oy}from"path";async function rb(){await X("Deactivating current Bun version...",async($)=>{let b=oy(z,"default");if(await K(b))await ny(b),$.succeed(J.green("Default Bun version deactivated.")),console.log(J.gray("Run `bvm use <version>` to reactivate.")),await f$();else $.info("No default Bun version is currently active.")},{failMessage:"Failed to deactivate"})}y$();B();I();W();N();async function eb($){if($==="dir"){console.log(T);return}if($==="clear"){await X("Clearing cache...",async(b)=>{await E$(T),await u(T),b.succeed(J.green("Cache cleared."))},{failMessage:"Failed to clear cache"});return}console.error(J.red(`Unknown cache command: ${$}`)),console.log("Usage: bvm cache dir | bvm cache clear")}W();B();N();I();import{join as v}from"path";import{tmpdir as ty}from"os";import{rm as $_,mkdir as b_}from"fs/promises";var __dirname="/home/runner/work/bvm/bvm/src/commands",Gb=O$.version;async function __(){let $=process.env.BVM_INSTALL_SOURCE;if($==="npm"||$==="bun"||__dirname.includes("node_modules")){await X(`Upgrading BVM via ${$||"package manager"}...`,async(_)=>{let y=await V(),f=$==="bun"?"bun":"npm";_.update(`Upgrading BVM via ${f} using ${y}...`);try{await b$([f,"install","-g","bvm-core","--registry",y]),_.succeed(J.green(`BVM upgraded via ${f} successfully.`))}catch(w){throw Error(`${f} upgrade failed: ${w.message}`)}});return}try{await X("Checking for BVM updates...",async(_)=>{let y=c()?{version:process.env.BVM_TEST_LATEST_VERSION?.replace("v","")||Gb,tarball:"https://example.com/bvm-test.tgz",shasum:"mock",integrity:"mock"}:await v$();if(!y)throw Error("Unable to determine the latest BVM version from NPM Registry.");let f=y.version;if(!n(f))throw Error(`Unrecognized version received: ${f}`);if(!N$(f,Gb)){_.succeed(J.green(`BVM is already up to date (v${Gb}).`)),console.log(J.blue("You are using the latest version."));return}if(_.text=`Updating BVM to v${f}...`,c()&&!process.env.BVM_TEST_REAL_UPGRADE){_.succeed(J.green("BVM updated successfully (test mode)."));return}_.update("Downloading update package...");let w=v(ty(),`bvm-upgrade-${Date.now()}`);await b_(w,{recursive:!0});let H=v(w,"bvm-core.tgz");if(c()){await h(H,"mock-tarball");let G=v(w,"package","dist");await b_(G,{recursive:!0}),await h(v(G,"index.js"),"// new cli"),await h(v(G,"bvm-shim.sh"),"# new shim"),await h(v(G,"bvm-shim.js"),"// new shim")}else{let G=await P(y.tarball,{timeout:30000});if(!G.ok)throw Error(`Failed to download tarball: ${G.statusText}`);let Q=await G.arrayBuffer();await I$(H,new Uint8Array(Q)),_.update("Extracting update...");try{await b$(["tar","-xzf",H,"-C",w])}catch(L){throw Error('Failed to extract update package. Ensure "tar" is available.')}}_.update("Applying updates...");let q=v(w,"package","dist");if(await K(v(q,"index.js")))await I$(v(O,"src","index.js"),await x(v(q,"index.js")));if(Y!=="win32"&&await K(v(q,"bvm-shim.sh")))await I$(v(O,"bin","bvm-shim.sh"),await x(v(q,"bvm-shim.sh")));if(Y==="win32"&&await K(v(q,"bvm-shim.js")))await I$(v(O,"bin","bvm-shim.js"),await x(v(q,"bvm-shim.js")));try{await $_(w,{recursive:!0,force:!0})}catch(G){}try{await $_(h$,{force:!0})}catch(G){}_.update("Finalizing environment..."),await _$(!1),_.succeed(J.green(`BVM updated to v${f} successfully.`)),console.log(J.yellow("Please restart your terminal to apply changes."))},{failMessage:"Failed to upgrade BVM"})}catch(_){throw Error(`Failed to upgrade BVM: ${_.message}`)}}W();B();I();N();import{homedir as ry}from"os";import{delimiter as ey,join as J_}from"path";import{rm as $1}from"fs/promises";import{existsSync as y_,readFileSync as f_,writeFileSync as iy}from"fs";import{homedir as sy}from"os";import{join as ay}from"path";class R${configPath;constructor($){this.configPath=$||ay(sy(),".bunfig.toml")}getPath(){return this.configPath}getRegistry(){if(!y_(this.configPath))return null;let $=f_(this.configPath,"utf-8"),b=$.indexOf("[install]");if(b===-1)return null;let _=$.indexOf("[",b+1),f=$.substring(b,_===-1?void 0:_).match(/registry\s*=\s*\"(.*?)\"/);return f?f[1]:null}setRegistry($){let b="";if(y_(this.configPath))b=f_(this.configPath,"utf-8");let _="[install]",y=b.indexOf(_);if(y===-1){let f=b.length>0&&!b.endsWith(`
590
602
  `)?`
591
- `:"";b+=`${q}${_}
603
+ `:"";b+=`${f}${_}
592
604
  registry = "${$}"
593
- `}else{let q=b.indexOf("[",J+1),K=q===-1?b.length:q,Q=b.substring(0,J),G=b.substring(J,K),Y=b.substring(K);if(G.match(/registry\s*=/)){let H=G.replace(/registry\s*=\s*".*?"/,`registry = "${$}"`);b=Q+H+Y}else{let H=G.replace(_,`${_}
594
- registry = "${$}"`);b=Q+H+Y}}t6(this.configPath,b,"utf-8")}}async function Z1(){await U("Gathering BVM diagnostics...",async()=>{let $=new B$,b={currentVersion:(await c()).version,installedVersions:await d(),aliases:await e6(),env:{BVM_DIR:L,BVM_BIN_DIR:j,BVM_SHIMS_DIR:f,BVM_VERSIONS_DIR:w,BVM_TEST_MODE:process.env.BVM_TEST_MODE,HOME:process.env.HOME||s6()},bunfig:{path:$.getPath(),registry:$.getRegistry()}};$0(b)})}async function e6(){if(!await X(C))return[];let $=await V(C),b=[];for(let _ of $){let J=r6(C,_);if(await X(J)){let q=await Bun.file(J).text();b.push({name:_,target:y(q.trim())})}}return b}function $0($){if(console.log(Z.bold(`
595
- System`)),console.log(` OS: ${Z.cyan(z)}`),console.log(` Arch: ${Z.cyan($$)} ${process.arch!==$$?Z.yellow(`(Process: ${process.arch})`):""}`),console.log(` AVX2: ${T$?Z.green("Supported"):Z.yellow("Not Supported (Baseline fallback enabled)")}`),console.log(Z.bold(`
596
- Directories`)),console.log(` BVM_DIR: ${Z.cyan($.env.BVM_DIR||"")}`),console.log(` BIN_DIR: ${Z.cyan(j)}`),console.log(` SHIMS_DIR: ${Z.cyan(f)}`),console.log(` VERSIONS_DIR: ${Z.cyan(w)}`),console.log(Z.bold(`
597
- Environment`)),console.log(` HOME: ${$.env.HOME||"n/a"}`),console.log(` BVM_TEST_MODE: ${$.env.BVM_TEST_MODE||"false"}`),console.log(Z.bold(`
598
- Installed Versions`)),$.installedVersions.length===0)console.log(" (none installed)");else $.installedVersions.forEach((b)=>{let _=b===$.currentVersion,J=_?Z.green("*"):" ",q=_?Z.green(b):b,K=_?Z.green(" (current)"):"";console.log(` ${J} ${q}${K}`)});if(console.log(Z.bold(`
599
- Configuration`)),console.log(` Bunfig: ${Z.cyan($.bunfig.path)}`),console.log(` Registry: ${$.bunfig.registry?Z.green($.bunfig.registry):Z.dim("default")}`),console.log(Z.bold(`
600
- Aliases`)),$.aliases.length===0)console.log(" (no aliases configured)");else $.aliases.forEach((b)=>{console.log(` ${b.name} ${Z.gray("->")} ${Z.cyan(b.target)}`)});console.log(`
601
- `+Z.green("Diagnostics complete."))}var F$={NPM:"https://registry.npmjs.org",NPM_MIRROR:"https://registry.npmmirror.com"};class Hb{timeoutMs;constructor($=3000){this.timeoutMs=$}async getFastestRegistry(){let $=async(b)=>{let _=Date.now();try{let J=new AbortController,q=setTimeout(()=>J.abort(),this.timeoutMs),K=await fetch(b,{method:"HEAD",signal:J.signal});if(clearTimeout(q),!K.ok)throw Error(`Status ${K.status}`);return b}catch(J){throw J}};try{return await Promise.any([$(F$.NPM).then(()=>F$.NPM),$(F$.NPM_MIRROR).then(()=>F$.NPM_MIRROR)])}catch(b){return F$.NPM}}}x();I();async function G1($){let[b,_,J]=$,q=new B$;if(b==="ls"||!b){console.log(Z.bold(`
602
- BVM Configuration (via ~/.bunfig.toml)`)),console.log(`Path: ${Z.dim(q.getPath())}`);let K=q.getRegistry();console.log(`Registry: ${K?Z.green(K):Z.yellow("(not set, using Bun default)")}`);return}if(b==="registry"){if(_==="auto")await U("Racing registries for optimal speed...",async(K)=>{let G=await new Hb().getFastestRegistry();q.setRegistry(G),K.succeed(Z.green(`\u2713 Set registry to ${G}`))});else if(_)q.setRegistry(_),console.log(Z.green(`\u2713 Registry set to ${_}`));else{let K=q.getRegistry();console.log(`Current registry: ${K||"default"}`)}return}console.log(Z.red(`Unknown config command: ${b}`)),console.log("Usage:"),console.log(" bvm config ls"),console.log(" bvm config registry <url|auto>")}var yb=["install","uninstall","use","ls","ls-remote","current","alias","unalias","run","exec","which","cache","setup","upgrade","doctor","completion","deactivate","help"],Y1={bash:`#!/usr/bin/env bash
605
+ `}else{let f=b.indexOf("[",y+1),w=f===-1?b.length:f,H=b.substring(0,y),q=b.substring(y,w),G=b.substring(w);if(q.match(/registry\s*=/)){let Q=q.replace(/registry\s*=\s*".*?"/,`registry = "${$}"`);b=H+Q+G}else{let Q=q.replace(_,`${_}
606
+ registry = "${$}"`);b=H+Q+G}}iy(this.configPath,b,"utf-8")}}async function q_(){await X("Gathering BVM diagnostics...",async()=>{let $=await y1(),b=new R$,_={currentVersion:(await g()).version,installedVersions:await m(),aliases:await b1(),env:{BVM_DIR:O,BVM_BIN_DIR:A,BVM_SHIMS_DIR:D,BVM_VERSIONS_DIR:M,BVM_TEST_MODE:process.env.BVM_TEST_MODE,HOME:process.env.HOME||ry()},bunfig:{path:b.getPath(),registry:b.getRegistry()},checks:$};q1(_)})}async function b1(){if(!await K(z))return[];let $=await d(z),b=[];for(let _ of $){let y=J_(z,_);if(await K(y)){let f=await Bun.file(y).text();b.push({name:_,target:C(f.trim())})}}return b}function _1($){let b=$.pathHasShims&&$.pathHasBin?"pass":!$.pathHasShims&&!$.pathHasBin?"fail":"warn",_=[];if(!$.pathHasShims)_.push(`${$.bvmDir}/shims`);if(!$.pathHasBin)_.push(`${$.bvmDir}/bin`);let y=["bash","zsh","fish"].includes($.shellType)?"pass":"warn",f=y==="pass"?`Detected ${$.shellType}`:`Unsupported or unknown shell (${$.shellRaw||"empty SHELL"})`,w=$.osPlatform==="win32"?'$env:BVM_DIR="$env:USERPROFILE\\.bvm"; New-Item -ItemType Directory -Force -Path $env:BVM_DIR':'export BVM_DIR="$HOME/.bvm" && mkdir -p "$BVM_DIR"',H=$.osPlatform==="win32"?'icacls "$env:BVM_DIR" /grant "$env:USERNAME:(OI)(CI)F" /T':'chmod -R u+rwX "$BVM_DIR"',q=$.osPlatform==="win32"?"bvm setup":'bvm setup && exec "$SHELL"',G=$.osPlatform==="win32"?"bvm setup":'export SHELL="$(command -v zsh || command -v bash || command -v fish)" && bvm setup';return[{key:"bvm_dir",title:"BVM_DIR",status:$.bvmDirExists?"pass":"warn",detail:$.bvmDirExists?`Found ${$.bvmDir}`:`Missing directory: ${$.bvmDir}`,fixCommand:w},{key:"path",title:"PATH",status:b,detail:b==="pass"?"PATH already includes bvm shims/bin":`Missing PATH entries: ${_.join(", ")}`,fixCommand:q},{key:"shell",title:"Shell Type",status:y,detail:f,fixCommand:G},{key:"permission",title:"Directory Permission",status:$.directoryWritable?"pass":"fail",detail:$.directoryWritable?`Writable: ${$.bvmDir}`:`No write permission: ${$.bvmDir}`,fixCommand:H},{key:"network",title:"Network Connectivity",status:$.networkReachable?"pass":"warn",detail:$.networkReachable?"Able to reach registry.npmjs.org":"Cannot reach registry.npmjs.org",fixCommand:"bvm config registry auto"}]}async function y1(){let $=process.env.SHELL||process.env.ComSpec||"",b=process.env.PATH||"",_=await K(O),y=w_(b,D),f=w_(b,A),w=await f1(),H=await w1();return _1({bvmDir:O,bvmDirExists:_,pathHasShims:y,pathHasBin:f,shellType:H1($),shellRaw:$,directoryWritable:w,networkReachable:H,osPlatform:Y})}async function f1(){let $=J_(O,`.doctor-write-test-${Date.now()}.tmp`);try{return await u(O),await Bun.write($,"ok"),await $1($,{force:!0}),!0}catch{return!1}}async function w1(){try{return(await P("https://registry.npmjs.org/-/ping",{timeout:2000,method:"GET"})).ok}catch{return!1}}function w_($,b){let _=$.split(ey).filter(Boolean),y=H_(b);return _.some((f)=>H_(f)===y)}function H_($){let b=$.replace(/\\/g,"/").replace(/\/+$/,"");return Y==="win32"?b.toLowerCase():b}function H1($){let b=$.toLowerCase();if(b.includes("zsh"))return"zsh";if(b.includes("bash"))return"bash";if(b.includes("fish"))return"fish";if(b.includes("pwsh")||b.includes("powershell"))return"powershell";if(b.includes("cmd.exe"))return"cmd";return"unknown"}function J1($){if($==="pass")return J.green("PASS");if($==="warn")return J.yellow("WARN");return J.red("FAIL")}function q1($){if(console.log(J.bold(`
607
+ System`)),console.log(` OS: ${J.cyan(Y)}`),console.log(` Arch: ${J.cyan(e)} ${process.arch!==e?J.yellow(`(Process: ${process.arch})`):""}`),console.log(` AVX2: ${A$?J.green("Supported"):J.yellow("Not Supported (Baseline fallback enabled)")}`),console.log(J.bold(`
608
+ Doctor Checks`)),$.checks.forEach((b)=>{console.log(` [${J1(b.status)}] ${b.title}: ${b.detail}`),console.log(` Fix: ${J.cyan(b.fixCommand)}`)}),console.log(J.bold(`
609
+ Directories`)),console.log(` BVM_DIR: ${J.cyan($.env.BVM_DIR||"")}`),console.log(` BIN_DIR: ${J.cyan(A)}`),console.log(` SHIMS_DIR: ${J.cyan(D)}`),console.log(` VERSIONS_DIR: ${J.cyan(M)}`),console.log(J.bold(`
610
+ Environment`)),console.log(` HOME: ${$.env.HOME||"n/a"}`),console.log(` BVM_TEST_MODE: ${$.env.BVM_TEST_MODE||"false"}`),console.log(J.bold(`
611
+ Installed Versions`)),$.installedVersions.length===0)console.log(" (none installed)");else $.installedVersions.forEach((b)=>{let _=b===$.currentVersion,y=_?J.green("*"):" ",f=_?J.green(b):b,w=_?J.green(" (current)"):"";console.log(` ${y} ${f}${w}`)});if(console.log(J.bold(`
612
+ Configuration`)),console.log(` Bunfig: ${J.cyan($.bunfig.path)}`),console.log(` Registry: ${$.bunfig.registry?J.green($.bunfig.registry):J.dim("default")}`),console.log(J.bold(`
613
+ Aliases`)),$.aliases.length===0)console.log(" (no aliases configured)");else $.aliases.forEach((b)=>{console.log(` ${b.name} ${J.gray("->")} ${J.cyan(b.target)}`)});console.log(`
614
+ `+J.green("Diagnostics complete."))}W();N();async function G_($){let[b,_,y]=$,f=new R$;if(b==="ls"||!b){console.log(J.bold(`
615
+ BVM Configuration (via ~/.bunfig.toml)`)),console.log(`Path: ${J.dim(f.getPath())}`);let w=f.getRegistry();console.log(`Registry: ${w?J.green(w):J.yellow("(not set, using Bun default)")}`);return}if(b==="registry"){if(_==="auto")await X("Racing registries for optimal speed...",async(w)=>{let H=await V();f.setRegistry(H),w.succeed(J.green(`\u2713 Set registry to ${H}`))});else if(_)f.setRegistry(_),console.log(J.green(`\u2713 Registry set to ${_}`));else{let w=f.getRegistry();console.log(`Current registry: ${w||"default"}`)}return}console.log(J.red(`Unknown config command: ${b}`)),console.log("Usage:"),console.log(" bvm config ls"),console.log(" bvm config registry <url|auto>")}var Kb=["install","uninstall","use","ls","ls-remote","current","alias","unalias","run","exec","which","cache","setup","upgrade","doctor","completion","deactivate","help"],K_={bash:`#!/usr/bin/env bash
603
616
  _bvm_completions() {
604
- COMPREPLY=( $(compgen -W "${yb.join(" ")}" -- "\${COMP_WORDS[COMP_CWORD]}") )
617
+ COMPREPLY=( $(compgen -W "${Kb.join(" ")}" -- "\${COMP_WORDS[COMP_CWORD]}") )
605
618
  }
606
619
  complete -F _bvm_completions bvm
607
620
  `,zsh:`#compdef bvm
608
621
  _bvm() {
609
622
  local -a commands
610
- commands=( ${yb.join(" ")} )
623
+ commands=( ${Kb.join(" ")} )
611
624
  _describe 'command' commands
612
625
  }
613
626
  compdef _bvm bvm
614
- `,fish:`complete -c bvm -f -a "${yb.join(" ")}"
615
- `};function X1($){let b=Y1[$];if(!b)throw Error(`Unsupported shell '${$}'. Supported shells: ${Object.keys(Y1).join(", ")}`);console.log(b)}x();M();N();import{join as H1}from"path";x();var y1="update-check.json",b0=86400000;async function U1(){if(process.env.CI||D())return;let $=H1(S,y1);try{if(await X($)){let b=await F($),_=JSON.parse(b);if(Date.now()-_.lastCheck<b0)return}}catch(b){}try{let b=await v$();if(b){let _=b.tagName.startsWith("v")?b.tagName.slice(1):b.tagName;await T(S),await m($,JSON.stringify({lastCheck:Date.now(),latestVersion:_}))}}catch(b){}}async function O1(){if(process.env.CI||D())return null;let $=O$.version,b=H1(S,y1);try{if(await X(b)){let _=await F(b),J=JSON.parse(_);if(J.latestVersion&&D$(J.latestVersion,$))return`
616
- ${Z.gray("Update available:")} ${Z.green(`v${J.latestVersion}`)} ${Z.dim(`(current: v${$})`)}
617
- ${Z.gray("Run")} ${Z.cyan("bvm upgrade")} ${Z.gray("to update.")}`}}catch(_){}return null}class W1{commands={};helpEntries=[];name;versionStr;constructor($){this.name=$,this.versionStr=O$.version}command($,b,_={}){let J=$.split(" ")[0],q={description:b,usage:`${this.name} ${$}`,action:async()=>{},aliases:_.aliases};if(this.commands[J]=q,this.helpEntries.push(` ${$.padEnd(35)} ${b}`),_.aliases)_.aliases.forEach((Q)=>{this.commands[Q]=q});let K={action:(Q)=>{return q.action=Q,K},option:(Q,G)=>K};return K}async run(){try{U1().catch(()=>{})}catch(Q){}let{values:$,positionals:b}=_0({args:Bun.argv.slice(2),strict:!1,allowPositionals:!0,options:{help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"},silent:{type:"boolean",short:"s"}}}),_=b[0],J=!!($.silent||$.s),q=!!($.version||$.v||$.help||$.h);if(!_){if($.version||$.v)console.log(this.versionStr),process.exit(0);if($.help||$.h)this.showHelp(),process.exit(0);this.showHelp(),process.exit(1)}if($.help||$.h)this.showHelp(),process.exit(0);let K=this.commands[_];if(!K)console.error(Z.yellow(`Unknown command '${_}'`)),this.showHelp(),process.exit(0);try{if(await K.action(b.slice(1),$),!q&&!J&&["ls","current","doctor","default"].includes(_)){let Q=await O1();if(Q)console.log(Q)}}catch(Q){if(!Q.reported)console.error(Z.red(`\u2716 ${Q.message}`));process.exit(1)}}showHelp(){console.log(`Bun Version Manager (bvm) v${this.versionStr}`),console.log(`Built with Bun \xB7 Runs with Bun \xB7 Tested on Bun
627
+ `,fish:`complete -c bvm -f -a "${Kb.join(" ")}"
628
+ `};function Q_($){let b=K_[$];if(!b)throw Error(`Unsupported shell '${$}'. Supported shells: ${Object.keys(K_).join(", ")}`);console.log(b)}W();B();I();import{join as C_}from"path";W();var X_="update-check.json",G1=86400000;async function Z_(){if(process.env.CI||c())return;let $=C_(T,X_);try{if(await K($)){let b=await x($),_=JSON.parse(b);if(Date.now()-_.lastCheck<G1)return}}catch(b){}try{let b=await v$();if(b){let _=b.version.startsWith("v")?b.version.slice(1):b.version;await u(T),await h($,JSON.stringify({lastCheck:Date.now(),latestVersion:_}))}}catch(b){}}async function O_(){if(process.env.CI||c())return null;let $=O$.version,b=C_(T,X_);try{if(await K(b)){let _=await x(b),y=JSON.parse(_);if(y.latestVersion&&N$(y.latestVersion,$))return`
629
+ ${J.gray("Update available:")} ${J.green(`v${y.latestVersion}`)} ${J.dim(`(current: v${$})`)}
630
+ ${J.gray("Run")} ${J.cyan("bvm upgrade")} ${J.gray("to update.")}`}}catch(_){}return null}class Y_{commands={};helpEntries=[];name;versionStr;constructor($){this.name=$,this.versionStr=O$.version}command($,b,_={}){let y=$.split(" ")[0],f={description:b,usage:`${this.name} ${$}`,action:async()=>{},aliases:_.aliases};if(this.commands[y]=f,this.helpEntries.push(` ${$.padEnd(35)} ${b}`),_.aliases)_.aliases.forEach((H)=>{this.commands[H]=f});let w={action:(H)=>{return f.action=H,w},option:(H,q)=>w};return w}async run(){try{Z_().catch(()=>{})}catch(H){}let{values:$,positionals:b}=K1({args:Bun.argv.slice(2),strict:!1,allowPositionals:!0,options:{help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"},silent:{type:"boolean",short:"s"}}}),_=b[0],y=!!($.silent||$.s),f=!!($.version||$.v||$.help||$.h);if(!_){if($.version||$.v)console.log(this.versionStr),process.exit(0);if($.help||$.h)this.showHelp(),process.exit(0);this.showHelp(),process.exit(1)}if($.help||$.h)this.showHelp(),process.exit(0);let w=this.commands[_];if(!w)console.error(J.yellow(`Unknown command '${_}'`)),this.showHelp(),process.exit(0);try{if(await w.action(b.slice(1),$),!f&&!y&&["ls","current","doctor","default"].includes(_)){let H=await O_();if(H)console.log(H)}}catch(H){if(!H.reported)console.error(J.red(`\u2716 ${H.message}`));process.exit(1)}}showHelp(){console.log(`Bun Version Manager (bvm) v${this.versionStr}`),console.log(`Built with Bun \xB7 Runs with Bun \xB7 Tested on Bun
618
631
  `),console.log("Usage:"),console.log(` ${this.name} <command> [flags]
619
632
  `),console.log("Commands:"),console.log(this.helpEntries.join(`
620
633
  `)),console.log(`
621
634
  Global Flags:`),console.log(" --help, -h Show this help message"),console.log(" --version, -v Show version number"),console.log(`
622
- Examples:`),console.log(" bvm install 1.0.0"),console.log(" bvm use 1.0.0"),console.log(" bvm run 1.0.0 index.ts")}}async function J0(){let $=new W1("bvm");$.command("rehash","Regenerate shims for all installed binaries").option("--silent","Suppress output").action(async(b,_)=>{await q$({silent:_.silent})}),$.command("install [version]","Install a Bun version and set as current").option("--global, -g","Install as a global tool (not just default)").action(async(b,_)=>{await Qb(b[0],{global:_.global||_.g})}),$.command("i [version]","Alias for install").action(async(b,_)=>{await Qb(b[0],{global:_.global||_.g})}),$.command("ls","List installed Bun versions",{aliases:["list"]}).action(async()=>{await lb()}),$.command("ls-remote","List all available remote Bun versions").action(async()=>{await pb()}),$.command("use <version>","Switch the active Bun version immediately (all terminals)").option("--fix-path","Auto-run setup if shims not active").option("--yes, -y","Assume yes for prompts").action(async(b,_)=>{if(!b[0])throw Error("Version is required");let J=!!_.fixPath||!!_["fix-path"],q=!!_.yes||!!_.y;await d$(b[0],{fixPath:J,yes:q})}),$.command("shell <version>","Switch Bun version for the current shell session").action(async(b)=>{if(!b[0])throw Error("Version is required");await rb(b[0])}),$.command("default [version]","Display or set the global default Bun version").action(async(b)=>{await eb(b[0])}),$.command("current","Display the currently active Bun version").action(async()=>{await nb()}),$.command("uninstall <version>","Uninstall a Bun version").action(async(b)=>{if(!b[0])throw Error("Version is required");await ob(b[0])}),$.command("alias <name> <version>","Create an alias for a Bun version").action(async(b)=>{if(!b[0]||!b[1])throw Error("Name and version are required");await L$(b[0],b[1])}),$.command("unalias <name>","Remove an existing alias").action(async(b)=>{if(!b[0])throw Error("Alias name is required");await tb(b[0])}),$.command("run <version> [...args]","Run a command with a specific Bun version").action(async(b)=>{let _=b[0];if(!_)throw Error("Version is required");let J=process.argv.indexOf("run"),q=J!==-1?process.argv.slice(J+2):[];await ib(_,q)}),$.command("exec <version> <cmd> [...args]","Execute a command with a specific Bun version's environment").action(async(b)=>{let _=b[0],J=b[1];if(!_||!J)throw Error("Version and command are required");let q=process.argv.indexOf("exec"),K=q!==-1?process.argv.slice(q+3):[];await ab(_,J,K)}),$.command("which [version]","Display path to installed bun version").action(async(b)=>{await sb(b[0])}),$.command("deactivate","Undo effects of bvm on current shell").action(async()=>{await $1()}),$.command("version <spec>","Resolve the given description to a single local version").action(async(b)=>{if(!b[0])throw Error("Version specifier is required");await bb(b[0])}),$.command("cache <action>","Manage bvm cache").action(async(b)=>{if(!b[0])throw Error("Action is required");await b1(b[0])}),$.command("setup","Configure shell environment automatically").option("--silent, -s","Suppress output").action(async(b,_)=>{await _$(!(_.silent||_.s))}),$.command("upgrade","Upgrade bvm to the latest version",{aliases:["self-update"]}).action(async()=>{await q1()}),$.command("config <subcommand>","Manage BVM configuration (registry)").action(async(b)=>{await G1(b)}),$.command("doctor","Show diagnostics for Bun/BVM setup").action(async()=>{await Z1()}),$.command("completion <shell>","Generate shell completion script (bash|zsh|fish)").action(async(b)=>{if(!b[0])throw Error("Shell name is required");X1(b[0])}),await $.run(),process.exit(0)}J0().catch(($)=>{console.error(Z.red(`
635
+ Examples:`),console.log(" bvm install 1.0.0"),console.log(" bvm use 1.0.0"),console.log(" bvm run 1.0.0 index.ts")}}async function Q1(){let $=new Y_("bvm");$.command("rehash","Regenerate shims for all installed binaries").option("--silent","Suppress output").action(async(b,_)=>{await f$({silent:_.silent})}),$.command("install [version]","Install a Bun version and set as current").option("--global, -g","Install as a global tool (not just default)").action(async(b,_)=>{await wb(b[0],{global:_.global||_.g})}),$.command("i [version]","Alias for install").action(async(b,_)=>{await wb(b[0],{global:_.global||_.g})}),$.command("ls","List installed Bun versions",{aliases:["list"]}).action(async()=>{await Vb()}),$.command("ls-remote","List all available remote Bun versions").action(async()=>{await Pb()}),$.command("use <version>","Switch the active Bun version immediately (all terminals)").option("--fix-path","Auto-run setup if shims not active").option("--yes, -y","Assume yes for prompts").action(async(b,_)=>{if(!b[0])throw Error("Version is required");let y=!!_.fixPath||!!_["fix-path"],f=!!_.yes||!!_.y;await F$(b[0],{fixPath:y,yes:f})}),$.command("shell <version>","Switch Bun version for the current shell session").action(async(b)=>{if(!b[0])throw Error("Version is required");await sb(b[0])}),$.command("default [version]","Display or set the global default Bun version").action(async(b)=>{await ab(b[0])}),$.command("current","Display the currently active Bun version").action(async()=>{await pb()}),$.command("uninstall <version>","Uninstall a Bun version").action(async(b)=>{if(!b[0])throw Error("Version is required");await lb(b[0])}),$.command("alias <name> <version>","Create an alias for a Bun version").action(async(b)=>{if(!b[0]||!b[1])throw Error("Name and version are required");await k$(b[0],b[1])}),$.command("unalias <name>","Remove an existing alias").action(async(b)=>{if(!b[0])throw Error("Alias name is required");await nb(b[0])}),$.command("run <version> [...args]","Run a command with a specific Bun version").action(async(b)=>{let _=b[0];if(!_)throw Error("Version is required");let y=process.argv.indexOf("run"),f=y!==-1?process.argv.slice(y+2):[];await ob(_,f)}),$.command("exec <version> <cmd> [...args]","Execute a command with a specific Bun version's environment").action(async(b)=>{let _=b[0],y=b[1];if(!_||!y)throw Error("Version and command are required");let f=process.argv.indexOf("exec"),w=f!==-1?process.argv.slice(f+3):[];await tb(_,y,w)}),$.command("which [version]","Display path to installed bun version").action(async(b)=>{await ib(b[0])}),$.command("deactivate","Undo effects of bvm on current shell").action(async()=>{await rb()}),$.command("version <spec>","Resolve the given description to a single local version").action(async(b)=>{if(!b[0])throw Error("Version specifier is required");await $b(b[0])}),$.command("cache <action>","Manage bvm cache").action(async(b)=>{if(!b[0])throw Error("Action is required");await eb(b[0])}),$.command("setup","Configure shell environment automatically").option("--silent, -s","Suppress output").action(async(b,_)=>{await _$(!(_.silent||_.s))}),$.command("upgrade","Upgrade bvm to the latest version",{aliases:["self-update"]}).action(async()=>{await __()}),$.command("config <subcommand>","Manage BVM configuration (registry)").action(async(b)=>{await G_(b)}),$.command("doctor","Show diagnostics for Bun/BVM setup").action(async()=>{await q_()}),$.command("completion <shell>","Generate shell completion script (bash|zsh|fish)").action(async(b)=>{if(!b[0])throw Error("Shell name is required");Q_(b[0])}),await $.run(),process.exit(0)}Q1().catch(($)=>{console.error(J.red(`
623
636
  [FATAL ERROR] Unexpected Crash:`)),console.error($),process.exit(1)});
package/install.ps1 CHANGED
@@ -40,7 +40,7 @@ function Detect-NetworkZone {
40
40
  $BVM_REGION = Detect-NetworkZone
41
41
  $REGISTRY = if ($BVM_REGION -eq "cn") { "registry.npmmirror.com" } else { "registry.npmjs.org" }
42
42
 
43
- $DEFAULT_BVM_VER = "v1.1.37"
43
+ $DEFAULT_BVM_VER = "v1.1.38"
44
44
  $BVM_VER = if ($env:BVM_INSTALL_VERSION) { $env:BVM_INSTALL_VERSION } else { "" }
45
45
  if (-not $BVM_VER) {
46
46
  try {
package/install.sh CHANGED
@@ -3,7 +3,7 @@
3
3
  set -e
4
4
 
5
5
  # --- Configuration ---
6
- DEFAULT_BVM_VERSION="v1.1.37" # Fallback
6
+ DEFAULT_BVM_VERSION="v1.1.38" # Fallback
7
7
  FALLBACK_BUN_VERSION="1.3.6"
8
8
  BVM_SRC_VERSION="${BVM_INSTALL_VERSION}" # If empty, will resolve dynamically
9
9
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bvm-core",
3
- "version": "1.1.37",
4
- "description": "Bun Version Manager (BVM) - Native, fast, and cross-platform.",
3
+ "version": "1.1.38",
4
+ "description": "Need a Bun version manager? BVM installs, switches, and isolates Bun versions across Windows, macOS, and Linux.",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
7
7
  "bvm": "bin/bvm-npm.js"
@@ -9,7 +9,11 @@
9
9
  "publishConfig": {
10
10
  "access": "public"
11
11
  },
12
- "homepage": "https://bvm-core.pages.dev",
12
+ "homepage": "https://bvm-core.pages.dev/from/npm",
13
+ "funding": {
14
+ "type": "url",
15
+ "url": "https://bvm-core.pages.dev/wechat"
16
+ },
13
17
  "bugs": {
14
18
  "url": "https://github.com/EricLLLLLL/bvm/issues"
15
19
  },
@@ -32,15 +36,25 @@
32
36
  },
33
37
  "keywords": [
34
38
  "bun",
35
- "version-manager",
36
- "cli",
37
39
  "bvm",
38
- "nvm",
39
- "nvm-windows",
40
- "fnm",
41
- "nodenv",
40
+ "bun-version-manager",
41
+ "version-manager",
42
42
  "bun-nvm",
43
- "version-switching"
43
+ "nvm-for-bun",
44
+ "nvm-alternative",
45
+ "fnm-alternative",
46
+ "bun-version-switching",
47
+ "bun-runtime-manager",
48
+ "bun-multi-version",
49
+ "bun-shims",
50
+ "bun-global-isolation",
51
+ "bun-bvmrc",
52
+ "bun-windows",
53
+ "bun-macos",
54
+ "bun-linux",
55
+ "cross-platform-cli",
56
+ "developer-tooling",
57
+ "toolchain-manager"
44
58
  ],
45
59
  "files": [
46
60
  "dist/index.js",
@@ -76,10 +90,10 @@
76
90
  "typescript": "^5"
77
91
  },
78
92
  "bvm_fingerprints": {
79
- "cli": "6e690eefb1f46c73861d84fe66aeef5b",
93
+ "cli": "ca3f0ed188afedcd75ebdac74edaf70e",
80
94
  "shim_win": "101ee1a30b9254e59c6f37756ff3ee09",
81
95
  "shim_unix": "7c1422b6c24c64e878b908f1b6e884dc",
82
- "install_sh": "551cb6103c423485b8bb85ad008a3873",
83
- "install_ps1": "4594bbc537c5effd2192b5270d6c2b4e"
96
+ "install_sh": "e52d127096e9b8e6488df2027b4199a0",
97
+ "install_ps1": "f60aeb3d7a3c15a4256b9eb8cd1a4c3b"
84
98
  }
85
99
  }