@crewx/sdk 0.9.0-rc.42 → 0.9.0-rc.43
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/dist/desktop/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var d=require('path'),fs=require('fs'),os=require('os'),child_process=require('child_process'),module$1=require('module');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var d__namespace=/*#__PURE__*/_interopNamespace(d);var N=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var p=class extends Error{code;constructor(e,n){super(`${e}: ${n}`),this.code=e,this.name="ShortcutError";}};var A={existsSync:t=>fs.existsSync(t),readFileSync:t=>fs.readFileSync(t,"utf8"),writeFileSync:(t,e)=>fs.writeFileSync(t,e,"utf8"),mkdirSync:t=>{fs.mkdirSync(t,{recursive:true});},unlinkSync:t=>{fs.unlinkSync(t);}},T=os.homedir;function y(t){return typeof t!="string"?void 0:t.trim()||void 0}function C(t){return y(t)?.toLowerCase()??""}function E(t){try{return fs.statSync(t).isFile()}catch{return false}}function yt(t,e){if(t===e)return true;let n=d__namespace.default.relative(t,e);return n!==""&&!n.startsWith("..")&&!d__namespace.default.isAbsolute(n)}function Ct(t,e){if(d__namespace.default.basename(t)!==".bin")return false;let n=d__namespace.default.dirname(t);if(d__namespace.default.basename(n)!=="node_modules")return false;let r=d__namespace.default.dirname(n);return yt(r,e)}function M(t,e={}){if(t.includes("/")||t.includes("\\")||d__namespace.default.isAbsolute(t))return t;let n=e.platform??process.platform,r=e.env??process.env,s=d__namespace.default.resolve(e.cwd??process.cwd()),c=(e.resolution??"global_first")==="global_first",o=r.PATH??r.Path??process.env.PATH??process.env.Path??"",i=n==="win32"?";":":",a=o.split(i).map(u=>u.trim()).filter(Boolean),l=d__namespace.default.extname(t).length>0,m=r.PATHEXT??r.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",h=n==="win32"?l?[""]:m.split(";").map(u=>u.trim()).filter(Boolean).map(u=>u.startsWith(".")?u:`.${u}`):[""];for(let u of a){let f=d__namespace.default.resolve(s,u);if(!(c&&Ct(f,s)))for(let L of h){let ft=C(L),ht=L.toUpperCase();for(let mt of [L,ft,ht]){let W=d__namespace.default.join(f,`${t}${mt}`);if(E(W))return W}}}return t}function xt(t){if(!E(t))return null;try{let e=fs.readFileSync(t,"utf8"),n=d__namespace.default.dirname(t),r=[];for(let i of e.matchAll(/"([^"\r\n]*)"/g)){let m=(i[1]??"").match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();if(!m)continue;let h=m.replace(/[\\/]+/g,d__namespace.default.sep).replace(/^[\\/]+/,""),u=d__namespace.default.resolve(n,h);E(u)&&r.push(u);}let s=[],c=new Map;for(let i of e.matchAll(/SET\s+"(\w+)=%~?dp0%?[\\/]?([^"]+)"/gi)){let a=i[1].toUpperCase(),l=i[2].trim().replace(/[\\/]+/g,d__namespace.default.sep).replace(/^[\\/]+/,"");c.set(a,d__namespace.default.resolve(n,l));}for(let i of e.split(/\r?\n/))if(i.includes("%*"))for(let a of i.matchAll(/"%(\w+)%"/g)){let l=c.get(a[1].toUpperCase());l&&E(l)&&s.push(l);}let o=i=>i.find(a=>{let l=C(d__namespace.default.basename(a));return l!=="node.exe"&&l!=="node"})??null;return o(s)??o(r)}catch{return null}}function kt(t,e){if(typeof e=="string")return y(e)||null;if(!e||typeof e!="object")return null;if(t){let n=e[t],r=typeof n=="string"?y(n):void 0;if(r)return r}for(let n of Object.values(e)){let r=typeof n=="string"?y(n):void 0;if(r)return r}return null}function _t(t,e){if(!e)return null;let n=d__namespace.default.dirname(t),r=[d__namespace.default.resolve(n,"..",e),d__namespace.default.resolve(n,"node_modules",e)];for(let s of r){let c=d__namespace.default.join(s,"package.json");if(E(c))try{let o=JSON.parse(fs.readFileSync(c,"utf8")),i=kt(e,o.bin);if(!i)continue;let a=d__namespace.default.resolve(s,i);if(E(a))return a}catch{}}return null}function Lt(t){let e=t.platform??process.platform,n=t.env??process.env,r=t.execPath??process.execPath,s=t.cwd,c=t.resolution;if(e!=="win32")return {command:M(t.command,{cwd:s,env:n,platform:e,resolution:c}),leadingArgv:[],resolution:"direct"};let o=M(t.command,{cwd:s,env:n,platform:e,resolution:c}),i=C(d__namespace.default.extname(o));if(i===".js"||i===".cjs"||i===".mjs")return {command:r,leadingArgv:[o],resolution:"node-entrypoint",windowsHide:true};if(i===".cmd"||i===".bat"){let a=xt(o)??_t(o,t.packageName);return a?C(d__namespace.default.extname(a))===".exe"?{command:a,leadingArgv:[],resolution:"exe-entrypoint",windowsHide:true}:{command:r,leadingArgv:[a],resolution:"node-entrypoint",windowsHide:true}:{command:o,leadingArgv:[],resolution:"unresolved-wrapper"}}return {command:o,leadingArgv:[],resolution:"direct"}}function Nt(t){if(t.candidate.resolution!=="unresolved-wrapper")return {command:t.candidate.command,leadingArgv:t.candidate.leadingArgv,resolution:t.candidate.resolution,windowsHide:t.candidate.windowsHide};throw new Error(`${d__namespace.default.basename(t.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function B(t){let e=Lt(t);return Nt({candidate:e})}function $(t,e){return {command:t.command,argv:[...t.leadingArgv,...e],resolution:t.resolution,shell:t.shell,windowsHide:t.windowsHide}}var X=3e4;function Ot(t){if(typeof t.pid!="number"){t.kill();return}if(process.platform==="win32"){child_process.spawn("taskkill",["/pid",String(t.pid),"/t","/f"],{windowsHide:true}).on("error",()=>{});return}try{process.kill(-t.pid,"SIGKILL");}catch{t.kill("SIGKILL");}}var H=(t,e,n={})=>new Promise((r,s)=>{let c=n.env??process.env,o=process.platform,i;try{let f=B({command:t,platform:o,env:c,cwd:n.cwd,allowShellFallback:!1});i=$(f,e);}catch(f){s(f instanceof Error?f:new Error(String(f)));return}let a=child_process.spawn(i.command,i.argv,{cwd:n.cwd,env:c,shell:i.shell,windowsHide:i.windowsHide??true,detached:o!=="win32"}),l="",m="",h=false,u=setTimeout(()=>{h||(h=true,Ot(a),s(new Error(`Command timed out after ${n.timeoutMs??X}ms: ${t} ${e.join(" ")}`)));},n.timeoutMs??X);a.stdout?.on("data",f=>{l+=f.toString();}),a.stderr?.on("data",f=>{m+=f.toString();}),a.on("error",f=>{h||(h=true,clearTimeout(u),s(f));}),a.on("close",f=>{h||(h=true,clearTimeout(u),r({code:f??0,stdout:l,stderr:m}));});});function Dt(){try{return (typeof N=="function"?N:module$1.createRequire(__filename)).resolve("@crewx/sdk/package.json")}catch{return null}}function Wt(){let t=[Dt(),d.join(__dirname,"../../package.json"),d.join(__dirname,"../../../package.json")].filter(e=>!!e);for(let e of t)try{let n=JSON.parse(fs.readFileSync(e,"utf8"));if(n.name==="@crewx/sdk"&&n.version)return n.version}catch{}return "0.0.0"}var j=Wt();var g=d__namespace.win32;function O(t){return g.join(t,".crewx")}function K(t){return g.join(O(t),"shortcut.json")}function U(t){return g.join(O(t),"launcher.json")}function z(t){return g.join(O(t),"bin","crewx-launcher.cmd")}function q(t){return g.join(t,"CrewX.lnk")}function Q(t,e){return g.normalize(t).toLowerCase()===g.normalize(e).toLowerCase()}var At="[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Environment]::GetFolderPath('DesktopDirectory')";async function Y(t){try{let n=await t.run("powershell",["-NoProfile","-NonInteractive","-Command",At],{env:t.env}),r=n.stdout.trim();if(n.code===0&&r)return {dir:r,source:"known-folder"}}catch{}let e=t.env.USERPROFILE||t.env.Userprofile||t.homedir();return e?{dir:g.join(e,"Desktop"),source:"fallback"}:null}function I(t,e){let n=g.resolve(e,"node_modules",".bin").toLowerCase();return t.split(";").filter(r=>r?g.resolve(r).toLowerCase()!==n:true).join(";")}function Z(t){return t?/\\Program Files( \(x86\))?\\/i.test(t)&&/crewx/i.test(t):false}function Tt(t,e){let n=a=>{let[l,...m]=a.split("-"),h=m.join("-")||void 0;return {parts:(l??"").split(".").map(f=>Number.parseInt(f,10)||0),pre:h}},r=n(t),s=n(e),c=Math.max(r.parts.length,s.parts.length);for(let a=0;a<c;a++){let l=r.parts[a]??0,m=s.parts[a]??0;if(l!==m)return l<m?-1:1}if(r.pre===s.pre)return 0;if(!r.pre&&s.pre)return 1;if(r.pre&&!s.pre)return -1;let o=Number.parseInt(r.pre.match(/(\d+)$/)?.[1]??"",10),i=Number.parseInt(s.pre.match(/(\d+)$/)?.[1]??"",10);return !Number.isNaN(o)&&!Number.isNaN(i)&&o!==i?o<i?-1:1:r.pre<s.pre?-1:r.pre>s.pre?1:0}function tt(t,e){return Tt(t,e)<0}var nt=d__namespace.win32,rt=1;function ot(t,e){if(!t.existsSync(e))return null;try{let n=JSON.parse(t.readFileSync(e));return {schema:n.schema??rt,shortcutPath:n.shortcutPath,version:n.version,owned:!!n.owned,declined:!!n.declined,desktopSource:n.desktopSource,updatedAt:n.updatedAt}}catch{return null}}function x(t,e,n){let r={schema:rt,...n,updatedAt:new Date().toISOString()};t.mkdirSync(nt.dirname(e)),t.writeFileSync(e,JSON.stringify(r,null,2));}function k(t,e){if(!t.existsSync(e))return null;try{let n=JSON.parse(t.readFileSync(e));return {schema:n.schema??0,binPath:n.binPath,updatedAt:n.updatedAt}}catch{return null}}function st(t,e,n){t.mkdirSync(nt.dirname(e)),t.writeFileSync(e,JSON.stringify(n,null,2));}var Mt=d__namespace.win32,R=1;function Ft(t){return t.replace(/%/g,"%%")}function Bt(t){return ["@echo off","setlocal DisableDelayedExpansion","chcp 65001 >nul","",'set "CREWX_WORKDIR=%USERPROFILE%\\crewx"','if not exist "%CREWX_WORKDIR%" mkdir "%CREWX_WORKDIR%" >nul 2>nul','cd /d "%CREWX_WORKDIR%"',"",'set "CREWX_PORT_EFFECTIVE=%CREWX_PORT%"','if "%CREWX_PORT_EFFECTIVE%"=="" set "CREWX_PORT_EFFECTIVE=8150"','set "CREWX_HEALTH_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/api/v1/health"','set "CREWX_ORIGIN_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/"',"",t.bakedBinPath?`set "CREWX_FALLBACK_BIN=${Ft(t.bakedBinPath)}"`:'set "CREWX_FALLBACK_BIN="','set "CREWX_RESOLVED_BIN=%CREWX_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" set "CREWX_RESOLVED_BIN=%CREWX_FALLBACK_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" (',` for /f "delims=" %%I in ('where crewx 2^>nul') do (`,' if not defined CREWX_RESOLVED_BIN set "CREWX_RESOLVED_BIN=%%I"'," )",")","",'powershell -NoProfile -NonInteractive -Command "try { $r = Invoke-WebRequest -Uri $env:CREWX_HEALTH_URL -TimeoutSec 1 -UseBasicParsing; if ($r.StatusCode -eq 200) { exit 0 } else { exit 1 } } catch { exit 1 }"',"if %ERRORLEVEL% EQU 0 (",' start "" "%CREWX_ORIGIN_URL%"'," exit /b 0",")","",'if "%CREWX_RESOLVED_BIN%"=="" ('," echo CrewX executable not found. Please reinstall the desktop shortcut."," pause"," exit /b 1",")","",'start "CrewX" /min "%CREWX_RESOLVED_BIN%"',""].join(`\r
|
|
2
|
-
`)}function
|
|
3
|
-
${
|
|
1
|
+
'use strict';var d=require('path'),fs=require('fs'),os=require('os'),child_process=require('child_process'),module$1=require('module');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var d__namespace=/*#__PURE__*/_interopNamespace(d);var O=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var f=class extends Error{code;constructor(e,n){super(`${e}: ${n}`),this.code=e,this.name="ShortcutError";}};var F={existsSync:t=>fs.existsSync(t),readFileSync:t=>fs.readFileSync(t,"utf8"),writeFileSync:(t,e)=>fs.writeFileSync(t,e,"utf8"),mkdirSync:t=>{fs.mkdirSync(t,{recursive:true});},unlinkSync:t=>{fs.unlinkSync(t);}},$=os.homedir;function L(t){return typeof t!="string"?void 0:t.trim()||void 0}function k(t){return L(t)?.toLowerCase()??""}function R(t){try{return fs.statSync(t).isFile()}catch{return false}}function xt(t,e){if(t===e)return true;let n=d__namespace.default.relative(t,e);return n!==""&&!n.startsWith("..")&&!d__namespace.default.isAbsolute(n)}function Lt(t,e){if(d__namespace.default.basename(t)!==".bin")return false;let n=d__namespace.default.dirname(t);if(d__namespace.default.basename(n)!=="node_modules")return false;let r=d__namespace.default.dirname(n);return xt(r,e)}function V(t,e={}){if(t.includes("/")||t.includes("\\")||d__namespace.default.isAbsolute(t))return t;let n=e.platform??process.platform,r=e.env??process.env,s=d__namespace.default.resolve(e.cwd??process.cwd()),c=(e.resolution??"global_first")==="global_first",o=r.PATH??r.Path??process.env.PATH??process.env.Path??"",i=n==="win32"?";":":",a=o.split(i).map(u=>u.trim()).filter(Boolean),l=d__namespace.default.extname(t).length>0,h=r.PATHEXT??r.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",m=n==="win32"?l?[""]:h.split(";").map(u=>u.trim()).filter(Boolean).map(u=>u.startsWith(".")?u:`.${u}`):[""];for(let u of a){let p=d__namespace.default.resolve(s,u);if(!(c&&Lt(p,s)))for(let g of m){let mt=k(g),gt=g.toUpperCase();for(let wt of [g,mt,gt]){let M=d__namespace.default.join(p,`${t}${wt}`);if(R(M))return M}}}return t}function kt(t){if(!R(t))return null;try{let e=fs.readFileSync(t,"utf8"),n=d__namespace.default.dirname(t),r=[];for(let i of e.matchAll(/"([^"\r\n]*)"/g)){let h=(i[1]??"").match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();if(!h)continue;let m=h.replace(/[\\/]+/g,d__namespace.default.sep).replace(/^[\\/]+/,""),u=d__namespace.default.resolve(n,m);R(u)&&r.push(u);}let s=[],c=new Map;for(let i of e.matchAll(/SET\s+"(\w+)=%~?dp0%?[\\/]?([^"]+)"/gi)){let a=i[1].toUpperCase(),l=i[2].trim().replace(/[\\/]+/g,d__namespace.default.sep).replace(/^[\\/]+/,"");c.set(a,d__namespace.default.resolve(n,l));}for(let i of e.split(/\r?\n/))if(i.includes("%*"))for(let a of i.matchAll(/"%(\w+)%"/g)){let l=c.get(a[1].toUpperCase());l&&R(l)&&s.push(l);}let o=i=>i.find(a=>{let l=k(d__namespace.default.basename(a));return l!=="node.exe"&&l!=="node"})??null;return o(s)??o(r)}catch{return null}}function It(t,e){if(typeof e=="string")return L(e)||null;if(!e||typeof e!="object")return null;if(t){let n=e[t],r=typeof n=="string"?L(n):void 0;if(r)return r}for(let n of Object.values(e)){let r=typeof n=="string"?L(n):void 0;if(r)return r}return null}function _t(t,e){if(!e)return null;let n=d__namespace.default.dirname(t),r=[d__namespace.default.resolve(n,"..",e),d__namespace.default.resolve(n,"node_modules",e)];for(let s of r){let c=d__namespace.default.join(s,"package.json");if(R(c))try{let o=JSON.parse(fs.readFileSync(c,"utf8")),i=It(e,o.bin);if(!i)continue;let a=d__namespace.default.resolve(s,i);if(R(a))return a}catch{}}return null}function Nt(t){let e=t.platform??process.platform,n=t.env??process.env,r=t.execPath??process.execPath,s=t.cwd,c=t.resolution;if(e!=="win32")return {command:V(t.command,{cwd:s,env:n,platform:e,resolution:c}),leadingArgv:[],resolution:"direct"};let o=V(t.command,{cwd:s,env:n,platform:e,resolution:c}),i=k(d__namespace.default.extname(o));if(i===".js"||i===".cjs"||i===".mjs")return {command:r,leadingArgv:[o],resolution:"node-entrypoint",windowsHide:true};if(i===".cmd"||i===".bat"){let a=kt(o)??_t(o,t.packageName);return a?k(d__namespace.default.extname(a))===".exe"?{command:a,leadingArgv:[],resolution:"exe-entrypoint",windowsHide:true}:{command:r,leadingArgv:[a],resolution:"node-entrypoint",windowsHide:true}:{command:o,leadingArgv:[],resolution:"unresolved-wrapper"}}return {command:o,leadingArgv:[],resolution:"direct"}}function Ot(t){if(t.candidate.resolution!=="unresolved-wrapper")return {command:t.candidate.command,leadingArgv:t.candidate.leadingArgv,resolution:t.candidate.resolution,windowsHide:t.candidate.windowsHide};throw new Error(`${d__namespace.default.basename(t.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function X(t){let e=Nt(t);return Ot({candidate:e})}function H(t,e){return {command:t.command,argv:[...t.leadingArgv,...e],resolution:t.resolution,shell:t.shell,windowsHide:t.windowsHide}}var G=3e4;function bt(t){if(typeof t.pid!="number"){t.kill();return}if(process.platform==="win32"){child_process.spawn("taskkill",["/pid",String(t.pid),"/t","/f"],{windowsHide:true}).on("error",()=>{});return}try{process.kill(-t.pid,"SIGKILL");}catch{t.kill("SIGKILL");}}var j=(t,e,n={})=>new Promise((r,s)=>{let c=n.env??process.env,o=process.platform,i;try{let p=X({command:t,platform:o,env:c,cwd:n.cwd,allowShellFallback:!1});i=H(p,e);}catch(p){s(p instanceof Error?p:new Error(String(p)));return}let a=child_process.spawn(i.command,i.argv,{cwd:n.cwd,env:c,shell:i.shell,windowsHide:i.windowsHide??true,detached:o!=="win32"}),l="",h="",m=false,u=setTimeout(()=>{m||(m=true,bt(a),s(new Error(`Command timed out after ${n.timeoutMs??G}ms: ${t} ${e.join(" ")}`)));},n.timeoutMs??G);a.stdout?.on("data",p=>{l+=p.toString();}),a.stderr?.on("data",p=>{h+=p.toString();}),a.on("error",p=>{m||(m=true,clearTimeout(u),s(p));}),a.on("close",p=>{m||(m=true,clearTimeout(u),r({code:p??0,stdout:l,stderr:h}));});});function Wt(){try{return (typeof O=="function"?O:module$1.createRequire(__filename)).resolve("@crewx/sdk/package.json")}catch{return null}}function Tt(){let t=[Wt(),d.join(__dirname,"../../package.json"),d.join(__dirname,"../../../package.json")].filter(e=>!!e);for(let e of t)try{let n=JSON.parse(fs.readFileSync(e,"utf8"));if(n.name==="@crewx/sdk"&&n.version)return n.version}catch{}return "0.0.0"}var K=Tt();var S=d__namespace.win32;function b(t){return S.join(t,".crewx")}function q(t){return S.join(b(t),"shortcut.json")}function Q(t){return S.join(b(t),"launcher.json")}function Y(t){return S.join(b(t),"bin","crewx-launcher.cmd")}function Z(t){return S.join(t,"CrewX.lnk")}function D(t,e){return S.normalize(t).toLowerCase()===S.normalize(e).toLowerCase()}var Mt="[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Environment]::GetFolderPath('DesktopDirectory')";async function tt(t){try{let n=await t.run("powershell",["-NoProfile","-NonInteractive","-Command",Mt],{env:t.env}),r=n.stdout.trim();if(n.code===0&&r)return {dir:r,source:"known-folder"}}catch{}let e=t.env.USERPROFILE||t.env.Userprofile||t.homedir();return e?{dir:S.join(e,"Desktop"),source:"fallback"}:null}function A(t,e){let n=S.resolve(e,"node_modules",".bin").toLowerCase();return t.split(";").filter(r=>r?S.resolve(r).toLowerCase()!==n:true).join(";")}function et(t){return t?/\\Program Files( \(x86\))?\\/i.test(t)&&/crewx/i.test(t):false}function Ft(t,e){let n=a=>{let[l,...h]=a.split("-"),m=h.join("-")||void 0;return {parts:(l??"").split(".").map(p=>Number.parseInt(p,10)||0),pre:m}},r=n(t),s=n(e),c=Math.max(r.parts.length,s.parts.length);for(let a=0;a<c;a++){let l=r.parts[a]??0,h=s.parts[a]??0;if(l!==h)return l<h?-1:1}if(r.pre===s.pre)return 0;if(!r.pre&&s.pre)return 1;if(r.pre&&!s.pre)return -1;let o=Number.parseInt(r.pre.match(/(\d+)$/)?.[1]??"",10),i=Number.parseInt(s.pre.match(/(\d+)$/)?.[1]??"",10);return !Number.isNaN(o)&&!Number.isNaN(i)&&o!==i?o<i?-1:1:r.pre<s.pre?-1:r.pre>s.pre?1:0}function v(t,e){return Ft(t,e)<0}var rt=d__namespace.win32,ot=1;function st(t,e){if(!t.existsSync(e))return null;try{let n=JSON.parse(t.readFileSync(e));return {schema:n.schema??ot,shortcutPath:n.shortcutPath,version:n.version,owned:!!n.owned,declined:!!n.declined,desktopSource:n.desktopSource,updatedAt:n.updatedAt}}catch{return null}}function I(t,e,n){let r={schema:ot,...n,updatedAt:new Date().toISOString()};t.mkdirSync(rt.dirname(e)),t.writeFileSync(e,JSON.stringify(r,null,2));}function _(t,e){if(!t.existsSync(e))return null;try{let n=JSON.parse(t.readFileSync(e));return {schema:n.schema??0,binPath:n.binPath,updatedAt:n.updatedAt}}catch{return null}}function it(t,e,n){t.mkdirSync(rt.dirname(e)),t.writeFileSync(e,JSON.stringify(n,null,2));}var $t=d__namespace.win32,y=1;function Vt(t){return t.replace(/%/g,"%%")}function Bt(t){return ["@echo off","setlocal DisableDelayedExpansion","chcp 65001 >nul","",'set "CREWX_WORKDIR=%USERPROFILE%\\crewx"','if not exist "%CREWX_WORKDIR%" mkdir "%CREWX_WORKDIR%" >nul 2>nul','cd /d "%CREWX_WORKDIR%"',"",'set "CREWX_PORT_EFFECTIVE=%CREWX_PORT%"','if "%CREWX_PORT_EFFECTIVE%"=="" set "CREWX_PORT_EFFECTIVE=8150"','set "CREWX_HEALTH_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/api/v1/health"','set "CREWX_ORIGIN_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/"',"",t.bakedBinPath?`set "CREWX_FALLBACK_BIN=${Vt(t.bakedBinPath)}"`:'set "CREWX_FALLBACK_BIN="','set "CREWX_RESOLVED_BIN=%CREWX_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" set "CREWX_RESOLVED_BIN=%CREWX_FALLBACK_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" (',` for /f "delims=" %%I in ('where crewx 2^>nul') do (`,' if not defined CREWX_RESOLVED_BIN set "CREWX_RESOLVED_BIN=%%I"'," )",")","",'powershell -NoProfile -NonInteractive -Command "try { $r = Invoke-WebRequest -Uri $env:CREWX_HEALTH_URL -TimeoutSec 1 -UseBasicParsing; if ($r.StatusCode -eq 200) { exit 0 } else { exit 1 } } catch { exit 1 }"',"if %ERRORLEVEL% EQU 0 (",' start "" "%CREWX_ORIGIN_URL%"'," exit /b 0",")","",'if "%CREWX_RESOLVED_BIN%"=="" ('," echo CrewX executable not found. Please reinstall the desktop shortcut."," pause"," exit /b 1",")","",'start "CrewX" /min "%CREWX_RESOLVED_BIN%"',""].join(`\r
|
|
2
|
+
`)}function ct(t){let e=_(t.fs,t.launcherManifestPath),n=!!e&&e.schema>=y&&t.fs.existsSync(t.wrapperPath),r=n&&!e.binPath&&!!t.bakedBinPath;if(n&&!r)return {wrapperPath:t.wrapperPath,wrote:false,schema:e.schema};let c=Bt({bakedBinPath:t.bakedBinPath});try{t.fs.mkdirSync($t.dirname(t.wrapperPath)),t.fs.writeFileSync(t.wrapperPath,c),it(t.fs,t.launcherManifestPath,{schema:y,binPath:t.bakedBinPath,updatedAt:new Date().toISOString()});}catch(o){throw o instanceof f?o:new f("WRITE_DENIED",`Could not write launcher wrapper: ${o instanceof Error?o.message:String(o)}`)}return {wrapperPath:t.wrapperPath,wrote:true,schema:y}}var Xt=["$ws = New-Object -ComObject WScript.Shell","$sc = $ws.CreateShortcut($env:CREWX_LNK_PATH)","$sc.TargetPath = $env:CREWX_LNK_TARGET","if ($env:CREWX_LNK_WORKDIR) { $sc.WorkingDirectory = $env:CREWX_LNK_WORKDIR }","$sc.WindowStyle = 7","if ($env:CREWX_LNK_ICON) { $sc.IconLocation = $env:CREWX_LNK_ICON }","$sc.Save()"].join("; "),Ht=["[Console]::OutputEncoding = [System.Text.Encoding]::UTF8","$ws = New-Object -ComObject WScript.Shell","$sc = $ws.CreateShortcut($env:CREWX_LNK_PATH)","[PSCustomObject]@{ TargetPath = $sc.TargetPath; WorkingDirectory = $sc.WorkingDirectory; IconLocation = $sc.IconLocation } | ConvertTo-Json -Compress"].join("; ");async function lt(t){let e={...t.env,CREWX_LNK_PATH:t.shortcutPath,CREWX_LNK_TARGET:t.targetPath,CREWX_LNK_WORKDIR:t.workingDirectory??"",CREWX_LNK_ICON:t.iconPath??""},n;try{n=await t.run("powershell",["-NoProfile","-NonInteractive","-Command",Xt],{env:e});}catch(r){throw new f("POWERSHELL_UNAVAILABLE",`Could not run PowerShell: ${r instanceof Error?r.message:String(r)}`)}if(n.code!==0)throw new f("POWERSHELL_UNAVAILABLE",`Failed to create desktop shortcut: ${n.stderr||n.stdout}`)}function ut(t){let e=t.trim(),n=e.lastIndexOf(",");return n!==-1&&/^-?\d+$/.test(e.slice(n+1).trim())&&(e=e.slice(0,n).trim()),e.length>=2&&e.startsWith('"')&&e.endsWith('"')&&(e=e.slice(1,-1).trim()),e}async function dt(t){try{let e={...t.env,CREWX_LNK_PATH:t.shortcutPath},n=await t.run("powershell",["-NoProfile","-NonInteractive","-Command",Ht],{env:e});if(n.code!==0||!n.stdout.trim())return null;let r=JSON.parse(n.stdout.trim());return {targetPath:r.TargetPath??"",workingDirectory:r.WorkingDirectory??"",iconLocation:r.IconLocation??""}}catch{return null}}var T=d__namespace.win32;async function C(t){let e=A(t.env.PATH??t.env.Path??"",t.cwd),n={...t.env,PATH:e,Path:e},r;try{r=await t.run("npm",["list","-g","crewx","--depth=0","--json"],{env:n});}catch{return {installed:false}}let s;try{s=JSON.parse(r.stdout||"{}");}catch{return {installed:false}}let c=s.dependencies?.crewx;if(!c?.version)return {installed:false};let o;try{let a=await t.run("npm",["prefix","-g"],{env:n});a.code===0&&(o=a.stdout.trim()||void 0);}catch{}let i=o?T.join(o,"crewx.cmd"):void 0;return {installed:true,version:c.version,binPath:i,prefix:o}}var Gt=/EACCES|EPERM|EROFS/,Ut=/ENOTFOUND|ETIMEDOUT|ECONNREFUSED|network|registry/i,jt=/^\d+\.\d+\.\d+/;function Jt(t){return !!t&&t!=="0.0.0"&&jt.test(t)}var W=10*6e4;async function ft(t){if(!Jt(t.targetVersion))throw new f("GLOBAL_INSTALL_FAILED",`RUNNING_VERSION_UNKNOWN: cannot reliably determine the running crewx version to install (got ${JSON.stringify(t.targetVersion)}); refusing to fall back to crewx@latest`);if(t.currentInfo?.installed&&t.currentInfo.version&&!v(t.currentInfo.version,t.targetVersion))return {info:t.currentInfo};let e=A(t.env.PATH??t.env.Path??"",t.cwd),n={...t.env,PATH:e,Path:e},r=`crewx@${t.targetVersion}`;t.onProgress?.({phase:"global-install",message:`Installing crewx globally (npm install -g ${r})`});let s;try{s=await t.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:n,timeoutMs:W});}catch(o){throw new f("NPM_UNAVAILABLE",`Could not run npm: ${o instanceof Error?o.message:String(o)}`)}if(s.code===0)return {info:await C({env:n,cwd:t.cwd,run:t.run})};let c=`${s.stdout}
|
|
3
|
+
${s.stderr}`;if(Gt.test(c)){t.onProgress?.({phase:"global-install",message:"Permission denied \u2014 retrying with a user-scoped npm prefix"});let o=t.env.LOCALAPPDATA||T.join(t.env.USERPROFILE??"","AppData","Local"),i={...n,npm_config_prefix:T.join(o,"crewx","npm")},a;try{a=await t.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:i,timeoutMs:W});}catch(l){throw new f("NPM_PERMISSION_DENIED",`Retry with user-scoped prefix failed: ${l instanceof Error?l.message:String(l)}`)}if(a.code===0)return {info:await C({env:i,cwd:t.cwd,run:t.run})};throw new f("NPM_PERMISSION_DENIED",`npm install -g failed after user-scoped prefix retry: ${a.stderr||a.stdout}`)}if(Ut.test(c)){if(!t.installRoot)throw new f("OFFLINE_NO_SOURCE","The npm registry is unreachable and no local installRoot was provided for an offline install");t.onProgress?.({phase:"global-install",message:`Registry unreachable \u2014 installing offline from ${t.installRoot}`});let o;try{o=await t.run("npm",["install","-g",t.installRoot,"--offline","--no-audit","--no-fund"],{env:n,timeoutMs:W});}catch(i){throw new f("GLOBAL_INSTALL_FAILED",`Offline install failed: ${i instanceof Error?i.message:String(i)}`)}if(o.code===0)return {info:await C({env:n,cwd:t.cwd,run:t.run})};throw new f("GLOBAL_INSTALL_FAILED",`Offline install failed: ${o.stderr||o.stdout}`)}throw new f("GLOBAL_INSTALL_FAILED",c.trim()||`npm install -g ${r} failed`)}function Kt(t){return t.run??j}function zt(t){return t.fs??F}async function N(t){let e=t.platform??process.platform,n=t.env??process.env,r=t.homedir??$,s=Kt(t),c=zt(t),o=t.runningVersion??K,i=t.cwd??process.cwd(),a=r(),l=q(a),h=Q(a),m=Y(a),u=null;e==="win32"&&(u=await tt({env:n,homedir:r,run:s}));let p=u?Z(u.dir):null;return {platform:e,env:n,homedir:r,run:s,fs:c,runningVersion:o,cwd:i,installRoot:t.installRoot,shortcutManifestPath:l,launcherManifestPath:h,wrapperPath:m,desktop:u,shortcutPath:p}}function qt(t){return t?d__namespace.win32.normalize(t).toLowerCase().endsWith(`${d__namespace.win32.sep}bin${d__namespace.win32.sep}crewx.ico`):false}async function P(t){if(t.platform!=="win32")return {supported:false,state:"unsupported",globalCrewx:null,runningVersion:t.runningVersion,errors:[],manifest:null,iconStale:false};let e=[];t.desktop||e.push("NO_DESKTOP_DIR: could not resolve the Windows Desktop directory");let n=st(t.fs,t.shortcutManifestPath),r=_(t.fs,t.launcherManifestPath),s=await C({env:t.env,cwd:t.cwd,run:t.run}),c=t.shortcutPath?t.fs.existsSync(t.shortcutPath):false,o,i=false;if(!c)o=n?.declined?"declined":"not-installed";else {let a=!!n?.owned&&!!t.shortcutPath&&n.shortcutPath===t.shortcutPath,l=false,h=t.shortcutPath?await dt({run:t.run,env:t.env,shortcutPath:t.shortcutPath}):null;if(a||(h&&D(h.targetPath,t.wrapperPath)?a=true:h&&et(h.targetPath)&&(l=true)),l)o="foreign",e.push("NSIS_PRESENT: an NSIS-installed CrewX shortcut was detected");else if(!a)o="foreign";else if(n?.version&&v(t.runningVersion,n.version))o="superseded",e.push(`SUPERSEDED: running version ${t.runningVersion} is older than the installed shortcut's version ${n.version}; refusing to modify it`);else {let m=!r||r.schema<y||!t.fs.existsSync(t.wrapperPath);if(h){let u=ut(h.iconLocation);if(!(!!u&&t.fs.existsSync(u)))i=true;else {let g=ht(s,t.fs);g?i=!D(u,g):i=!qt(u);}}o=m||i?"stale":"installed";}}return {supported:true,state:o,shortcutPath:t.shortcutPath??void 0,desktopDir:t.desktop?.dir,desktopSource:t.desktop?.source,wrapperPath:t.wrapperPath,wrapperSchema:r?.schema,globalCrewx:s.installed?s:{installed:false},runningVersion:t.runningVersion,errors:e,manifest:n,iconStale:i}}function ht(t,e){if(!t?.installed||!t.prefix)return;let n=d__namespace.win32.join(t.prefix,"node_modules","crewx","bin","crewx.ico");return e.existsSync(n)?n:void 0}function E(t){let{manifest:e,iconStale:n,...r}=t;return r}async function Qt(t={}){let e=await N(t),n=await P(e);return E(n)}async function Yt(t={}){let e=await N(t);t.onProgress?.({phase:"detect",message:"Checking current shortcut status"});let n=await P(e),r=E(n);if(!r.supported)return {...r,changed:false,installedGlobal:false};if(r.state==="superseded")return {...r,changed:false,installedGlobal:false};if(r.state==="foreign"){if(n.errors.some(g=>g.startsWith("NSIS_PRESENT")))throw new f("NSIS_PRESENT",`An NSIS-installed CrewX shortcut was detected at ${r.shortcutPath}`);if(!t.force)throw new f("FOREIGN_SHORTCUT",`An existing shortcut at ${r.shortcutPath} is not managed by CrewX`)}if(!e.desktop||!e.shortcutPath)throw new f("NO_DESKTOP_DIR","Could not resolve the Windows Desktop directory");let s=false,c=false,o=r.globalCrewx,i=[];if(!!o?.installed&&!!o.version&&v(o.version,e.runningVersion)||!o?.installed&&r.state!=="installed"){let g=await ft({env:e.env,cwd:e.cwd,run:e.run,targetVersion:e.runningVersion,currentInfo:o??void 0,installRoot:e.installRoot,onProgress:t.onProgress});o=g.info,c=g.info.installed,s=true,c||i.push(`GLOBAL_INSTALL_UNCONFIRMED: npm install -g crewx@${e.runningVersion} exited successfully but a follow-up check could not confirm the global install`);}if(t.onProgress?.({phase:"wrapper",message:"Ensuring launcher wrapper"}),ct({fs:e.fs,wrapperPath:e.wrapperPath,launcherManifestPath:e.launcherManifestPath,bakedBinPath:o?.binPath}).wrote&&(s=true),!((r.state==="installed"||r.state==="stale")&&!n.iconStale)){let g=ht(o,e.fs);if(n.iconStale&&!g)throw new f("ICON_UNAVAILABLE",`Could not locate the global CrewX icon (bin\\crewx.ico) to repair the desktop shortcut at ${e.shortcutPath}; the existing shortcut was left untouched`);t.onProgress?.({phase:"lnk",message:"Creating desktop shortcut"}),await lt({run:e.run,env:e.env,shortcutPath:e.shortcutPath,targetPath:e.wrapperPath,iconPath:g}),s=true;}s&&I(e.fs,e.shortcutManifestPath,{shortcutPath:e.shortcutPath,version:e.runningVersion,owned:true,declined:false,desktopSource:e.desktop.source});let u=await P(e),p=E(u);return {...p,errors:[...p.errors,...i],changed:s,installedGlobal:c}}async function Zt(t={}){let e=await N(t),n=await P(e),r=E(n);if(!r.supported)return r;if((r.state==="installed"||r.state==="stale")&&e.shortcutPath)try{e.fs.unlinkSync(e.shortcutPath);}catch{}I(e.fs,e.shortcutManifestPath,{shortcutPath:void 0,version:n.manifest?.version,owned:false,declined:true,desktopSource:void 0});let s=await P(e);return E(s)}async function te(t={}){let e=await N(t),n=await P(e),r=E(n);if(!r.supported)return r;I(e.fs,e.shortcutManifestPath,{shortcutPath:n.manifest?.shortcutPath,version:n.manifest?.version,owned:n.manifest?.owned??false,declined:true,desktopSource:n.manifest?.desktopSource});let s=await P(e);return E(s)}exports.ShortcutError=f;exports.dismissShortcutNotice=te;exports.getShortcutStatus=Qt;exports.installShortcut=Yt;exports.uninstallShortcut=Zt;
|
package/dist/desktop/lnk.d.ts
CHANGED
package/dist/desktop/types.d.ts
CHANGED
|
@@ -59,7 +59,7 @@ export interface InstallShortcutOptions extends ShortcutEnvOptions {
|
|
|
59
59
|
onProgress?: (event: ShortcutProgressEvent) => void;
|
|
60
60
|
installRoot?: string;
|
|
61
61
|
}
|
|
62
|
-
export type ShortcutErrorCode = 'NOT_WINDOWS' | 'NO_DESKTOP_DIR' | 'NPM_UNAVAILABLE' | 'NPM_PERMISSION_DENIED' | 'OFFLINE_NO_SOURCE' | 'GLOBAL_INSTALL_FAILED' | 'POWERSHELL_UNAVAILABLE' | 'WRITE_DENIED' | 'FOREIGN_SHORTCUT' | 'NSIS_PRESENT';
|
|
62
|
+
export type ShortcutErrorCode = 'NOT_WINDOWS' | 'NO_DESKTOP_DIR' | 'NPM_UNAVAILABLE' | 'NPM_PERMISSION_DENIED' | 'OFFLINE_NO_SOURCE' | 'GLOBAL_INSTALL_FAILED' | 'POWERSHELL_UNAVAILABLE' | 'WRITE_DENIED' | 'FOREIGN_SHORTCUT' | 'NSIS_PRESENT' | 'ICON_UNAVAILABLE';
|
|
63
63
|
export declare class ShortcutError extends Error {
|
|
64
64
|
readonly code: ShortcutErrorCode;
|
|
65
65
|
constructor(code: ShortcutErrorCode, message: string);
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import*as d from'path';import d__default,{join}from'path';import {fileURLToPath}from'url';import {readFileSync,unlinkSync,mkdirSync,writeFileSync,existsSync,statSync}from'fs';import {homedir}from'os';import {spawn}from'child_process';import {createRequire}from'module';var O=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var T=()=>fileURLToPath(import.meta.url),Et=()=>d__default.dirname(T()),w=Et(),g=T();var p=class extends Error{code;constructor(e,n){super(`${e}: ${n}`),this.code=e,this.name="ShortcutError";}};var M={existsSync:t=>existsSync(t),readFileSync:t=>readFileSync(t,"utf8"),writeFileSync:(t,e)=>writeFileSync(t,e,"utf8"),mkdirSync:t=>{mkdirSync(t,{recursive:true});},unlinkSync:t=>{unlinkSync(t);}},F=homedir;function C(t){return typeof t!="string"?void 0:t.trim()||void 0}function x(t){return C(t)?.toLowerCase()??""}function R(t){try{return statSync(t).isFile()}catch{return false}}function Lt(t,e){if(t===e)return true;let n=d__default.relative(t,e);return n!==""&&!n.startsWith("..")&&!d__default.isAbsolute(n)}function Nt(t,e){if(d__default.basename(t)!==".bin")return false;let n=d__default.dirname(t);if(d__default.basename(n)!=="node_modules")return false;let r=d__default.dirname(n);return Lt(r,e)}function B(t,e={}){if(t.includes("/")||t.includes("\\")||d__default.isAbsolute(t))return t;let n=e.platform??process.platform,r=e.env??process.env,s=d__default.resolve(e.cwd??process.cwd()),c=(e.resolution??"global_first")==="global_first",o=r.PATH??r.Path??process.env.PATH??process.env.Path??"",i=n==="win32"?";":":",a=o.split(i).map(u=>u.trim()).filter(Boolean),l=d__default.extname(t).length>0,m=r.PATHEXT??r.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",h=n==="win32"?l?[""]:m.split(";").map(u=>u.trim()).filter(Boolean).map(u=>u.startsWith(".")?u:`.${u}`):[""];for(let u of a){let f=d__default.resolve(s,u);if(!(c&&Nt(f,s)))for(let N of h){let mt=x(N),wt=N.toUpperCase();for(let gt of [N,mt,wt]){let A=d__default.join(f,`${t}${gt}`);if(R(A))return A}}}return t}function Ot(t){if(!R(t))return null;try{let e=readFileSync(t,"utf8"),n=d__default.dirname(t),r=[];for(let i of e.matchAll(/"([^"\r\n]*)"/g)){let m=(i[1]??"").match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();if(!m)continue;let h=m.replace(/[\\/]+/g,d__default.sep).replace(/^[\\/]+/,""),u=d__default.resolve(n,h);R(u)&&r.push(u);}let s=[],c=new Map;for(let i of e.matchAll(/SET\s+"(\w+)=%~?dp0%?[\\/]?([^"]+)"/gi)){let a=i[1].toUpperCase(),l=i[2].trim().replace(/[\\/]+/g,d__default.sep).replace(/^[\\/]+/,"");c.set(a,d__default.resolve(n,l));}for(let i of e.split(/\r?\n/))if(i.includes("%*"))for(let a of i.matchAll(/"%(\w+)%"/g)){let l=c.get(a[1].toUpperCase());l&&R(l)&&s.push(l);}let o=i=>i.find(a=>{let l=x(d__default.basename(a));return l!=="node.exe"&&l!=="node"})??null;return o(s)??o(r)}catch{return null}}function It(t,e){if(typeof e=="string")return C(e)||null;if(!e||typeof e!="object")return null;if(t){let n=e[t],r=typeof n=="string"?C(n):void 0;if(r)return r}for(let n of Object.values(e)){let r=typeof n=="string"?C(n):void 0;if(r)return r}return null}function bt(t,e){if(!e)return null;let n=d__default.dirname(t),r=[d__default.resolve(n,"..",e),d__default.resolve(n,"node_modules",e)];for(let s of r){let c=d__default.join(s,"package.json");if(R(c))try{let o=JSON.parse(readFileSync(c,"utf8")),i=It(e,o.bin);if(!i)continue;let a=d__default.resolve(s,i);if(R(a))return a}catch{}}return null}function Dt(t){let e=t.platform??process.platform,n=t.env??process.env,r=t.execPath??process.execPath,s=t.cwd,c=t.resolution;if(e!=="win32")return {command:B(t.command,{cwd:s,env:n,platform:e,resolution:c}),leadingArgv:[],resolution:"direct"};let o=B(t.command,{cwd:s,env:n,platform:e,resolution:c}),i=x(d__default.extname(o));if(i===".js"||i===".cjs"||i===".mjs")return {command:r,leadingArgv:[o],resolution:"node-entrypoint",windowsHide:true};if(i===".cmd"||i===".bat"){let a=Ot(o)??bt(o,t.packageName);return a?x(d__default.extname(a))===".exe"?{command:a,leadingArgv:[],resolution:"exe-entrypoint",windowsHide:true}:{command:r,leadingArgv:[a],resolution:"node-entrypoint",windowsHide:true}:{command:o,leadingArgv:[],resolution:"unresolved-wrapper"}}return {command:o,leadingArgv:[],resolution:"direct"}}function Wt(t){if(t.candidate.resolution!=="unresolved-wrapper")return {command:t.candidate.command,leadingArgv:t.candidate.leadingArgv,resolution:t.candidate.resolution,windowsHide:t.candidate.windowsHide};throw new Error(`${d__default.basename(t.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function X(t){let e=Dt(t);return Wt({candidate:e})}function V(t,e){return {command:t.command,argv:[...t.leadingArgv,...e],resolution:t.resolution,shell:t.shell,windowsHide:t.windowsHide}}var H=3e4;function At(t){if(typeof t.pid!="number"){t.kill();return}if(process.platform==="win32"){spawn("taskkill",["/pid",String(t.pid),"/t","/f"],{windowsHide:true}).on("error",()=>{});return}try{process.kill(-t.pid,"SIGKILL");}catch{t.kill("SIGKILL");}}var j=(t,e,n={})=>new Promise((r,s)=>{let c=n.env??process.env,o=process.platform,i;try{let f=X({command:t,platform:o,env:c,cwd:n.cwd,allowShellFallback:!1});i=V(f,e);}catch(f){s(f instanceof Error?f:new Error(String(f)));return}let a=spawn(i.command,i.argv,{cwd:n.cwd,env:c,shell:i.shell,windowsHide:i.windowsHide??true,detached:o!=="win32"}),l="",m="",h=false,u=setTimeout(()=>{h||(h=true,At(a),s(new Error(`Command timed out after ${n.timeoutMs??H}ms: ${t} ${e.join(" ")}`)));},n.timeoutMs??H);a.stdout?.on("data",f=>{l+=f.toString();}),a.stderr?.on("data",f=>{m+=f.toString();}),a.on("error",f=>{h||(h=true,clearTimeout(u),s(f));}),a.on("close",f=>{h||(h=true,clearTimeout(u),r({code:f??0,stdout:l,stderr:m}));});});function Ft(){try{return (typeof O=="function"?O:createRequire(g)).resolve("@crewx/sdk/package.json")}catch{return null}}function Bt(){let t=[Ft(),join(w,"../../package.json"),join(w,"../../../package.json")].filter(e=>!!e);for(let e of t)try{let n=JSON.parse(readFileSync(e,"utf8"));if(n.name==="@crewx/sdk"&&n.version)return n.version}catch{}return "0.0.0"}var J=Bt();var S=d.win32;function I(t){return S.join(t,".crewx")}function z(t){return S.join(I(t),"shortcut.json")}function q(t){return S.join(I(t),"launcher.json")}function Q(t){return S.join(I(t),"bin","crewx-launcher.cmd")}function Y(t){return S.join(t,"CrewX.lnk")}function Z(t,e){return S.normalize(t).toLowerCase()===S.normalize(e).toLowerCase()}var $t="[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Environment]::GetFolderPath('DesktopDirectory')";async function tt(t){try{let n=await t.run("powershell",["-NoProfile","-NonInteractive","-Command",$t],{env:t.env}),r=n.stdout.trim();if(n.code===0&&r)return {dir:r,source:"known-folder"}}catch{}let e=t.env.USERPROFILE||t.env.Userprofile||t.homedir();return e?{dir:S.join(e,"Desktop"),source:"fallback"}:null}function b(t,e){let n=S.resolve(e,"node_modules",".bin").toLowerCase();return t.split(";").filter(r=>r?S.resolve(r).toLowerCase()!==n:true).join(";")}function et(t){return t?/\\Program Files( \(x86\))?\\/i.test(t)&&/crewx/i.test(t):false}function Xt(t,e){let n=a=>{let[l,...m]=a.split("-"),h=m.join("-")||void 0;return {parts:(l??"").split(".").map(f=>Number.parseInt(f,10)||0),pre:h}},r=n(t),s=n(e),c=Math.max(r.parts.length,s.parts.length);for(let a=0;a<c;a++){let l=r.parts[a]??0,m=s.parts[a]??0;if(l!==m)return l<m?-1:1}if(r.pre===s.pre)return 0;if(!r.pre&&s.pre)return 1;if(r.pre&&!s.pre)return -1;let o=Number.parseInt(r.pre.match(/(\d+)$/)?.[1]??"",10),i=Number.parseInt(s.pre.match(/(\d+)$/)?.[1]??"",10);return !Number.isNaN(o)&&!Number.isNaN(i)&&o!==i?o<i?-1:1:r.pre<s.pre?-1:r.pre>s.pre?1:0}function nt(t,e){return Xt(t,e)<0}var ot=d.win32,st=1;function it(t,e){if(!t.existsSync(e))return null;try{let n=JSON.parse(t.readFileSync(e));return {schema:n.schema??st,shortcutPath:n.shortcutPath,version:n.version,owned:!!n.owned,declined:!!n.declined,desktopSource:n.desktopSource,updatedAt:n.updatedAt}}catch{return null}}function k(t,e,n){let r={schema:st,...n,updatedAt:new Date().toISOString()};t.mkdirSync(ot.dirname(e)),t.writeFileSync(e,JSON.stringify(r,null,2));}function _(t,e){if(!t.existsSync(e))return null;try{let n=JSON.parse(t.readFileSync(e));return {schema:n.schema??0,binPath:n.binPath,updatedAt:n.updatedAt}}catch{return null}}function at(t,e,n){t.mkdirSync(ot.dirname(e)),t.writeFileSync(e,JSON.stringify(n,null,2));}var Vt=d.win32,v=1;function Ht(t){return t.replace(/%/g,"%%")}function Gt(t){return ["@echo off","setlocal DisableDelayedExpansion","chcp 65001 >nul","",'set "CREWX_WORKDIR=%USERPROFILE%\\crewx"','if not exist "%CREWX_WORKDIR%" mkdir "%CREWX_WORKDIR%" >nul 2>nul','cd /d "%CREWX_WORKDIR%"',"",'set "CREWX_PORT_EFFECTIVE=%CREWX_PORT%"','if "%CREWX_PORT_EFFECTIVE%"=="" set "CREWX_PORT_EFFECTIVE=8150"','set "CREWX_HEALTH_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/api/v1/health"','set "CREWX_ORIGIN_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/"',"",t.bakedBinPath?`set "CREWX_FALLBACK_BIN=${Ht(t.bakedBinPath)}"`:'set "CREWX_FALLBACK_BIN="','set "CREWX_RESOLVED_BIN=%CREWX_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" set "CREWX_RESOLVED_BIN=%CREWX_FALLBACK_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" (',` for /f "delims=" %%I in ('where crewx 2^>nul') do (`,' if not defined CREWX_RESOLVED_BIN set "CREWX_RESOLVED_BIN=%%I"'," )",")","",'powershell -NoProfile -NonInteractive -Command "try { $r = Invoke-WebRequest -Uri $env:CREWX_HEALTH_URL -TimeoutSec 1 -UseBasicParsing; if ($r.StatusCode -eq 200) { exit 0 } else { exit 1 } } catch { exit 1 }"',"if %ERRORLEVEL% EQU 0 (",' start "" "%CREWX_ORIGIN_URL%"'," exit /b 0",")","",'if "%CREWX_RESOLVED_BIN%"=="" ('," echo CrewX executable not found. Please reinstall the desktop shortcut."," pause"," exit /b 1",")","",'start "CrewX" /min "%CREWX_RESOLVED_BIN%"',""].join(`\r
|
|
2
|
-
`)}function
|
|
3
|
-
${
|
|
1
|
+
import*as d from'path';import d__default,{join}from'path';import {fileURLToPath}from'url';import {readFileSync,unlinkSync,mkdirSync,writeFileSync,existsSync,statSync}from'fs';import {homedir}from'os';import {spawn}from'child_process';import {createRequire}from'module';var b=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var $=()=>fileURLToPath(import.meta.url),vt=()=>d__default.dirname($()),w=vt(),S=$();var f=class extends Error{code;constructor(e,n){super(`${e}: ${n}`),this.code=e,this.name="ShortcutError";}};var V={existsSync:t=>existsSync(t),readFileSync:t=>readFileSync(t,"utf8"),writeFileSync:(t,e)=>writeFileSync(t,e,"utf8"),mkdirSync:t=>{mkdirSync(t,{recursive:true});},unlinkSync:t=>{unlinkSync(t);}},B=homedir;function k(t){return typeof t!="string"?void 0:t.trim()||void 0}function I(t){return k(t)?.toLowerCase()??""}function v(t){try{return statSync(t).isFile()}catch{return false}}function _t(t,e){if(t===e)return true;let n=d__default.relative(t,e);return n!==""&&!n.startsWith("..")&&!d__default.isAbsolute(n)}function Ot(t,e){if(d__default.basename(t)!==".bin")return false;let n=d__default.dirname(t);if(d__default.basename(n)!=="node_modules")return false;let r=d__default.dirname(n);return _t(r,e)}function X(t,e={}){if(t.includes("/")||t.includes("\\")||d__default.isAbsolute(t))return t;let n=e.platform??process.platform,r=e.env??process.env,s=d__default.resolve(e.cwd??process.cwd()),c=(e.resolution??"global_first")==="global_first",o=r.PATH??r.Path??process.env.PATH??process.env.Path??"",i=n==="win32"?";":":",a=o.split(i).map(u=>u.trim()).filter(Boolean),l=d__default.extname(t).length>0,h=r.PATHEXT??r.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",m=n==="win32"?l?[""]:h.split(";").map(u=>u.trim()).filter(Boolean).map(u=>u.startsWith(".")?u:`.${u}`):[""];for(let u of a){let p=d__default.resolve(s,u);if(!(c&&Ot(p,s)))for(let g of m){let wt=I(g),St=g.toUpperCase();for(let Pt of [g,wt,St]){let F=d__default.join(p,`${t}${Pt}`);if(v(F))return F}}}return t}function bt(t){if(!v(t))return null;try{let e=readFileSync(t,"utf8"),n=d__default.dirname(t),r=[];for(let i of e.matchAll(/"([^"\r\n]*)"/g)){let h=(i[1]??"").match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();if(!h)continue;let m=h.replace(/[\\/]+/g,d__default.sep).replace(/^[\\/]+/,""),u=d__default.resolve(n,m);v(u)&&r.push(u);}let s=[],c=new Map;for(let i of e.matchAll(/SET\s+"(\w+)=%~?dp0%?[\\/]?([^"]+)"/gi)){let a=i[1].toUpperCase(),l=i[2].trim().replace(/[\\/]+/g,d__default.sep).replace(/^[\\/]+/,"");c.set(a,d__default.resolve(n,l));}for(let i of e.split(/\r?\n/))if(i.includes("%*"))for(let a of i.matchAll(/"%(\w+)%"/g)){let l=c.get(a[1].toUpperCase());l&&v(l)&&s.push(l);}let o=i=>i.find(a=>{let l=I(d__default.basename(a));return l!=="node.exe"&&l!=="node"})??null;return o(s)??o(r)}catch{return null}}function Dt(t,e){if(typeof e=="string")return k(e)||null;if(!e||typeof e!="object")return null;if(t){let n=e[t],r=typeof n=="string"?k(n):void 0;if(r)return r}for(let n of Object.values(e)){let r=typeof n=="string"?k(n):void 0;if(r)return r}return null}function At(t,e){if(!e)return null;let n=d__default.dirname(t),r=[d__default.resolve(n,"..",e),d__default.resolve(n,"node_modules",e)];for(let s of r){let c=d__default.join(s,"package.json");if(v(c))try{let o=JSON.parse(readFileSync(c,"utf8")),i=Dt(e,o.bin);if(!i)continue;let a=d__default.resolve(s,i);if(v(a))return a}catch{}}return null}function Wt(t){let e=t.platform??process.platform,n=t.env??process.env,r=t.execPath??process.execPath,s=t.cwd,c=t.resolution;if(e!=="win32")return {command:X(t.command,{cwd:s,env:n,platform:e,resolution:c}),leadingArgv:[],resolution:"direct"};let o=X(t.command,{cwd:s,env:n,platform:e,resolution:c}),i=I(d__default.extname(o));if(i===".js"||i===".cjs"||i===".mjs")return {command:r,leadingArgv:[o],resolution:"node-entrypoint",windowsHide:true};if(i===".cmd"||i===".bat"){let a=bt(o)??At(o,t.packageName);return a?I(d__default.extname(a))===".exe"?{command:a,leadingArgv:[],resolution:"exe-entrypoint",windowsHide:true}:{command:r,leadingArgv:[a],resolution:"node-entrypoint",windowsHide:true}:{command:o,leadingArgv:[],resolution:"unresolved-wrapper"}}return {command:o,leadingArgv:[],resolution:"direct"}}function Tt(t){if(t.candidate.resolution!=="unresolved-wrapper")return {command:t.candidate.command,leadingArgv:t.candidate.leadingArgv,resolution:t.candidate.resolution,windowsHide:t.candidate.windowsHide};throw new Error(`${d__default.basename(t.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function G(t){let e=Wt(t);return Tt({candidate:e})}function U(t,e){return {command:t.command,argv:[...t.leadingArgv,...e],resolution:t.resolution,shell:t.shell,windowsHide:t.windowsHide}}var j=3e4;function Mt(t){if(typeof t.pid!="number"){t.kill();return}if(process.platform==="win32"){spawn("taskkill",["/pid",String(t.pid),"/t","/f"],{windowsHide:true}).on("error",()=>{});return}try{process.kill(-t.pid,"SIGKILL");}catch{t.kill("SIGKILL");}}var K=(t,e,n={})=>new Promise((r,s)=>{let c=n.env??process.env,o=process.platform,i;try{let p=G({command:t,platform:o,env:c,cwd:n.cwd,allowShellFallback:!1});i=U(p,e);}catch(p){s(p instanceof Error?p:new Error(String(p)));return}let a=spawn(i.command,i.argv,{cwd:n.cwd,env:c,shell:i.shell,windowsHide:i.windowsHide??true,detached:o!=="win32"}),l="",h="",m=false,u=setTimeout(()=>{m||(m=true,Mt(a),s(new Error(`Command timed out after ${n.timeoutMs??j}ms: ${t} ${e.join(" ")}`)));},n.timeoutMs??j);a.stdout?.on("data",p=>{l+=p.toString();}),a.stderr?.on("data",p=>{h+=p.toString();}),a.on("error",p=>{m||(m=true,clearTimeout(u),s(p));}),a.on("close",p=>{m||(m=true,clearTimeout(u),r({code:p??0,stdout:l,stderr:h}));});});function Vt(){try{return (typeof b=="function"?b:createRequire(S)).resolve("@crewx/sdk/package.json")}catch{return null}}function Bt(){let t=[Vt(),join(w,"../../package.json"),join(w,"../../../package.json")].filter(e=>!!e);for(let e of t)try{let n=JSON.parse(readFileSync(e,"utf8"));if(n.name==="@crewx/sdk"&&n.version)return n.version}catch{}return "0.0.0"}var q=Bt();var P=d.win32;function D(t){return P.join(t,".crewx")}function Y(t){return P.join(D(t),"shortcut.json")}function Z(t){return P.join(D(t),"launcher.json")}function tt(t){return P.join(D(t),"bin","crewx-launcher.cmd")}function et(t){return P.join(t,"CrewX.lnk")}function A(t,e){return P.normalize(t).toLowerCase()===P.normalize(e).toLowerCase()}var Xt="[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Environment]::GetFolderPath('DesktopDirectory')";async function nt(t){try{let n=await t.run("powershell",["-NoProfile","-NonInteractive","-Command",Xt],{env:t.env}),r=n.stdout.trim();if(n.code===0&&r)return {dir:r,source:"known-folder"}}catch{}let e=t.env.USERPROFILE||t.env.Userprofile||t.homedir();return e?{dir:P.join(e,"Desktop"),source:"fallback"}:null}function W(t,e){let n=P.resolve(e,"node_modules",".bin").toLowerCase();return t.split(";").filter(r=>r?P.resolve(r).toLowerCase()!==n:true).join(";")}function rt(t){return t?/\\Program Files( \(x86\))?\\/i.test(t)&&/crewx/i.test(t):false}function Ht(t,e){let n=a=>{let[l,...h]=a.split("-"),m=h.join("-")||void 0;return {parts:(l??"").split(".").map(p=>Number.parseInt(p,10)||0),pre:m}},r=n(t),s=n(e),c=Math.max(r.parts.length,s.parts.length);for(let a=0;a<c;a++){let l=r.parts[a]??0,h=s.parts[a]??0;if(l!==h)return l<h?-1:1}if(r.pre===s.pre)return 0;if(!r.pre&&s.pre)return 1;if(r.pre&&!s.pre)return -1;let o=Number.parseInt(r.pre.match(/(\d+)$/)?.[1]??"",10),i=Number.parseInt(s.pre.match(/(\d+)$/)?.[1]??"",10);return !Number.isNaN(o)&&!Number.isNaN(i)&&o!==i?o<i?-1:1:r.pre<s.pre?-1:r.pre>s.pre?1:0}function y(t,e){return Ht(t,e)<0}var st=d.win32,it=1;function at(t,e){if(!t.existsSync(e))return null;try{let n=JSON.parse(t.readFileSync(e));return {schema:n.schema??it,shortcutPath:n.shortcutPath,version:n.version,owned:!!n.owned,declined:!!n.declined,desktopSource:n.desktopSource,updatedAt:n.updatedAt}}catch{return null}}function N(t,e,n){let r={schema:it,...n,updatedAt:new Date().toISOString()};t.mkdirSync(st.dirname(e)),t.writeFileSync(e,JSON.stringify(r,null,2));}function _(t,e){if(!t.existsSync(e))return null;try{let n=JSON.parse(t.readFileSync(e));return {schema:n.schema??0,binPath:n.binPath,updatedAt:n.updatedAt}}catch{return null}}function ct(t,e,n){t.mkdirSync(st.dirname(e)),t.writeFileSync(e,JSON.stringify(n,null,2));}var Gt=d.win32,x=1;function Ut(t){return t.replace(/%/g,"%%")}function jt(t){return ["@echo off","setlocal DisableDelayedExpansion","chcp 65001 >nul","",'set "CREWX_WORKDIR=%USERPROFILE%\\crewx"','if not exist "%CREWX_WORKDIR%" mkdir "%CREWX_WORKDIR%" >nul 2>nul','cd /d "%CREWX_WORKDIR%"',"",'set "CREWX_PORT_EFFECTIVE=%CREWX_PORT%"','if "%CREWX_PORT_EFFECTIVE%"=="" set "CREWX_PORT_EFFECTIVE=8150"','set "CREWX_HEALTH_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/api/v1/health"','set "CREWX_ORIGIN_URL=http://127.0.0.1:%CREWX_PORT_EFFECTIVE%/"',"",t.bakedBinPath?`set "CREWX_FALLBACK_BIN=${Ut(t.bakedBinPath)}"`:'set "CREWX_FALLBACK_BIN="','set "CREWX_RESOLVED_BIN=%CREWX_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" set "CREWX_RESOLVED_BIN=%CREWX_FALLBACK_BIN%"','if "%CREWX_RESOLVED_BIN%"=="" (',` for /f "delims=" %%I in ('where crewx 2^>nul') do (`,' if not defined CREWX_RESOLVED_BIN set "CREWX_RESOLVED_BIN=%%I"'," )",")","",'powershell -NoProfile -NonInteractive -Command "try { $r = Invoke-WebRequest -Uri $env:CREWX_HEALTH_URL -TimeoutSec 1 -UseBasicParsing; if ($r.StatusCode -eq 200) { exit 0 } else { exit 1 } } catch { exit 1 }"',"if %ERRORLEVEL% EQU 0 (",' start "" "%CREWX_ORIGIN_URL%"'," exit /b 0",")","",'if "%CREWX_RESOLVED_BIN%"=="" ('," echo CrewX executable not found. Please reinstall the desktop shortcut."," pause"," exit /b 1",")","",'start "CrewX" /min "%CREWX_RESOLVED_BIN%"',""].join(`\r
|
|
2
|
+
`)}function ut(t){let e=_(t.fs,t.launcherManifestPath),n=!!e&&e.schema>=x&&t.fs.existsSync(t.wrapperPath),r=n&&!e.binPath&&!!t.bakedBinPath;if(n&&!r)return {wrapperPath:t.wrapperPath,wrote:false,schema:e.schema};let c=jt({bakedBinPath:t.bakedBinPath});try{t.fs.mkdirSync(Gt.dirname(t.wrapperPath)),t.fs.writeFileSync(t.wrapperPath,c),ct(t.fs,t.launcherManifestPath,{schema:x,binPath:t.bakedBinPath,updatedAt:new Date().toISOString()});}catch(o){throw o instanceof f?o:new f("WRITE_DENIED",`Could not write launcher wrapper: ${o instanceof Error?o.message:String(o)}`)}return {wrapperPath:t.wrapperPath,wrote:true,schema:x}}var Jt=["$ws = New-Object -ComObject WScript.Shell","$sc = $ws.CreateShortcut($env:CREWX_LNK_PATH)","$sc.TargetPath = $env:CREWX_LNK_TARGET","if ($env:CREWX_LNK_WORKDIR) { $sc.WorkingDirectory = $env:CREWX_LNK_WORKDIR }","$sc.WindowStyle = 7","if ($env:CREWX_LNK_ICON) { $sc.IconLocation = $env:CREWX_LNK_ICON }","$sc.Save()"].join("; "),Kt=["[Console]::OutputEncoding = [System.Text.Encoding]::UTF8","$ws = New-Object -ComObject WScript.Shell","$sc = $ws.CreateShortcut($env:CREWX_LNK_PATH)","[PSCustomObject]@{ TargetPath = $sc.TargetPath; WorkingDirectory = $sc.WorkingDirectory; IconLocation = $sc.IconLocation } | ConvertTo-Json -Compress"].join("; ");async function dt(t){let e={...t.env,CREWX_LNK_PATH:t.shortcutPath,CREWX_LNK_TARGET:t.targetPath,CREWX_LNK_WORKDIR:t.workingDirectory??"",CREWX_LNK_ICON:t.iconPath??""},n;try{n=await t.run("powershell",["-NoProfile","-NonInteractive","-Command",Jt],{env:e});}catch(r){throw new f("POWERSHELL_UNAVAILABLE",`Could not run PowerShell: ${r instanceof Error?r.message:String(r)}`)}if(n.code!==0)throw new f("POWERSHELL_UNAVAILABLE",`Failed to create desktop shortcut: ${n.stderr||n.stdout}`)}function pt(t){let e=t.trim(),n=e.lastIndexOf(",");return n!==-1&&/^-?\d+$/.test(e.slice(n+1).trim())&&(e=e.slice(0,n).trim()),e.length>=2&&e.startsWith('"')&&e.endsWith('"')&&(e=e.slice(1,-1).trim()),e}async function ft(t){try{let e={...t.env,CREWX_LNK_PATH:t.shortcutPath},n=await t.run("powershell",["-NoProfile","-NonInteractive","-Command",Kt],{env:e});if(n.code!==0||!n.stdout.trim())return null;let r=JSON.parse(n.stdout.trim());return {targetPath:r.TargetPath??"",workingDirectory:r.WorkingDirectory??"",iconLocation:r.IconLocation??""}}catch{return null}}var M=d.win32;async function C(t){let e=W(t.env.PATH??t.env.Path??"",t.cwd),n={...t.env,PATH:e,Path:e},r;try{r=await t.run("npm",["list","-g","crewx","--depth=0","--json"],{env:n});}catch{return {installed:false}}let s;try{s=JSON.parse(r.stdout||"{}");}catch{return {installed:false}}let c=s.dependencies?.crewx;if(!c?.version)return {installed:false};let o;try{let a=await t.run("npm",["prefix","-g"],{env:n});a.code===0&&(o=a.stdout.trim()||void 0);}catch{}let i=o?M.join(o,"crewx.cmd"):void 0;return {installed:true,version:c.version,binPath:i,prefix:o}}var zt=/EACCES|EPERM|EROFS/,qt=/ENOTFOUND|ETIMEDOUT|ECONNREFUSED|network|registry/i,Qt=/^\d+\.\d+\.\d+/;function Yt(t){return !!t&&t!=="0.0.0"&&Qt.test(t)}var T=10*6e4;async function mt(t){if(!Yt(t.targetVersion))throw new f("GLOBAL_INSTALL_FAILED",`RUNNING_VERSION_UNKNOWN: cannot reliably determine the running crewx version to install (got ${JSON.stringify(t.targetVersion)}); refusing to fall back to crewx@latest`);if(t.currentInfo?.installed&&t.currentInfo.version&&!y(t.currentInfo.version,t.targetVersion))return {info:t.currentInfo};let e=W(t.env.PATH??t.env.Path??"",t.cwd),n={...t.env,PATH:e,Path:e},r=`crewx@${t.targetVersion}`;t.onProgress?.({phase:"global-install",message:`Installing crewx globally (npm install -g ${r})`});let s;try{s=await t.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:n,timeoutMs:T});}catch(o){throw new f("NPM_UNAVAILABLE",`Could not run npm: ${o instanceof Error?o.message:String(o)}`)}if(s.code===0)return {info:await C({env:n,cwd:t.cwd,run:t.run})};let c=`${s.stdout}
|
|
3
|
+
${s.stderr}`;if(zt.test(c)){t.onProgress?.({phase:"global-install",message:"Permission denied \u2014 retrying with a user-scoped npm prefix"});let o=t.env.LOCALAPPDATA||M.join(t.env.USERPROFILE??"","AppData","Local"),i={...n,npm_config_prefix:M.join(o,"crewx","npm")},a;try{a=await t.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:i,timeoutMs:T});}catch(l){throw new f("NPM_PERMISSION_DENIED",`Retry with user-scoped prefix failed: ${l instanceof Error?l.message:String(l)}`)}if(a.code===0)return {info:await C({env:i,cwd:t.cwd,run:t.run})};throw new f("NPM_PERMISSION_DENIED",`npm install -g failed after user-scoped prefix retry: ${a.stderr||a.stdout}`)}if(qt.test(c)){if(!t.installRoot)throw new f("OFFLINE_NO_SOURCE","The npm registry is unreachable and no local installRoot was provided for an offline install");t.onProgress?.({phase:"global-install",message:`Registry unreachable \u2014 installing offline from ${t.installRoot}`});let o;try{o=await t.run("npm",["install","-g",t.installRoot,"--offline","--no-audit","--no-fund"],{env:n,timeoutMs:T});}catch(i){throw new f("GLOBAL_INSTALL_FAILED",`Offline install failed: ${i instanceof Error?i.message:String(i)}`)}if(o.code===0)return {info:await C({env:n,cwd:t.cwd,run:t.run})};throw new f("GLOBAL_INSTALL_FAILED",`Offline install failed: ${o.stderr||o.stdout}`)}throw new f("GLOBAL_INSTALL_FAILED",c.trim()||`npm install -g ${r} failed`)}function Zt(t){return t.run??K}function te(t){return t.fs??V}async function O(t){let e=t.platform??process.platform,n=t.env??process.env,r=t.homedir??B,s=Zt(t),c=te(t),o=t.runningVersion??q,i=t.cwd??process.cwd(),a=r(),l=Y(a),h=Z(a),m=tt(a),u=null;e==="win32"&&(u=await nt({env:n,homedir:r,run:s}));let p=u?et(u.dir):null;return {platform:e,env:n,homedir:r,run:s,fs:c,runningVersion:o,cwd:i,installRoot:t.installRoot,shortcutManifestPath:l,launcherManifestPath:h,wrapperPath:m,desktop:u,shortcutPath:p}}function ee(t){return t?d.win32.normalize(t).toLowerCase().endsWith(`${d.win32.sep}bin${d.win32.sep}crewx.ico`):false}async function E(t){if(t.platform!=="win32")return {supported:false,state:"unsupported",globalCrewx:null,runningVersion:t.runningVersion,errors:[],manifest:null,iconStale:false};let e=[];t.desktop||e.push("NO_DESKTOP_DIR: could not resolve the Windows Desktop directory");let n=at(t.fs,t.shortcutManifestPath),r=_(t.fs,t.launcherManifestPath),s=await C({env:t.env,cwd:t.cwd,run:t.run}),c=t.shortcutPath?t.fs.existsSync(t.shortcutPath):false,o,i=false;if(!c)o=n?.declined?"declined":"not-installed";else {let a=!!n?.owned&&!!t.shortcutPath&&n.shortcutPath===t.shortcutPath,l=false,h=t.shortcutPath?await ft({run:t.run,env:t.env,shortcutPath:t.shortcutPath}):null;if(a||(h&&A(h.targetPath,t.wrapperPath)?a=true:h&&rt(h.targetPath)&&(l=true)),l)o="foreign",e.push("NSIS_PRESENT: an NSIS-installed CrewX shortcut was detected");else if(!a)o="foreign";else if(n?.version&&y(t.runningVersion,n.version))o="superseded",e.push(`SUPERSEDED: running version ${t.runningVersion} is older than the installed shortcut's version ${n.version}; refusing to modify it`);else {let m=!r||r.schema<x||!t.fs.existsSync(t.wrapperPath);if(h){let u=pt(h.iconLocation);if(!(!!u&&t.fs.existsSync(u)))i=true;else {let g=gt(s,t.fs);g?i=!A(u,g):i=!ee(u);}}o=m||i?"stale":"installed";}}return {supported:true,state:o,shortcutPath:t.shortcutPath??void 0,desktopDir:t.desktop?.dir,desktopSource:t.desktop?.source,wrapperPath:t.wrapperPath,wrapperSchema:r?.schema,globalCrewx:s.installed?s:{installed:false},runningVersion:t.runningVersion,errors:e,manifest:n,iconStale:i}}function gt(t,e){if(!t?.installed||!t.prefix)return;let n=d.win32.join(t.prefix,"node_modules","crewx","bin","crewx.ico");return e.existsSync(n)?n:void 0}function R(t){let{manifest:e,iconStale:n,...r}=t;return r}async function ne(t={}){let e=await O(t),n=await E(e);return R(n)}async function re(t={}){let e=await O(t);t.onProgress?.({phase:"detect",message:"Checking current shortcut status"});let n=await E(e),r=R(n);if(!r.supported)return {...r,changed:false,installedGlobal:false};if(r.state==="superseded")return {...r,changed:false,installedGlobal:false};if(r.state==="foreign"){if(n.errors.some(g=>g.startsWith("NSIS_PRESENT")))throw new f("NSIS_PRESENT",`An NSIS-installed CrewX shortcut was detected at ${r.shortcutPath}`);if(!t.force)throw new f("FOREIGN_SHORTCUT",`An existing shortcut at ${r.shortcutPath} is not managed by CrewX`)}if(!e.desktop||!e.shortcutPath)throw new f("NO_DESKTOP_DIR","Could not resolve the Windows Desktop directory");let s=false,c=false,o=r.globalCrewx,i=[];if(!!o?.installed&&!!o.version&&y(o.version,e.runningVersion)||!o?.installed&&r.state!=="installed"){let g=await mt({env:e.env,cwd:e.cwd,run:e.run,targetVersion:e.runningVersion,currentInfo:o??void 0,installRoot:e.installRoot,onProgress:t.onProgress});o=g.info,c=g.info.installed,s=true,c||i.push(`GLOBAL_INSTALL_UNCONFIRMED: npm install -g crewx@${e.runningVersion} exited successfully but a follow-up check could not confirm the global install`);}if(t.onProgress?.({phase:"wrapper",message:"Ensuring launcher wrapper"}),ut({fs:e.fs,wrapperPath:e.wrapperPath,launcherManifestPath:e.launcherManifestPath,bakedBinPath:o?.binPath}).wrote&&(s=true),!((r.state==="installed"||r.state==="stale")&&!n.iconStale)){let g=gt(o,e.fs);if(n.iconStale&&!g)throw new f("ICON_UNAVAILABLE",`Could not locate the global CrewX icon (bin\\crewx.ico) to repair the desktop shortcut at ${e.shortcutPath}; the existing shortcut was left untouched`);t.onProgress?.({phase:"lnk",message:"Creating desktop shortcut"}),await dt({run:e.run,env:e.env,shortcutPath:e.shortcutPath,targetPath:e.wrapperPath,iconPath:g}),s=true;}s&&N(e.fs,e.shortcutManifestPath,{shortcutPath:e.shortcutPath,version:e.runningVersion,owned:true,declined:false,desktopSource:e.desktop.source});let u=await E(e),p=R(u);return {...p,errors:[...p.errors,...i],changed:s,installedGlobal:c}}async function oe(t={}){let e=await O(t),n=await E(e),r=R(n);if(!r.supported)return r;if((r.state==="installed"||r.state==="stale")&&e.shortcutPath)try{e.fs.unlinkSync(e.shortcutPath);}catch{}N(e.fs,e.shortcutManifestPath,{shortcutPath:void 0,version:n.manifest?.version,owned:false,declined:true,desktopSource:void 0});let s=await E(e);return R(s)}async function se(t={}){let e=await O(t),n=await E(e),r=R(n);if(!r.supported)return r;N(e.fs,e.shortcutManifestPath,{shortcutPath:n.manifest?.shortcutPath,version:n.manifest?.version,owned:n.manifest?.owned??false,declined:true,desktopSource:n.manifest?.desktopSource});let s=await E(e);return R(s)}export{f as ShortcutError,se as dismissShortcutNotice,ne as getShortcutStatus,re as installShortcut,oe as uninstallShortcut};
|