@crewx/sdk 0.9.0-rc.93 → 0.9.0-rc.95
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/account/config.d.ts +29 -0
- package/dist/account/env-bootstrap.d.ts +5 -0
- package/dist/account/errors.d.ts +1 -1
- package/dist/account/index.d.ts +4 -2
- package/dist/account/index.js +2 -1
- package/dist/conversation/types.d.ts +1 -0
- package/dist/desktop/index.d.ts +1 -0
- package/dist/desktop/index.js +3 -3
- package/dist/esm/account/index.js +2 -1
- package/dist/esm/desktop/index.js +3 -3
- package/dist/esm/index.js +263 -225
- package/dist/esm/plugins/index.js +119 -88
- package/dist/esm/process/index.js +1 -0
- package/dist/esm/repository/index.js +205 -93
- package/dist/events/types.d.ts +1 -0
- package/dist/index.browser.js +4 -4
- package/dist/index.d.ts +14 -2
- package/dist/index.js +264 -226
- package/dist/lifecycle/task-heartbeat.d.ts +41 -0
- package/dist/lifecycle/task-stop.d.ts +30 -0
- package/dist/migrations/0025_task_heartbeat.sql +8 -0
- package/dist/migrations/meta/_journal.json +7 -0
- package/dist/plugins/index.d.ts +1 -1
- package/dist/plugins/index.js +119 -88
- package/dist/plugins/sqlite-tracing.d.ts +10 -0
- package/dist/process/index.d.ts +2 -0
- package/dist/process/index.js +1 -0
- package/dist/process/process-control.d.ts +40 -0
- package/dist/prompt/tag-names.d.ts +18 -0
- package/dist/provider/task-error.types.d.ts +2 -1
- package/dist/repository/index.d.ts +13 -2
- package/dist/repository/index.js +255 -143
- package/dist/repository/task-status.d.ts +14 -0
- package/dist/repository/task.repository.d.ts +69 -8
- package/dist/repository/usage-backfill.d.ts +62 -0
- package/dist/repository/usage-from-logs.d.ts +21 -0
- package/dist/schema/tasks.d.ts +55 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/utils/runner-env.d.ts +3 -0
- package/package.json +9 -1
- package/templates/agents/default.yaml +37 -23
- package/templates/documents/crewx-quick-guide.md +1 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import*as f from'path';import f__default,{join}from'path';import {fileURLToPath}from'url';import {createHash}from'crypto';import {readFileSync,unlinkSync,mkdirSync,writeFileSync,existsSync,statSync}from'fs';import {homedir}from'os';import {execFile,spawn}from'child_process';import {StringDecoder}from'string_decoder';import {createRequire}from'module';var M=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var z=()=>fileURLToPath(import.meta.url),Fe=()=>f__default.dirname(z()),S=Fe(),P=z();var h=class extends Error{code;constructor(t,n){super(`${t}: ${n}`),this.code=t,this.name="ShortcutError";}};var Y={existsSync:e=>existsSync(e),readFileSync:e=>readFileSync(e,"utf8"),readBinaryFileSync:e=>new Uint8Array(readFileSync(e)),writeFileSync:(e,t)=>writeFileSync(e,t,"utf8"),mkdirSync:e=>{mkdirSync(e,{recursive:true});},unlinkSync:e=>{unlinkSync(e);}},Q=homedir;function O(e){return typeof e!="string"?void 0:e.trim()||void 0}function D(e){return O(e)?.toLowerCase()??""}function k(e){try{return statSync(e).isFile()}catch{return false}}function Xe(e,t){if(e===t)return true;let n=f__default.relative(e,t);return n!==""&&!n.startsWith("..")&&!f__default.isAbsolute(n)}function Ge(e,t){if(f__default.basename(e)!==".bin")return false;let n=f__default.dirname(e);if(f__default.basename(n)!=="node_modules")return false;let r=f__default.dirname(n);return Xe(r,t)}function Z(e,t={}){if(e.includes("/")||e.includes("\\")||f__default.isAbsolute(e))return e;let n=t.platform??process.platform,r=t.env??process.env,i=f__default.resolve(t.cwd??process.cwd()),l=(t.resolution??"global_first")==="global_first",o=r.PATH??r.Path??process.env.PATH??process.env.Path??"",a=n==="win32"?";":":",s=o.split(a).map(u=>u.trim()).filter(Boolean),c=f__default.extname(e).length>0,d=r.PATHEXT??r.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",p=n==="win32"?c?[""]:d.split(";").map(u=>u.trim()).filter(Boolean).map(u=>u.startsWith(".")?u:`.${u}`):[""];for(let u of s){let E=f__default.resolve(i,u);if(!(l&&Ge(E,i)))for(let w of p){let y=D(w),m=w.toUpperCase();for(let g of [w,y,m]){let C=f__default.join(E,`${e}${g}`);if(k(C))return C}}}return e}function Je(e){if(!k(e))return null;try{let t=readFileSync(e,"utf8"),n=f__default.dirname(e),r=[];for(let a of t.matchAll(/"([^"\r\n]*)"/g)){let d=(a[1]??"").match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();if(!d)continue;let p=d.replace(/[\\/]+/g,f__default.sep).replace(/^[\\/]+/,""),u=f__default.resolve(n,p);k(u)&&r.push(u);}let i=[],l=new Map;for(let a of t.matchAll(/SET\s+"(\w+)=%~?dp0%?[\\/]?([^"]+)"/gi)){let s=a[1].toUpperCase(),c=a[2].trim().replace(/[\\/]+/g,f__default.sep).replace(/^[\\/]+/,"");l.set(s,f__default.resolve(n,c));}for(let a of t.split(/\r?\n/))if(a.includes("%*"))for(let s of a.matchAll(/"%(\w+)%"/g)){let c=l.get(s[1].toUpperCase());c&&k(c)&&i.push(c);}let o=a=>a.find(s=>{let c=D(f__default.basename(s));return c!=="node.exe"&&c!=="node"})??null;return o(i)??o(r)}catch{return null}}function je(e,t){if(typeof t=="string")return O(t)||null;if(!t||typeof t!="object")return null;if(e){let n=t[e],r=typeof n=="string"?O(n):void 0;if(r)return r}for(let n of Object.values(t)){let r=typeof n=="string"?O(n):void 0;if(r)return r}return null}function Ke(e,t){if(!t)return null;let n=f__default.dirname(e),r=[f__default.resolve(n,"..",t),f__default.resolve(n,"node_modules",t)];for(let i of r){let l=f__default.join(i,"package.json");if(k(l))try{let o=JSON.parse(readFileSync(l,"utf8")),a=je(t,o.bin);if(!a)continue;let s=f__default.resolve(i,a);if(k(s))return s}catch{}}return null}function ze(e){let t=e.platform??process.platform,n=e.env??process.env,r=e.execPath??process.execPath,i=e.cwd,l=e.resolution;if(t!=="win32")return {command:Z(e.command,{cwd:i,env:n,platform:t,resolution:l}),leadingArgv:[],resolution:"direct"};let o=Z(e.command,{cwd:i,env:n,platform:t,resolution:l}),a=D(f__default.extname(o));if(a===".js"||a===".cjs"||a===".mjs")return {command:r,leadingArgv:[o],resolution:"node-entrypoint",windowsHide:true};if(a===".cmd"||a===".bat"){let s=Je(o)??Ke(o,e.packageName);return s?D(f__default.extname(s))===".exe"?{command:s,leadingArgv:[],resolution:"exe-entrypoint",windowsHide:true}:{command:r,leadingArgv:[s],resolution:"node-entrypoint",windowsHide:true}:{command:o,leadingArgv:[],resolution:"unresolved-wrapper"}}return {command:o,leadingArgv:[],resolution:"direct"}}function qe(e){if(e.candidate.resolution!=="unresolved-wrapper")return {command:e.candidate.command,leadingArgv:e.candidate.leadingArgv,resolution:e.candidate.resolution,windowsHide:e.candidate.windowsHide};throw new Error(`${f__default.basename(e.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function te(e){let t=ze(e);return qe({candidate:t})}function ne(e,t){return {command:e.command,argv:[...e.leadingArgv,...t],resolution:e.resolution,shell:e.shell,windowsHide:e.windowsHide}}var T="\uFFFD",$=8,oe=1e3,Qe=new Map([[437,"ibm437"],[720,"ibm720"],[737,"ibm737"],[775,"ibm775"],[850,"ibm850"],[852,"ibm852"],[855,"ibm855"],[857,"ibm857"],[858,"ibm858"],[862,"ibm862"],[864,"ibm864"],[932,"shift_jis"],[936,"gb18030"],[949,"euc-kr"],[950,"big5"],[866,"ibm866"],[869,"ibm869"],[1250,"windows-1250"],[1251,"windows-1251"],[1252,"windows-1252"],[1253,"windows-1253"],[1254,"windows-1254"],[1255,"windows-1255"],[1256,"windows-1256"],[1257,"windows-1257"],[1258,"windows-1258"]]),A;function V(e){let t=0;for(let n of e)n===T&&(t+=1);return t}function H(e,t){return V(t)<V(e)?t:e}function Ze(e){let t=e.match(/(?:^|[^0-9])([0-9]{1,5})(?![0-9])/);if(!t)return null;let n=Number(t[1]);return Number.isInteger(n)&&n>0&&n<=65535?n:null}function et(e){if(e!==65001)return Qe.get(e)}function tt(e){let t=et(e);if(!t)return null;try{return new TextDecoder(t)}catch{return null}}function nt(){return new Promise(e=>{let t=false,n,r=i=>{t||(t=true,n&&clearTimeout(n),e(i));};n=setTimeout(()=>r(null),oe),n.unref();try{execFile("chcp.com",[],{encoding:"ascii",timeout:oe,windowsHide:!0},(l,o)=>{if(l){r(null);return}r(Ze(String(o)));}).once("error",()=>r(null));}catch{r(null);}})}function ae(){return process.platform!=="win32"?Promise.resolve(null):(A||(A=nt(),A.then(e=>{},()=>{})),A)}function rt(){process.platform==="win32"&&ae();}function se(e,t){if(t.length>=$)return t.subarray(t.length-$);let n=$-t.length,r=e.length>n?e.subarray(e.length-n):e;return Buffer.concat([r,t])}var x=class{platform;detectCodePage;utf8Decoder=new StringDecoder("utf8");codePage;fallbackDecoder;replayTail=Buffer.alloc(0);pendingUtf8="";pendingFallback="";pendingBytes=Buffer.alloc(0);queue=Promise.resolve();ended=false;constructor(t={}){this.platform=t.platform??process.platform,this.detectCodePage=t.detectCodePage??ae,this.codePage=t.codePage;}write(t){let n=Buffer.from(t);return this.enqueue(()=>this.decodeChunk(n))}end(){return this.enqueue(()=>this.finish())}enqueue(t){let n=this.queue.then(t);return this.queue=n.then(()=>{},()=>{}),n}clearPendingCandidate(){this.pendingUtf8="",this.pendingFallback="",this.pendingBytes=Buffer.alloc(0);}async resolveCodePage(){if(this.codePage!==void 0)return this.codePage;try{this.codePage=await this.detectCodePage();}catch{this.codePage=null;}return this.codePage}async getFallbackDecoder(){if(this.fallbackDecoder!==void 0)return this.fallbackDecoder;let t=await this.resolveCodePage();return this.fallbackDecoder=t===null?null:tt(t),this.fallbackDecoder}async decodeChunk(t){if(this.ended)return "";let n=this.utf8Decoder.write(t),r=n.includes(T);if(r&&(this.utf8Decoder=new StringDecoder("utf8")),this.platform!=="win32")return n;if(this.fallbackDecoder){let s=this.fallbackDecoder.decode(t,{stream:true}),c=se(this.pendingBytes,t);if(r){let d=this.pendingUtf8+n,p=this.pendingFallback+s;return this.clearPendingCandidate(),H(d,p)}if(V(s)>0){let d=this.pendingUtf8+n;return this.clearPendingCandidate(),this.fallbackDecoder=void 0,this.replayTail=c,d}if(this.pendingUtf8||this.pendingFallback){if(this.pendingUtf8+=n,this.pendingFallback+=s,this.pendingBytes=c,n.length===0||s.length===0)return "";let d=this.pendingUtf8;return this.clearPendingCandidate(),d}return n.length===0&&s.length>0?(this.pendingUtf8=n,this.pendingFallback=s,this.pendingBytes=c,""):n}let i=this.replayTail;if(this.fallbackDecoder===void 0&&(this.replayTail=se(this.replayTail,t)),!r)return n;let l=this.fallbackDecoder===void 0,o=await this.getFallbackDecoder();if(!o)return this.replayTail=Buffer.alloc(0),n;l&&i.length>0&&o.decode(i,{stream:true}),this.replayTail=Buffer.alloc(0);let a=o.decode(t,{stream:true});return H(n,a)}async finish(){if(this.ended)return "";this.ended=true;let t=this.utf8Decoder.end();if(this.platform!=="win32")return t;if(this.fallbackDecoder===void 0&&t.includes(T)){let l=await this.getFallbackDecoder();l&&this.replayTail.length>0&&(l.decode(this.replayTail,{stream:true}),this.replayTail=Buffer.alloc(0));}let n=this.pendingUtf8+t,r=this.fallbackDecoder?.decode()??"",i=this.pendingFallback+r;return this.clearPendingCandidate(),n.includes(T)?H(n,i):n}};rt();var ce=3e4;function ot(e){if(typeof e.pid!="number"){e.kill();return}if(process.platform==="win32"){spawn("taskkill",["/pid",String(e.pid),"/t","/f"],{windowsHide:true}).on("error",()=>{});return}try{process.kill(-e.pid,"SIGKILL");}catch{e.kill("SIGKILL");}}var ue=(e,t,n={})=>new Promise((r,i)=>{let l=n.env??process.env,o=process.platform,a;try{let g=te({command:e,platform:o,env:l,cwd:n.cwd,allowShellFallback:!1});a=ne(g,t);}catch(g){i(g instanceof Error?g:new Error(String(g)));return}let s=spawn(a.command,a.argv,{cwd:n.cwd,env:l,shell:a.shell,windowsHide:a.windowsHide??true,detached:o!=="win32"}),c="",d="",p=false,u=new x({platform:o}),E=new x({platform:o}),w=Promise.resolve(),y=Promise.resolve(),m=setTimeout(()=>{p||(p=true,ot(s),i(new Error(`Command timed out after ${n.timeoutMs??ce}ms: ${e} ${t.join(" ")}`)));},n.timeoutMs??ce);s.stdout?.on("data",g=>{w=w.then(async()=>{c+=await u.write(g);});}),s.stderr?.on("data",g=>{y=y.then(async()=>{d+=await E.write(g);});}),s.on("error",g=>{p||(p=true,clearTimeout(m),i(g));}),s.on("close",g=>{p||(async()=>{await Promise.all([w,y]);let[C,Ae]=await Promise.all([u.end(),E.end()]);p||(c+=C,d+=Ae,p=true,clearTimeout(m),r({code:g??0,stdout:c,stderr:d}));})().catch(C=>{p||(p=true,clearTimeout(m),i(C instanceof Error?C:new Error(String(C))));});});});function at(){try{return (typeof M=="function"?M:createRequire(P)).resolve("@crewx/sdk/package.json")}catch{return null}}function ct(){let e=[at(),join(S,"../../package.json"),join(S,"../../../package.json")].filter(t=>!!t);for(let t of e)try{let n=JSON.parse(readFileSync(t,"utf8"));if(n.name==="@crewx/sdk"&&n.version)return n.version}catch{}return "0.0.0"}var fe=ct();var v=f.win32;function U(e){return v.join(e,".crewx")}function he(e){return v.join(U(e),"shortcut.json")}function me(e){return v.join(U(e),"launcher.json")}function ge(e){return v.join(U(e),"bin","crewx-launcher.cmd")}function we(e){return v.join(e,"CrewX.lnk")}function X(e,t){return v.normalize(e).toLowerCase()===v.normalize(t).toLowerCase()}var lt="[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Environment]::GetFolderPath('DesktopDirectory')";async function Se(e){try{let n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",lt],{env:e.env}),r=n.stdout.trim();if(n.code===0&&r)return {dir:r,source:"known-folder"}}catch{}let t=e.env.USERPROFILE||e.env.Userprofile||e.homedir();return t?{dir:v.join(t,"Desktop"),source:"fallback"}:null}function G(e,t){let n=v.resolve(t,"node_modules",".bin").toLowerCase();return e.split(";").filter(r=>r?v.resolve(r).toLowerCase()!==n:true).join(";")}function Pe(e){return e?/\\Program Files( \(x86\))?\\/i.test(e)&&/crewx/i.test(e):false}function ut(e,t){let n=s=>{let[c,...d]=s.split("-"),p=d.join("-")||void 0;return {parts:(c??"").split(".").map(E=>Number.parseInt(E,10)||0),pre:p}},r=n(e),i=n(t),l=Math.max(r.parts.length,i.parts.length);for(let s=0;s<l;s++){let c=r.parts[s]??0,d=i.parts[s]??0;if(c!==d)return c<d?-1:1}if(r.pre===i.pre)return 0;if(!r.pre&&i.pre)return 1;if(r.pre&&!i.pre)return -1;let o=Number.parseInt(r.pre.match(/(\d+)$/)?.[1]??"",10),a=Number.parseInt(i.pre.match(/(\d+)$/)?.[1]??"",10);return !Number.isNaN(o)&&!Number.isNaN(a)&&o!==a?o<a?-1:1:r.pre<i.pre?-1:r.pre>i.pre?1:0}function _(e,t){return ut(e,t)<0}var ve=f.win32,ye=1;function Ce(e,t){if(!e.existsSync(t))return null;try{let n=JSON.parse(e.readFileSync(t));return {schema:n.schema??ye,shortcutPath:n.shortcutPath,version:n.version,iconHash:typeof n.iconHash=="string"?n.iconHash:void 0,owned:!!n.owned,declined:!!n.declined,desktopSource:n.desktopSource,updatedAt:n.updatedAt}}catch{return null}}function W(e,t,n){let r={schema:ye,...n,updatedAt:new Date().toISOString()};e.mkdirSync(ve.dirname(t)),e.writeFileSync(t,JSON.stringify(r,null,2));}function F(e,t){if(!e.existsSync(t))return null;try{let n=JSON.parse(e.readFileSync(t));return {schema:n.schema??0,binPath:n.binPath,updatedAt:n.updatedAt}}catch{return null}}function Re(e,t,n){e.mkdirSync(ve.dirname(t)),e.writeFileSync(t,JSON.stringify(n,null,2));}var dt=f.win32,I=1;function ft(e){return e.replace(/%/g,"%%")}function pt(e){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%/"',"",e.bakedBinPath?`set "CREWX_FALLBACK_BIN=${ft(e.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 m from'path';import m__default,{join}from'path';import {fileURLToPath}from'url';import {createHash}from'crypto';import {readFileSync,unlinkSync,mkdirSync,writeFileSync,existsSync,statSync}from'fs';import {homedir}from'os';import {execFile,spawn}from'child_process';import {StringDecoder}from'string_decoder';import {createRequire}from'module';var $=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var q=()=>fileURLToPath(import.meta.url),Ge=()=>m__default.dirname(q()),P=Ge(),S=q();var p=class extends Error{code;constructor(t,n){super(`${t}: ${n}`),this.code=t,this.name="ShortcutError";}};var Q={existsSync:e=>existsSync(e),readFileSync:e=>readFileSync(e,"utf8"),readBinaryFileSync:e=>new Uint8Array(readFileSync(e)),writeFileSync:(e,t)=>writeFileSync(e,t,"utf8"),mkdirSync:e=>{mkdirSync(e,{recursive:true});},unlinkSync:e=>{unlinkSync(e);}},Z=homedir;function O(e){return typeof e!="string"?void 0:e.trim()||void 0}function D(e){return O(e)?.toLowerCase()??""}function k(e){try{return statSync(e).isFile()}catch{return false}}function Qe(e,t){if(e===t)return true;let n=m__default.relative(e,t);return n!==""&&!n.startsWith("..")&&!m__default.isAbsolute(n)}function Ze(e,t){if(m__default.basename(e)!==".bin")return false;let n=m__default.dirname(e);if(m__default.basename(n)!=="node_modules")return false;let r=m__default.dirname(n);return Qe(r,t)}function ee(e,t={}){if(e.includes("/")||e.includes("\\")||m__default.isAbsolute(e))return e;let n=t.platform??process.platform,r=t.env??process.env,o=m__default.resolve(t.cwd??process.cwd()),c=(t.resolution??"global_first")==="global_first",s=r.PATH??r.Path??process.env.PATH??process.env.Path??"",i=n==="win32"?";":":",a=s.split(i).map(u=>u.trim()).filter(Boolean),l=m__default.extname(e).length>0,d=r.PATHEXT??r.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",f=n==="win32"?l?[""]:d.split(";").map(u=>u.trim()).filter(Boolean).map(u=>u.startsWith(".")?u:`.${u}`):[""];for(let u of a){let E=m__default.resolve(o,u);if(!(c&&Ze(E,o)))for(let h of f){let y=D(h),g=h.toUpperCase();for(let w of [h,y,g]){let v=m__default.join(E,`${e}${w}`);if(k(v))return v}}}return e}function et(e){if(!k(e))return null;try{let t=readFileSync(e,"utf8"),n=m__default.dirname(e),r=[];for(let i of t.matchAll(/"([^"\r\n]*)"/g)){let d=(i[1]??"").match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();if(!d)continue;let f=d.replace(/[\\/]+/g,m__default.sep).replace(/^[\\/]+/,""),u=m__default.resolve(n,f);k(u)&&r.push(u);}let o=[],c=new Map;for(let i of t.matchAll(/SET\s+"(\w+)=%~?dp0%?[\\/]?([^"]+)"/gi)){let a=i[1].toUpperCase(),l=i[2].trim().replace(/[\\/]+/g,m__default.sep).replace(/^[\\/]+/,"");c.set(a,m__default.resolve(n,l));}for(let i of t.split(/\r?\n/))if(i.includes("%*"))for(let a of i.matchAll(/"%(\w+)%"/g)){let l=c.get(a[1].toUpperCase());l&&k(l)&&o.push(l);}let s=i=>i.find(a=>{let l=D(m__default.basename(a));return l!=="node.exe"&&l!=="node"})??null;return s(o)??s(r)}catch{return null}}function tt(e,t){if(typeof t=="string")return O(t)||null;if(!t||typeof t!="object")return null;if(e){let n=t[e],r=typeof n=="string"?O(n):void 0;if(r)return r}for(let n of Object.values(t)){let r=typeof n=="string"?O(n):void 0;if(r)return r}return null}function nt(e,t){if(!t)return null;let n=m__default.dirname(e),r=[m__default.resolve(n,"..",t),m__default.resolve(n,"node_modules",t)];for(let o of r){let c=m__default.join(o,"package.json");if(k(c))try{let s=JSON.parse(readFileSync(c,"utf8")),i=tt(t,s.bin);if(!i)continue;let a=m__default.resolve(o,i);if(k(a))return a}catch{}}return null}function rt(e){let t=e.platform??process.platform,n=e.env??process.env,r=e.execPath??process.execPath,o=e.cwd,c=e.resolution;if(t!=="win32")return {command:ee(e.command,{cwd:o,env:n,platform:t,resolution:c}),leadingArgv:[],resolution:"direct"};let s=ee(e.command,{cwd:o,env:n,platform:t,resolution:c}),i=D(m__default.extname(s));if(i===".js"||i===".cjs"||i===".mjs")return {command:r,leadingArgv:[s],resolution:"node-entrypoint",windowsHide:true};if(i===".cmd"||i===".bat"){let a=et(s)??nt(s,e.packageName);return a?D(m__default.extname(a))===".exe"?{command:a,leadingArgv:[],resolution:"exe-entrypoint",windowsHide:true}:{command:r,leadingArgv:[a],resolution:"node-entrypoint",windowsHide:true}:{command:s,leadingArgv:[],resolution:"unresolved-wrapper"}}return {command:s,leadingArgv:[],resolution:"direct"}}function ot(e){if(e.candidate.resolution!=="unresolved-wrapper")return {command:e.candidate.command,leadingArgv:e.candidate.leadingArgv,resolution:e.candidate.resolution,windowsHide:e.candidate.windowsHide};throw new Error(`${m__default.basename(e.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function ne(e){let t=rt(e);return ot({candidate:t})}function re(e,t){return {command:e.command,argv:[...e.leadingArgv,...t],resolution:e.resolution,shell:e.shell,windowsHide:e.windowsHide}}var A="\uFFFD",H=8,se=1e3,it=new Map([[437,"ibm437"],[720,"ibm720"],[737,"ibm737"],[775,"ibm775"],[850,"ibm850"],[852,"ibm852"],[855,"ibm855"],[857,"ibm857"],[858,"ibm858"],[862,"ibm862"],[864,"ibm864"],[932,"shift_jis"],[936,"gb18030"],[949,"euc-kr"],[950,"big5"],[866,"ibm866"],[869,"ibm869"],[1250,"windows-1250"],[1251,"windows-1251"],[1252,"windows-1252"],[1253,"windows-1253"],[1254,"windows-1254"],[1255,"windows-1255"],[1256,"windows-1256"],[1257,"windows-1257"],[1258,"windows-1258"]]),T;function V(e){let t=0;for(let n of e)n===A&&(t+=1);return t}function U(e,t){return V(t)<V(e)?t:e}function at(e){let t=e.match(/(?:^|[^0-9])([0-9]{1,5})(?![0-9])/);if(!t)return null;let n=Number(t[1]);return Number.isInteger(n)&&n>0&&n<=65535?n:null}function ct(e){if(e!==65001)return it.get(e)}function lt(e){let t=ct(e);if(!t)return null;try{return new TextDecoder(t)}catch{return null}}function ut(){return new Promise(e=>{let t=false,n,r=o=>{t||(t=true,n&&clearTimeout(n),e(o));};n=setTimeout(()=>r(null),se),n.unref();try{execFile("chcp.com",[],{encoding:"ascii",timeout:se,windowsHide:!0},(c,s)=>{if(c){r(null);return}r(at(String(s)));}).once("error",()=>r(null));}catch{r(null);}})}function ce(){return process.platform!=="win32"?Promise.resolve(null):(T||(T=ut(),T.then(e=>{},()=>{})),T)}function dt(){process.platform==="win32"&&ce();}function ae(e,t){if(t.length>=H)return t.subarray(t.length-H);let n=H-t.length,r=e.length>n?e.subarray(e.length-n):e;return Buffer.concat([r,t])}var _=class{platform;detectCodePage;utf8Decoder=new StringDecoder("utf8");codePage;fallbackDecoder;replayTail=Buffer.alloc(0);pendingUtf8="";pendingFallback="";pendingBytes=Buffer.alloc(0);queue=Promise.resolve();ended=false;constructor(t={}){this.platform=t.platform??process.platform,this.detectCodePage=t.detectCodePage??ce,this.codePage=t.codePage;}write(t){let n=Buffer.from(t);return this.enqueue(()=>this.decodeChunk(n))}end(){return this.enqueue(()=>this.finish())}enqueue(t){let n=this.queue.then(t);return this.queue=n.then(()=>{},()=>{}),n}clearPendingCandidate(){this.pendingUtf8="",this.pendingFallback="",this.pendingBytes=Buffer.alloc(0);}async resolveCodePage(){if(this.codePage!==void 0)return this.codePage;try{this.codePage=await this.detectCodePage();}catch{this.codePage=null;}return this.codePage}async getFallbackDecoder(){if(this.fallbackDecoder!==void 0)return this.fallbackDecoder;let t=await this.resolveCodePage();return this.fallbackDecoder=t===null?null:lt(t),this.fallbackDecoder}async decodeChunk(t){if(this.ended)return "";let n=this.utf8Decoder.write(t),r=n.includes(A);if(r&&(this.utf8Decoder=new StringDecoder("utf8")),this.platform!=="win32")return n;if(this.fallbackDecoder){let a=this.fallbackDecoder.decode(t,{stream:true}),l=ae(this.pendingBytes,t);if(r){let d=this.pendingUtf8+n,f=this.pendingFallback+a;return this.clearPendingCandidate(),U(d,f)}if(V(a)>0){let d=this.pendingUtf8+n;return this.clearPendingCandidate(),this.fallbackDecoder=void 0,this.replayTail=l,d}if(this.pendingUtf8||this.pendingFallback){if(this.pendingUtf8+=n,this.pendingFallback+=a,this.pendingBytes=l,n.length===0||a.length===0)return "";let d=this.pendingUtf8;return this.clearPendingCandidate(),d}return n.length===0&&a.length>0?(this.pendingUtf8=n,this.pendingFallback=a,this.pendingBytes=l,""):n}let o=this.replayTail;if(this.fallbackDecoder===void 0&&(this.replayTail=ae(this.replayTail,t)),!r)return n;let c=this.fallbackDecoder===void 0,s=await this.getFallbackDecoder();if(!s)return this.replayTail=Buffer.alloc(0),n;c&&o.length>0&&s.decode(o,{stream:true}),this.replayTail=Buffer.alloc(0);let i=s.decode(t,{stream:true});return U(n,i)}async finish(){if(this.ended)return "";this.ended=true;let t=this.utf8Decoder.end();if(this.platform!=="win32")return t;if(this.fallbackDecoder===void 0&&t.includes(A)){let c=await this.getFallbackDecoder();c&&this.replayTail.length>0&&(c.decode(this.replayTail,{stream:true}),this.replayTail=Buffer.alloc(0));}let n=this.pendingUtf8+t,r=this.fallbackDecoder?.decode()??"",o=this.pendingFallback+r;return this.clearPendingCandidate(),n.includes(A)?U(n,o):n}};dt();var le=3e3,mt=2e3,pt=25,ht=100;function fe(e){return e instanceof Error?e:e===void 0?void 0:new Error(String(e))}function ue(e){return typeof e=="object"&&e!==null&&"code"in e?String(e.code):void 0}function gt(e){return Number.isSafeInteger(e)&&e>0}function wt(e,t){return new Promise(n=>{let r;try{r=spawn(e,t,{windowsHide:!0});}catch(l){n({status:null,stdout:"",stderr:"",error:fe(l)});return}let o="",c="",s=false,i,a=setTimeout(()=>{try{r.kill();}catch{}i({status:null,stdout:o,stderr:c,error:new Error(`Command timed out after ${le}ms`)});},le);i=l=>{s||(s=true,clearTimeout(a),n(l));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",l=>{o+=String(l);}),r.stderr?.on("data",l=>{c+=String(l);}),r.once("error",l=>{i({status:null,stdout:o,stderr:c,error:l});}),r.once("close",l=>{i({status:l,stdout:o,stderr:c});});})}async function Pt(e,t,n){return n.runCommandAsync?n.runCommandAsync(e,t):n.runCommand?n.runCommand(e,t):wt(e,t)}function St(e){return new Promise(t=>{setTimeout(t,Math.max(0,e));})}function Et(){return new Promise(e=>{setImmediate(e);})}function W(e,t=process.kill){try{return t(e,0),"alive"}catch(n){return ue(n)==="ESRCH"?"not_found":ue(n)==="EPERM"?"alive":"unknown"}}function Ct(e,t){let n=W(-e,t),r=W(e,t);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function me(e,t,n,r){let o=Math.max(0,n),c=Math.max(1,r.pollIntervalMs??pt),s=Date.now()+o,i,a=o===0,l=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(d=>{i=setTimeout(d,o);});l.then(()=>{a=true;});try{for(await Et();;){let d=Ct(e,t);if(d==="not_found")return d;let f=s-Date.now();if(a||f<=0)return d;await Promise.race([l,St(Math.min(c,f))]);}}finally{i!==void 0&&clearTimeout(i);}}async function de(e,t,n,r,o){let c=await me(e,t,o.hardConfirmMs??ht,{...o,sleep:void 0});return c==="not_found"?n?{status:"not_found",pid:e,method:r}:{status:"terminated",pid:e,method:r}:c==="alive"?{status:"failed",pid:e,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:e,method:r,error:"Unable to verify process termination"}}async function pe(e,t={}){let n=t.platform??process.platform,r=n==="win32"?"taskkill":"process-group",o=u=>({status:"failed",pid:e,method:r,error:u});if(!gt(e))return o("Invalid process ID");let c=t.kill??process.kill,s=W(e,c);if(s==="not_found")return {status:"not_found",pid:e,method:r};if(s!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let u;try{u=await Pt("taskkill",["/PID",String(e),"/T","/F"],t);}catch(h){u={status:null,stdout:"",stderr:"",error:fe(h)};}let E=W(e,c);return E==="not_found"?u.status===0&&!u.error?{status:"terminated",pid:e,method:r}:{status:"not_found",pid:e,method:r}:o(E==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let i,a=t.signal??"SIGKILL";try{c(-e,a);}catch(u){i=u;}if(a==="SIGKILL")return de(e,c,i,r,t);if(await me(e,c,t.graceMs??mt,t)==="not_found")return i?{status:"not_found",pid:e,method:r}:{status:"terminated",pid:e,method:r};let d;try{c(-e,"SIGKILL");}catch(u){d=u;}let f=await de(e,c,d,r,t);return f.status==="terminated"?f:f.status==="not_found"?i?f:{status:"terminated",pid:e,method:r}:o(f.error??"Process termination failed")}var yt=["CREWX_ASSIGNED_TASK_ID","CREWX_DETACHED_RUNNER"];function vt(e,t){let n={};for(let[r,o]of Object.entries(e))o!==void 0&&(t.includes(r)||(n[r]=o));return n}function he(e){return vt(e,yt)}var ge=3e4;function we(e){if(typeof e.pid!="number"){try{e.kill();}catch{}return}pe(e.pid,{signal:"SIGKILL"}).then(t=>{if(t.status==="failed")try{e.kill("SIGKILL");}catch{}},()=>{try{e.kill("SIGKILL");}catch{}});}var Pe=(e,t,n={})=>new Promise((r,o)=>{let c=he(n.env??process.env),s=process.platform,i;try{let w=ne({command:e,platform:s,env:c,cwd:n.cwd,allowShellFallback:!1});i=re(w,t);}catch(w){o(w instanceof Error?w:new Error(String(w)));return}let a=spawn(i.command,i.argv,{cwd:n.cwd,env:c,shell:i.shell,windowsHide:i.windowsHide??true,detached:s!=="win32"}),l="",d="",f=false,u=new _({platform:s}),E=new _({platform:s}),h=Promise.resolve(),y=Promise.resolve(),g=setTimeout(()=>{f||(f=true,we(a),o(new Error(`Command timed out after ${n.timeoutMs??ge}ms: ${e} ${t.join(" ")}`)));},n.timeoutMs??ge);a.stdout?.on("data",w=>{h=h.then(async()=>{l+=await u.write(w);});}),a.stderr?.on("data",w=>{y=y.then(async()=>{d+=await E.write(w);});}),a.on("error",w=>{f||(f=true,clearTimeout(g),o(w));}),a.on("close",w=>{f||(async()=>{await Promise.all([h,y]);let[v,Ue]=await Promise.all([u.end(),E.end()]);f||(l+=v,d+=Ue,f=true,clearTimeout(g),r({code:w??0,stdout:l,stderr:d}));})().catch(v=>{f||(f=true,clearTimeout(g),o(v instanceof Error?v:new Error(String(v))));});});});function _t(){try{return (typeof $=="function"?$:createRequire(S)).resolve("@crewx/sdk/package.json")}catch{return null}}function xt(){let e=[_t(),join(P,"../../package.json"),join(P,"../../../package.json")].filter(t=>!!t);for(let t of e)try{let n=JSON.parse(readFileSync(t,"utf8"));if(n.name==="@crewx/sdk"&&n.version)return n.version}catch{}return "0.0.0"}var Ee=xt();var C=m.win32;function X(e){return C.join(e,".crewx")}function ye(e){return C.join(X(e),"shortcut.json")}function ve(e){return C.join(X(e),"launcher.json")}function Re(e){return C.join(X(e),"bin","crewx-launcher.cmd")}function be(e){return C.join(e,"CrewX.lnk")}function G(e,t){return C.normalize(e).toLowerCase()===C.normalize(t).toLowerCase()}var It="[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Environment]::GetFolderPath('DesktopDirectory')";async function ke(e){try{let n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",It],{env:e.env}),r=n.stdout.trim();if(n.code===0&&r)return {dir:r,source:"known-folder"}}catch{}let t=e.env.USERPROFILE||e.env.Userprofile||e.homedir();return t?{dir:C.join(t,"Desktop"),source:"fallback"}:null}function J(e,t){let n=C.resolve(t,"node_modules",".bin").toLowerCase();return e.split(";").filter(r=>r?C.resolve(r).toLowerCase()!==n:true).join(";")}function _e(e){return e?/\\Program Files( \(x86\))?\\/i.test(e)&&/crewx/i.test(e):false}function Lt(e,t){let n=a=>{let[l,...d]=a.split("-"),f=d.join("-")||void 0;return {parts:(l??"").split(".").map(E=>Number.parseInt(E,10)||0),pre:f}},r=n(e),o=n(t),c=Math.max(r.parts.length,o.parts.length);for(let a=0;a<c;a++){let l=r.parts[a]??0,d=o.parts[a]??0;if(l!==d)return l<d?-1:1}if(r.pre===o.pre)return 0;if(!r.pre&&o.pre)return 1;if(r.pre&&!o.pre)return -1;let s=Number.parseInt(r.pre.match(/(\d+)$/)?.[1]??"",10),i=Number.parseInt(o.pre.match(/(\d+)$/)?.[1]??"",10);return !Number.isNaN(s)&&!Number.isNaN(i)&&s!==i?s<i?-1:1:r.pre<o.pre?-1:r.pre>o.pre?1:0}function x(e,t){return Lt(e,t)<0}var Ie=m.win32,Le=1;function Ne(e,t){if(!e.existsSync(t))return null;try{let n=JSON.parse(e.readFileSync(t));return {schema:n.schema??Le,shortcutPath:n.shortcutPath,version:n.version,iconHash:typeof n.iconHash=="string"?n.iconHash:void 0,owned:!!n.owned,declined:!!n.declined,desktopSource:n.desktopSource,updatedAt:n.updatedAt}}catch{return null}}function M(e,t,n){let r={schema:Le,...n,updatedAt:new Date().toISOString()};e.mkdirSync(Ie.dirname(t)),e.writeFileSync(t,JSON.stringify(r,null,2));}function F(e,t){if(!e.existsSync(t))return null;try{let n=JSON.parse(e.readFileSync(t));return {schema:n.schema??0,binPath:n.binPath,updatedAt:n.updatedAt}}catch{return null}}function Oe(e,t,n){e.mkdirSync(Ie.dirname(t)),e.writeFileSync(t,JSON.stringify(n,null,2));}var Nt=m.win32,I=1;function Ot(e){return e.replace(/%/g,"%%")}function Dt(e){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%/"',"",e.bakedBinPath?`set "CREWX_FALLBACK_BIN=${Ot(e.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 Te(e){let t=F(e.fs,e.launcherManifestPath),n=!!t&&t.schema>=I&&e.fs.existsSync(e.wrapperPath),r=n&&!t.binPath&&!!e.bakedBinPath;if(n&&!r)return {wrapperPath:e.wrapperPath,wrote:false,schema:t.schema};let c=Dt({bakedBinPath:e.bakedBinPath});try{e.fs.mkdirSync(Nt.dirname(e.wrapperPath)),e.fs.writeFileSync(e.wrapperPath,c),Oe(e.fs,e.launcherManifestPath,{schema:I,binPath:e.bakedBinPath,updatedAt:new Date().toISOString()});}catch(s){throw s instanceof p?s:new p("WRITE_DENIED",`Could not write launcher wrapper: ${s instanceof Error?s.message:String(s)}`)}return {wrapperPath:e.wrapperPath,wrote:true,schema:I}}var Tt=["$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("; "),At=["[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 Ae(e){let t={...e.env,CREWX_LNK_PATH:e.shortcutPath,CREWX_LNK_TARGET:e.targetPath,CREWX_LNK_WORKDIR:e.workingDirectory??"",CREWX_LNK_ICON:e.iconPath??""},n;try{n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",Tt],{env:t});}catch(r){throw new p("POWERSHELL_UNAVAILABLE",`Could not run PowerShell: ${r instanceof Error?r.message:String(r)}`)}if(n.code!==0)throw new p("POWERSHELL_UNAVAILABLE",`Failed to create desktop shortcut: ${n.stderr||n.stdout}`)}function We(e){let t=e.trim(),n=t.lastIndexOf(",");return n!==-1&&/^-?\d+$/.test(t.slice(n+1).trim())&&(t=t.slice(0,n).trim()),t.length>=2&&t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1).trim()),t}async function Me(e){try{let t={...e.env,CREWX_LNK_PATH:e.shortcutPath},n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",At],{env:t});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 j=m.win32;async function L(e){let t=J(e.env.PATH??e.env.Path??"",e.cwd),n={...e.env,PATH:t,Path:t},r;try{r=await e.run("npm",["list","-g","crewx","--depth=0","--json"],{env:n});}catch{return {installed:false}}let o;try{o=JSON.parse(r.stdout||"{}");}catch{return {installed:false}}let c=o.dependencies?.crewx;if(!c?.version)return {installed:false};let s;try{let a=await e.run("npm",["prefix","-g"],{env:n});a.code===0&&(s=a.stdout.trim()||void 0);}catch{}let i=s?j.join(s,"crewx.cmd"):void 0;return {installed:true,version:c.version,binPath:i,prefix:s}}var Wt=/EACCES|EPERM|EROFS/,Mt=/ENOTFOUND|ETIMEDOUT|ECONNREFUSED|network|registry/i,Ft=/^\d+\.\d+\.\d+/;function Bt(e){return !!e&&e!=="0.0.0"&&Ft.test(e)}var K=10*6e4;async function Be(e){if(!Bt(e.targetVersion))throw new p("GLOBAL_INSTALL_FAILED",`RUNNING_VERSION_UNKNOWN: cannot reliably determine the running crewx version to install (got ${JSON.stringify(e.targetVersion)}); refusing to fall back to crewx@latest`);if(e.currentInfo?.installed&&e.currentInfo.version&&!x(e.currentInfo.version,e.targetVersion))return {info:e.currentInfo};let t=J(e.env.PATH??e.env.Path??"",e.cwd),n={...e.env,PATH:t,Path:t},r=`crewx@${e.targetVersion}`;e.onProgress?.({phase:"global-install",message:`Installing crewx globally (npm install -g ${r})`});let o;try{o=await e.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:n,timeoutMs:K});}catch(s){throw new p("NPM_UNAVAILABLE",`Could not run npm: ${s instanceof Error?s.message:String(s)}`)}if(o.code===0)return {info:await L({env:n,cwd:e.cwd,run:e.run})};let c=`${o.stdout}
|
|
3
|
+
${o.stderr}`;if(Wt.test(c)){e.onProgress?.({phase:"global-install",message:"Permission denied \u2014 retrying with a user-scoped npm prefix"});let s=e.env.LOCALAPPDATA||j.join(e.env.USERPROFILE??"","AppData","Local"),i={...n,npm_config_prefix:j.join(s,"crewx","npm")},a;try{a=await e.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:i,timeoutMs:K});}catch(l){throw new p("NPM_PERMISSION_DENIED",`Retry with user-scoped prefix failed: ${l instanceof Error?l.message:String(l)}`)}if(a.code===0)return {info:await L({env:i,cwd:e.cwd,run:e.run})};throw new p("NPM_PERMISSION_DENIED",`npm install -g failed after user-scoped prefix retry: ${a.stderr||a.stdout}`)}if(Mt.test(c)){if(!e.installRoot)throw new p("OFFLINE_NO_SOURCE","The npm registry is unreachable and no local installRoot was provided for an offline install");e.onProgress?.({phase:"global-install",message:`Registry unreachable \u2014 installing offline from ${e.installRoot}`});let s;try{s=await e.run("npm",["install","-g",e.installRoot,"--offline","--no-audit","--no-fund"],{env:n,timeoutMs:K});}catch(i){throw new p("GLOBAL_INSTALL_FAILED",`Offline install failed: ${i instanceof Error?i.message:String(i)}`)}if(s.code===0)return {info:await L({env:n,cwd:e.cwd,run:e.run})};throw new p("GLOBAL_INSTALL_FAILED",`Offline install failed: ${s.stderr||s.stdout}`)}throw new p("GLOBAL_INSTALL_FAILED",c.trim()||`npm install -g ${r} failed`)}function Ht(e){return e.run??Pe}function Ut(e){return e.fs??Q}async function B(e){let t=e.platform??process.platform,n=e.env??process.env,r=e.homedir??Z,o=Ht(e),c=Ut(e),s=e.runningVersion??Ee,i=e.cwd??process.cwd(),a=r(),l=ye(a),d=ve(a),f=Re(a),u=null;t==="win32"&&(u=await ke({env:n,homedir:r,run:o}));let E=u?be(u.dir):null;return {platform:t,env:n,homedir:r,run:o,fs:c,runningVersion:s,cwd:i,installRoot:e.installRoot,shortcutManifestPath:l,launcherManifestPath:d,wrapperPath:f,desktop:u,shortcutPath:E}}function $e(e){return e?m.win32.normalize(e).toLowerCase().endsWith(`${m.win32.sep}bin${m.win32.sep}crewx.ico`):false}function z(e,t){let n=e.readBinaryFileSync;if(n)try{return createHash("sha256").update(n(t)).digest("hex")}catch{return}}async function Vt(e){try{await e.run("ie4uinit.exe",["-show"],{env:e.env});}catch{}}async function R(e){if(e.platform!=="win32")return {supported:false,state:"unsupported",globalCrewx:null,runningVersion:e.runningVersion,errors:[],manifest:null,iconStale:false};let t=[];e.desktop||t.push("NO_DESKTOP_DIR: could not resolve the Windows Desktop directory");let n=Ne(e.fs,e.shortcutManifestPath),r=F(e.fs,e.launcherManifestPath),o=await L({env:e.env,cwd:e.cwd,run:e.run}),c=e.shortcutPath?e.fs.existsSync(e.shortcutPath):false,s,i=false,a,l;if(!c)s=n?.declined?"declined":"not-installed";else {let d=!!n?.owned&&!!e.shortcutPath&&n.shortcutPath===e.shortcutPath,f=false,u=e.shortcutPath?await Me({run:e.run,env:e.env,shortcutPath:e.shortcutPath}):null;if(d||(u&&G(u.targetPath,e.wrapperPath)?d=true:u&&_e(u.targetPath)&&(f=true)),f)s="foreign",t.push("NSIS_PRESENT: an NSIS-installed CrewX shortcut was detected");else if(!d)s="foreign";else if(n?.version&&x(e.runningVersion,n.version))s="superseded",t.push(`SUPERSEDED: running version ${e.runningVersion} is older than the installed shortcut's version ${n.version}; refusing to modify it`);else {let E=!r||r.schema<I||!e.fs.existsSync(e.wrapperPath);if(u){let h=We(u.iconLocation);if(!(!!h&&e.fs.existsSync(h)))i=true;else {a=h;let g=He(o,e.fs);g?G(h,g)?(l=z(e.fs,h),i=!l||n?.iconHash!==l):i=true:$e(h)?(l=z(e.fs,h),i=!l||n?.iconHash!==l):i=true;}}s=E||i?"stale":"installed";}}return {supported:true,state:s,shortcutPath:e.shortcutPath??void 0,desktopDir:e.desktop?.dir,desktopSource:e.desktop?.source,wrapperPath:e.wrapperPath,wrapperSchema:r?.schema,globalCrewx:o.installed?o:{installed:false},runningVersion:e.runningVersion,errors:t,manifest:n,iconStale:i,iconPath:a,iconHash:l}}function He(e,t){if(!e?.installed||!e.prefix)return;let n=m.win32.join(e.prefix,"node_modules","crewx","bin","crewx.ico");return t.existsSync(n)?n:void 0}function b(e){let{manifest:t,iconStale:n,iconPath:r,iconHash:o,...c}=e;return c}async function Xt(e={}){let t=await B(e),n=await R(t);return b(n)}async function Gt(e={}){let t=await B(e);e.onProgress?.({phase:"detect",message:"Checking current shortcut status"});let n=await R(t),r=b(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 p("NSIS_PRESENT",`An NSIS-installed CrewX shortcut was detected at ${r.shortcutPath}`);if(!e.force)throw new p("FOREIGN_SHORTCUT",`An existing shortcut at ${r.shortcutPath} is not managed by CrewX`)}if(!t.desktop||!t.shortcutPath)throw new p("NO_DESKTOP_DIR","Could not resolve the Windows Desktop directory");let o=false,c=false,s=r.globalCrewx,i=[],a=n.manifest?.iconHash,l=false;if(!!s?.installed&&!!s.version&&x(s.version,t.runningVersion)||!s?.installed&&r.state!=="installed"){let g=await Be({env:t.env,cwd:t.cwd,run:t.run,targetVersion:t.runningVersion,currentInfo:s??void 0,installRoot:t.installRoot,onProgress:e.onProgress});s=g.info,c=g.info.installed,o=true,c||i.push(`GLOBAL_INSTALL_UNCONFIRMED: npm install -g crewx@${t.runningVersion} exited successfully but a follow-up check could not confirm the global install`);}if(e.onProgress?.({phase:"wrapper",message:"Ensuring launcher wrapper"}),Te({fs:t.fs,wrapperPath:t.wrapperPath,launcherManifestPath:t.launcherManifestPath,bakedBinPath:s?.binPath}).wrote&&(o=true),!((r.state==="installed"||r.state==="stale")&&!n.iconStale)){let g=He(s,t.fs)??(n.iconPath&&$e(n.iconPath)&&t.fs.existsSync(n.iconPath)?n.iconPath:void 0);if(n.iconStale&&!g)throw new p("ICON_UNAVAILABLE",`Could not locate the global CrewX icon (bin\\crewx.ico) to repair the desktop shortcut at ${t.shortcutPath}; the existing shortcut was left untouched`);e.onProgress?.({phase:"lnk",message:"Creating desktop shortcut"}),await Ae({run:t.run,env:t.env,shortcutPath:t.shortcutPath,targetPath:t.wrapperPath,iconPath:g}),o=true,l=n.iconStale;let w=g?z(t.fs,g):void 0;w&&(a=w);}o&&M(t.fs,t.shortcutManifestPath,{shortcutPath:t.shortcutPath,version:t.runningVersion,owned:true,declined:false,desktopSource:t.desktop.source,iconHash:a}),l&&await Vt(t);let h=await R(t),y=b(h);return {...y,errors:[...y.errors,...i],changed:o,installedGlobal:c}}async function Jt(e={}){let t=await B(e),n=await R(t),r=b(n);if(!r.supported)return r;if((r.state==="installed"||r.state==="stale")&&t.shortcutPath)try{t.fs.unlinkSync(t.shortcutPath);}catch{}M(t.fs,t.shortcutManifestPath,{shortcutPath:void 0,version:n.manifest?.version,owned:false,declined:true,desktopSource:void 0,iconHash:void 0});let o=await R(t);return b(o)}async function Kt(e={}){let t=await B(e),n=await R(t),r=b(n);if(!r.supported)return r;M(t.fs,t.shortcutManifestPath,{shortcutPath:n.manifest?.shortcutPath,version:n.manifest?.version,owned:n.manifest?.owned??false,declined:true,desktopSource:n.manifest?.desktopSource,iconHash:n.manifest?.iconHash});let o=await R(t);return b(o)}export{p as ShortcutError,Kt as dismissShortcutNotice,Xt as getShortcutStatus,Gt as installShortcut,we as killProcessTree,Jt as uninstallShortcut};
|