@xship/cli 0.0.191 → 0.0.192

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.
@@ -1 +1 @@
1
- import{spawnSync as t}from"child_process";import{existsSync as e,mkdirSync as o,readFileSync as n,readdirSync as r,realpathSync as a,rmSync as s,statSync as i,writeFileSync as l}from"fs";import{delimiter as c,dirname as u,isAbsolute as p,join as d,sep as m}from"path";import{fileURLToPath as f}from"url";import g from"chalk";import{brand as h,CLI_NAME as w}from"./brand.js";import{configManager as v}from"./config.js";import{npmCacheArgs as y}from"./npm-cache.js";import{i18n as b}from"./i18n.js";import{appLatest as _,appStatus as $,appStatusWith as P,cachedAppStatus as x,getApp as A}from"./app-update.js";import{compareVersions as k}from"./model-registry.js";import{isJsonMode as D}from"./runtime-options.js";import{maskSecrets as S,track as j}from"./telemetry.js";import{failureContext as L,lastCommandExit as E,lastCommandOutput as C,runWatched as R}from"./tool-upgrade.js";import{runInstallScript as T,traceSummary as M}from"./install-script.js";import{atomicWriteFile as N}from"./tools/backup.js";import{getAdapter as O}from"./tools/registry.js";import{findInstallsIncludingNative as U,forgetInstalls as I,NPM_MIRROR as B,npmMirrorVersion as F}from"./tools/tool-installs.js";import{toolHome as J}from"./tools/types.js";import{logger as V}from"../utils/logger.js";let H=null;export function parseManifest(t){const e=JSON.parse(t);if(1!==e.schema||!Array.isArray(e.components))throw new Error("components.json: schema must be 1 with a components list");const o=new Set;for(const t of e.components){if(!t.id||!t.name||!["runtime","cli","app"].includes(t.category))throw new Error(`components.json: bad entry ${JSON.stringify(t.id)}`);for(const e of[t.id,...t.aliases??[]]){if(o.has(e))throw new Error(`components.json: duplicate name ${e}`);o.add(e)}if("runtime"===t.category&&(!t.detect||"script"!==t.install.type))throw new Error(`components.json: runtime ${t.id} needs detect + a script`);if("cli"===t.category&&!t.adapter)throw new Error(`components.json: cli ${t.id} needs an adapter`);if("app"===t.category&&!t.app)throw new Error(`components.json: app ${t.id} needs an app id`)}for(const t of e.components)for(const e of t.requires)if(!o.has(e))throw new Error(`components.json: ${t.id} requires unknown ${e}`);return e}function W(){return H||(H=parseManifest(n(function(){const t=u(f(import.meta.url)),o=[d(t,"..","..","components.json"),d(t,"..","components.json"),d(t,"components.json")],n=o.find(t=>e(t));if(!n)throw new Error(`components.json not found, searched: ${o.join(", ")}`);return n}(),"utf-8"))),H}export function setComponentManifestForTests(t){H=null===t?null:parseManifest(t)}export function listComponents(){return W().components}export function resolveComponent(t){const e=t.trim().toLowerCase();return listComponents().find(t=>t.id===e||(t.aliases??[]).includes(e))}let G=null;export function componentPlatform(){return G??process.platform}export function expandUrl(t){const e=h().installMirror??{};let o=!1;const n=t.replace(/\{(scripts|agy|devtools)\}/g,(t,n)=>{const r="devtools"===n?W().devtools:e[n];return r||(o=!0),r??""});return o?null:n}export function componentSource(t,e=componentPlatform()){return(t.sources[e]??t.sources.all??"").replace(/\{(scripts|agy|devtools)\}/g,(t,e)=>("devtools"===e?W().devtools:h().installMirror?.[e])??t)}export function installBlocker(t=process.env,e=componentPlatform()){return"win32"===e?/\\system32\\config\\systemprofile/i.test(t.USERPROFILE??"")||t.USERNAME?.endsWith("$")?"system":null:0===(q??process.getuid?.())&&t.SUDO_USER&&"root"!==t.SUDO_USER?"sudo":null}let q=null,K=!0,X=e=>{const o=/\.(cmd|bat)$/i.test(e)?t(`"${e}" --version`,{encoding:"utf-8",timeout:1e4,windowsHide:!0,shell:!0,stdio:["ignore","pipe","pipe"]}):t(e,["--version"],{encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]});return`${o.stdout??""}${o.stderr??""}`},Z=()=>0===t("xcode-select",["-p"],{stdio:"ignore",timeout:1e4}).status;function z(t){try{return a(t)}catch{return t}}function Y(t,e){return"win32"===e?[`${t}.exe`,`${t}.cmd`]:[t]}export function knownRuntimePaths(t,e=componentPlatform(),o=process.env){const n=J();if("node"===t){if("win32"===e){const t=o.FNM_DIR||d(o.APPDATA||d(n,"AppData","Roaming"),"fnm");return[d(t,"aliases","default","node.exe"),d(o.LOCALAPPDATA||d(n,"AppData","Local"),"Programs","nodejs","node.exe")]}return[d(Q(e,o),"aliases","default","bin","node"),"/opt/homebrew/bin/node","/usr/local/bin/node","/usr/bin/node"]}if("uv"===t)return"win32"===e?[d(n,".local","bin","uv.exe"),d(n,".cargo","bin","uv.exe")]:[d(o.UV_INSTALL_DIR||d(n,".local","bin"),"uv"),d(n,".cargo","bin","uv"),"/opt/homebrew/bin/uv","/usr/local/bin/uv"];if("git"===t){if("win32"===e){const t=o.LOCALAPPDATA||d(n,"AppData","Local");return[d(t,"Programs","Git","cmd","git.exe"),d(o.ProgramFiles||"C:\\Program Files","Git","cmd","git.exe")]}return["/opt/homebrew/bin/git","/usr/local/bin/git","/usr/bin/git"]}return[]}function Q(t,o){if(o.FNM_DIR)return o.FNM_DIR;const n=J();if("win32"===t)return d(o.APPDATA||d(n,"AppData","Roaming"),"fnm");const r=d(n,".local","share","fnm"),a=d(n,"Library","Application Support","fnm");return"darwin"===t&&!e(r)&&e(a)?a:r}let tt=()=>{const e=e=>{const o=`${t("reg",["query",e,"/v","Path"],{encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","ignore"]}).stdout??""}`.split(/\r?\n/).find(t=>/\sREG_(EXPAND_)?SZ\s/.test(t));return o?o.replace(/^.*?REG_(EXPAND_)?SZ\s+/,""):""};return[e("HKCU\\Environment"),e("HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment")].flatMap(t=>{return(e=t,e.replace(/%([^%]+)%/g,(t,e)=>process.env[e]??t)).split(";");var e}).map(t=>t.trim().replace(/^"|"$/g,"")).filter(Boolean)},et=null;export function probeRuntime(t,e=componentPlatform()){const o=t.detect,n=new RegExp(o.pattern),r=new Set,a=[],s=o=>{if(!function(t){try{return i(t).isFile()}catch{return!1}}(o))return;if("darwin"===e&&"git"===t.id&&"/usr/bin/git"===o&&!Z())return;const s=z(o),l="win32"===e?s.toLowerCase():s;if(r.has(l))return;r.add(l);const c=n.exec(X(o));c&&a.push({path:o,version:c[1]??null})},l=(process.env.PATH??"").split("win32"===e?";":c);"win32"===e&&l.push(...et??=it(()=>tt())??[]);for(const t of l)if(t&&p(t))for(const n of Y(o.command,e))s(d(t,n));for(const o of knownRuntimePaths(t.id,e))(K||o.startsWith(J()))&&s(o);return a}export function scriptTarget(t,e=componentPlatform(),o=process.env){const n=J();return"node"===t?"win32"===e?d(Q(e,o),"aliases","default","node.exe"):d(Q(e,o),"aliases","default","bin","node"):"uv"===t?d(o.UV_INSTALL_DIR||d(n,".local","bin"),"win32"===e?"uv.exe":"uv"):"git"===t&&"win32"===e?d(o.LOCALAPPDATA||d(n,"AppData","Local"),"Programs","Git","cmd","git.exe"):null}export function runtimeManager(t,e,o=componentPlatform(),n=process.env){const r=z(e),a=t=>"win32"===o?t.replace(/\//g,"\\").toLowerCase():t,s=a(r),i=a(e),l="win32"===o?"\\":"\\"===m?"/":m,c=t=>s.includes(a(t))||i.includes(a(t)),p=t=>s.startsWith(a(t)+l)||i.startsWith(a(t)+l),f=J(),g=/[\\/](Cellar|Caskroom|homebrew)[\\/]/i.test(r)||/^\/opt\/homebrew\//.test(e)||/^\/usr\/local\/(Cellar|opt)\//.test(r);if("node"===t)return c(`${l}fnm${l}`)||p(Q(o,n))?{by:"fnm",auto:!0}:g?{by:"brew",auto:!1,hint:"brew upgrade node"}:c(`${l}.nvm${l}`)?{by:"nvm",auto:!1,hint:"nvm install --lts --reinstall-packages-from=current"}:c(`${l}nvm${l}`)&&"win32"===o?{by:"nvm",auto:!1,hint:"nvm install lts"}:c(`${l}.volta${l}`)||c(`${l}volta${l}`)?{by:"volta",auto:!1,hint:"volta install node@lts"}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update nodejs-lts"}:c(`${l}.asdf${l}`)?{by:"asdf",auto:!1,hint:"asdf install nodejs latest"}:c(`${l}mise${l}`)?{by:"mise",auto:!1,hint:"mise use -g node@lts"}:{by:"system",auto:!1};if("uv"===t)return[n.UV_INSTALL_DIR,d(f,".local","bin"),d(f,".cargo","bin")].filter(Boolean).some(t=>a(u(e))===a(t)||a(u(r))===a(t))?{by:"standalone",auto:!0}:g?{by:"brew",auto:!1,hint:"brew upgrade uv"}:c("pipx")?{by:"pipx",auto:!1,hint:"pipx upgrade uv"}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update uv"}:c("winget")?{by:"winget",auto:!1,hint:"winget upgrade astral-sh.uv"}:c("site-packages")||c(`${l}python`)?{by:"pip",auto:!1,hint:"pip install -U uv"}:{by:"other",auto:!1};if("git"===t){if("win32"===o){const t=n.LOCALAPPDATA||d(f,"AppData","Local");return p(d(t,"Programs","Git"))?{by:"git-for-windows-user",auto:!0}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update git"}:{by:"git-for-windows",auto:!1,hint:"git update-git-for-windows"}}return g?{by:"brew",auto:!1,hint:"brew upgrade git"}:"darwin"===o?{by:"xcode",auto:!1,hint:"softwareupdate --list"}:{by:"system",auto:!1}}return{by:"other",auto:!1}}function ot(){return d(v.getConfigDir(),"component-releases.json")}function nt(){try{const t=JSON.parse(n(ot(),"utf-8"));return t&&"object"==typeof t?t:{}}catch{return{}}}function rt(t,e){try{o(v.getConfigDir(),{recursive:!0}),l(ot(),JSON.stringify({...nt(),[t]:e},null,2))}catch(t){V.logError("components.writeCache",t)}}let at=async(t,e=15e3)=>{const o=await fetch(t,{signal:AbortSignal.timeout(e)});if(!o.ok)throw new Error(`HTTP ${o.status} ${t}`);return o.text()};const st=/(\d+\.\d+\.\d+)/;export function latestNodeLts(t){const e=JSON.parse(t).find(t=>"string"==typeof t.lts&&t.lts&&"string"==typeof t.version);if(!e)throw new Error("no LTS release in the Node index");return e.version.replace(/^v/,"")}export function devtoolsVersion(t,e){const o=t.split(/\r?\n/).find(t=>t.startsWith(`${e}=`)),n=o?st.exec(o.slice(e.length+1)):null;if(!n)throw new Error(`${e} is not in versions.txt`);return n[1]}export async function latestVersion(t,e={}){const o=componentPlatform(),n=`${t.id}:${o}`,r=nt()[n],a=r&&Date.now()-r.checked_at<(r.version?36e5:6e5);if(r&&a&&!e.refresh)return{version:r.version??null,...r.error?{error:r.error}:{}};try{const e=await async function(t,e){const o=t.latest;switch(o.type){case"node-lts":return latestNodeLts(await at(o.url));case"devtools":return o.platforms&&!o.platforms.includes(e)?null:devtoolsVersion(await at(`${W().devtools}/versions.txt`),o.key);case"npm":{if(o.staleTag){const e=O(t.adapter??"")?.installSpec,o=e?await F(e):"latest";if("latest"!==o)return o}const e=JSON.parse(await at(`${B}/${o.package}/latest`));if(!e.version)throw new Error(`no version for ${o.package}`);return e.version}case"version-file":{const t=expandUrl(o.url);if(!t)return null;const e=st.exec(await at(t));if(!e)throw new Error(`no version in ${t}`);return e[1]}default:return null}}(t,o);return e&&rt(n,{version:e,checked_at:Date.now()}),{version:e}}catch(e){const o=e instanceof Error?e.message:String(e);return V.logError(`components.latest(${t.id})`,e),rt(n,{error:o,checked_at:Date.now()}),{version:r?.version??null,error:o}}}export async function prefetchLatest(t,e={}){const o=componentPlatform(),n=await Promise.all(t.map(async t=>t.platforms.includes(o)?"app"===t.category?[t.id,A(t.app)?await _(t.app,e):{version:null}]:[t.id,await latestVersion(t,e)]:[t.id,{version:null}]));return new Map(n)}export async function componentStatus(t,e={}){const o=componentPlatform(),n={id:t.id,name:t.name,category:t.category,supported:t.platforms.includes(o),source:componentSource(t,o)},r={...n,installed:!1,current:null,latest:null,outdated:!1,path:null,managed_by:null,auto_upgrade:!1,blocker:n.supported?installBlocker():"unsupported_platform"};if(!n.supported)return r;if("app"===t.category){const o=A(t.app);if(!o)return{...r,blocker:"unsupported_platform"};const n=e.latest?P(t.app,e.latest):e.offline?x(t.app):await $(t.app,{refresh:e.refresh});return{...r,installed:n.installed,current:n.current,latest:n.latest,outdated:n.outdated,path:n.installed?it(()=>o.appInstaller.installedPath()):null,managed_by:n.installed?"app":null,auto_upgrade:n.installed&&!n.blocker,blocker:n.blocker??installBlocker(),...n.error?{error:n.error}:{}}}let a=null,s=null,i=null;if("cli"===t.category){const e=O(t.adapter)?.installSpec,o=e?U(e)[0]:void 0;o&&(a=o.version,s=o.path,i={by:o.kind,auto:!0})}else{const e=probeRuntime(t,o)[0];e&&(a=e.version,s=e.path,i=runtimeManager(t.id,e.path,o))}const{version:l,error:c}=e.latest?e.latest:e.offline?{version:nt()[`${t.id}:${o}`]?.version??null,error:void 0}:await latestVersion(t,{refresh:e.refresh}),u=l?nt()[`${t.id}:${o}:ceiling`]:void 0,p=Boolean(u?.version&&u.error===l&&a&&k(a,u.version)>=0);return{...r,installed:Boolean(s),current:a,latest:l,outdated:Boolean(a&&l&&k(a,l)<0&&!p),...p?{capped_at:u.version}:{},path:s,managed_by:i?.by??null,auto_upgrade:i?.auto??!1,...i?.hint?{hint:i.hint}:{},...c?{error:c}:{}}}function it(t){try{return t()}catch{return null}}const lt={idleMs:18e4,timeoutMs:36e5};let ct,ut=async(t,e)=>(ct=await T({name:(/([a-z0-9-]+)\.(?:ps1|sh)$/i.exec(t)?.[1]??"runtime").toLowerCase(),url:t,platform:componentPlatform(),limits:{...lt,env:e},output:C,run:(t,e,o)=>R(t,e,o)}),"ok"===ct.outcome),pt=async(t,e)=>"ok"===await R(t,e,lt);function dt(t){D()?process.stderr.write(t+"\n"):console.log(t)}export function globalPackages(t,e=componentPlatform()){const o=u(z(t)),a="win32"===e?d(o,"node_modules"):d(u(o),"lib","node_modules"),s=[],i=(t,e)=>{try{const o=JSON.parse(n(d(t,"package.json"),"utf-8"));o.version&&s.push({name:e,version:o.version})}catch{}};let l=[];try{l=r(a)}catch{return s}for(const t of l)if(!t.startsWith(".")&&"npm"!==t&&"corepack"!==t)if(t.startsWith("@"))try{for(const e of r(d(a,t)))e.startsWith(".")||i(d(a,t,e),`${t}/${e}`)}catch{}else i(d(a,t),t);return s}function mt(t,e,o={}){const n=["installed","upgraded","reinstalled","up_to_date","already_installed"].includes(e);return{tool:t.id,category:t.category,current:t.current,latest:t.latest,result:e,version_after:null,ok:n,...o}}function ft(t){return`${w} upgrade ${t}`}export async function runRuntime(t,e,n={}){const r=Date.now(),a=componentPlatform(),s=await componentStatus(t,{refresh:!0}),i=t.name;if(!s.supported)return dt(g.yellow(" ! "+b.t("components.unsupported_platform",{tool:i}))),mt(s,"unavailable",{reason:"unsupported_platform"});if(s.blocker)return dt(g.yellow(" ! "+function(t,e){return b.t(`components.blocked_${t}`,{tool:e})}(s.blocker,i))),mt(s,"unavailable",{reason:s.blocker});const l=function(t){if("script"!==t.install.type)return null;const e=h().installMirror?.scripts;return e?`${e}/${t.install.script}.${"win32"===componentPlatform()?"ps1":"sh"}`:null}(t);if(s.installed&&!n.force){const o=g.gray(`(${s.path})`);if(s.latest&&!s.outdated)return dt(g.green(" √ "+b.t("components.up_to_date",{tool:i,current:s.current??"?"}))+o),"upgrade"===e&&dt(g.gray(" "+b.t("components.force_hint",{command:`${ft(t.id)} --force`}))),mt(s,"install"===e?"already_installed":"up_to_date");if("install"===e)return dt(g.green(" √ "+b.t("components.already_installed",{tool:i,current:s.current??"?"}))+o),s.outdated&&dt(g.yellow(" ! "+upgradeAdvice(s))),mt(s,"already_installed",s.outdated?{hint:upgradeAdvice(s)}:{});if(!s.latest)return dt(g.yellow(" ! "+b.t("components.no_latest",{tool:i,current:s.current??"?",how:ht(s)}))),mt(s,"manual",{reason:s.error??"no_latest",hint:s.hint});if(!s.auto_upgrade)return dt(g.yellow(" ! "+upgradeAdvice(s))),mt(s,"manual",{hint:s.hint})}if(!l)return dt(g.yellow(" ! "+b.t("components.no_mirror",{tool:i}))),mt(s,"unavailable",{reason:"no_mirror"});s.installed&&!s.auto_upgrade&&dt(g.yellow(" ! "+b.t("components.force_beside",{tool:i,path:s.path??"?",by:s.managed_by??"?"})));const p={};s.installed&&"script"===t.install.type&&Object.assign(p,t.install.forceEnv??{}),"uv"===t.id&&s.installed&&s.auto_upgrade&&s.path&&(p.UV_INSTALL_DIR=u(s.path));const d=t.upgrade?.migrateGlobalPackages&&s.installed&&"fnm"===s.managed_by&&s.path,m=d?globalPackages(s.path,a):[],f=d?z(s.path):null;dt(g.gray(" "+b.t(s.installed?"components.upgrading":"components.installing",{tool:i,latest:s.latest??"",source:s.source}))),j(`component:${t.id}`,"start",{detail:{mode:e,force:Boolean(n.force),current:s.current}}),d&&m.length&&f&&function(t){try{o(v.getConfigDir(),{recursive:!0}),N(vt(),JSON.stringify({...t,noted_at:Date.now()},null,2),384)}catch(t){V.logError("components: note migration",t)}}({packages:m,old_node:f}),ct=void 0;const w=await ut(l,p);I(),et=null;const y=probeRuntime(t,a),_=scriptTarget(t.id,a,{...process.env,...p}),$=(_?y.find(t=>{return e=t.path,o=_,"win32"===a?z(e).toLowerCase()===z(o).toLowerCase():z(e)===z(o);var e,o}):void 0)??y.find(e=>runtimeManager(t.id,e.path,a).auto)??y[0];if(!w||!$){yt();const e=ct;return j(`component:${t.id}`,"fail",{duration_ms:Date.now()-r,error:S(C())||void 0,detail:{reason:w?"not_found_after":"script_failed",...e?{how:e.how,...e.fileProblem?{file_problem:e.fileProblem}:{},...M(e.trace)}:{},...E(),...L()}}),dt(g.red(" × "+b.t("components.script_failed",{tool:i,command:(s.installed?ft:gt)(t.id)}))),mt(s,"failed",{reason:w?"not_found_after":"script_failed"})}let P;d&&m.length&&f&&z($.path)!==f&&(P=await wt(m,$.path,a)?"done":"failed"),"failed"!==P&&yt();const x=y[0];x&&x.path!==$.path&&x.version&&$.version&&k(x.version,$.version)<0&&dt(g.yellow(" ! "+b.t("components.path_shadowed",{tool:i,active:x.path,version:$.version,path:$.path}))),s.latest&&$.version&&k($.version,s.latest)<0&&(rt(`${t.id}:${a}:ceiling`,{version:$.version,error:s.latest,checked_at:Date.now()}),dt(g.yellow(" ! "+b.t("components.capped",{tool:i,latest:s.latest,version:$.version})))),j(`component:${t.id}`,"ok",{duration_ms:Date.now()-r,detail:{version:$.version,...P?{migration:P}:{}}});const A=s.installed?n.force&&!s.outdated?"reinstalled":"upgraded":"installed";var D;return dt(g.green(" √ "+("installed"===A?b.t("components.installed",{tool:i,version:$.version??"?"}):"reinstalled"===A?b.t("components.reinstalled",{tool:i,version:$.version??"?"}):b.t("components.upgraded",{tool:i,from:s.current??"?",to:$.version??"?"})))+g.gray(`(${$.path})`)),D=u($.path),(process.env.PATH??"").split("win32"===componentPlatform()?";":c).some(t=>"win32"===componentPlatform()?t.toLowerCase()===D.toLowerCase():t===D)||dt(g.gray(" "+b.t("components.new_terminal"))),mt(s,A,{version_after:$.version})}function gt(t){return`${w} install ${t}`}function ht(t){return t.hint?t.hint:b.t(`components.how_${t.managed_by??"other"}`,{tool:t.name})}export function upgradeAdvice(t){return t.auto_upgrade?b.t("components.outdated_auto",{tool:t.name,current:t.current??"?",latest:t.latest??"?",command:ft(t.id)}):b.t("components.outdated_manual",{tool:t.name,current:t.current??"?",latest:t.latest??"?",by:t.managed_by??"?",how:ht(t),command:`${ft(t.id)} --force`})}async function wt(t,e,o){const n=new Set(globalPackages(e,o).map(t=>t.name)),r=t.filter(t=>!n.has(t.name));if(!r.length)return!0;dt(g.gray(" "+b.t("components.migrating_globals",{packages:r.map(t=>t.name).join("、")})));const a=function(t,e){const o=u(z(t));return d(o,"win32"===e?"npm.cmd":"npm")}(e,o),s=["install","-g",...r.map(t=>`${t.name}@${t.version}`),`--registry=${B}`,"--no-fund","--no-audit","--loglevel=error",...y(v.getConfigDir())];return!!await pt(a,s)||(dt(g.yellow(" ! "+b.t("components.migrate_failed",{command:[a,...s].join(" ")}))),!1)}const vt=()=>d(v.getConfigDir(),"node-migration.json");function yt(){try{s(vt(),{force:!0})}catch(t){V.logError("components: clear migration",t)}}export async function resumePendingMigration(){let t;try{if(!e(vt()))return"none";t=JSON.parse(n(vt(),"utf-8"))}catch{return yt(),"none"}const o=componentPlatform(),r=listComponents().find(t=>"node"===t.id),a=r?probeRuntime(r,o).find(t=>"fnm"===runtimeManager("node",t.path,o).by):void 0;if(!Array.isArray(t.packages)||"number"!=typeof t.noted_at||Date.now()-t.noted_at>2592e6||!a||z(a.path)===t.old_node)return yt(),"none";j("component:node","start",{detail:{mode:"resume-migration"}});const s=await wt(t.packages,a.path,o);return s&&yt(),j("component:node",s?"ok":"fail",{detail:{mode:"resume-migration",migration:s?"done":"failed"}}),s?"done":"failed"}export function setComponentDepsForTests(t){void 0!==t.platform&&(G=t.platform),void 0!==t.uid&&(q=t.uid),void 0!==t.systemPaths&&(K=t.systemPaths),t.registryPath&&(tt=t.registryPath,et=null),t.versionRunner&&(X=t.versionRunner),t.macDeveloperTools&&(Z=t.macDeveloperTools),t.fetchText&&(at=t.fetchText),t.scriptRunner&&(ut=t.scriptRunner),t.commandRunner&&(pt=t.commandRunner)}
1
+ import{spawnSync as t}from"child_process";import{existsSync as e,mkdirSync as o,readFileSync as n,readdirSync as r,realpathSync as a,rmSync as i,statSync as s,writeFileSync as l}from"fs";import{delimiter as c,dirname as u,isAbsolute as p,join as d,sep as m}from"path";import{fileURLToPath as f}from"url";import g from"chalk";import{brand as h,CLI_NAME as w}from"./brand.js";import{configManager as v}from"./config.js";import{npmCacheArgs as y}from"./npm-cache.js";import{i18n as b}from"./i18n.js";import{appLatest as _,appStatus as $,appStatusWith as P,cachedAppStatus as x,getApp as A}from"./app-update.js";import{compareVersions as k}from"./model-registry.js";import{isJsonMode as D}from"./runtime-options.js";import{maskSecrets as S,track as j}from"./telemetry.js";import{failureContext as L,lastCommandExit as E,lastCommandOutput as C,runWatched as R}from"./tool-upgrade.js";import{runInstallScript as M,traceSummary as T}from"./install-script.js";import{atomicWriteFile as N}from"./tools/backup.js";import{getAdapter as O}from"./tools/registry.js";import{findInstallsIncludingNative as U,forgetInstalls as I,NPM_MIRROR as B,npmMirrorVersion as F}from"./tools/tool-installs.js";import{toolHome as J}from"./tools/types.js";import{logger as V}from"../utils/logger.js";let H=null;export function parseManifest(t){const e=JSON.parse(t);if(1!==e.schema||!Array.isArray(e.components))throw new Error("components.json: schema must be 1 with a components list");const o=new Set;for(const t of e.components){if(!t.id||!t.name||!["runtime","cli","app"].includes(t.category))throw new Error(`components.json: bad entry ${JSON.stringify(t.id)}`);for(const e of[t.id,...t.aliases??[]]){if(o.has(e))throw new Error(`components.json: duplicate name ${e}`);o.add(e)}if("runtime"===t.category&&(!t.detect||"script"!==t.install.type))throw new Error(`components.json: runtime ${t.id} needs detect + a script`);if("cli"===t.category&&!t.adapter)throw new Error(`components.json: cli ${t.id} needs an adapter`);if("app"===t.category&&!t.app)throw new Error(`components.json: app ${t.id} needs an app id`)}for(const t of e.components)for(const e of t.requires)if(!o.has(e))throw new Error(`components.json: ${t.id} requires unknown ${e}`);return e}export function setComponentManifestForTests(t){H=null===t?null:parseManifest(t)}export function listComponents(){return(H||(H=parseManifest(n(function(){const t=u(f(import.meta.url)),o=[d(t,"..","..","components.json"),d(t,"..","components.json"),d(t,"components.json")],n=o.find(t=>e(t));if(!n)throw new Error(`components.json not found, searched: ${o.join(", ")}`);return n}(),"utf-8"))),H).components}export function resolveComponent(t){const e=t.trim().toLowerCase();return listComponents().find(t=>t.id===e||(t.aliases??[]).includes(e))}let W=null;export function componentPlatform(){return W??process.platform}const G=/\{(scripts|agy|devtools|claudeDesktop|chatgptDesktop)\}/g;export function devtoolsMirror(){return h().installMirror?.devtools?.replace(/\/+$/,"")||void 0}export function expandUrl(t){const e=h().installMirror??{};let o=!1;const n=t.replace(G,(t,n)=>{const r=e[n];return r||(o=!0),r??""});return o?null:n}export function componentSource(t,e=componentPlatform()){return(t.sources[e]??t.sources.all??"").replace(G,(t,e)=>{const o=h().installMirror?.[e];return o??t})}export function installBlocker(t=process.env,e=componentPlatform()){return"win32"===e?/\\system32\\config\\systemprofile/i.test(t.USERPROFILE??"")||t.USERNAME?.endsWith("$")?"system":null:0===(q??process.getuid?.())&&t.SUDO_USER&&"root"!==t.SUDO_USER?"sudo":null}let q=null,K=!0,X=e=>{const o=/\.(cmd|bat)$/i.test(e)?t(`"${e}" --version`,{encoding:"utf-8",timeout:1e4,windowsHide:!0,shell:!0,stdio:["ignore","pipe","pipe"]}):t(e,["--version"],{encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]});return`${o.stdout??""}${o.stderr??""}`},Z=()=>0===t("xcode-select",["-p"],{stdio:"ignore",timeout:1e4}).status;function z(t){try{return a(t)}catch{return t}}function Y(t,e){return"win32"===e?[`${t}.exe`,`${t}.cmd`]:[t]}export function knownRuntimePaths(t,e=componentPlatform(),o=process.env){const n=J();if("node"===t){if("win32"===e){const t=o.FNM_DIR||d(o.APPDATA||d(n,"AppData","Roaming"),"fnm");return[d(t,"aliases","default","node.exe"),d(o.LOCALAPPDATA||d(n,"AppData","Local"),"Programs","nodejs","node.exe")]}return[d(Q(e,o),"aliases","default","bin","node"),"/opt/homebrew/bin/node","/usr/local/bin/node","/usr/bin/node"]}if("uv"===t)return"win32"===e?[d(n,".local","bin","uv.exe"),d(n,".cargo","bin","uv.exe")]:[d(o.UV_INSTALL_DIR||d(n,".local","bin"),"uv"),d(n,".cargo","bin","uv"),"/opt/homebrew/bin/uv","/usr/local/bin/uv"];if("git"===t){if("win32"===e){const t=o.LOCALAPPDATA||d(n,"AppData","Local");return[d(t,"Programs","Git","cmd","git.exe"),d(o.ProgramFiles||"C:\\Program Files","Git","cmd","git.exe")]}return["/opt/homebrew/bin/git","/usr/local/bin/git","/usr/bin/git"]}return[]}function Q(t,o){if(o.FNM_DIR)return o.FNM_DIR;const n=J();if("win32"===t)return d(o.APPDATA||d(n,"AppData","Roaming"),"fnm");const r=d(n,".local","share","fnm"),a=d(n,"Library","Application Support","fnm");return"darwin"===t&&!e(r)&&e(a)?a:r}let tt=()=>{const e=e=>{const o=`${t("reg",["query",e,"/v","Path"],{encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","ignore"]}).stdout??""}`.split(/\r?\n/).find(t=>/\sREG_(EXPAND_)?SZ\s/.test(t));return o?o.replace(/^.*?REG_(EXPAND_)?SZ\s+/,""):""};return[e("HKCU\\Environment"),e("HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment")].flatMap(t=>{return(e=t,e.replace(/%([^%]+)%/g,(t,e)=>process.env[e]??t)).split(";");var e}).map(t=>t.trim().replace(/^"|"$/g,"")).filter(Boolean)},et=null;export function probeRuntime(t,e=componentPlatform()){const o=t.detect,n=new RegExp(o.pattern),r=new Set,a=[],i=o=>{if(!function(t){try{return s(t).isFile()}catch{return!1}}(o))return;if("darwin"===e&&"git"===t.id&&"/usr/bin/git"===o&&!Z())return;const i=z(o),l="win32"===e?i.toLowerCase():i;if(r.has(l))return;r.add(l);const c=n.exec(X(o));c&&a.push({path:o,version:c[1]??null})},l=(process.env.PATH??"").split("win32"===e?";":c);"win32"===e&&l.push(...et??=st(()=>tt())??[]);for(const t of l)if(t&&p(t))for(const n of Y(o.command,e))i(d(t,n));for(const o of knownRuntimePaths(t.id,e))(K||o.startsWith(J()))&&i(o);return a}export function scriptTarget(t,e=componentPlatform(),o=process.env){const n=J();return"node"===t?"win32"===e?d(Q(e,o),"aliases","default","node.exe"):d(Q(e,o),"aliases","default","bin","node"):"uv"===t?d(o.UV_INSTALL_DIR||d(n,".local","bin"),"win32"===e?"uv.exe":"uv"):"git"===t&&"win32"===e?d(o.LOCALAPPDATA||d(n,"AppData","Local"),"Programs","Git","cmd","git.exe"):null}export function runtimeManager(t,e,o=componentPlatform(),n=process.env){const r=z(e),a=t=>"win32"===o?t.replace(/\//g,"\\").toLowerCase():t,i=a(r),s=a(e),l="win32"===o?"\\":"\\"===m?"/":m,c=t=>i.includes(a(t))||s.includes(a(t)),p=t=>i.startsWith(a(t)+l)||s.startsWith(a(t)+l),f=J(),g=/[\\/](Cellar|Caskroom|homebrew)[\\/]/i.test(r)||/^\/opt\/homebrew\//.test(e)||/^\/usr\/local\/(Cellar|opt)\//.test(r);if("node"===t)return c(`${l}fnm${l}`)||p(Q(o,n))?{by:"fnm",auto:!0}:g?{by:"brew",auto:!1,hint:"brew upgrade node"}:c(`${l}.nvm${l}`)?{by:"nvm",auto:!1,hint:"nvm install --lts --reinstall-packages-from=current"}:c(`${l}nvm${l}`)&&"win32"===o?{by:"nvm",auto:!1,hint:"nvm install lts"}:c(`${l}.volta${l}`)||c(`${l}volta${l}`)?{by:"volta",auto:!1,hint:"volta install node@lts"}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update nodejs-lts"}:c(`${l}.asdf${l}`)?{by:"asdf",auto:!1,hint:"asdf install nodejs latest"}:c(`${l}mise${l}`)?{by:"mise",auto:!1,hint:"mise use -g node@lts"}:{by:"system",auto:!1};if("uv"===t)return[n.UV_INSTALL_DIR,d(f,".local","bin"),d(f,".cargo","bin")].filter(Boolean).some(t=>a(u(e))===a(t)||a(u(r))===a(t))?{by:"standalone",auto:!0}:g?{by:"brew",auto:!1,hint:"brew upgrade uv"}:c("pipx")?{by:"pipx",auto:!1,hint:"pipx upgrade uv"}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update uv"}:c("winget")?{by:"winget",auto:!1,hint:"winget upgrade astral-sh.uv"}:c("site-packages")||c(`${l}python`)?{by:"pip",auto:!1,hint:"pip install -U uv"}:{by:"other",auto:!1};if("git"===t){if("win32"===o){const t=n.LOCALAPPDATA||d(f,"AppData","Local");return p(d(t,"Programs","Git"))?{by:"git-for-windows-user",auto:!0}:c(`${l}scoop${l}`)?{by:"scoop",auto:!1,hint:"scoop update git"}:{by:"git-for-windows",auto:!1,hint:"git update-git-for-windows"}}return g?{by:"brew",auto:!1,hint:"brew upgrade git"}:"darwin"===o?{by:"xcode",auto:!1,hint:"softwareupdate --list"}:{by:"system",auto:!1}}return{by:"other",auto:!1}}function ot(){return d(v.getConfigDir(),"component-releases.json")}function nt(){try{const t=JSON.parse(n(ot(),"utf-8"));return t&&"object"==typeof t?t:{}}catch{return{}}}function rt(t,e){try{o(v.getConfigDir(),{recursive:!0}),l(ot(),JSON.stringify({...nt(),[t]:e},null,2))}catch(t){V.logError("components.writeCache",t)}}let at=async(t,e=15e3)=>{const o=await fetch(t,{signal:AbortSignal.timeout(e)});if(!o.ok)throw new Error(`HTTP ${o.status} ${t}`);return o.text()};const it=/(\d+\.\d+\.\d+)/;export function latestNodeLts(t){const e=JSON.parse(t).find(t=>"string"==typeof t.lts&&t.lts&&"string"==typeof t.version);if(!e)throw new Error("no LTS release in the Node index");return e.version.replace(/^v/,"")}export function devtoolsVersion(t,e){const o=t.split(/\r?\n/).find(t=>t.startsWith(`${e}=`)),n=o?it.exec(o.slice(e.length+1)):null;if(!n)throw new Error(`${e} is not in versions.txt`);return n[1]}export async function latestVersion(t,e={}){const o=componentPlatform(),n=`${t.id}:${o}`,r=nt()[n],a=r&&Date.now()-r.checked_at<(r.version?36e5:6e5);if(r&&a&&!e.refresh)return{version:r.version??null,...r.error?{error:r.error}:{}};try{const e=await async function(t,e){const o=t.latest;switch(o.type){case"node-lts":return latestNodeLts(await at(o.url));case"devtools":if(o.platforms&&!o.platforms.includes(e))return null;{const t=devtoolsMirror();return t?devtoolsVersion(await at(`${t}/versions.txt`),o.key):null}case"npm":{if(o.staleTag){const e=O(t.adapter??"")?.installSpec,o=e?await F(e):"latest";if("latest"!==o)return o}const e=JSON.parse(await at(`${B}/${o.package}/latest`));if(!e.version)throw new Error(`no version for ${o.package}`);return e.version}case"version-file":{const t=expandUrl(o.url);if(!t)return null;const e=it.exec(await at(t));if(!e)throw new Error(`no version in ${t}`);return e[1]}default:return null}}(t,o);return e&&rt(n,{version:e,checked_at:Date.now()}),{version:e}}catch(e){const o=e instanceof Error?e.message:String(e);return V.logError(`components.latest(${t.id})`,e),rt(n,{error:o,checked_at:Date.now()}),{version:r?.version??null,error:o}}}export async function prefetchLatest(t,e={}){const o=componentPlatform(),n=await Promise.all(t.map(async t=>t.platforms.includes(o)?"app"===t.category?[t.id,A(t.app)?await _(t.app,e):{version:null}]:[t.id,await latestVersion(t,e)]:[t.id,{version:null}]));return new Map(n)}export async function componentStatus(t,e={}){const o=componentPlatform(),n={id:t.id,name:t.name,category:t.category,supported:t.platforms.includes(o),source:componentSource(t,o)},r={...n,installed:!1,current:null,latest:null,outdated:!1,path:null,managed_by:null,auto_upgrade:!1,blocker:n.supported?installBlocker():"unsupported_platform"};if(!n.supported)return r;if("app"===t.category){const o=A(t.app);if(!o)return{...r,blocker:"unsupported_platform"};const n=e.latest?P(t.app,e.latest):e.offline?x(t.app):await $(t.app,{refresh:e.refresh});return{...r,installed:n.installed,current:n.current,latest:n.latest,outdated:n.outdated,path:n.installed?st(()=>o.appInstaller.installedPath()):null,managed_by:n.installed?"app":null,auto_upgrade:n.installed&&!n.blocker,blocker:n.blocker??installBlocker(),...n.error?{error:n.error}:{}}}let a=null,i=null,s=null;if("cli"===t.category){const e=O(t.adapter)?.installSpec,o=e?U(e)[0]:void 0;o&&(a=o.version,i=o.path,s={by:o.kind,auto:!0})}else{const e=probeRuntime(t,o)[0];e&&(a=e.version,i=e.path,s=runtimeManager(t.id,e.path,o))}const{version:l,error:c}=e.latest?e.latest:e.offline?{version:nt()[`${t.id}:${o}`]?.version??null,error:void 0}:await latestVersion(t,{refresh:e.refresh}),u=l?nt()[`${t.id}:${o}:ceiling`]:void 0,p=Boolean(u?.version&&u.error===l&&a&&k(a,u.version)>=0);return{...r,installed:Boolean(i),current:a,latest:l,outdated:Boolean(a&&l&&k(a,l)<0&&!p),...p?{capped_at:u.version}:{},path:i,managed_by:s?.by??null,auto_upgrade:s?.auto??!1,...s?.hint?{hint:s.hint}:{},...c?{error:c}:{}}}function st(t){try{return t()}catch{return null}}const lt={idleMs:18e4,timeoutMs:36e5};let ct,ut=async(t,e)=>(ct=await M({name:(/([a-z0-9-]+)\.(?:ps1|sh)$/i.exec(t)?.[1]??"runtime").toLowerCase(),url:t,platform:componentPlatform(),limits:{...lt,env:e},output:C,run:(t,e,o)=>R(t,e,o)}),"ok"===ct.outcome),pt=async(t,e)=>"ok"===await R(t,e,lt);function dt(t){D()?process.stderr.write(t+"\n"):console.log(t)}export function globalPackages(t,e=componentPlatform()){const o=u(z(t)),a="win32"===e?d(o,"node_modules"):d(u(o),"lib","node_modules"),i=[],s=(t,e)=>{try{const o=JSON.parse(n(d(t,"package.json"),"utf-8"));o.version&&i.push({name:e,version:o.version})}catch{}};let l=[];try{l=r(a)}catch{return i}for(const t of l)if(!t.startsWith(".")&&"npm"!==t&&"corepack"!==t)if(t.startsWith("@"))try{for(const e of r(d(a,t)))e.startsWith(".")||s(d(a,t,e),`${t}/${e}`)}catch{}else s(d(a,t),t);return i}function mt(t,e,o={}){const n=["installed","upgraded","reinstalled","up_to_date","already_installed"].includes(e);return{tool:t.id,category:t.category,current:t.current,latest:t.latest,result:e,version_after:null,ok:n,...o}}function ft(t){return`${w} upgrade ${t}`}export async function runRuntime(t,e,n={}){const r=Date.now(),a=componentPlatform(),i=await componentStatus(t,{refresh:!0}),s=t.name;if(!i.supported)return dt(g.yellow(" ! "+b.t("components.unsupported_platform",{tool:s}))),mt(i,"unavailable",{reason:"unsupported_platform"});if(i.blocker)return dt(g.yellow(" ! "+function(t,e){return b.t(`components.blocked_${t}`,{tool:e})}(i.blocker,s))),mt(i,"unavailable",{reason:i.blocker});const l=function(t){if("script"!==t.install.type)return null;const e=h().installMirror?.scripts;return e?`${e}/${t.install.script}.${"win32"===componentPlatform()?"ps1":"sh"}`:null}(t);if(i.installed&&!n.force){const o=g.gray(`(${i.path})`);if(i.latest&&!i.outdated)return dt(g.green(" √ "+b.t("components.up_to_date",{tool:s,current:i.current??"?"}))+o),"upgrade"===e&&dt(g.gray(" "+b.t("components.force_hint",{command:`${ft(t.id)} --force`}))),mt(i,"install"===e?"already_installed":"up_to_date");if("install"===e)return dt(g.green(" √ "+b.t("components.already_installed",{tool:s,current:i.current??"?"}))+o),i.outdated&&dt(g.yellow(" ! "+upgradeAdvice(i))),mt(i,"already_installed",i.outdated?{hint:upgradeAdvice(i)}:{});if(!i.latest)return dt(g.yellow(" ! "+b.t("components.no_latest",{tool:s,current:i.current??"?",how:ht(i)}))),mt(i,"manual",{reason:i.error??"no_latest",hint:i.hint});if(!i.auto_upgrade)return dt(g.yellow(" ! "+upgradeAdvice(i))),mt(i,"manual",{hint:i.hint})}if(!l)return dt(g.yellow(" ! "+b.t("components.no_mirror",{tool:s}))),mt(i,"unavailable",{reason:"no_mirror"});i.installed&&!i.auto_upgrade&&dt(g.yellow(" ! "+b.t("components.force_beside",{tool:s,path:i.path??"?",by:i.managed_by??"?"})));const p={};i.installed&&"script"===t.install.type&&Object.assign(p,t.install.forceEnv??{}),"uv"===t.id&&i.installed&&i.auto_upgrade&&i.path&&(p.UV_INSTALL_DIR=u(i.path));const d=t.upgrade?.migrateGlobalPackages&&i.installed&&"fnm"===i.managed_by&&i.path,m=d?globalPackages(i.path,a):[],f=d?z(i.path):null;dt(g.gray(" "+b.t(i.installed?"components.upgrading":"components.installing",{tool:s,latest:i.latest??"",source:i.source}))),j(`component:${t.id}`,"start",{detail:{mode:e,force:Boolean(n.force),current:i.current}}),d&&m.length&&f&&function(t){try{o(v.getConfigDir(),{recursive:!0}),N(vt(),JSON.stringify({...t,noted_at:Date.now()},null,2),384)}catch(t){V.logError("components: note migration",t)}}({packages:m,old_node:f}),ct=void 0;const w=await ut(l,p);I(),et=null;const y=probeRuntime(t,a),_=scriptTarget(t.id,a,{...process.env,...p}),$=(_?y.find(t=>{return e=t.path,o=_,"win32"===a?z(e).toLowerCase()===z(o).toLowerCase():z(e)===z(o);var e,o}):void 0)??y.find(e=>runtimeManager(t.id,e.path,a).auto)??y[0];if(!w||!$){yt();const e=ct;return j(`component:${t.id}`,"fail",{duration_ms:Date.now()-r,error:S(C())||void 0,detail:{reason:w?"not_found_after":"script_failed",...e?{how:e.how,...e.fileProblem?{file_problem:e.fileProblem}:{},...T(e.trace)}:{},...E(),...L()}}),dt(g.red(" × "+b.t("components.script_failed",{tool:s,command:(i.installed?ft:gt)(t.id)}))),mt(i,"failed",{reason:w?"not_found_after":"script_failed"})}let P;d&&m.length&&f&&z($.path)!==f&&(P=await wt(m,$.path,a)?"done":"failed"),"failed"!==P&&yt();const x=y[0];x&&x.path!==$.path&&x.version&&$.version&&k(x.version,$.version)<0&&dt(g.yellow(" ! "+b.t("components.path_shadowed",{tool:s,active:x.path,version:$.version,path:$.path}))),i.latest&&$.version&&k($.version,i.latest)<0&&(rt(`${t.id}:${a}:ceiling`,{version:$.version,error:i.latest,checked_at:Date.now()}),dt(g.yellow(" ! "+b.t("components.capped",{tool:s,latest:i.latest,version:$.version})))),j(`component:${t.id}`,"ok",{duration_ms:Date.now()-r,detail:{version:$.version,...P?{migration:P}:{}}});const A=i.installed?n.force&&!i.outdated?"reinstalled":"upgraded":"installed";var D;return dt(g.green(" √ "+("installed"===A?b.t("components.installed",{tool:s,version:$.version??"?"}):"reinstalled"===A?b.t("components.reinstalled",{tool:s,version:$.version??"?"}):b.t("components.upgraded",{tool:s,from:i.current??"?",to:$.version??"?"})))+g.gray(`(${$.path})`)),D=u($.path),(process.env.PATH??"").split("win32"===componentPlatform()?";":c).some(t=>"win32"===componentPlatform()?t.toLowerCase()===D.toLowerCase():t===D)||dt(g.gray(" "+b.t("components.new_terminal"))),mt(i,A,{version_after:$.version})}function gt(t){return`${w} install ${t}`}function ht(t){return t.hint?t.hint:b.t(`components.how_${t.managed_by??"other"}`,{tool:t.name})}export function upgradeAdvice(t){return t.auto_upgrade?b.t("components.outdated_auto",{tool:t.name,current:t.current??"?",latest:t.latest??"?",command:ft(t.id)}):b.t("components.outdated_manual",{tool:t.name,current:t.current??"?",latest:t.latest??"?",by:t.managed_by??"?",how:ht(t),command:`${ft(t.id)} --force`})}async function wt(t,e,o){const n=new Set(globalPackages(e,o).map(t=>t.name)),r=t.filter(t=>!n.has(t.name));if(!r.length)return!0;dt(g.gray(" "+b.t("components.migrating_globals",{packages:r.map(t=>t.name).join("、")})));const a=function(t,e){const o=u(z(t));return d(o,"win32"===e?"npm.cmd":"npm")}(e,o),i=["install","-g",...r.map(t=>`${t.name}@${t.version}`),`--registry=${B}`,"--no-fund","--no-audit","--loglevel=error",...y(v.getConfigDir())];return!!await pt(a,i)||(dt(g.yellow(" ! "+b.t("components.migrate_failed",{command:[a,...i].join(" ")}))),!1)}const vt=()=>d(v.getConfigDir(),"node-migration.json");function yt(){try{i(vt(),{force:!0})}catch(t){V.logError("components: clear migration",t)}}export async function resumePendingMigration(){let t;try{if(!e(vt()))return"none";t=JSON.parse(n(vt(),"utf-8"))}catch{return yt(),"none"}const o=componentPlatform(),r=listComponents().find(t=>"node"===t.id),a=r?probeRuntime(r,o).find(t=>"fnm"===runtimeManager("node",t.path,o).by):void 0;if(!Array.isArray(t.packages)||"number"!=typeof t.noted_at||Date.now()-t.noted_at>2592e6||!a||z(a.path)===t.old_node)return yt(),"none";j("component:node","start",{detail:{mode:"resume-migration"}});const i=await wt(t.packages,a.path,o);return i&&yt(),j("component:node",i?"ok":"fail",{detail:{mode:"resume-migration",migration:i?"done":"failed"}}),i?"done":"failed"}export function setComponentDepsForTests(t){void 0!==t.platform&&(W=t.platform),void 0!==t.uid&&(q=t.uid),void 0!==t.systemPaths&&(K=t.systemPaths),t.registryPath&&(tt=t.registryPath,et=null),t.versionRunner&&(X=t.versionRunner),t.macDeveloperTools&&(Z=t.macDeveloperTools),t.fetchText&&(at=t.fetchText),t.scriptRunner&&(ut=t.scriptRunner),t.commandRunner&&(pt=t.commandRunner)}
@@ -1 +1 @@
1
- import{spawnSync as t}from"child_process";import{logger as n}from"../../utils/logger.js";import{brand as e}from"../brand.js";import{powerShellEnv as r}from"../powershell-env.js";import{existsSync as i}from"fs";import{join as o}from"path";import{appPlatform as s,createDesktopAppInstaller as a,isArm64Machine as p,macAppVersion as l,macBundleId as c}from"./desktop-app-installer.js";import{toolHome as u}from"./types.js";export const OPENAI_TEAM_ID="2DC432GLL2";const d="com.openai.codex";export const CHATGPT_PACKAGE_FAMILY="OpenAI.Codex_2p2nqsd0c76g0";const g=a({id:"chatgpt-desktop",mirror:()=>e().installMirror?.chatgptDesktop,asset:(t,n)=>"darwin"===t?n?"ChatGPT-mac-arm64.dmg":null:"win32"===t?n?"ChatGPT-win-arm64.msix":"ChatGPT-win-x64.msix":null,versionFile:(t,n)=>"win32"===t?`version-win-${n?"arm64":"x64"}.txt`:"version.txt",macApp:{source:"ChatGPT.app",installedNames:["ChatGPT.app","Codex.app"],bundleId:d,teamId:"2DC432GLL2"},windows:{signer:new RegExp("^CN=50BDFD77-8903-4850-9FFE-6E8522F64D5B$"),packageFilter:`$_.PackageFamilyName -eq '${CHATGPT_PACKAGE_FAMILY}'`},extraBlocker:t=>"darwin"===t&&!g.installedMacApp()&&["/Applications",o(u(),"Applications")].some(t=>{const n=o(t,"ChatGPT.app");return i(o(n,"Contents","Info.plist"))&&c(n)!==d})?"other_app":null});export const chatgptInstaller=g;let h=(e,i,o=3e4)=>{const s=t(e,i,{encoding:"utf-8",timeout:o,windowsHide:!0,stdio:["ignore","pipe","pipe"],env:r()});return s.error&&n.logError(`chatgpt-desktop: ${e}`,s.error),{status:s.status,stdout:`${s.stdout??""}`,stderr:`${s.stderr??""}`}};export function setChatgptProcessRunnerForTests(t){h=t}function m(t,n){return h("powershell.exe",["-NoProfile","-NonInteractive","-Command",t],n)}const f=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),C="Get-Process -ErrorAction SilentlyContinue | Where-Object { $_.Path -like '*\\WindowsApps\\OpenAI.Codex_*\\app\\ChatGPT.exe' }";function w(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}export function isChatgptRunning(){if("darwin"===s()){const t=g.installedMacApp();return Boolean(t)&&0===h("pgrep",["-f",`^${f(t)}/Contents/MacOS/`]).status}return"win32"===s()&&Number(m(`@(${C}).Count`).stdout.trim())>0}let A=!1;export function chatgptQuitRefused(){return A}export function quitChatgpt(){if(A=!1,"darwin"===s()){const t=g.installedMacApp();if(macQuitRefused(h("osascript",["-e",`tell application id "${d}" to quit`]))&&(A=isChatgptRunning(),A))return!1;for(let t=0;t<30&&isChatgptRunning();t++)w(500);t&&isChatgptRunning()&&h("pkill",["-f",`^${f(t)}/Contents/MacOS/`]),w(1e3)}else{if("win32"!==s())return!1;m([`$p = @(${C})`,"$p | ForEach-Object { [void]$_.CloseMainWindow() }","Start-Sleep -Seconds 3",`@(${C}) | Stop-Process -Force -ErrorAction SilentlyContinue`,"Start-Sleep -Seconds 1"].join("\n"),6e4)}return!isChatgptRunning()}export function launchChatgpt(){if("darwin"===s()){const t=g.installedMacApp();if(!t)return!1;h("open",[t])}else{if("win32"!==s())return!1;m(`Start-Process 'shell:AppsFolder\\${CHATGPT_PACKAGE_FAMILY}!App'`,6e4)}for(let t=0;t<20;t++){if(isChatgptRunning())return!0;w(500)}return!1}export function macQuitRefused(t){return null===t.status||/\(-128\)|-1712/.test(t.stderr??"")}export const chatgptDesktopApp={name:"chatgpt",displayName:"ChatGPT",installedVersion:function(){if("darwin"===s()){const t=g.installedMacApp();return t?l(t):null}return"win32"===s()?g.windowsPackageVersion():null},runningApp:{isRunning:isChatgptRunning,quit:quitChatgpt,quitRefused:chatgptQuitRefused,launch:launchChatgpt},appInstaller:{vendor:"OpenAI",sizeMb:()=>"darwin"===s()?800:p()?1050:1e3,downloadPage:"https://chatgpt.com/download",blocker:g.blocker,latestVersion:()=>g.latestVersion(),installedPath:()=>"darwin"===s()?g.installedMacApp():"win32"!==s()?null:g.windowsPackageVersion()?"MSIX":null,install:t=>g.install(t)}};
1
+ import{spawnSync as t}from"child_process";import{logger as n}from"../../utils/logger.js";import{brand as e}from"../brand.js";import{powerShellEnv as r}from"../powershell-env.js";import{existsSync as i}from"fs";import{join as o}from"path";import{appPlatform as s,createDesktopAppInstaller as a,isArm64Machine as p,macAppVersion as l,macBundleId as c}from"./desktop-app-installer.js";import{toolHome as u}from"./types.js";export const OPENAI_TEAM_ID="2DC432GLL2";const d="com.openai.codex";export const CHATGPT_PACKAGE_FAMILY="OpenAI.Codex_2p2nqsd0c76g0";const g=a({id:"chatgpt-desktop",mirror:()=>e().installMirror?.chatgptDesktop,asset:(t,n)=>"darwin"===t?n?"d2-mac-arm64.dmg":null:"win32"===t?n?"d2-win-arm64.msix":"d2-win-x64.msix":null,versionFile:(t,n)=>"win32"===t?`version-win-${n?"arm64":"x64"}.txt`:"version.txt",macApp:{source:"ChatGPT.app",installedNames:["ChatGPT.app","Codex.app"],bundleId:d,teamId:"2DC432GLL2"},windows:{signer:new RegExp("^CN=50BDFD77-8903-4850-9FFE-6E8522F64D5B$"),packageFilter:`$_.PackageFamilyName -eq '${CHATGPT_PACKAGE_FAMILY}'`},extraBlocker:t=>"darwin"===t&&!g.installedMacApp()&&["/Applications",o(u(),"Applications")].some(t=>{const n=o(t,"ChatGPT.app");return i(o(n,"Contents","Info.plist"))&&c(n)!==d})?"other_app":null});export const chatgptInstaller=g;let m=(e,i,o=3e4)=>{const s=t(e,i,{encoding:"utf-8",timeout:o,windowsHide:!0,stdio:["ignore","pipe","pipe"],env:r()});return s.error&&n.logError(`chatgpt-desktop: ${e}`,s.error),{status:s.status,stdout:`${s.stdout??""}`,stderr:`${s.stderr??""}`}};export function setChatgptProcessRunnerForTests(t){m=t}function f(t,n){return m("powershell.exe",["-NoProfile","-NonInteractive","-Command",t],n)}const h=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),C="Get-Process -ErrorAction SilentlyContinue | Where-Object { $_.Path -like '*\\WindowsApps\\OpenAI.Codex_*\\app\\ChatGPT.exe' }";function w(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}export function isChatgptRunning(){if("darwin"===s()){const t=g.installedMacApp();return Boolean(t)&&0===m("pgrep",["-f",`^${h(t)}/Contents/MacOS/`]).status}return"win32"===s()&&Number(f(`@(${C}).Count`).stdout.trim())>0}let A=!1;export function chatgptQuitRefused(){return A}export function quitChatgpt(){if(A=!1,"darwin"===s()){const t=g.installedMacApp();if(macQuitRefused(m("osascript",["-e",`tell application id "${d}" to quit`]))&&(A=isChatgptRunning(),A))return!1;for(let t=0;t<30&&isChatgptRunning();t++)w(500);t&&isChatgptRunning()&&m("pkill",["-f",`^${h(t)}/Contents/MacOS/`]),w(1e3)}else{if("win32"!==s())return!1;f([`$p = @(${C})`,"$p | ForEach-Object { [void]$_.CloseMainWindow() }","Start-Sleep -Seconds 3",`@(${C}) | Stop-Process -Force -ErrorAction SilentlyContinue`,"Start-Sleep -Seconds 1"].join("\n"),6e4)}return!isChatgptRunning()}export function launchChatgpt(){if("darwin"===s()){const t=g.installedMacApp();if(!t)return!1;m("open",[t])}else{if("win32"!==s())return!1;f(`Start-Process 'shell:AppsFolder\\${CHATGPT_PACKAGE_FAMILY}!App'`,6e4)}for(let t=0;t<20;t++){if(isChatgptRunning())return!0;w(500)}return!1}export function macQuitRefused(t){return null===t.status||/\(-128\)|-1712/.test(t.stderr??"")}export const chatgptDesktopApp={name:"chatgpt",displayName:"ChatGPT",installedVersion:function(){if("darwin"===s()){const t=g.installedMacApp();return t?l(t):null}return"win32"===s()?g.windowsPackageVersion():null},runningApp:{isRunning:isChatgptRunning,quit:quitChatgpt,quitRefused:chatgptQuitRefused,launch:launchChatgpt},appInstaller:{vendor:"OpenAI",sizeMb:()=>"darwin"===s()?800:p()?1050:1e3,downloadPage:"https://chatgpt.com/download",blocker:g.blocker,latestVersion:()=>g.latestVersion(),installedPath:()=>"darwin"===s()?g.installedMacApp():"win32"!==s()?null:g.windowsPackageVersion()?"MSIX":null,install:t=>g.install(t)}};
@@ -1 +1 @@
1
- import{existsSync as e}from"fs";import{join as s}from"path";import{brand as t}from"../brand.js";import{WINDOWS_PACKAGE_FAMILIES as o}from"./desktop-process.js";import{createDesktopAppInstaller as a}from"./desktop-app-installer.js";import{toolHome as r}from"./types.js";export const ANTHROPIC_TEAM_ID="Q6L2SF6YDW";export{DesktopInstallError,parseSha256Sums,setDesktopAppDepsForTests}from"./desktop-app-installer.js";const p=a({id:"claude-desktop",mirror:()=>t().installMirror?.claudeDesktop,asset:(e,s)=>"darwin"===e?"Claude-mac-universal.dmg":"win32"===e?s?"Claude-win-arm64.msix":"Claude-win-x64.msix":null,versionFile:()=>"version.txt",releaseTag:e=>`v${e}`,macApp:{source:"Claude.app",installedNames:["Claude.app"],bundleId:"com.anthropic.claudefordesktop",teamId:"Q6L2SF6YDW"},windows:{signer:/(^|,\s*)O="?Anthropic, PBC"?(,|$)/,packageFilter:`@(${o.map(e=>`'${e}'`).join(",")}) -contains $_.PackageFamilyName`},extraBlocker:t=>"win32"===t&&function(){const t=process.env.LOCALAPPDATA||s(r(),"AppData","Local");return e(s(t,"AnthropicClaude","Update.exe"))}()?"classic_install":null});export const desktopAssetName=p.assetName;export const desktopInstallBlocker=p.blocker;export const fetchLatestDesktopVersion=(e=8e3)=>p.latestVersion(e);export const installedMacApp=p.installedMacApp;export const verifyMacApp=p.verifyMacApp;export const verifyWindowsPackage=p.verifyWindowsPackage;export function installLatestDesktop(e={}){return p.install(e)}
1
+ import{existsSync as e}from"fs";import{join as s}from"path";import{brand as t}from"../brand.js";import{WINDOWS_PACKAGE_FAMILIES as o}from"./desktop-process.js";import{createDesktopAppInstaller as r}from"./desktop-app-installer.js";import{toolHome as a}from"./types.js";export const ANTHROPIC_TEAM_ID="Q6L2SF6YDW";export{DesktopInstallError,parseSha256Sums,setDesktopAppDepsForTests}from"./desktop-app-installer.js";const p=r({id:"claude-desktop",mirror:()=>t().installMirror?.claudeDesktop,asset:(e,s)=>"darwin"===e?"d1-mac-universal.dmg":"win32"===e?s?"d1-win-arm64.msix":"d1-win-x64.msix":null,versionFile:()=>"version.txt",releaseTag:e=>`v${e}`,macApp:{source:"Claude.app",installedNames:["Claude.app"],bundleId:"com.anthropic.claudefordesktop",teamId:"Q6L2SF6YDW"},windows:{signer:/(^|,\s*)O="?Anthropic, PBC"?(,|$)/,packageFilter:`@(${o.map(e=>`'${e}'`).join(",")}) -contains $_.PackageFamilyName`},extraBlocker:t=>"win32"===t&&function(){const t=process.env.LOCALAPPDATA||s(a(),"AppData","Local");return e(s(t,"AnthropicClaude","Update.exe"))}()?"classic_install":null});export const desktopAssetName=p.assetName;export const desktopInstallBlocker=p.blocker;export const fetchLatestDesktopVersion=(e=8e3)=>p.latestVersion(e);export const installedMacApp=p.installedMacApp;export const verifyMacApp=p.verifyMacApp;export const verifyWindowsPackage=p.verifyWindowsPackage;export function installLatestDesktop(e={}){return p.install(e)}
@@ -1 +1 @@
1
- import{execFileSync as e}from"child_process";import{createHash as r}from"crypto";import{createReadStream as t,createWriteStream as o,existsSync as s,readdirSync as n,readFileSync as i}from"fs";import{copyFile as a,mkdir as l,readFile as c,rename as u,rm as f,writeFile as p}from"fs/promises";import{isAbsolute as d,join as m,normalize as h,sep as w}from"path";import{Readable as g,Writable as b}from"stream";import{pipeline as v}from"stream/promises";import*as D from"zlib";import{logger as y}from"../../utils/logger.js";import{brand as k,brandEnv as $}from"../brand.js";import{downloadNativeBinary as C,nativeLayout as S,nativePlatformKey as x}from"./claude-native-mirror.js";import{WINDOWS_PACKAGE_FAMILIES as N}from"./desktop-process.js";import{toolHome as A}from"./types.js";import{mirrorFileUrl as P,withDownloadFallback as L}from"../mirror-url.js";import{powerShellEnv as O}from"../powershell-env.js";export function readDesktopCliPin(e,r,t=!1){const o=e.indexOf('claude-code-releases","sdkWrapperVersion"');if(o<0)return null;const s=e.lastIndexOf("JSON.parse('",o),n=e.indexOf("')",o);if(s<0||n<0)return null;try{const o=JSON.parse(e.subarray(s+12,n).toString("utf-8")),i="string"==typeof o.version?o.version:"",a=o.manifest?.platforms?.[r],l=t?a?.bundle?.checksum:a?.checksum;return/^\d+\.\d+\.\d+$/.test(i)&&"string"==typeof l&&/^[0-9a-f]{64}$/.test(l)?{version:i,checksum:l}:null}catch{return null}}function E(){const r=m(process.env.LOCALAPPDATA||"","AnthropicClaude");if(process.env.LOCALAPPDATA&&s(r)){const e=n(r).filter(e=>/^app-\d+\.\d+\.\d+$/.test(e)).sort((e,r)=>r.localeCompare(e,void 0,{numeric:!0}));for(const t of e){const e=m(r,t,"resources","app.asar");if(s(e))return e}}try{const r=e("powershell.exe",["-NoProfile","-Command",`Get-AppxPackage | Where-Object { @(${N.map(e=>`'${e}'`).join(",")}) -contains $_.PackageFamilyName } | ForEach-Object { $_.InstallLocation }`],{encoding:"utf-8",timeout:15e3,windowsHide:!0,stdio:["ignore","pipe","ignore"],env:O()});for(const e of r.split(/\r?\n/).map(e=>e.trim()).filter(Boolean)){const r=m(e,"app","resources","app.asar");if(s(r))return r}}catch(e){y.logError("claude-desktop-cli.windowsAsarPath",e)}return null}function j(){if($("TEST_HOME")?.trim())return null;for(const e of["/usr/lib/claude-desktop","/opt/Claude"]){const r=m(e,"resources","app.asar");if(s(r))return r}return null}function F(){for(const e of["/Applications/Claude.app",m(A(),"Applications","Claude.app")]){const r=m(e,"Contents","Resources","app.asar");if(s(r))return r}return null}export function installedDesktopAsarPath(){return"win32"===process.platform?E():"darwin"===process.platform?F():"linux"===process.platform?j():null}class T extends b{dest;buffer=Buffer.alloc(0);remaining=0;padding=0;file=null;longName=null;collectingLongName=null;constructor(e){super(),this.dest=e}_write(e,r,t){this.buffer=this.buffer.length?Buffer.concat([this.buffer,e]):e,this.drain().then(()=>t()).catch(t)}_final(e){this.remaining>0?e(new Error("archive ends inside an entry")):e()}target(e){const r=h(e);if(!r||d(r)||".."===r||r.startsWith(`..${w}`))throw new Error(`unsafe path in archive: ${e}`);return m(this.dest,r)}async closeFile(){const e=this.file;this.file=null,e&&await new Promise((r,t)=>e.end(e=>e?t(e):r()))}async drain(){for(;;){if(this.remaining>0){if(0===this.buffer.length)return;const e=this.buffer.subarray(0,Math.min(this.remaining,this.buffer.length));this.buffer=this.buffer.subarray(e.length),this.remaining-=e.length,this.collectingLongName?this.collectingLongName.push(e):this.file&&!this.file.write(e)&&await new Promise(e=>this.file.once("drain",()=>e())),0===this.remaining&&(this.collectingLongName&&(this.longName=Buffer.concat(this.collectingLongName).toString("utf-8").replace(/\0.*$/s,""),this.collectingLongName=null),await this.closeFile());continue}if(this.padding>0){if(this.buffer.length<this.padding)return;this.buffer=this.buffer.subarray(this.padding),this.padding=0}if(this.buffer.length<512)return;const e=this.buffer.subarray(0,512);if(this.buffer=this.buffer.subarray(512),e.every(e=>0===e))continue;const r=(r,t)=>e.subarray(r,r+t).toString("utf-8").replace(/\0.*$/s,""),t=r(345,155);let s=t?`${t}/${r(0,100)}`:r(0,100);null!==this.longName&&(s=this.longName,this.longName=null);const n=parseInt(r(124,12).trim()||"0",8),i=511&parseInt(r(100,8).trim()||"644",8),a=r(156,1)||"0";if(this.remaining=n,this.padding=(512-n%512)%512,"L"===a)this.collectingLongName=[];else if("x"===a||"g"===a);else if("5"===a)await l(this.target(s),{recursive:!0});else{if("0"!==a)throw new Error(`unexpected entry type ${a} in archive: ${s}`);{const e=this.target(s);await l(m(e,".."),{recursive:!0}),this.file=o(e,{mode:i||420}),0===n&&await this.closeFile()}}}}}export async function installDesktopCli(e){const o=readDesktopCliPin(e.asar,e.platformKey,e.bundle);if(!o)return{status:"skipped",reason:"unknown app layout"};if(e.bundle&&!e.download)return{status:"skipped",reason:"no bundle mirror"};const n=e.platformKey.startsWith("win32")?"claude.exe":"claude",i=m(e.userDataDir,"claude-code",o.version),d=m(i,o.checksum.slice(0,12)),h=e.bundle?m(d,"claude.app","Contents","MacOS","claude"):m(d,n),w=m(d,".verified");try{if(s(h)&&(await c(w,"utf-8")).trim()===o.checksum)return{status:"present",version:o.version}}catch{}await l(i,{recursive:!0});const g=m(i,`.partial-${o.checksum.slice(0,12)}`),y=`${g}.download`;try{await f(w,{force:!0}),await f(g,{recursive:!0,force:!0});let n="mirror";if(e.bundle){if(e.onStart?.(o.version,"mirror"),e.onDownload?.(o.version),await e.download(o.version,y),await async function(e,o,s){const n=r("sha256");if(await v(t(e),new b({write(e,r,t){n.update(e),t()}})),n.digest("hex")!==o)throw new Error("downloaded bundle does not match the app's checksum");const i=D.createZstdDecompress;if(!i)throw new Error(`Node ${process.version} cannot decompress zstd (needs 22.15 or newer)`);await v(t(e),i(),new T(s))}(y,o.checksum,g),!s(m(g,"claude.app","Contents","MacOS","claude")))throw new Error("bundle has no claude.app");await f(d,{recursive:!0,force:!0}),await u(g,d)}else{const r=e.localVersionsDir?m(e.localVersionsDir,o.version):null;if(r&&s(r))e.onStart?.(o.version,"local"),await a(r,g),n="local";else{e.onStart?.(o.version,"mirror"),e.onDownload?.(o.version);const r=e.download??((r,t)=>C(e.platformKey,r,t));await r(o.version,g)}await l(d,{recursive:!0}),await u(g,h)}return await p(w,o.checksum),{status:"installed",version:o.version,source:n}}finally{await f(g,{recursive:!0,force:!0}),await f(y,{force:!0}),await f(`${g}.download`,{force:!0})}}let K=(...e)=>fetch(...e);export function setDesktopCliFetchForTests(e){K=e}export async function ensureDesktopCli(e){const r=x();if(!r)return{status:"skipped",reason:"unsupported architecture"};if("win32"===process.platform){const t=E();return t?installDesktopCli({userDataDir:e.userDataDir,asar:i(t),platformKey:r,localVersionsDir:S().versionsDir,onDownload:e.onDownload,onStart:e.onStart}):{status:"skipped",reason:"app.asar not found"}}if("darwin"===process.platform){const t=F();if(!t)return{status:"skipped",reason:"app.asar not found"};const{mirror:s,desktopVersion:n}=e;return installDesktopCli({userDataDir:e.userDataDir,asar:i(t),platformKey:r,bundle:!0,onDownload:e.onDownload,onStart:e.onStart,download:s&&n?(e,t)=>L(P(s,`claude-code-${e}-${r}.app.tar.zst`,`v${n}`),k().installMirror?.downloadCounter,e=>async function(e,r){const t=await K(e,{signal:AbortSignal.timeout(9e5)});if(!t.ok||!t.body)throw new Error(`${e}: HTTP ${t.status}`);await v(g.fromWeb(t.body),o(r))}(e,t)):void 0})}if("linux"===process.platform){const t=j();return t?installDesktopCli({userDataDir:e.userDataDir,asar:i(t),platformKey:r.replace(/-musl$/,""),localVersionsDir:r.endsWith("-musl")?void 0:S().versionsDir,onDownload:e.onDownload,onStart:e.onStart}):{status:"skipped",reason:"app.asar not found"}}return{status:"skipped",reason:"unsupported platform"}}
1
+ import{execFileSync as r}from"child_process";import{createHash as e}from"crypto";import{createReadStream as t,createWriteStream as o,existsSync as s,readdirSync as n,readFileSync as i}from"fs";import{copyFile as a,mkdir as l,readFile as c,rename as u,rm as f,writeFile as p}from"fs/promises";import{isAbsolute as d,join as m,normalize as h,sep as w}from"path";import{Readable as g,Writable as b}from"stream";import{pipeline as v}from"stream/promises";import*as D from"zlib";import{logger as y}from"../../utils/logger.js";import{brand as k,brandEnv as $}from"../brand.js";import{downloadNativeBinary as C,nativeLayout as S,nativePlatformKey as x}from"./claude-native-mirror.js";import{WINDOWS_PACKAGE_FAMILIES as N}from"./desktop-process.js";import{toolHome as A}from"./types.js";import{mirrorFileUrl as P,withDownloadFallback as L}from"../mirror-url.js";import{powerShellEnv as O}from"../powershell-env.js";export function readDesktopCliPin(r,e,t=!1){const o=r.indexOf('claude-code-releases","sdkWrapperVersion"');if(o<0)return null;const s=r.lastIndexOf("JSON.parse('",o),n=r.indexOf("')",o);if(s<0||n<0)return null;try{const o=JSON.parse(r.subarray(s+12,n).toString("utf-8")),i="string"==typeof o.version?o.version:"",a=o.manifest?.platforms?.[e],l=t?a?.bundle?.checksum:a?.checksum;return/^\d+\.\d+\.\d+$/.test(i)&&"string"==typeof l&&/^[0-9a-f]{64}$/.test(l)?{version:i,checksum:l}:null}catch{return null}}function E(){const e=m(process.env.LOCALAPPDATA||"","AnthropicClaude");if(process.env.LOCALAPPDATA&&s(e)){const r=n(e).filter(r=>/^app-\d+\.\d+\.\d+$/.test(r)).sort((r,e)=>e.localeCompare(r,void 0,{numeric:!0}));for(const t of r){const r=m(e,t,"resources","app.asar");if(s(r))return r}}try{const e=r("powershell.exe",["-NoProfile","-Command",`Get-AppxPackage | Where-Object { @(${N.map(r=>`'${r}'`).join(",")}) -contains $_.PackageFamilyName } | ForEach-Object { $_.InstallLocation }`],{encoding:"utf-8",timeout:15e3,windowsHide:!0,stdio:["ignore","pipe","ignore"],env:O()});for(const r of e.split(/\r?\n/).map(r=>r.trim()).filter(Boolean)){const e=m(r,"app","resources","app.asar");if(s(e))return e}}catch(r){y.logError("claude-desktop-cli.windowsAsarPath",r)}return null}function j(){if($("TEST_HOME")?.trim())return null;for(const r of["/usr/lib/claude-desktop","/opt/Claude"]){const e=m(r,"resources","app.asar");if(s(e))return e}return null}function F(){for(const r of["/Applications/Claude.app",m(A(),"Applications","Claude.app")]){const e=m(r,"Contents","Resources","app.asar");if(s(e))return e}return null}export function installedDesktopAsarPath(){return"win32"===process.platform?E():"darwin"===process.platform?F():"linux"===process.platform?j():null}class T extends b{dest;buffer=Buffer.alloc(0);remaining=0;padding=0;file=null;longName=null;collectingLongName=null;constructor(r){super(),this.dest=r}_write(r,e,t){this.buffer=this.buffer.length?Buffer.concat([this.buffer,r]):r,this.drain().then(()=>t()).catch(t)}_final(r){this.remaining>0?r(new Error("archive ends inside an entry")):r()}target(r){const e=h(r);if(!e||d(e)||".."===e||e.startsWith(`..${w}`))throw new Error(`unsafe path in archive: ${r}`);return m(this.dest,e)}async closeFile(){const r=this.file;this.file=null,r&&await new Promise((e,t)=>r.end(r=>r?t(r):e()))}async drain(){for(;;){if(this.remaining>0){if(0===this.buffer.length)return;const r=this.buffer.subarray(0,Math.min(this.remaining,this.buffer.length));this.buffer=this.buffer.subarray(r.length),this.remaining-=r.length,this.collectingLongName?this.collectingLongName.push(r):this.file&&!this.file.write(r)&&await new Promise(r=>this.file.once("drain",()=>r())),0===this.remaining&&(this.collectingLongName&&(this.longName=Buffer.concat(this.collectingLongName).toString("utf-8").replace(/\0.*$/s,""),this.collectingLongName=null),await this.closeFile());continue}if(this.padding>0){if(this.buffer.length<this.padding)return;this.buffer=this.buffer.subarray(this.padding),this.padding=0}if(this.buffer.length<512)return;const r=this.buffer.subarray(0,512);if(this.buffer=this.buffer.subarray(512),r.every(r=>0===r))continue;const e=(e,t)=>r.subarray(e,e+t).toString("utf-8").replace(/\0.*$/s,""),t=e(345,155);let s=t?`${t}/${e(0,100)}`:e(0,100);null!==this.longName&&(s=this.longName,this.longName=null);const n=parseInt(e(124,12).trim()||"0",8),i=511&parseInt(e(100,8).trim()||"644",8),a=e(156,1)||"0";if(this.remaining=n,this.padding=(512-n%512)%512,"L"===a)this.collectingLongName=[];else if("x"===a||"g"===a);else if("5"===a)await l(this.target(s),{recursive:!0});else{if("0"!==a)throw new Error(`unexpected entry type ${a} in archive: ${s}`);{const r=this.target(s);await l(m(r,".."),{recursive:!0}),this.file=o(r,{mode:i||420}),0===n&&await this.closeFile()}}}}}export async function installDesktopCli(r){const o=readDesktopCliPin(r.asar,r.platformKey,r.bundle);if(!o)return{status:"skipped",reason:"unknown app layout"};if(r.bundle&&!r.download)return{status:"skipped",reason:"no bundle mirror"};const n=r.platformKey.startsWith("win32")?"claude.exe":"claude",i=m(r.userDataDir,"claude-code",o.version),d=m(i,o.checksum.slice(0,12)),h=r.bundle?m(d,"claude.app","Contents","MacOS","claude"):m(d,n),w=m(d,".verified");try{if(s(h)&&(await c(w,"utf-8")).trim()===o.checksum)return{status:"present",version:o.version}}catch{}await l(i,{recursive:!0});const g=m(i,`.partial-${o.checksum.slice(0,12)}`),y=`${g}.download`;try{await f(w,{force:!0}),await f(g,{recursive:!0,force:!0});let n="mirror";if(r.bundle){if(r.onStart?.(o.version,"mirror"),r.onDownload?.(o.version),await r.download(o.version,y),await async function(r,o,s){const n=e("sha256");if(await v(t(r),new b({write(r,e,t){n.update(r),t()}})),n.digest("hex")!==o)throw new Error("downloaded bundle does not match the app's checksum");const i=D.createZstdDecompress;if(!i)throw new Error(`Node ${process.version} cannot decompress zstd (needs 22.15 or newer)`);await v(t(r),i(),new T(s))}(y,o.checksum,g),!s(m(g,"claude.app","Contents","MacOS","claude")))throw new Error("bundle has no claude.app");await f(d,{recursive:!0,force:!0}),await u(g,d)}else{const e=r.localVersionsDir?m(r.localVersionsDir,o.version):null;if(e&&s(e))r.onStart?.(o.version,"local"),await a(e,g),n="local";else{r.onStart?.(o.version,"mirror"),r.onDownload?.(o.version);const e=r.download??((e,t)=>C(r.platformKey,e,t));await e(o.version,g)}await l(d,{recursive:!0}),await u(g,h)}return await p(w,o.checksum),{status:"installed",version:o.version,source:n}}finally{await f(g,{recursive:!0,force:!0}),await f(y,{force:!0}),await f(`${g}.download`,{force:!0})}}let K=(...r)=>fetch(...r);export function setDesktopCliFetchForTests(r){K=r}export async function ensureDesktopCli(r){const e=x();if(!e)return{status:"skipped",reason:"unsupported architecture"};if("win32"===process.platform){const t=E();return t?installDesktopCli({userDataDir:r.userDataDir,asar:i(t),platformKey:e,localVersionsDir:S().versionsDir,onDownload:r.onDownload,onStart:r.onStart}):{status:"skipped",reason:"app.asar not found"}}if("darwin"===process.platform){const t=F();if(!t)return{status:"skipped",reason:"app.asar not found"};const{mirror:s,desktopVersion:n}=r;return installDesktopCli({userDataDir:r.userDataDir,asar:i(t),platformKey:e,bundle:!0,onDownload:r.onDownload,onStart:r.onStart,download:s&&n?(r,t)=>L(P(s,`d1-cli-${r}-${e}.tar.zst`,`v${n}`),k().installMirror?.downloadCounter,r=>async function(r,e){const t=await K(r,{signal:AbortSignal.timeout(9e5)});if(!t.ok||!t.body)throw new Error(`${r}: HTTP ${t.status}`);await v(g.fromWeb(t.body),o(e))}(r,t)):void 0})}if("linux"===process.platform){const t=j();return t?installDesktopCli({userDataDir:r.userDataDir,asar:i(t),platformKey:e.replace(/-musl$/,""),localVersionsDir:e.endsWith("-musl")?void 0:S().versionsDir,onDownload:r.onDownload,onStart:r.onStart}):{status:"skipped",reason:"app.asar not found"}}return{status:"skipped",reason:"unsupported platform"}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xship/cli",
3
- "version": "0.0.191",
3
+ "version": "0.0.192",
4
4
  "description": "Configure Claude Code, Codex, Grok Build and other coding tools for Xship AI with one command",
5
5
  "main": "dist/index.js",
6
6
  "bin": {