@chatpanel/gateway 0.64.0 → 0.75.0

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/src/service.js CHANGED
@@ -1,10 +1,10 @@
1
- import g from"node:os";import d from"node:path";import{mkdirSync as A,writeFileSync as E,readFileSync as de,rmSync as w,existsSync as h,statSync as fe,realpathSync as K}from"node:fs";import{spawnSync as me,spawn as k}from"node:child_process";import{loadConfig as he}from"./config.js";import{VERSION as W}from"./version.js";const $="net.chatpanel.gateway",ge="ChatPanel Privacy Gateway";function we(e,t){const n=String(e||"").split(".").map(r=>parseInt(r,10)),s=String(t||"").split(".").map(r=>parseInt(r,10));if(n.some(Number.isNaN)||s.some(Number.isNaN)||n.length<3||s.length<3)return 0;for(let r=0;r<3;r+=1)if(n[r]!==s[r])return n[r]>s[r]?1:-1;return 0}function I(e,{real:t=K.native||K}={}){if(!e)return e;try{return t(e)}catch{return e}}function ye(e,{exists:t=h}={}){const n=/^(.*)\/Cellar\/(node(?:@[\w.]+)?)\/[^/]+\/bin\/(node|bun)$/.exec(String(e||""));if(!n)return e;const s=`${n[1]}/opt/${n[2]}/bin/${n[3]}`;return t(s)?s:e}function N({execPath:e=ye(I(process.execPath)),argv1:t=I(process.argv[1]||"")}={}){const n=d.basename(e).toLowerCase();return(n.startsWith("node")||n.startsWith("bun"))&&t?{program:e,args:[d.resolve(t)]}:{program:e,args:[]}}function S(){const e=d.join(g.homedir(),".chatpanel");return A(e,{recursive:!0}),{out:d.join(e,"gateway.log"),err:d.join(e,"gateway.err.log")}}function p(e,t,n={}){return me(e,t,{encoding:"utf8",...n})}const R=()=>d.join(g.homedir(),"Library","LaunchAgents",`${$}.plist`),xe={MallocLargeCache:"0"};function $e({program:e,args:t,out:n,err:s,env:r=xe,label:i=$}={}){const o=c=>String(c).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),a=[e,...t].map(c=>` <string>${o(c)}</string>`).join(`
2
- `),u=Object.entries(r).map(([c,l])=>` <key>${o(c)}</key><string>${o(l)}</string>`).join(`
1
+ import g from"node:os";import{SERVICE_ENV as ft}from"@chatpanel/events/service-standby.js";import d from"node:path";import{mkdirSync as k,writeFileSync as I,readFileSync as L,rmSync as w,existsSync as h,statSync as ht,realpathSync as Y}from"node:fs";import{spawnSync as mt,spawn as N}from"node:child_process";import{loadConfig as gt}from"./config.js";import{VERSION as U}from"./version.js";const S="net.chatpanel.gateway",wt="ChatPanel Privacy Gateway";function yt(t,e){const n=String(t||"").split(".").map(r=>parseInt(r,10)),s=String(e||"").split(".").map(r=>parseInt(r,10));if(n.some(Number.isNaN)||s.some(Number.isNaN)||n.length<3||s.length<3)return 0;for(let r=0;r<3;r+=1)if(n[r]!==s[r])return n[r]>s[r]?1:-1;return 0}function R(t,{real:e=Y.native||Y}={}){if(!t)return t;try{return e(t)}catch{return t}}function xt(t,{exists:e=h}={}){const n=/^(.*)\/Cellar\/(node(?:@[\w.]+)?)\/[^/]+\/bin\/(node|bun)$/.exec(String(t||""));if(!n)return t;const s=`${n[1]}/opt/${n[2]}/bin/${n[3]}`;return e(s)?s:t}function C({execPath:t=xt(R(process.execPath)),argv1:e=R(process.argv[1]||"")}={}){const n=d.basename(t).toLowerCase();return(n.startsWith("node")||n.startsWith("bun"))&&e?{program:t,args:[d.resolve(e)]}:{program:t,args:[]}}function v(){const t=d.join(g.homedir(),".chatpanel");return k(t,{recursive:!0}),{out:d.join(t,"gateway.log"),err:d.join(t,"gateway.err.log")}}function p(t,e,n={}){return mt(t,e,{encoding:"utf8",...n})}const P=()=>d.join(g.homedir(),"Library","LaunchAgents",`${S}.plist`),$t={MallocLargeCache:"0"};function St({program:t,args:e,out:n,err:s,env:r={...$t,...ft},label:o=S}={}){const i=c=>String(c).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),a=[t,...e].map(c=>` <string>${i(c)}</string>`).join(`
2
+ `),u=Object.entries(r).map(([c,l])=>` <key>${i(c)}</key><string>${i(l)}</string>`).join(`
3
3
  `);return`<?xml version="1.0" encoding="UTF-8"?>
4
4
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
5
5
  <plist version="1.0">
6
6
  <dict>
7
- <key>Label</key><string>${i}</string>
7
+ <key>Label</key><string>${o}</string>
8
8
  <key>ProgramArguments</key>
9
9
  <array>
10
10
  ${a}
@@ -15,28 +15,29 @@ ${u}
15
15
  </dict>
16
16
  <key>RunAtLoad</key><true/>
17
17
  <key>KeepAlive</key><true/>
18
- <key>StandardOutPath</key><string>${o(n)}</string>
19
- <key>StandardErrorPath</key><string>${o(s)}</string>
18
+ <key>StandardOutPath</key><string>${i(n)}</string>
19
+ <key>StandardErrorPath</key><string>${i(s)}</string>
20
20
  </dict>
21
21
  </plist>
22
- `}function Se(){const{program:e,args:t}=N(),{out:n,err:s}=S(),r=$e({program:e,args:t,out:n,err:s}),i=R();A(d.dirname(i),{recursive:!0}),E(i,r),p("launchctl",["unload",i]);const o=p("launchctl",["load","-w",i]);if(o.status!==0)throw new Error((o.stderr||"").trim()||"launchctl load failed")}function ve(){const e=R();p("launchctl",["unload","-w",e]),h(e)&&w(e)}function Pe(){return(p("launchctl",["list"]).stdout||"").includes($)}function j({execPath:e=I(process.execPath),argv1:t=I(process.argv[1]||""),platform:n=process.platform,isFile:s=Y}={}){const r=n==="win32"?d.win32:d.posix,i=r.basename(e).toLowerCase();if(!(i.startsWith("node")||i.startsWith("bun")))return r.dirname(e);const o=n==="win32"?"chatpanel-gateway.cmd":"chatpanel-gateway";let a=r.dirname(r.resolve(t));for(let u=0;u<6;u++){const c=r.dirname(a);if(c===a)break;if(a=c,s(r.join(a,o)))return a;if(s(r.join(a,"bin",o)))return r.join(a,"bin")}return""}const Y=e=>{try{return fe(e).isFile()}catch{return!1}};function _(e,t,{delimiter:n=d.delimiter,platform:s=process.platform,env:r=process.env}={}){const i=u=>s==="win32"?u.replace(/%([^%]+)%/g,(c,l)=>r[l]??r[l.toUpperCase()]??c):u,o=u=>{const c=i(u.trim()).replace(/[\\/]+$/,"");return s==="win32"?c.toLowerCase():c},a=String(e||"").split(n).filter(u=>u.trim());return a.some(u=>o(u)===o(t))?null:[...a,t].join(n)}function L({dir:e=j(),pathEnv:t=process.env.PATH||"",platform:n=process.platform,isFile:s=Y}={}){if(!e)return"";const r=n==="win32"?d.win32:d.posix,i=n==="win32"?";":":",o=u=>{const c=String(u).trim().replace(/[\\/]+$/,"");return n==="win32"?c.toLowerCase():c},a=n==="win32"?["chatpanel-gateway.cmd","chatpanel-gateway.exe"]:["chatpanel-gateway"];for(const u of String(t).split(i)){const c=u.trim();if(c){if(o(c)===o(e))return"";if(a.some(l=>s(r.join(c,l))))return c}}return""}const y="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",U="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run",m="ChatPanelGateway",D=()=>d.join(g.homedir(),".chatpanel","gateway-launch.vbs"),z=e=>Buffer.from(e,"utf16le").toString("base64");function O({systemRoot:e=process.env.SystemRoot||"C:\\Windows",exists:t=h}={}){return t(d.join(e,"System32","vbscript.dll"))}function X({program:e,args:t=[],out:n,err:s,vbs:r,vbscript:i=!0}){const o=f=>`"${f}"`;if(i){const f=`cmd.exe /c "${[e,...t].map(o).join(" ")} >> ${o(n)} 2>> ${o(s)}"`;return{kind:"vbs",file:r,text:`CreateObject("WScript.Shell").Run "${f.replace(/"/g,'""')}", 0, False\r
23
- `,runValue:`wscript.exe "${r}"`,argv:["wscript.exe",r]}}const a=f=>`'${String(f).replace(/'/g,"''")}'`,u=t.length?` -ArgumentList @(${t.map(f=>a(o(f))).join(", ")})`:"",c=`Start-Process -WindowStyle Hidden -FilePath ${a(e)}${u} -RedirectStandardOutput ${a(n)} -RedirectStandardError ${a(s)}`,l=["powershell.exe","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",z(c)];return{kind:"powershell",file:"",text:c,runValue:l.join(" "),argv:l}}function B(e=p){const t=e("reg",["query",y,"/v",m]);if(t.status!==0)return"";const n=new RegExp(`${m}\\s+REG_\\w+\\s+(.*)$`,"m").exec(t.stdout||"");return n?n[1].trim():""}function be(e=p){const t=e("reg",["query",U,"/v",m]);if(t.status!==0)return!1;const n=/REG_BINARY\s+([0-9A-Fa-f]{2})/.exec(t.stdout||"");return!!n&&(parseInt(n[1],16)&1)===1}function J(e=p){const t=e("reg",["query","HKCU\\Environment","/v","Path"]),n=/\bPath\s+(REG_EXPAND_SZ|REG_SZ)\s+(.*)$/mi.exec(t.stdout||"");return n?{type:n[1],value:n[2].trim()}:{type:"REG_EXPAND_SZ",value:""}}const Ae=`$sig = '[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);'
22
+ `}function vt(){const{program:t,args:e}=C(),{out:n,err:s}=v(),r=St({program:t,args:e,out:n,err:s}),o=P();k(d.dirname(o),{recursive:!0}),I(o,r),p("launchctl",["unload",o]);const i=p("launchctl",["load","-w",o]);if(i.status!==0)throw new Error((i.stderr||"").trim()||"launchctl load failed")}function Pt(){const t=P();p("launchctl",["unload","-w",t]),h(t)&&w(t)}function bt(){return(p("launchctl",["list"]).stdout||"").includes(S)}function _({execPath:t=R(process.execPath),argv1:e=R(process.argv[1]||""),platform:n=process.platform,isFile:s=z}={}){const r=n==="win32"?d.win32:d.posix,o=r.basename(t).toLowerCase();if(!(o.startsWith("node")||o.startsWith("bun")))return r.dirname(t);const i=n==="win32"?"chatpanel-gateway.cmd":"chatpanel-gateway";let a=r.dirname(r.resolve(e));for(let u=0;u<6;u++){const c=r.dirname(a);if(c===a)break;if(a=c,s(r.join(a,i)))return a;if(s(r.join(a,"bin",i)))return r.join(a,"bin")}return""}const z=t=>{try{return ht(t).isFile()}catch{return!1}};function j(t,e,{delimiter:n=d.delimiter,platform:s=process.platform,env:r=process.env}={}){const o=u=>s==="win32"?u.replace(/%([^%]+)%/g,(c,l)=>r[l]??r[l.toUpperCase()]??c):u,i=u=>{const c=o(u.trim()).replace(/[\\/]+$/,"");return s==="win32"?c.toLowerCase():c},a=String(t||"").split(n).filter(u=>u.trim());return a.some(u=>i(u)===i(e))?null:[...a,e].join(n)}function D({dir:t=_(),pathEnv:e=process.env.PATH||"",platform:n=process.platform,isFile:s=z}={}){if(!t)return"";const r=n==="win32"?d.win32:d.posix,o=n==="win32"?";":":",i=u=>{const c=String(u).trim().replace(/[\\/]+$/,"");return n==="win32"?c.toLowerCase():c},a=n==="win32"?["chatpanel-gateway.cmd","chatpanel-gateway.exe"]:["chatpanel-gateway"];for(const u of String(e).split(o)){const c=u.trim();if(c){if(i(c)===i(t))return"";if(a.some(l=>s(r.join(c,l))))return c}}return""}const y="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",O="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run",m="ChatPanelGateway",B=()=>d.join(g.homedir(),".chatpanel","gateway-launch.vbs"),X=t=>Buffer.from(t,"utf16le").toString("base64");function G({systemRoot:t=process.env.SystemRoot||"C:\\Windows",exists:e=h}={}){return e(d.join(t,"System32","vbscript.dll"))}function J({program:t,args:e=[],out:n,err:s,vbs:r,vbscript:o=!0}){const i=f=>`"${f}"`;if(o){const f=`cmd.exe /c "${[t,...e].map(i).join(" ")} >> ${i(n)} 2>> ${i(s)}"`;return{kind:"vbs",file:r,text:`CreateObject("WScript.Shell").Run "${f.replace(/"/g,'""')}", 0, False\r
23
+ `,runValue:`wscript.exe "${r}"`,argv:["wscript.exe",r]}}const a=f=>`'${String(f).replace(/'/g,"''")}'`,u=e.length?` -ArgumentList @(${e.map(f=>a(i(f))).join(", ")})`:"",c=`Start-Process -WindowStyle Hidden -FilePath ${a(t)}${u} -RedirectStandardOutput ${a(n)} -RedirectStandardError ${a(s)}`,l=["powershell.exe","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",X(c)];return{kind:"powershell",file:"",text:c,runValue:l.join(" "),argv:l}}function H(t=p){const e=t("reg",["query",y,"/v",m]);if(e.status!==0)return"";const n=new RegExp(`${m}\\s+REG_\\w+\\s+(.*)$`,"m").exec(e.stdout||"");return n?n[1].trim():""}function At(t=p){const e=t("reg",["query",O,"/v",m]);if(e.status!==0)return!1;const n=/REG_BINARY\s+([0-9A-Fa-f]{2})/.exec(e.stdout||"");return!!n&&(parseInt(n[1],16)&1)===1}function Q(t=p){const e=t("reg",["query","HKCU\\Environment","/v","Path"]),n=/\bPath\s+(REG_EXPAND_SZ|REG_SZ)\s+(.*)$/mi.exec(e.stdout||"");return n?{type:n[1],value:n[2].trim()}:{type:"REG_EXPAND_SZ",value:""}}const Et=`$sig = '[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);'
24
24
  $t = Add-Type -MemberDefinition $sig -Name 'Env' -Namespace 'ChatPanelWin32' -PassThru
25
25
  $r = [UIntPtr]::Zero
26
- [void]$t::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$r)`;function Ee(e,{runImpl:t=p,env:n=process.env}={}){if(!e)return{added:!1,dir:e};const s=J(t),r=_(s.value,e,{delimiter:";",platform:"win32",env:n});if(r===null)return{added:!1,dir:e,onPath:!0};const i=t("reg",["add","HKCU\\Environment","/v","Path","/t",s.type,"/d",r,"/f"]);return i.status!==0?{added:!1,dir:e,error:(i.stderr||"").trim()||"reg add failed"}:(t("powershell.exe",["-NoProfile","-NonInteractive","-EncodedCommand",z(Ae)],{timeout:15e3}),{added:!0,dir:e,onPath:!0})}function ke(e,{runImpl:t=p,env:n=process.env}={}){if(!e)return!0;const s=n.Path??n.PATH??"";return _(J(t).value,e,{delimiter:";",platform:"win32",env:n})===null||_(s,e,{delimiter:";",platform:"win32",env:n})===null}function Ie({pid:e=process.pid}={}){return`${`$keep = @(${e}, $PID); $p = Get-CimInstance Win32_Process -Filter 'ProcessId = ${e}'; $n = 0; while ($p -and $n++ -lt 8) { $keep += $p.ParentProcessId; $p = Get-CimInstance Win32_Process -Filter "ProcessId = $($p.ParentProcessId)" }`}; Get-CimInstance Win32_Process | Where-Object { $keep -notcontains $_.ProcessId -and (($_.Name -ieq 'chatpanel-gateway.exe') -or ($_.CommandLine -match '[\\\\/]chatpanel-gateway\\.js(["'' ]|$)')) } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`}function Ne({pid:e=process.pid}={}){return[["powershell.exe",["-NoProfile","-NonInteractive","-Command",Ie({pid:e})]],["taskkill",["/F","/FI","IMAGENAME eq chatpanel-gateway.exe","/FI",`PID ne ${e}`]]]}function G(e=p){for(const[t,n]of Ne())e(t,n,{timeout:15e3})}function Re(){return process.platform==="win32"?G():(process.platform==="darwin"?p("launchctl",["bootout",`gui/${process.getuid?.()??""}/${$}`]):p("systemctl",["--user","stop","chatpanel-gateway.service"]),te())}function je(){const{program:e,args:t}=N(),{out:n,err:s}=S(),r=X({program:e,args:t,out:n,err:s,vbs:D(),vbscript:O()});r.file?E(r.file,r.text):w(D(),{force:!0});const i=p("reg",["add",y,"/v",m,"/t","REG_SZ","/d",r.runValue,"/f"]);if(i.status!==0)throw new Error((i.stderr||"").trim()||"reg add failed");p("reg",["delete",U,"/v",m,"/f"]);const o=Ee(j());return G(),p("powershell.exe",["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 800"]),p(r.argv[0],r.argv.slice(1),{windowsHide:!0,timeout:2e4}),{launcher:r.kind,path:o}}function _e(){p("reg",["delete",y,"/v",m,"/f"]),w(D(),{force:!0}),G()}function Q(){return p("reg",["query",y,"/v",m]).status===0}function x({env:e=process.env,release:t=g.release(),platform:n=process.platform}={}){return n==="linux"&&(!!e.WSL_DISTRO_NAME||/microsoft/i.test(t))}function v(e=p){const t=["/mnt/c/Windows/System32/cmd.exe","cmd.exe"];let n=null;for(const c of t){if(n=e(c,["/c","echo %USERPROFILE%|%SystemRoot%"],{cwd:"/mnt/c",timeout:15e3}),n&&!n.error&&n.status===0)break;n=null}const[s,r]=(n?.stdout||"").trim().split("|");if(!/^[A-Za-z]:\\/.test(s||"")||!/^[A-Za-z]:\\/.test(r||""))return null;const i=c=>(e("wslpath",["-u",c]).stdout||"").trim(),o=i(r),a=i(s);if(!o||!a)return null;const u=d.posix.join(o,"System32");return{home:s,homeUnix:a,sysRoot:r,sysUnix:o,exe:{reg:d.posix.join(u,"reg.exe"),wscript:d.posix.join(u,"wscript.exe"),powershell:d.posix.join(u,"WindowsPowerShell","v1.0","powershell.exe")}}}const Ce=["^[^ ]*chatpanel-gateway( |$)","^[^ ]*(node|bun)[^ ]*( +-[^ ]+)* +[^ ]*chatpanel-gateway\\.js( |$)"];function ee(e,t=p){const n=t("ps",["-o","ppid=","-p",String(e)]);return Number((n.stdout||"").trim())||0}function Te({pid:e=process.pid,ppid:t=process.ppid,parentOf:n=ee,depth:s=8}={}){const r=new Set([e]);let i=t;for(let o=0;o<s&&i>1&&!r.has(i);o+=1)r.add(i),i=n(i);return r}function te({runImpl:e=p,keep:t=null,kill:n=r=>process.kill(r,"SIGTERM"),patterns:s=Ce}={}){const r=t||Te({parentOf:a=>ee(a,e)}),i=[],o=new Set;for(const a of s){const u=e("pgrep",["-f",a]);for(const c of(u.stdout||"").split(`
27
- `)){const l=Number(c.trim());if(!(!l||r.has(l)||o.has(l))){o.add(l);try{n(l),i.push(l)}catch{}}}}return i}const ne=()=>te(),re=e=>({win:`${e.home}\\.chatpanel\\gateway-launch.vbs`,unix:d.posix.join(e.homeUnix,".chatpanel","gateway-launch.vbs")});function We(e,t){const[n,...s]=t.argv;return[n==="wscript.exe"?e.exe.wscript:e.exe.powershell,...s]}function Le(e){const{program:t,args:n}=N(),{out:s,err:r}=S(),i=P=>`'${String(P).replace(/'/g,"'\\''")}'`,o=`exec ${[t,...n].map(i).join(" ")} >> ${i(s)} 2>> ${i(r)}`,a=process.env.WSL_DISTRO_NAME?["-d",process.env.WSL_DISTRO_NAME]:[],u=re(e),c=X({program:"wsl.exe",args:[...a,"-u",g.userInfo().username,"--","bash","-lc",o],vbs:u.win,vbscript:O({systemRoot:e.sysUnix})});A(d.dirname(u.unix),{recursive:!0}),c.file?E(u.unix,c.text):w(u.unix,{force:!0});const l=p(e.exe.reg,["add",y,"/v",m,"/t","REG_SZ","/d",c.runValue,"/f"]);if(l.status!==0)throw new Error((l.stderr||"").trim()||"reg.exe add failed");p(e.exe.reg,["delete",U,"/v",m,"/f"]),ne(),De(800);const f=We(e,c);return p(f[0],f.slice(1),{timeout:2e4}),{launcher:c.kind,wsl:!0,path:{added:!1,dir:j()}}}function Ue(e){p(e.exe.reg,["delete",y,"/v",m,"/f"]),w(re(e).unix,{force:!0}),ne()}function se(e){return p(e.exe.reg,["query",y,"/v",m]).status===0}function De(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{}}const H=()=>d.join(g.homedir(),".config","systemd","user","chatpanel-gateway.service");function Oe({exec:e,display:t=ge}={}){return`[Unit]
28
- Description=${t}
26
+ [void]$t::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$r)`;function kt(t,{runImpl:e=p,env:n=process.env}={}){if(!t)return{added:!1,dir:t};const s=Q(e),r=j(s.value,t,{delimiter:";",platform:"win32",env:n});if(r===null)return{added:!1,dir:t,onPath:!0};const o=e("reg",["add","HKCU\\Environment","/v","Path","/t",s.type,"/d",r,"/f"]);return o.status!==0?{added:!1,dir:t,error:(o.stderr||"").trim()||"reg add failed"}:(e("powershell.exe",["-NoProfile","-NonInteractive","-EncodedCommand",X(Et)],{timeout:15e3}),{added:!0,dir:t,onPath:!0})}function It(t,{runImpl:e=p,env:n=process.env}={}){if(!t)return!0;const s=n.Path??n.PATH??"";return j(Q(e).value,t,{delimiter:";",platform:"win32",env:n})===null||j(s,t,{delimiter:";",platform:"win32",env:n})===null}function Nt({pid:t=process.pid}={}){return`${`$keep = @(${t}, $PID); $p = Get-CimInstance Win32_Process -Filter 'ProcessId = ${t}'; $n = 0; while ($p -and $n++ -lt 8) { $keep += $p.ParentProcessId; $p = Get-CimInstance Win32_Process -Filter "ProcessId = $($p.ParentProcessId)" }`}; Get-CimInstance Win32_Process | Where-Object { $keep -notcontains $_.ProcessId -and (($_.Name -ieq 'chatpanel-gateway.exe') -or ($_.CommandLine -match '[\\\\/]chatpanel-gateway\\.js(["'' ]|$)')) } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`}function Rt({pid:t=process.pid}={}){return[["powershell.exe",["-NoProfile","-NonInteractive","-Command",Nt({pid:t})]],["taskkill",["/F","/FI","IMAGENAME eq chatpanel-gateway.exe","/FI",`PID ne ${t}`]]]}function V(t=p){for(const[e,n]of Rt())t(e,n,{timeout:15e3})}function Ct(){return process.platform==="win32"?V():(process.platform==="darwin"?p("launchctl",["bootout",`gui/${process.getuid?.()??""}/${S}`]):p("systemctl",["--user","stop","chatpanel-gateway.service"]),nt())}function _t(){const{program:t,args:e}=C(),{out:n,err:s}=v(),r=J({program:t,args:e,out:n,err:s,vbs:B(),vbscript:G()});r.file?I(r.file,r.text):w(B(),{force:!0});const o=p("reg",["add",y,"/v",m,"/t","REG_SZ","/d",r.runValue,"/f"]);if(o.status!==0)throw new Error((o.stderr||"").trim()||"reg add failed");p("reg",["delete",O,"/v",m,"/f"]);const i=kt(_());return V(),p("powershell.exe",["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 800"]),p(r.argv[0],r.argv.slice(1),{windowsHide:!0,timeout:2e4}),{launcher:r.kind,path:i}}function jt(){p("reg",["delete",y,"/v",m,"/f"]),w(B(),{force:!0}),V()}function tt(){return p("reg",["query",y,"/v",m]).status===0}function $({env:t=process.env,release:e=g.release(),platform:n=process.platform}={}){return n==="linux"&&(!!t.WSL_DISTRO_NAME||/microsoft/i.test(e))}function b(t=p){const e=["/mnt/c/Windows/System32/cmd.exe","cmd.exe"];let n=null;for(const c of e){if(n=t(c,["/c","echo %USERPROFILE%|%SystemRoot%"],{cwd:"/mnt/c",timeout:15e3}),n&&!n.error&&n.status===0)break;n=null}const[s,r]=(n?.stdout||"").trim().split("|");if(!/^[A-Za-z]:\\/.test(s||"")||!/^[A-Za-z]:\\/.test(r||""))return null;const o=c=>(t("wslpath",["-u",c]).stdout||"").trim(),i=o(r),a=o(s);if(!i||!a)return null;const u=d.posix.join(i,"System32");return{home:s,homeUnix:a,sysRoot:r,sysUnix:i,exe:{reg:d.posix.join(u,"reg.exe"),wscript:d.posix.join(u,"wscript.exe"),powershell:d.posix.join(u,"WindowsPowerShell","v1.0","powershell.exe")}}}const Tt=["^[^ ]*chatpanel-gateway( |$)","^[^ ]*(node|bun)[^ ]*( +-[^ ]+)* +[^ ]*chatpanel-gateway\\.js( |$)"];function et(t,e=p){const n=e("ps",["-o","ppid=","-p",String(t)]);return Number((n.stdout||"").trim())||0}function Wt({pid:t=process.pid,ppid:e=process.ppid,parentOf:n=et,depth:s=8}={}){const r=new Set([t]);let o=e;for(let i=0;i<s&&o>1&&!r.has(o);i+=1)r.add(o),o=n(o);return r}function nt({runImpl:t=p,keep:e=null,kill:n=r=>process.kill(r,"SIGTERM"),patterns:s=Tt}={}){const r=e||Wt({parentOf:a=>et(a,t)}),o=[],i=new Set;for(const a of s){const u=t("pgrep",["-f",a]);for(const c of(u.stdout||"").split(`
27
+ `)){const l=Number(c.trim());if(!(!l||r.has(l)||i.has(l))){i.add(l);try{n(l),o.push(l)}catch{}}}}return o}const rt=()=>nt(),st=t=>({win:`${t.home}\\.chatpanel\\gateway-launch.vbs`,unix:d.posix.join(t.homeUnix,".chatpanel","gateway-launch.vbs")});function Lt(t,e){const[n,...s]=e.argv;return[n==="wscript.exe"?t.exe.wscript:t.exe.powershell,...s]}function Ut(t){const{program:e,args:n}=C(),{out:s,err:r}=v(),o=x=>`'${String(x).replace(/'/g,"'\\''")}'`,i=`exec ${[e,...n].map(o).join(" ")} >> ${o(s)} 2>> ${o(r)}`,a=process.env.WSL_DISTRO_NAME?["-d",process.env.WSL_DISTRO_NAME]:[],u=st(t),c=J({program:"wsl.exe",args:[...a,"-u",g.userInfo().username,"--","bash","-lc",i],vbs:u.win,vbscript:G({systemRoot:t.sysUnix})});k(d.dirname(u.unix),{recursive:!0}),c.file?I(u.unix,c.text):w(u.unix,{force:!0});const l=p(t.exe.reg,["add",y,"/v",m,"/t","REG_SZ","/d",c.runValue,"/f"]);if(l.status!==0)throw new Error((l.stderr||"").trim()||"reg.exe add failed");p(t.exe.reg,["delete",O,"/v",m,"/f"]),rt(),Ot(800);const f=Lt(t,c);return p(f[0],f.slice(1),{timeout:2e4}),{launcher:c.kind,wsl:!0,path:{added:!1,dir:_()}}}function Dt(t){p(t.exe.reg,["delete",y,"/v",m,"/f"]),w(st(t).unix,{force:!0}),rt()}function ot(t){return p(t.exe.reg,["query",y,"/v",m]).status===0}function Ot(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{}}const T=()=>d.join(g.homedir(),".config","systemd","user","chatpanel-gateway.service");function Bt({exec:t,display:e=wt}={}){return`[Unit]
28
+ Description=${e}
29
29
  After=network.target
30
30
 
31
31
  [Service]
32
- ExecStart=${e}
32
+ ExecStart=${t}
33
+ Environment=CHATPANEL_SERVICE=1
33
34
  Restart=always
34
35
  RestartSec=2
35
36
 
36
37
  [Install]
37
38
  WantedBy=default.target
38
- `}function Be(){const e=x()?v():null;if(e)return Le(e);if(x()&&!h("/run/systemd/system"))throw new Error("WSL: Windows interop is off (cmd.exe cannot run from here) and systemd is not enabled in /etc/wsl.conf — nothing here can start the gateway at login. Enable one of them, or run `chatpanel-gateway` from a shell.");const{program:t,args:n}=N(),s=[t,...n].map(a=>/\s/.test(a)?`"${a}"`:a).join(" "),r=Oe({exec:s}),i=H();A(d.dirname(i),{recursive:!0}),E(i,r),p("systemctl",["--user","daemon-reload"]);const o=p("systemctl",["--user","enable","--now","chatpanel-gateway"]);if(o.status!==0)throw new Error((o.stderr||"").trim()||"systemctl enable failed")}function Ge(){const e=x()?v():null;e&&Ue(e),p("systemctl",["--user","disable","--now","chatpanel-gateway"]);const t=H();h(t)&&w(t)}function oe(){const e=x()?v():null;return e&&se(e)?!0:(p("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function He({home:e=g.homedir(),platform:t=process.platform,env:n=process.env}={}){const s=t==="win32"?d.win32:d.posix;return t==="win32"?[s.join(n.LOCALAPPDATA||s.join(e,"AppData","Local"),"ChatPanel","chatpanel-bridge.exe")]:[s.join(e,".local","bin","chatpanel-bridge")]}const ie="net.chatpanel.bridge",F="ChatPanelBridge";function Fe({platform:e=process.platform,runImpl:t=p,paths:n=He(),home:s=g.homedir()}={}){if(e==="win32"){t("reg",["delete",y,"/v",F,"/f"]),t("schtasks",["/End","/TN",F]),t("schtasks",["/Delete","/TN",F,"/F"]);for(const r of n){const i=`Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq '${r.replace(/'/g,"''")}' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;t("powershell.exe",["-NoProfile","-NonInteractive","-Command",i],{timeout:15e3})}return}if(e==="darwin"){t("launchctl",["bootout",`gui/${process.getuid?.()??""}/${ie}`]);const r=d.join(s,"Library","LaunchAgents",`${ie}.plist`);h(r)&&w(r,{force:!0})}else{t("systemctl",["--user","disable","--now","chatpanel-bridge.service"]);const r=d.join(s,".config","systemd","user","chatpanel-bridge.service");h(r)&&w(r,{force:!0})}for(const r of n)t("pkill",["-f",`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`])}function C(e,t,n){if(process.platform==="darwin")return e();if(process.platform==="win32")return t();if(process.platform==="linux")return n();throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the gateway directly.`)}function Me({env:e=process.env}={}){return{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:!0,env:e}}function Je({winInstall:e=""}={}){try{if(process.platform==="darwin")return h(R())?(k("launchctl",["kickstart","-k",`gui/${process.getuid?.()??0}/${$}`],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="linux"){const t=x()?v():null;if(t&&se(t)){const n=B((r,i,o)=>p(r==="reg"?t.exe.reg:r,i,o));return n?(k("sh",["-c",`sleep 3; cd /mnt/c 2>/dev/null; exec cmd.exe /c ${(r=>`'${String(r).replace(/'/g,"'\\''")}'`)(n)}`],{detached:!0,stdio:"ignore"}).unref(),setTimeout(()=>process.exit(0),300),!0):!1}return h(H())?(k("systemctl",["--user","restart","chatpanel-gateway"],{detached:!0,stdio:"ignore"}).unref(),!0):!1}if(process.platform==="win32"){const t=B();if(!t)return!1;const n=d.dirname(process.execPath),s=`timeout /t 3 >nul & ${e?`${e} & `:""}${t} & del /q "${d.join(n,"chatpanel-gateway.old-*.exe")}" >nul 2>&1`,r={...process.env},i=Object.keys(r).find(o=>o.toLowerCase()==="path")||"Path";return r[i]=[n,...(r[i]||"").split(";").filter(Boolean)].filter((o,a,u)=>u.indexOf(o)===a).join(";"),k("cmd",["/c",s],Me({env:r})).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function Qe(){try{return C(()=>h(R()),Q,oe)}catch{return!1}}function ae(){try{return`http://127.0.0.1:${he().port||4320}`}catch{return"http://127.0.0.1:4320"}}async function ce(e=ae(),{timeoutMs:t=2e3}={}){try{const n=await fetch(`${e}/health`,{signal:AbortSignal.timeout(t)});if(!n.ok)return{ok:!1,url:e};const s=await n.json();return{ok:!0,url:e,version:String(s.version||""),managedBy:s.managedBy?String(s.managedBy):""}}catch{return{ok:!1,url:e}}}function ue(e=8){try{const t=de(S().err,"utf8").trimEnd();return t?t.split(`
39
- `).slice(-e).join(`
40
- `):""}catch{return""}}async function et({waitMs:e=4e4,version:t="",probe:n=ce,stop:s=Re,install:r=()=>C(Se,je,Be),retire:i=Fe,wait:o=c=>new Promise(l=>setTimeout(l,c)),now:a=()=>Date.now(),force:u=!1}={}){const c=ae(),l=await n(c);if(!u&&l.ok&&t&&l.version&&we(l.version,t)>0)return{ok:!1,newer:!0,health:l,shadow:L()};i();const f=l.ok&&l.managedBy&&l.managedBy!=="gateway"?l.managedBy:"",P=!!(l.ok&&t&&l.version&&l.version!==t),T=P&&!f;T&&(s(),await o(1200));const le=r()||{},M=T?t:"",V=Z=>Z.ok&&(!M||Z.version===M),pe=a()+e;let b=await n(c);for(;!V(b)&&a()<pe;)await o(500),b=await n(c);const q=V(b);return{...le,health:b,ok:q,replaced:T?l.version:"",deferredTo:P?f:"",shadow:L(),errLog:q?"":ue()}}function tt(){return C(ve,_e,Ge)}function Ve(){return C(Pe,Q,oe)}async function nt({platform:e=process.platform}={}){const t=[];let n=!1;try{n=Ve()}catch(a){t.push(`auto-start: ${a.message}`)}t.push(n?"auto-start: registered":"auto-start: not registered — `chatpanel-gateway --install`");const s=e==="linux"&&x()?v():null;if(e==="win32"||s){const a=s?(c,l,f)=>p(c==="reg"?s.exe.reg:c,l,f):p,u=n?B(a):"";u&&t.push(` launcher: ${u.length>120?`${u.slice(0,117)}…`:u}`),u.startsWith("wscript")&&!O(s?{systemRoot:s.sysUnix}:{})&&t.push(" ✕ VBScript is not installed on this Windows, so that launcher cannot run — `--install` again registers one that does not need it"),n&&be(a)&&t.push(" ✕ switched off in Task Manager › Startup — `--install` again turns it back on"),s&&t.push(` WSL: starts at Windows login through wsl.exe (${process.env.WSL_DISTRO_NAME||"default distro"})`)}const r=j();r&&(e==="win32"?t.push(ke(r)?`command: ${r} (on PATH)`:`command: ${r} — NOT on your PATH; \`--install\` adds it`):t.push(_(process.env.PATH||"",r,{platform:e})===null?`command: ${r} (on PATH)`:`command: ${r} — not on your PATH: export PATH="${r}:$PATH"`));const i=L({platform:e});i&&t.push(` ✕ ${i}/chatpanel-gateway is EARLIER on your PATH — that copy is what the name runs, not this v${W}`);const o=await ce();if(o.ok){const a=o.version===W?"":` — this command is v${W}; \`--install\` makes it the one that runs`;t.push(`running: v${o.version} at ${o.url}${o.managedBy?` (run by ${o.managedBy})`:""}${o.managedBy?"":a}`)}else{t.push(`running: nothing answers at ${o.url}`);const a=ue();a&&t.push(` last of ${S().err}:`,...a.split(`
41
- `).map(u=>` ${u}`))}return t.join(`
42
- `)}export{xe as DARWIN_LAUNCH_ENV,Ce as GATEWAY_ARGV_PATTERNS,j as commandDir,we as compareVersions,ue as errLogTail,et as installService,x as isWsl,Oe as linUnitText,$e as macPlistText,L as pathShadow,_ as pathWithDir,ce as probeHealth,z as psEncode,I as realPath,N as resolveLaunch,Je as restartService,Fe as retireStandaloneBridge,Te as selfAndAncestors,Qe as serviceRegistered,nt as serviceReport,Ve as serviceStatus,ye as stableNodePath,He as standaloneCandidates,te as stopOtherGateways,Re as stopService,tt as uninstallService,O as vbscriptAvailable,ke as winCommandOnPath,Ee as winEnsureOnPath,X as winLauncher,Me as winRelaunchOpts,be as winStartupDisabled,Ne as winStopArgs,Ie as winStopScript};
39
+ `}function Gt(){const t=$()?b():null;if(t)return Ut(t);if($()&&!h("/run/systemd/system"))throw new Error("WSL: Windows interop is off (cmd.exe cannot run from here) and systemd is not enabled in /etc/wsl.conf — nothing here can start the gateway at login. Enable one of them, or run `chatpanel-gateway` from a shell.");const{program:e,args:n}=C(),s=[e,...n].map(a=>/\s/.test(a)?`"${a}"`:a).join(" "),r=Bt({exec:s}),o=T();k(d.dirname(o),{recursive:!0}),I(o,r),p("systemctl",["--user","daemon-reload"]);const i=p("systemctl",["--user","enable","--now","chatpanel-gateway"]);if(i.status!==0)throw new Error((i.stderr||"").trim()||"systemctl enable failed")}function Ht(){const t=$()?b():null;t&&Dt(t),p("systemctl",["--user","disable","--now","chatpanel-gateway"]);const e=T();h(e)&&w(e)}function it(){const t=$()?b():null;return t&&ot(t)?!0:(p("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function Vt({home:t=g.homedir(),platform:e=process.platform,env:n=process.env}={}){const s=e==="win32"?d.win32:d.posix;return e==="win32"?[s.join(n.LOCALAPPDATA||s.join(t,"AppData","Local"),"ChatPanel","chatpanel-bridge.exe")]:[s.join(t,".local","bin","chatpanel-bridge")]}const at="net.chatpanel.bridge",F="ChatPanelBridge";function Ft({platform:t=process.platform,runImpl:e=p,paths:n=Vt(),home:s=g.homedir()}={}){if(t==="win32"){e("reg",["delete",y,"/v",F,"/f"]),e("schtasks",["/End","/TN",F]),e("schtasks",["/Delete","/TN",F,"/F"]);for(const r of n){const o=`Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq '${r.replace(/'/g,"''")}' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;e("powershell.exe",["-NoProfile","-NonInteractive","-Command",o],{timeout:15e3})}return}if(t==="darwin"){e("launchctl",["bootout",`gui/${process.getuid?.()??""}/${at}`]);const r=d.join(s,"Library","LaunchAgents",`${at}.plist`);h(r)&&w(r,{force:!0})}else{e("systemctl",["--user","disable","--now","chatpanel-bridge.service"]);const r=d.join(s,".config","systemd","user","chatpanel-bridge.service");h(r)&&w(r,{force:!0})}for(const r of n)e("pkill",["-f",`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`])}function A(t,e,n){if(process.platform==="darwin")return t();if(process.platform==="win32")return e();if(process.platform==="linux")return n();throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the gateway directly.`)}function Mt({env:t=process.env}={}){return{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:!0,env:t}}function re({winInstall:t=""}={}){try{if(process.platform==="darwin")return h(P())?(N("launchctl",["kickstart","-k",`gui/${process.getuid?.()??0}/${S}`],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="linux"){const e=$()?b():null;if(e&&ot(e)){const n=H((r,o,i)=>p(r==="reg"?e.exe.reg:r,o,i));return n?(N("sh",["-c",`sleep 3; cd /mnt/c 2>/dev/null; exec cmd.exe /c ${(r=>`'${String(r).replace(/'/g,"'\\''")}'`)(n)}`],{detached:!0,stdio:"ignore"}).unref(),setTimeout(()=>process.exit(0),300),!0):!1}return h(T())?(N("systemctl",["--user","restart","chatpanel-gateway"],{detached:!0,stdio:"ignore"}).unref(),!0):!1}if(process.platform==="win32"){const e=H();if(!e)return!1;const n=d.dirname(process.execPath),s=`timeout /t 3 >nul & ${t?`${t} & `:""}${e} & del /q "${d.join(n,"chatpanel-gateway.old-*.exe")}" >nul 2>&1`,r={...process.env},o=Object.keys(r).find(i=>i.toLowerCase()==="path")||"Path";return r[o]=[n,...(r[o]||"").split(";").filter(Boolean)].filter((i,a,u)=>u.indexOf(i)===a).join(";"),N("cmd",["/c",s],Mt({env:r})).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function se(){try{return A(()=>h(P()),tt,it)}catch{return!1}}function ct(){try{return`http://127.0.0.1:${gt().port||4320}`}catch{return"http://127.0.0.1:4320"}}async function ut(t=ct(),{timeoutMs:e=2e3}={}){try{const n=await fetch(`${t}/health`,{signal:AbortSignal.timeout(e)});if(!n.ok)return{ok:!1,url:t};const s=await n.json();return{ok:!0,url:t,version:String(s.version||""),managedBy:s.managedBy?String(s.managedBy):""}}catch{return{ok:!1,url:t}}}function lt(t=8){try{const e=L(v().err,"utf8").trimEnd();return e?e.split(`
40
+ `).slice(-t).join(`
41
+ `):""}catch{return""}}async function oe({waitMs:t=4e4,version:e="",probe:n=ut,stop:s=Ct,install:r=()=>A(vt,_t,Gt),retire:o=Ft,wait:i=c=>new Promise(l=>setTimeout(l,c)),now:a=()=>Date.now(),force:u=!1}={}){const c=ct(),l=await n(c);if(!u&&l.ok&&e&&l.version&&yt(l.version,e)>0)return{ok:!1,newer:!0,health:l,shadow:D()};o();const f=l.ok&&l.managedBy&&l.managedBy!=="gateway"?l.managedBy:"",x=!!(l.ok&&e&&l.version&&l.version!==e),W=x&&!f;W&&(s(),await i(1200));const pt=r()||{},M=W?e:"",q=K=>K.ok&&(!M||K.version===M),dt=a()+t;let E=await n(c);for(;!q(E)&&a()<dt;)await i(500),E=await n(c);const Z=q(E);return{...pt,health:E,ok:Z,replaced:W?l.version:"",deferredTo:x?f:"",shadow:D(),errLog:Z?"":lt()}}function ie(){return A(Pt,jt,Ht)}function qt(){return A(bt,tt,it)}function Zt(t,e=process.platform){const n=String(t||"");if(e==="darwin"){const r=/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(n);if(!r)return[];const o=i=>i.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&");return[...r[1].matchAll(/<string>([\s\S]*?)<\/string>/g)].map(i=>o(i[1]))}const s=/^ExecStart=(.*)$/m.exec(n);return s?[...s[1].matchAll(/"([^"]*)"|(\S+)/g)].map(r=>r[1]??r[2]):[]}function Kt({text:t,loaded:e,exists:n=h,platform:s=process.platform}){if(!t)return{state:"none",missing:[]};const i=Zt(t,s).slice(0,2).filter((a,u)=>u===0||/[\\/]/.test(a)&&!a.startsWith("-")).filter(a=>a.startsWith("/")&&!n(a));return i.length?{state:"gone",missing:i}:{state:e?"ok":"unloaded",missing:[]}}function Yt(){try{return A(()=>L(P(),"utf8"),()=>"",()=>L(T(),"utf8"))}catch{return""}}async function ae({platform:t=process.platform}={}){const e=[];let n=!1;try{n=qt()}catch(u){e.push(`auto-start: ${u.message}`)}const s=t==="win32"?{state:"none",missing:[]}:Kt({text:Yt(),loaded:n,platform:t});s.state==="gone"?e.push(`auto-start: ✕ registered, but it starts ${s.missing.join(" and ")}, which is gone (a Node upgrade or a version manager removed it) — \`chatpanel-gateway --install\` registers it again with this copy`):s.state==="unloaded"?e.push("auto-start: installed but switched off (the service manager is not running it) — `chatpanel-gateway --install` turns it back on"):e.push(n?"auto-start: registered":"auto-start: not registered — `chatpanel-gateway --install`");const r=t==="linux"&&$()?b():null;if(t==="win32"||r){const u=r?(l,f,x)=>p(l==="reg"?r.exe.reg:l,f,x):p,c=n?H(u):"";c&&e.push(` launcher: ${c.length>120?`${c.slice(0,117)}…`:c}`),c.startsWith("wscript")&&!G(r?{systemRoot:r.sysUnix}:{})&&e.push(" ✕ VBScript is not installed on this Windows, so that launcher cannot run — `--install` again registers one that does not need it"),n&&At(u)&&e.push(" ✕ switched off in Task Manager › Startup — `--install` again turns it back on"),r&&e.push(` WSL: starts at Windows login through wsl.exe (${process.env.WSL_DISTRO_NAME||"default distro"})`)}const o=_();o&&(t==="win32"?e.push(It(o)?`command: ${o} (on PATH)`:`command: ${o} — NOT on your PATH; \`--install\` adds it`):e.push(j(process.env.PATH||"",o,{platform:t})===null?`command: ${o} (on PATH)`:`command: ${o} — not on your PATH: export PATH="${o}:$PATH"`));const i=D({platform:t});i&&e.push(` ✕ ${i}/chatpanel-gateway is EARLIER on your PATH — that copy is what the name runs, not this v${U}`);const a=await ut();if(a.ok){const u=a.version===U?"":` — this command is v${U}; \`--install\` makes it the one that runs`;e.push(`running: v${a.version} at ${a.url}${a.managedBy?` (run by ${a.managedBy})`:""}${a.managedBy?"":u}`)}else{e.push(`running: nothing answers at ${a.url}`);const u=lt();u&&e.push(` last of ${v().err}:`,...u.split(`
42
+ `).map(c=>` ${c}`))}return e.join(`
43
+ `)}export{$t as DARWIN_LAUNCH_ENV,Tt as GATEWAY_ARGV_PATTERNS,_ as commandDir,yt as compareVersions,lt as errLogTail,oe as installService,$ as isWsl,Bt as linUnitText,St as macPlistText,D as pathShadow,j as pathWithDir,ut as probeHealth,X as psEncode,R as realPath,C as resolveLaunch,re as restartService,Ft as retireStandaloneBridge,Wt as selfAndAncestors,se as serviceRegistered,ae as serviceReport,qt as serviceStatus,xt as stableNodePath,Vt as standaloneCandidates,nt as stopOtherGateways,Ct as stopService,ie as uninstallService,Kt as unitHealth,Zt as unitLaunch,G as vbscriptAvailable,It as winCommandOnPath,kt as winEnsureOnPath,J as winLauncher,Mt as winRelaunchOpts,At as winStartupDisabled,Rt as winStopArgs,Nt as winStopScript};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.64.0";export{o as VERSION};
1
+ const o="0.75.0";export{o as VERSION};
@@ -0,0 +1,7 @@
1
+ import{createHash as C}from"node:crypto";const O="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",n={cont:0,text:1,binary:2,close:8,ping:9,pong:10},P=o=>C("sha1").update(String(o)+O).digest("base64");function k(o,e,f=""){const g={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",426:"Upgrade Required",429:"Too Many Requests"}[e]||"Error",i=f?JSON.stringify({error:f}):"";try{o.end(`HTTP/1.1 ${e} ${g}\r
2
+ connection: close\r
3
+ content-type: application/json\r
4
+ content-length: ${Buffer.byteLength(i)}\r
5
+ \r
6
+ ${i}`)}catch{}}function m(o,e=Buffer.alloc(0)){const f=e.length,g=f<126?Buffer.from([128|o,f]):f<65536?Buffer.from([128|o,126,f>>8,f&255]):null;if(g)return Buffer.concat([g,e]);const i=Buffer.alloc(10);return i[0]=128|o,i[1]=127,i.writeBigUInt64BE(BigInt(f),2),Buffer.concat([i,e])}function N(o,e,f,{protocol:g=null,maxMessage:i=65535}={}){const A=o.headers["sec-websocket-key"];if(String(o.headers.upgrade||"").toLowerCase()!=="websocket"||!A||o.headers["sec-websocket-version"]!=="13")return k(e,426,"websocket upgrade required"),null;const I=String(o.headers["sec-websocket-protocol"]||"").split(",").map(t=>t.trim());e.setNoDelay?.(!0),e.write(["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${P(A)}`,...g&&I.includes(g)?[`Sec-WebSocket-Protocol: ${g}`]:[],"",""].join(`\r
7
+ `));const d={readyState:1,onmessage:null,onclose:null,binaryType:"arraybuffer"};let r=f?.length?Buffer.from(f):Buffer.alloc(0),x=[],U=0,b=0,B=!1;const S=t=>{if(!B){B=!0,d.readyState=3;try{e.destroy()}catch{}queueMicrotask(()=>d.onclose?.({code:t}))}},c=(t,s="")=>{if(B)return;const h=Buffer.from(String(s).slice(0,120)),u=Buffer.alloc(2+h.length);u.writeUInt16BE(t,0),h.copy(u,2);try{e.write(m(n.close,u)),e.end()}catch{}d.readyState=2,setTimeout(()=>S(t),1e3).unref?.()};function E(){for(;;){if(r.length<2)return;const t=r[0],s=r[1],h=(t&128)!==0,u=t&15;if(t&112)return c(1002,"reserved bits");if(!(s&128))return c(1002,"client frames are masked");let l=s&127,y=2;if(l===126){if(r.length<4)return;l=r.readUInt16BE(2),y=4}else if(l===127){if(r.length<10)return;const a=r.readBigUInt64BE(2);if(a>BigInt(i))return c(1009,"too large");l=Number(a),y=10}if(l>i)return c(1009,"too large");if(r.length<y+4+l)return;const T=r.subarray(y,y+4),p=Buffer.from(r.subarray(y+4,y+4+l));for(let a=0;a<p.length;a++)p[a]^=T[a&3];if(r=r.subarray(y+4+l),u>=8){if(!h||l>125)return c(1002,"bad control frame");if(u===n.ping){try{e.write(m(n.pong,p))}catch{}continue}if(u===n.pong)continue;if(u===n.close){const a=p.length>=2?p.readUInt16BE(0):1005;try{e.write(m(n.close,p.subarray(0,2))),e.end()}catch{}S(a);return}return c(1002,"unknown opcode")}if(u===n.cont?!b:b)return c(1002,"bad continuation");if(u!==n.cont&&(b=u),b!==n.text&&b!==n.binary)return c(1002,"unknown opcode");if(U+=p.length,U>i)return c(1009,"too large");if(x.push(p),!h)continue;const w=x.length===1?x[0]:Buffer.concat(x),$=b;if(x=[],U=0,b=0,$===n.text){if(w.toString("utf8")==="ping"){try{e.write(m(n.text,Buffer.from("pong")))}catch{}continue}return c(1003,"binary frames only")}else d.onmessage?.({data:w.buffer.slice(w.byteOffset,w.byteOffset+w.length)});if(B)return}}return e.on("data",t=>{B||(r=r.length?Buffer.concat([r,t]):t,E())}),e.on("close",()=>S(1006)),e.on("error",()=>S(1006)),queueMicrotask(E),d.send=t=>{if(B||d.readyState!==1)return;const s=typeof t=="string",h=s?Buffer.from(t):Buffer.from(t instanceof ArrayBuffer?new Uint8Array(t):t);e.write(m(s?n.text:n.binary,h))},d.close=(t=1e3,s="")=>c(t,s),d}export{P as acceptKey,N as acceptWebSocket,k as refuseUpgrade};