@crewx/sdk 0.9.0-rc.90 → 0.9.0-rc.91
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 +3 -3
- package/dist/esm/desktop/index.js +3 -3
- package/dist/esm/index.js +114 -114
- package/dist/index.d.ts +2 -0
- package/dist/index.js +113 -113
- package/dist/internal/console-decoder.d.ts +38 -0
- package/dist/provider/acp/connection.d.ts +2 -0
- package/package.json +1 -1
package/dist/desktop/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var d=require('path'),crypto=require('crypto'),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 D=(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 f=class extends Error{code;constructor(t,n){super(`${t}: ${n}`),this.code=t,this.name="ShortcutError";}};var X={existsSync:e=>fs.existsSync(e),readFileSync:e=>fs.readFileSync(e,"utf8"),readBinaryFileSync:e=>new Uint8Array(fs.readFileSync(e)),writeFileSync:(e,t)=>fs.writeFileSync(e,t,"utf8"),mkdirSync:e=>{fs.mkdirSync(e,{recursive:true});},unlinkSync:e=>{fs.unlinkSync(e);}},G=os.homedir;function _(e){return typeof e!="string"?void 0:e.trim()||void 0}function N(e){return _(e)?.toLowerCase()??""}function v(e){try{return fs.statSync(e).isFile()}catch{return false}}function Le(e,t){if(e===t)return true;let n=d__namespace.default.relative(e,t);return n!==""&&!n.startsWith("..")&&!d__namespace.default.isAbsolute(n)}function ke(e,t){if(d__namespace.default.basename(e)!==".bin")return false;let n=d__namespace.default.dirname(e);if(d__namespace.default.basename(n)!=="node_modules")return false;let r=d__namespace.default.dirname(n);return Le(r,t)}function U(e,t={}){if(e.includes("/")||e.includes("\\")||d__namespace.default.isAbsolute(e))return e;let n=t.platform??process.platform,r=t.env??process.env,i=d__namespace.default.resolve(t.cwd??process.cwd()),l=(t.resolution??"global_first")==="global_first",o=r.PATH??r.Path??process.env.PATH??process.env.Path??"",s=n==="win32"?";":":",a=o.split(s).map(u=>u.trim()).filter(Boolean),c=d__namespace.default.extname(e).length>0,h=r.PATHEXT??r.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",m=n==="win32"?c?[""]: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(i,u);if(!(l&&ke(p,i)))for(let w of m){let y=N(w),g=w.toUpperCase();for(let k of [w,y,g]){let H=d__namespace.default.join(p,`${e}${k}`);if(v(H))return H}}}return e}function _e(e){if(!v(e))return null;try{let t=fs.readFileSync(e,"utf8"),n=d__namespace.default.dirname(e),r=[];for(let s of t.matchAll(/"([^"\r\n]*)"/g)){let h=(s[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);v(u)&&r.push(u);}let i=[],l=new Map;for(let s of t.matchAll(/SET\s+"(\w+)=%~?dp0%?[\\/]?([^"]+)"/gi)){let a=s[1].toUpperCase(),c=s[2].trim().replace(/[\\/]+/g,d__namespace.default.sep).replace(/^[\\/]+/,"");l.set(a,d__namespace.default.resolve(n,c));}for(let s of t.split(/\r?\n/))if(s.includes("%*"))for(let a of s.matchAll(/"%(\w+)%"/g)){let c=l.get(a[1].toUpperCase());c&&v(c)&&i.push(c);}let o=s=>s.find(a=>{let c=N(d__namespace.default.basename(a));return c!=="node.exe"&&c!=="node"})??null;return o(i)??o(r)}catch{return null}}function Ne(e,t){if(typeof t=="string")return _(t)||null;if(!t||typeof t!="object")return null;if(e){let n=t[e],r=typeof n=="string"?_(n):void 0;if(r)return r}for(let n of Object.values(t)){let r=typeof n=="string"?_(n):void 0;if(r)return r}return null}function Oe(e,t){if(!t)return null;let n=d__namespace.default.dirname(e),r=[d__namespace.default.resolve(n,"..",t),d__namespace.default.resolve(n,"node_modules",t)];for(let i of r){let l=d__namespace.default.join(i,"package.json");if(v(l))try{let o=JSON.parse(fs.readFileSync(l,"utf8")),s=Ne(t,o.bin);if(!s)continue;let a=d__namespace.default.resolve(i,s);if(v(a))return a}catch{}}return null}function be(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:U(e.command,{cwd:i,env:n,platform:t,resolution:l}),leadingArgv:[],resolution:"direct"};let o=U(e.command,{cwd:i,env:n,platform:t,resolution:l}),s=N(d__namespace.default.extname(o));if(s===".js"||s===".cjs"||s===".mjs")return {command:r,leadingArgv:[o],resolution:"node-entrypoint",windowsHide:true};if(s===".cmd"||s===".bat"){let a=_e(o)??Oe(o,e.packageName);return a?N(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 Ae(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(`${d__namespace.default.basename(e.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function J(e){let t=be(e);return Ae({candidate:t})}function K(e,t){return {command:e.command,argv:[...e.leadingArgv,...t],resolution:e.resolution,shell:e.shell,windowsHide:e.windowsHide}}var z=3e4;function De(e){if(typeof e.pid!="number"){e.kill();return}if(process.platform==="win32"){child_process.spawn("taskkill",["/pid",String(e.pid),"/t","/f"],{windowsHide:true}).on("error",()=>{});return}try{process.kill(-e.pid,"SIGKILL");}catch{e.kill("SIGKILL");}}var Q=(e,t,n={})=>new Promise((r,i)=>{let l=n.env??process.env,o=process.platform,s;try{let p=J({command:e,platform:o,env:l,cwd:n.cwd,allowShellFallback:!1});s=K(p,t);}catch(p){i(p instanceof Error?p:new Error(String(p)));return}let a=child_process.spawn(s.command,s.argv,{cwd:n.cwd,env:l,shell:s.shell,windowsHide:s.windowsHide??true,detached:o!=="win32"}),c="",h="",m=false,u=setTimeout(()=>{m||(m=true,De(a),i(new Error(`Command timed out after ${n.timeoutMs??z}ms: ${e} ${t.join(" ")}`)));},n.timeoutMs??z);a.stdout?.on("data",p=>{c+=p.toString();}),a.stderr?.on("data",p=>{h+=p.toString();}),a.on("error",p=>{m||(m=true,clearTimeout(u),i(p));}),a.on("close",p=>{m||(m=true,clearTimeout(u),r({code:p??0,stdout:c,stderr:h}));});});function Fe(){try{return (typeof D=="function"?D:module$1.createRequire(__filename)).resolve("@crewx/sdk/package.json")}catch{return null}}function Me(){let e=[Fe(),d.join(__dirname,"../../package.json"),d.join(__dirname,"../../../package.json")].filter(t=>!!t);for(let t of e)try{let n=JSON.parse(fs.readFileSync(t,"utf8"));if(n.name==="@crewx/sdk"&&n.version)return n.version}catch{}return "0.0.0"}var Z=Me();var P=d__namespace.win32;function W(e){return P.join(e,".crewx")}function te(e){return P.join(W(e),"shortcut.json")}function ne(e){return P.join(W(e),"launcher.json")}function re(e){return P.join(W(e),"bin","crewx-launcher.cmd")}function oe(e){return P.join(e,"CrewX.lnk")}function T(e,t){return P.normalize(e).toLowerCase()===P.normalize(t).toLowerCase()}var Be="[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Environment]::GetFolderPath('DesktopDirectory')";async function se(e){try{let n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",Be],{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:P.join(t,"Desktop"),source:"fallback"}:null}function F(e,t){let n=P.resolve(t,"node_modules",".bin").toLowerCase();return e.split(";").filter(r=>r?P.resolve(r).toLowerCase()!==n:true).join(";")}function ie(e){return e?/\\Program Files( \(x86\))?\\/i.test(e)&&/crewx/i.test(e):false}function $e(e,t){let n=a=>{let[c,...h]=a.split("-"),m=h.join("-")||void 0;return {parts:(c??"").split(".").map(p=>Number.parseInt(p,10)||0),pre:m}},r=n(e),i=n(t),l=Math.max(r.parts.length,i.parts.length);for(let a=0;a<l;a++){let c=r.parts[a]??0,h=i.parts[a]??0;if(c!==h)return c<h?-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),s=Number.parseInt(i.pre.match(/(\d+)$/)?.[1]??"",10);return !Number.isNaN(o)&&!Number.isNaN(s)&&o!==s?o<s?-1:1:r.pre<i.pre?-1:r.pre>i.pre?1:0}function C(e,t){return $e(e,t)<0}var ce=d__namespace.win32,le=1;function ue(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 O(e,t,n){let r={schema:le,...n,updatedAt:new Date().toISOString()};e.mkdirSync(ce.dirname(t)),e.writeFileSync(t,JSON.stringify(r,null,2));}function b(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 de(e,t,n){e.mkdirSync(ce.dirname(t)),e.writeFileSync(t,JSON.stringify(n,null,2));}var He=d__namespace.win32,x=1;function Ve(e){return e.replace(/%/g,"%%")}function Xe(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=${Ve(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
|
-
${i.stderr}`;if(
|
|
1
|
+
'use strict';var f=require('path'),crypto=require('crypto'),fs=require('fs'),os=require('os'),child_process=require('child_process'),string_decoder=require('string_decoder'),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 f__namespace=/*#__PURE__*/_interopNamespace(f);var B=(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 h=class extends Error{code;constructor(t,n){super(`${t}: ${n}`),this.code=t,this.name="ShortcutError";}};var z={existsSync:e=>fs.existsSync(e),readFileSync:e=>fs.readFileSync(e,"utf8"),readBinaryFileSync:e=>new Uint8Array(fs.readFileSync(e)),writeFileSync:(e,t)=>fs.writeFileSync(e,t,"utf8"),mkdirSync:e=>{fs.mkdirSync(e,{recursive:true});},unlinkSync:e=>{fs.unlinkSync(e);}},q=os.homedir;function N(e){return typeof e!="string"?void 0:e.trim()||void 0}function O(e){return N(e)?.toLowerCase()??""}function b(e){try{return fs.statSync(e).isFile()}catch{return false}}function Me(e,t){if(e===t)return true;let n=f__namespace.default.relative(e,t);return n!==""&&!n.startsWith("..")&&!f__namespace.default.isAbsolute(n)}function $e(e,t){if(f__namespace.default.basename(e)!==".bin")return false;let n=f__namespace.default.dirname(e);if(f__namespace.default.basename(n)!=="node_modules")return false;let r=f__namespace.default.dirname(n);return Me(r,t)}function Y(e,t={}){if(e.includes("/")||e.includes("\\")||f__namespace.default.isAbsolute(e))return e;let n=t.platform??process.platform,r=t.env??process.env,i=f__namespace.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__namespace.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 S=f__namespace.default.resolve(i,u);if(!(l&&$e(S,i)))for(let w of p){let v=O(w),m=w.toUpperCase();for(let g of [w,v,m]){let y=f__namespace.default.join(S,`${e}${g}`);if(b(y))return y}}}return e}function He(e){if(!b(e))return null;try{let t=fs.readFileSync(e,"utf8"),n=f__namespace.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__namespace.default.sep).replace(/^[\\/]+/,""),u=f__namespace.default.resolve(n,p);b(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__namespace.default.sep).replace(/^[\\/]+/,"");l.set(s,f__namespace.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&&b(c)&&i.push(c);}let o=a=>a.find(s=>{let c=O(f__namespace.default.basename(s));return c!=="node.exe"&&c!=="node"})??null;return o(i)??o(r)}catch{return null}}function Ve(e,t){if(typeof t=="string")return N(t)||null;if(!t||typeof t!="object")return null;if(e){let n=t[e],r=typeof n=="string"?N(n):void 0;if(r)return r}for(let n of Object.values(t)){let r=typeof n=="string"?N(n):void 0;if(r)return r}return null}function Ue(e,t){if(!t)return null;let n=f__namespace.default.dirname(e),r=[f__namespace.default.resolve(n,"..",t),f__namespace.default.resolve(n,"node_modules",t)];for(let i of r){let l=f__namespace.default.join(i,"package.json");if(b(l))try{let o=JSON.parse(fs.readFileSync(l,"utf8")),a=Ve(t,o.bin);if(!a)continue;let s=f__namespace.default.resolve(i,a);if(b(s))return s}catch{}}return null}function Xe(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:Y(e.command,{cwd:i,env:n,platform:t,resolution:l}),leadingArgv:[],resolution:"direct"};let o=Y(e.command,{cwd:i,env:n,platform:t,resolution:l}),a=O(f__namespace.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=He(o)??Ue(o,e.packageName);return s?O(f__namespace.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 Ge(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__namespace.default.basename(e.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function Z(e){let t=Xe(e);return Ge({candidate:t})}function ee(e,t){return {command:e.command,argv:[...e.leadingArgv,...t],resolution:e.resolution,shell:e.shell,windowsHide:e.windowsHide}}var A="\uFFFD",M=8,ne=1e3,je=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"]]),D;function H(e){let t=0;for(let n of e)n===A&&(t+=1);return t}function $(e,t){return H(t)<H(e)?t:e}function Ke(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 ze(e){if(e!==65001)return je.get(e)}function qe(e){let t=ze(e);if(!t)return null;try{return new TextDecoder(t)}catch{return null}}function Ye(){return new Promise(e=>{let t=false,n,r=i=>{t||(t=true,n&&clearTimeout(n),e(i));};n=setTimeout(()=>r(null),ne),n.unref();try{child_process.execFile("chcp.com",[],{encoding:"ascii",timeout:ne,windowsHide:!0},(l,o)=>{if(l){r(null);return}r(Ke(String(o)));}).once("error",()=>r(null));}catch{r(null);}})}function ie(){return process.platform!=="win32"?Promise.resolve(null):(D||(D=Ye(),D.then(e=>{},()=>{})),D)}function Qe(){process.platform==="win32"&&ie();}function oe(e,t){if(t.length>=M)return t.subarray(t.length-M);let n=M-t.length,r=e.length>n?e.subarray(e.length-n):e;return Buffer.concat([r,t])}var k=class{platform;detectCodePage;utf8Decoder=new string_decoder.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??ie,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:qe(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 string_decoder.StringDecoder("utf8")),this.platform!=="win32")return n;if(this.fallbackDecoder){let s=this.fallbackDecoder.decode(t,{stream:true}),c=oe(this.pendingBytes,t);if(r){let d=this.pendingUtf8+n,p=this.pendingFallback+s;return this.clearPendingCandidate(),$(d,p)}if(H(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=oe(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 $(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(A)){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(A)?$(n,i):n}};Qe();var se=3e4;function Ze(e){if(typeof e.pid!="number"){e.kill();return}if(process.platform==="win32"){child_process.spawn("taskkill",["/pid",String(e.pid),"/t","/f"],{windowsHide:true}).on("error",()=>{});return}try{process.kill(-e.pid,"SIGKILL");}catch{e.kill("SIGKILL");}}var ce=(e,t,n={})=>new Promise((r,i)=>{let l=n.env??process.env,o=process.platform,a;try{let g=Z({command:e,platform:o,env:l,cwd:n.cwd,allowShellFallback:!1});a=ee(g,t);}catch(g){i(g instanceof Error?g:new Error(String(g)));return}let s=child_process.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 k({platform:o}),S=new k({platform:o}),w=Promise.resolve(),v=Promise.resolve(),m=setTimeout(()=>{p||(p=true,Ze(s),i(new Error(`Command timed out after ${n.timeoutMs??se}ms: ${e} ${t.join(" ")}`)));},n.timeoutMs??se);s.stdout?.on("data",g=>{w=w.then(async()=>{c+=await u.write(g);});}),s.stderr?.on("data",g=>{v=v.then(async()=>{d+=await S.write(g);});}),s.on("error",g=>{p||(p=true,clearTimeout(m),i(g));}),s.on("close",g=>{p||(async()=>{await Promise.all([w,v]);let[y,Oe]=await Promise.all([u.end(),S.end()]);p||(c+=y,d+=Oe,p=true,clearTimeout(m),r({code:g??0,stdout:c,stderr:d}));})().catch(y=>{p||(p=true,clearTimeout(m),i(y instanceof Error?y:new Error(String(y))));});});});function nt(){try{return (typeof B=="function"?B:module$1.createRequire(__filename)).resolve("@crewx/sdk/package.json")}catch{return null}}function rt(){let e=[nt(),f.join(__dirname,"../../package.json"),f.join(__dirname,"../../../package.json")].filter(t=>!!t);for(let t of e)try{let n=JSON.parse(fs.readFileSync(t,"utf8"));if(n.name==="@crewx/sdk"&&n.version)return n.version}catch{}return "0.0.0"}var ue=rt();var E=f__namespace.win32;function V(e){return E.join(e,".crewx")}function fe(e){return E.join(V(e),"shortcut.json")}function pe(e){return E.join(V(e),"launcher.json")}function he(e){return E.join(V(e),"bin","crewx-launcher.cmd")}function me(e){return E.join(e,"CrewX.lnk")}function U(e,t){return E.normalize(e).toLowerCase()===E.normalize(t).toLowerCase()}var ot="[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Environment]::GetFolderPath('DesktopDirectory')";async function ge(e){try{let n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",ot],{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:E.join(t,"Desktop"),source:"fallback"}:null}function X(e,t){let n=E.resolve(t,"node_modules",".bin").toLowerCase();return e.split(";").filter(r=>r?E.resolve(r).toLowerCase()!==n:true).join(";")}function we(e){return e?/\\Program Files( \(x86\))?\\/i.test(e)&&/crewx/i.test(e):false}function it(e,t){let n=s=>{let[c,...d]=s.split("-"),p=d.join("-")||void 0;return {parts:(c??"").split(".").map(S=>Number.parseInt(S,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 x(e,t){return it(e,t)<0}var Pe=f__namespace.win32,Ee=1;function ve(e,t){if(!e.existsSync(t))return null;try{let n=JSON.parse(e.readFileSync(t));return {schema:n.schema??Ee,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 T(e,t,n){let r={schema:Ee,...n,updatedAt:new Date().toISOString()};e.mkdirSync(Pe.dirname(t)),e.writeFileSync(t,JSON.stringify(r,null,2));}function W(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 ye(e,t,n){e.mkdirSync(Pe.dirname(t)),e.writeFileSync(t,JSON.stringify(n,null,2));}var st=f__namespace.win32,_=1;function at(e){return e.replace(/%/g,"%%")}function ct(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=${at(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 Re(e){let t=W(e.fs,e.launcherManifestPath),n=!!t&&t.schema>=_&&e.fs.existsSync(e.wrapperPath),r=n&&!t.binPath&&!!e.bakedBinPath;if(n&&!r)return {wrapperPath:e.wrapperPath,wrote:false,schema:t.schema};let l=ct({bakedBinPath:e.bakedBinPath});try{e.fs.mkdirSync(st.dirname(e.wrapperPath)),e.fs.writeFileSync(e.wrapperPath,l),ye(e.fs,e.launcherManifestPath,{schema:_,binPath:e.bakedBinPath,updatedAt:new Date().toISOString()});}catch(o){throw o instanceof h?o:new h("WRITE_DENIED",`Could not write launcher wrapper: ${o instanceof Error?o.message:String(o)}`)}return {wrapperPath:e.wrapperPath,wrote:true,schema:_}}var lt=["$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("; "),ut=["[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 be(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",lt],{env:t});}catch(r){throw new h("POWERSHELL_UNAVAILABLE",`Could not run PowerShell: ${r instanceof Error?r.message:String(r)}`)}if(n.code!==0)throw new h("POWERSHELL_UNAVAILABLE",`Failed to create desktop shortcut: ${n.stderr||n.stdout}`)}function ke(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 xe(e){try{let t={...e.env,CREWX_LNK_PATH:e.shortcutPath},n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",ut],{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=f__namespace.win32;async function I(e){let t=X(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 i;try{i=JSON.parse(r.stdout||"{}");}catch{return {installed:false}}let l=i.dependencies?.crewx;if(!l?.version)return {installed:false};let o;try{let s=await e.run("npm",["prefix","-g"],{env:n});s.code===0&&(o=s.stdout.trim()||void 0);}catch{}let a=o?J.join(o,"crewx.cmd"):void 0;return {installed:true,version:l.version,binPath:a,prefix:o}}var dt=/EACCES|EPERM|EROFS/,ft=/ENOTFOUND|ETIMEDOUT|ECONNREFUSED|network|registry/i,pt=/^\d+\.\d+\.\d+/;function ht(e){return !!e&&e!=="0.0.0"&&pt.test(e)}var G=10*6e4;async function Ie(e){if(!ht(e.targetVersion))throw new h("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=X(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 i;try{i=await e.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:n,timeoutMs:G});}catch(o){throw new h("NPM_UNAVAILABLE",`Could not run npm: ${o instanceof Error?o.message:String(o)}`)}if(i.code===0)return {info:await I({env:n,cwd:e.cwd,run:e.run})};let l=`${i.stdout}
|
|
3
|
+
${i.stderr}`;if(dt.test(l)){e.onProgress?.({phase:"global-install",message:"Permission denied \u2014 retrying with a user-scoped npm prefix"});let o=e.env.LOCALAPPDATA||J.join(e.env.USERPROFILE??"","AppData","Local"),a={...n,npm_config_prefix:J.join(o,"crewx","npm")},s;try{s=await e.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:a,timeoutMs:G});}catch(c){throw new h("NPM_PERMISSION_DENIED",`Retry with user-scoped prefix failed: ${c instanceof Error?c.message:String(c)}`)}if(s.code===0)return {info:await I({env:a,cwd:e.cwd,run:e.run})};throw new h("NPM_PERMISSION_DENIED",`npm install -g failed after user-scoped prefix retry: ${s.stderr||s.stdout}`)}if(ft.test(l)){if(!e.installRoot)throw new h("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 o;try{o=await e.run("npm",["install","-g",e.installRoot,"--offline","--no-audit","--no-fund"],{env:n,timeoutMs:G});}catch(a){throw new h("GLOBAL_INSTALL_FAILED",`Offline install failed: ${a instanceof Error?a.message:String(a)}`)}if(o.code===0)return {info:await I({env:n,cwd:e.cwd,run:e.run})};throw new h("GLOBAL_INSTALL_FAILED",`Offline install failed: ${o.stderr||o.stdout}`)}throw new h("GLOBAL_INSTALL_FAILED",l.trim()||`npm install -g ${r} failed`)}function gt(e){return e.run??ce}function wt(e){return e.fs??z}async function F(e){let t=e.platform??process.platform,n=e.env??process.env,r=e.homedir??q,i=gt(e),l=wt(e),o=e.runningVersion??ue,a=e.cwd??process.cwd(),s=r(),c=fe(s),d=pe(s),p=he(s),u=null;t==="win32"&&(u=await ge({env:n,homedir:r,run:i}));let S=u?me(u.dir):null;return {platform:t,env:n,homedir:r,run:i,fs:l,runningVersion:o,cwd:a,installRoot:e.installRoot,shortcutManifestPath:c,launcherManifestPath:d,wrapperPath:p,desktop:u,shortcutPath:S}}function Le(e){return e?f__namespace.win32.normalize(e).toLowerCase().endsWith(`${f__namespace.win32.sep}bin${f__namespace.win32.sep}crewx.ico`):false}function j(e,t){let n=e.readBinaryFileSync;if(n)try{return crypto.createHash("sha256").update(n(t)).digest("hex")}catch{return}}async function St(e){try{await e.run("ie4uinit.exe",["-show"],{env:e.env});}catch{}}async function C(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=ve(e.fs,e.shortcutManifestPath),r=W(e.fs,e.launcherManifestPath),i=await I({env:e.env,cwd:e.cwd,run:e.run}),l=e.shortcutPath?e.fs.existsSync(e.shortcutPath):false,o,a=false,s,c;if(!l)o=n?.declined?"declined":"not-installed";else {let d=!!n?.owned&&!!e.shortcutPath&&n.shortcutPath===e.shortcutPath,p=false,u=e.shortcutPath?await xe({run:e.run,env:e.env,shortcutPath:e.shortcutPath}):null;if(d||(u&&U(u.targetPath,e.wrapperPath)?d=true:u&&we(u.targetPath)&&(p=true)),p)o="foreign",t.push("NSIS_PRESENT: an NSIS-installed CrewX shortcut was detected");else if(!d)o="foreign";else if(n?.version&&x(e.runningVersion,n.version))o="superseded",t.push(`SUPERSEDED: running version ${e.runningVersion} is older than the installed shortcut's version ${n.version}; refusing to modify it`);else {let S=!r||r.schema<_||!e.fs.existsSync(e.wrapperPath);if(u){let w=ke(u.iconLocation);if(!(!!w&&e.fs.existsSync(w)))a=true;else {s=w;let m=Ne(i,e.fs);m?U(w,m)?(c=j(e.fs,w),a=!c||n?.iconHash!==c):a=true:Le(w)?(c=j(e.fs,w),a=!c||n?.iconHash!==c):a=true;}}o=S||a?"stale":"installed";}}return {supported:true,state:o,shortcutPath:e.shortcutPath??void 0,desktopDir:e.desktop?.dir,desktopSource:e.desktop?.source,wrapperPath:e.wrapperPath,wrapperSchema:r?.schema,globalCrewx:i.installed?i:{installed:false},runningVersion:e.runningVersion,errors:t,manifest:n,iconStale:a,iconPath:s,iconHash:c}}function Ne(e,t){if(!e?.installed||!e.prefix)return;let n=f__namespace.win32.join(e.prefix,"node_modules","crewx","bin","crewx.ico");return t.existsSync(n)?n:void 0}function R(e){let{manifest:t,iconStale:n,iconPath:r,iconHash:i,...l}=e;return l}async function Pt(e={}){let t=await F(e),n=await C(t);return R(n)}async function Et(e={}){let t=await F(e);e.onProgress?.({phase:"detect",message:"Checking current shortcut status"});let n=await C(t),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(m=>m.startsWith("NSIS_PRESENT")))throw new h("NSIS_PRESENT",`An NSIS-installed CrewX shortcut was detected at ${r.shortcutPath}`);if(!e.force)throw new h("FOREIGN_SHORTCUT",`An existing shortcut at ${r.shortcutPath} is not managed by CrewX`)}if(!t.desktop||!t.shortcutPath)throw new h("NO_DESKTOP_DIR","Could not resolve the Windows Desktop directory");let i=false,l=false,o=r.globalCrewx,a=[],s=n.manifest?.iconHash,c=false;if(!!o?.installed&&!!o.version&&x(o.version,t.runningVersion)||!o?.installed&&r.state!=="installed"){let m=await Ie({env:t.env,cwd:t.cwd,run:t.run,targetVersion:t.runningVersion,currentInfo:o??void 0,installRoot:t.installRoot,onProgress:e.onProgress});o=m.info,l=m.info.installed,i=true,l||a.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"}),Re({fs:t.fs,wrapperPath:t.wrapperPath,launcherManifestPath:t.launcherManifestPath,bakedBinPath:o?.binPath}).wrote&&(i=true),!((r.state==="installed"||r.state==="stale")&&!n.iconStale)){let m=Ne(o,t.fs)??(n.iconPath&&Le(n.iconPath)&&t.fs.existsSync(n.iconPath)?n.iconPath:void 0);if(n.iconStale&&!m)throw new h("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 be({run:t.run,env:t.env,shortcutPath:t.shortcutPath,targetPath:t.wrapperPath,iconPath:m}),i=true,c=n.iconStale;let g=m?j(t.fs,m):void 0;g&&(s=g);}i&&T(t.fs,t.shortcutManifestPath,{shortcutPath:t.shortcutPath,version:t.runningVersion,owned:true,declined:false,desktopSource:t.desktop.source,iconHash:s}),c&&await St(t);let w=await C(t),v=R(w);return {...v,errors:[...v.errors,...a],changed:i,installedGlobal:l}}async function vt(e={}){let t=await F(e),n=await C(t),r=R(n);if(!r.supported)return r;if((r.state==="installed"||r.state==="stale")&&t.shortcutPath)try{t.fs.unlinkSync(t.shortcutPath);}catch{}T(t.fs,t.shortcutManifestPath,{shortcutPath:void 0,version:n.manifest?.version,owned:false,declined:true,desktopSource:void 0,iconHash:void 0});let i=await C(t);return R(i)}async function yt(e={}){let t=await F(e),n=await C(t),r=R(n);if(!r.supported)return r;T(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 i=await C(t);return R(i)}exports.ShortcutError=h;exports.dismissShortcutNotice=yt;exports.getShortcutStatus=Pt;exports.installShortcut=Et;exports.uninstallShortcut=vt;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import*as d from'path';import d__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 {spawn}from'child_process';import {createRequire}from'module';var W=(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 X=()=>fileURLToPath(import.meta.url),xe=()=>d__default.dirname(X()),w=xe(),P=X();var f=class extends Error{code;constructor(t,n){super(`${t}: ${n}`),this.code=t,this.name="ShortcutError";}};var U={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);}},j=homedir;function N(e){return typeof e!="string"?void 0:e.trim()||void 0}function O(e){return N(e)?.toLowerCase()??""}function y(e){try{return statSync(e).isFile()}catch{return false}}function be(e,t){if(e===t)return true;let n=d__default.relative(e,t);return n!==""&&!n.startsWith("..")&&!d__default.isAbsolute(n)}function Ae(e,t){if(d__default.basename(e)!==".bin")return false;let n=d__default.dirname(e);if(d__default.basename(n)!=="node_modules")return false;let r=d__default.dirname(n);return be(r,t)}function J(e,t={}){if(e.includes("/")||e.includes("\\")||d__default.isAbsolute(e))return e;let n=t.platform??process.platform,r=t.env??process.env,i=d__default.resolve(t.cwd??process.cwd()),l=(t.resolution??"global_first")==="global_first",o=r.PATH??r.Path??process.env.PATH??process.env.Path??"",s=n==="win32"?";":":",a=o.split(s).map(u=>u.trim()).filter(Boolean),c=d__default.extname(e).length>0,h=r.PATHEXT??r.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",m=n==="win32"?c?[""]:h.split(";").map(u=>u.trim()).filter(Boolean).map(u=>u.startsWith(".")?u:`.${u}`):[""];for(let u of a){let p=d__default.resolve(i,u);if(!(l&&Ae(p,i)))for(let S of m){let C=O(S),g=S.toUpperCase();for(let _ of [S,C,g]){let V=d__default.join(p,`${e}${_}`);if(y(V))return V}}}return e}function De(e){if(!y(e))return null;try{let t=readFileSync(e,"utf8"),n=d__default.dirname(e),r=[];for(let s of t.matchAll(/"([^"\r\n]*)"/g)){let h=(s[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);y(u)&&r.push(u);}let i=[],l=new Map;for(let s of t.matchAll(/SET\s+"(\w+)=%~?dp0%?[\\/]?([^"]+)"/gi)){let a=s[1].toUpperCase(),c=s[2].trim().replace(/[\\/]+/g,d__default.sep).replace(/^[\\/]+/,"");l.set(a,d__default.resolve(n,c));}for(let s of t.split(/\r?\n/))if(s.includes("%*"))for(let a of s.matchAll(/"%(\w+)%"/g)){let c=l.get(a[1].toUpperCase());c&&y(c)&&i.push(c);}let o=s=>s.find(a=>{let c=O(d__default.basename(a));return c!=="node.exe"&&c!=="node"})??null;return o(i)??o(r)}catch{return null}}function We(e,t){if(typeof t=="string")return N(t)||null;if(!t||typeof t!="object")return null;if(e){let n=t[e],r=typeof n=="string"?N(n):void 0;if(r)return r}for(let n of Object.values(t)){let r=typeof n=="string"?N(n):void 0;if(r)return r}return null}function Te(e,t){if(!t)return null;let n=d__default.dirname(e),r=[d__default.resolve(n,"..",t),d__default.resolve(n,"node_modules",t)];for(let i of r){let l=d__default.join(i,"package.json");if(y(l))try{let o=JSON.parse(readFileSync(l,"utf8")),s=We(t,o.bin);if(!s)continue;let a=d__default.resolve(i,s);if(y(a))return a}catch{}}return null}function Fe(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:J(e.command,{cwd:i,env:n,platform:t,resolution:l}),leadingArgv:[],resolution:"direct"};let o=J(e.command,{cwd:i,env:n,platform:t,resolution:l}),s=O(d__default.extname(o));if(s===".js"||s===".cjs"||s===".mjs")return {command:r,leadingArgv:[o],resolution:"node-entrypoint",windowsHide:true};if(s===".cmd"||s===".bat"){let a=De(o)??Te(o,e.packageName);return a?O(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 Me(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(`${d__default.basename(e.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function z(e){let t=Fe(e);return Me({candidate:t})}function q(e,t){return {command:e.command,argv:[...e.leadingArgv,...t],resolution:e.resolution,shell:e.shell,windowsHide:e.windowsHide}}var Q=3e4;function Be(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 Z=(e,t,n={})=>new Promise((r,i)=>{let l=n.env??process.env,o=process.platform,s;try{let p=z({command:e,platform:o,env:l,cwd:n.cwd,allowShellFallback:!1});s=q(p,t);}catch(p){i(p instanceof Error?p:new Error(String(p)));return}let a=spawn(s.command,s.argv,{cwd:n.cwd,env:l,shell:s.shell,windowsHide:s.windowsHide??true,detached:o!=="win32"}),c="",h="",m=false,u=setTimeout(()=>{m||(m=true,Be(a),i(new Error(`Command timed out after ${n.timeoutMs??Q}ms: ${e} ${t.join(" ")}`)));},n.timeoutMs??Q);a.stdout?.on("data",p=>{c+=p.toString();}),a.stderr?.on("data",p=>{h+=p.toString();}),a.on("error",p=>{m||(m=true,clearTimeout(u),i(p));}),a.on("close",p=>{m||(m=true,clearTimeout(u),r({code:p??0,stdout:c,stderr:h}));});});function Ve(){try{return (typeof W=="function"?W:createRequire(P)).resolve("@crewx/sdk/package.json")}catch{return null}}function Xe(){let e=[Ve(),join(w,"../../package.json"),join(w,"../../../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 te=Xe();var E=d.win32;function T(e){return E.join(e,".crewx")}function re(e){return E.join(T(e),"shortcut.json")}function oe(e){return E.join(T(e),"launcher.json")}function se(e){return E.join(T(e),"bin","crewx-launcher.cmd")}function ie(e){return E.join(e,"CrewX.lnk")}function F(e,t){return E.normalize(e).toLowerCase()===E.normalize(t).toLowerCase()}var Ge="[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Environment]::GetFolderPath('DesktopDirectory')";async function ae(e){try{let n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",Ge],{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:E.join(t,"Desktop"),source:"fallback"}:null}function M(e,t){let n=E.resolve(t,"node_modules",".bin").toLowerCase();return e.split(";").filter(r=>r?E.resolve(r).toLowerCase()!==n:true).join(";")}function ce(e){return e?/\\Program Files( \(x86\))?\\/i.test(e)&&/crewx/i.test(e):false}function Ue(e,t){let n=a=>{let[c,...h]=a.split("-"),m=h.join("-")||void 0;return {parts:(c??"").split(".").map(p=>Number.parseInt(p,10)||0),pre:m}},r=n(e),i=n(t),l=Math.max(r.parts.length,i.parts.length);for(let a=0;a<l;a++){let c=r.parts[a]??0,h=i.parts[a]??0;if(c!==h)return c<h?-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),s=Number.parseInt(i.pre.match(/(\d+)$/)?.[1]??"",10);return !Number.isNaN(o)&&!Number.isNaN(s)&&o!==s?o<s?-1:1:r.pre<i.pre?-1:r.pre>i.pre?1:0}function x(e,t){return Ue(e,t)<0}var ue=d.win32,de=1;function pe(e,t){if(!e.existsSync(t))return null;try{let n=JSON.parse(e.readFileSync(t));return {schema:n.schema??de,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 b(e,t,n){let r={schema:de,...n,updatedAt:new Date().toISOString()};e.mkdirSync(ue.dirname(t)),e.writeFileSync(t,JSON.stringify(r,null,2));}function A(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 fe(e,t,n){e.mkdirSync(ue.dirname(t)),e.writeFileSync(t,JSON.stringify(n,null,2));}var je=d.win32,L=1;function Je(e){return e.replace(/%/g,"%%")}function Ke(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=${Je(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
|
-
${i.stderr}`;if(
|
|
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 ke(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 l=pt({bakedBinPath:e.bakedBinPath});try{e.fs.mkdirSync(dt.dirname(e.wrapperPath)),e.fs.writeFileSync(e.wrapperPath,l),Re(e.fs,e.launcherManifestPath,{schema:I,binPath:e.bakedBinPath,updatedAt:new Date().toISOString()});}catch(o){throw o instanceof h?o:new h("WRITE_DENIED",`Could not write launcher wrapper: ${o instanceof Error?o.message:String(o)}`)}return {wrapperPath:e.wrapperPath,wrote:true,schema:I}}var ht=["$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("; "),mt=["[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 xe(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",ht],{env:t});}catch(r){throw new h("POWERSHELL_UNAVAILABLE",`Could not run PowerShell: ${r instanceof Error?r.message:String(r)}`)}if(n.code!==0)throw new h("POWERSHELL_UNAVAILABLE",`Failed to create desktop shortcut: ${n.stderr||n.stdout}`)}function _e(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 Ie(e){try{let t={...e.env,CREWX_LNK_PATH:e.shortcutPath},n=await e.run("powershell",["-NoProfile","-NonInteractive","-Command",mt],{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=f.win32;async function L(e){let t=G(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 i;try{i=JSON.parse(r.stdout||"{}");}catch{return {installed:false}}let l=i.dependencies?.crewx;if(!l?.version)return {installed:false};let o;try{let s=await e.run("npm",["prefix","-g"],{env:n});s.code===0&&(o=s.stdout.trim()||void 0);}catch{}let a=o?j.join(o,"crewx.cmd"):void 0;return {installed:true,version:l.version,binPath:a,prefix:o}}var gt=/EACCES|EPERM|EROFS/,wt=/ENOTFOUND|ETIMEDOUT|ECONNREFUSED|network|registry/i,St=/^\d+\.\d+\.\d+/;function Pt(e){return !!e&&e!=="0.0.0"&&St.test(e)}var J=10*6e4;async function Ne(e){if(!Pt(e.targetVersion))throw new h("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&&!_(e.currentInfo.version,e.targetVersion))return {info:e.currentInfo};let t=G(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 i;try{i=await e.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:n,timeoutMs:J});}catch(o){throw new h("NPM_UNAVAILABLE",`Could not run npm: ${o instanceof Error?o.message:String(o)}`)}if(i.code===0)return {info:await L({env:n,cwd:e.cwd,run:e.run})};let l=`${i.stdout}
|
|
3
|
+
${i.stderr}`;if(gt.test(l)){e.onProgress?.({phase:"global-install",message:"Permission denied \u2014 retrying with a user-scoped npm prefix"});let o=e.env.LOCALAPPDATA||j.join(e.env.USERPROFILE??"","AppData","Local"),a={...n,npm_config_prefix:j.join(o,"crewx","npm")},s;try{s=await e.run("npm",["install","-g",r,"--no-audit","--no-fund"],{env:a,timeoutMs:J});}catch(c){throw new h("NPM_PERMISSION_DENIED",`Retry with user-scoped prefix failed: ${c instanceof Error?c.message:String(c)}`)}if(s.code===0)return {info:await L({env:a,cwd:e.cwd,run:e.run})};throw new h("NPM_PERMISSION_DENIED",`npm install -g failed after user-scoped prefix retry: ${s.stderr||s.stdout}`)}if(wt.test(l)){if(!e.installRoot)throw new h("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 o;try{o=await e.run("npm",["install","-g",e.installRoot,"--offline","--no-audit","--no-fund"],{env:n,timeoutMs:J});}catch(a){throw new h("GLOBAL_INSTALL_FAILED",`Offline install failed: ${a instanceof Error?a.message:String(a)}`)}if(o.code===0)return {info:await L({env:n,cwd:e.cwd,run:e.run})};throw new h("GLOBAL_INSTALL_FAILED",`Offline install failed: ${o.stderr||o.stdout}`)}throw new h("GLOBAL_INSTALL_FAILED",l.trim()||`npm install -g ${r} failed`)}function vt(e){return e.run??ue}function yt(e){return e.fs??Y}async function B(e){let t=e.platform??process.platform,n=e.env??process.env,r=e.homedir??Q,i=vt(e),l=yt(e),o=e.runningVersion??fe,a=e.cwd??process.cwd(),s=r(),c=he(s),d=me(s),p=ge(s),u=null;t==="win32"&&(u=await Se({env:n,homedir:r,run:i}));let E=u?we(u.dir):null;return {platform:t,env:n,homedir:r,run:i,fs:l,runningVersion:o,cwd:a,installRoot:e.installRoot,shortcutManifestPath:c,launcherManifestPath:d,wrapperPath:p,desktop:u,shortcutPath:E}}function Oe(e){return e?f.win32.normalize(e).toLowerCase().endsWith(`${f.win32.sep}bin${f.win32.sep}crewx.ico`):false}function K(e,t){let n=e.readBinaryFileSync;if(n)try{return createHash("sha256").update(n(t)).digest("hex")}catch{return}}async function Ct(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=Ce(e.fs,e.shortcutManifestPath),r=F(e.fs,e.launcherManifestPath),i=await L({env:e.env,cwd:e.cwd,run:e.run}),l=e.shortcutPath?e.fs.existsSync(e.shortcutPath):false,o,a=false,s,c;if(!l)o=n?.declined?"declined":"not-installed";else {let d=!!n?.owned&&!!e.shortcutPath&&n.shortcutPath===e.shortcutPath,p=false,u=e.shortcutPath?await Ie({run:e.run,env:e.env,shortcutPath:e.shortcutPath}):null;if(d||(u&&X(u.targetPath,e.wrapperPath)?d=true:u&&Pe(u.targetPath)&&(p=true)),p)o="foreign",t.push("NSIS_PRESENT: an NSIS-installed CrewX shortcut was detected");else if(!d)o="foreign";else if(n?.version&&_(e.runningVersion,n.version))o="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 w=_e(u.iconLocation);if(!(!!w&&e.fs.existsSync(w)))a=true;else {s=w;let m=De(i,e.fs);m?X(w,m)?(c=K(e.fs,w),a=!c||n?.iconHash!==c):a=true:Oe(w)?(c=K(e.fs,w),a=!c||n?.iconHash!==c):a=true;}}o=E||a?"stale":"installed";}}return {supported:true,state:o,shortcutPath:e.shortcutPath??void 0,desktopDir:e.desktop?.dir,desktopSource:e.desktop?.source,wrapperPath:e.wrapperPath,wrapperSchema:r?.schema,globalCrewx:i.installed?i:{installed:false},runningVersion:e.runningVersion,errors:t,manifest:n,iconStale:a,iconPath:s,iconHash:c}}function De(e,t){if(!e?.installed||!e.prefix)return;let n=f.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:i,...l}=e;return l}async function Rt(e={}){let t=await B(e),n=await R(t);return b(n)}async function bt(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(m=>m.startsWith("NSIS_PRESENT")))throw new h("NSIS_PRESENT",`An NSIS-installed CrewX shortcut was detected at ${r.shortcutPath}`);if(!e.force)throw new h("FOREIGN_SHORTCUT",`An existing shortcut at ${r.shortcutPath} is not managed by CrewX`)}if(!t.desktop||!t.shortcutPath)throw new h("NO_DESKTOP_DIR","Could not resolve the Windows Desktop directory");let i=false,l=false,o=r.globalCrewx,a=[],s=n.manifest?.iconHash,c=false;if(!!o?.installed&&!!o.version&&_(o.version,t.runningVersion)||!o?.installed&&r.state!=="installed"){let m=await Ne({env:t.env,cwd:t.cwd,run:t.run,targetVersion:t.runningVersion,currentInfo:o??void 0,installRoot:t.installRoot,onProgress:e.onProgress});o=m.info,l=m.info.installed,i=true,l||a.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"}),ke({fs:t.fs,wrapperPath:t.wrapperPath,launcherManifestPath:t.launcherManifestPath,bakedBinPath:o?.binPath}).wrote&&(i=true),!((r.state==="installed"||r.state==="stale")&&!n.iconStale)){let m=De(o,t.fs)??(n.iconPath&&Oe(n.iconPath)&&t.fs.existsSync(n.iconPath)?n.iconPath:void 0);if(n.iconStale&&!m)throw new h("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 xe({run:t.run,env:t.env,shortcutPath:t.shortcutPath,targetPath:t.wrapperPath,iconPath:m}),i=true,c=n.iconStale;let g=m?K(t.fs,m):void 0;g&&(s=g);}i&&W(t.fs,t.shortcutManifestPath,{shortcutPath:t.shortcutPath,version:t.runningVersion,owned:true,declined:false,desktopSource:t.desktop.source,iconHash:s}),c&&await Ct(t);let w=await R(t),y=b(w);return {...y,errors:[...y.errors,...a],changed:i,installedGlobal:l}}async function kt(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{}W(t.fs,t.shortcutManifestPath,{shortcutPath:void 0,version:n.manifest?.version,owned:false,declined:true,desktopSource:void 0,iconHash:void 0});let i=await R(t);return b(i)}async function xt(e={}){let t=await B(e),n=await R(t),r=b(n);if(!r.supported)return r;W(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 i=await R(t);return b(i)}export{h as ShortcutError,xt as dismissShortcutNotice,Rt as getShortcutStatus,bt as installShortcut,kt as uninstallShortcut};
|