@termiq/cli 3.18.2 → 3.18.3
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/bin.js +3 -3
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
`).replace(/\r/g,`
|
|
15
15
|
`).replace(/\n{3,}/g,`
|
|
16
16
|
|
|
17
|
-
`)}scheduleStatusUpdate(e,t){let i=this.states.get(e);i&&i.status!==t&&i.pendingStatus!==t&&(i.pendingUpdate&&clearTimeout(i.pendingUpdate),i.pendingStatus=t,i.pendingUpdate=setTimeout(()=>{i.pendingStatus=null,this.emitStatus(e,t),i.pendingUpdate=null},hi.DEBOUNCE_MS))}emitStatus(e,t){let i=this.states.get(e);if(!i||i.status===t)return;i.status=t,i.lastUpdate=Date.now();let n;if(t==="waiting"){let s=this.detectPrompt(i.outputBuffer);n=s&&s.type!=="free-input"?s:i.pendingPrompt||s||void 0,i.emittedPromptKey=n?this.promptKey(n):null,i.lastSeenPromptKey=i.emittedPromptKey}else i.pendingPrompt=null,i.emittedPromptKey=null,i.lastSeenPromptKey=null,i.promptRefreshTimer&&(clearTimeout(i.promptRefreshTimer),i.promptRefreshTimer=null);this.onStatusChange(e,t,n)}promptKey(e){let t=(e.choices||[]).map(i=>`${i.key}=${i.label}`).join("\xA7");return`${e.type}|${e.question}|${t}`}schedulePromptRefresh(e){let t=this.states.get(e);t&&(t.promptRefreshTimer&&clearTimeout(t.promptRefreshTimer),t.promptRefreshTimer=setTimeout(()=>{let i=this.states.get(e);if(!i||(i.promptRefreshTimer=null,i.status!=="waiting"||Date.now()<i.resolveGraceUntil))return;let n=this.detectPrompt(i.outputBuffer),s=n&&n.type!=="free-input"?n:i.pendingPrompt;if(!s)return;let a=this.promptKey(s);a!==i.emittedPromptKey&&(i.emittedPromptKey=a,i.lastSeenPromptKey=a,this.onStatusChange(e,"waiting",s))},hi.PROMPT_REFRESH_MS))}resetWorkingTimeout(e,t){t.workingTimeout&&clearTimeout(t.workingTimeout),t.status==="working"&&(t.workingTimeout=setTimeout(()=>{let i=this.states.get(e);i&&i.status==="working"&&(this.analyzeOutput(i.outputBuffer)==="waiting"?this.emitStatus(e,"waiting"):this.onStatusChange(e,"working",void 0))},hi.WORKING_TIMEOUT_MS))}resolvePrompt(e){let t=this.states.get(e);t&&t.status==="waiting"&&(t.resolveGraceUntil=Date.now()+hi.RESOLVE_GRACE_MS,t.pendingPrompt=null,t.emittedPromptKey=null,t.lastSeenPromptKey=null,t.promptRefreshTimer&&(clearTimeout(t.promptRefreshTimer),t.promptRefreshTimer=null),t.outputBuffer="",this.scheduleStatusUpdate(e,"working"))}forceStatus(e,t){this.emitStatus(e,t)}getStatus(e){return this.states.get(e)?.status??null}dispose(){for(let e of this.states.keys())this.stopTracking(e)}};Sn.StatusDetector=ta;function Fg(r){for(let e=0;e<r.length;e++){let t=r.charCodeAt(e);if(t===27){let i=r[e+1];if(i==="["||i==="O"){for(e+=2;e<r.length&&!/[A-Za-z~]/.test(r[e]);)e++;continue}if(i==="]"){for(e+=2;e<r.length&&r.charCodeAt(e)!==7;)e++;continue}return!0}if(t===13||t===10||t===3||t>=32&&t!==127)return!0}return!1}});var vu=M((SE,bu)=>{var Mi=require("fs"),_u=require("url"),Dg=require("child_process").spawn;bu.exports=ra;ra.XMLHttpRequest=ra;function ra(r){"use strict";r=r||{};var e=this,t=require("http"),i=require("https"),n,s,a={},c=!1,u={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},d=Object.assign({},u),p=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","content-transfer-encoding","cookie","cookie2","date","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"],m=["TRACE","TRACK","CONNECT"],_=!1,E=!1,S=!1,T={};this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.readyState=this.UNSENT,this.onreadystatechange=null,this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),this.status=null,this.statusText=null;var z=function(R){return c||R&&p.indexOf(R.toLowerCase())===-1},ge=function(R){return R&&m.indexOf(R)===-1};this.open=function(R,B,re,K,U){if(this.abort(),E=!1,S=!1,!ge(R))throw new Error("SecurityError: Request method not allowed");a={method:R,url:B.toString(),async:typeof re!="boolean"?!0:re,user:K||null,password:U||null},ee(this.OPENED)},this.setDisableHeaderCheck=function(R){c=R},this.setRequestHeader=function(R,B){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!z(R))return console.warn('Refused to set unsafe header "'+R+'"'),!1;if(_)throw new Error("INVALID_STATE_ERR: send flag is true");return d[R]=B,!0},this.getResponseHeader=function(R){return typeof R=="string"&&this.readyState>this.OPENED&&s.headers[R.toLowerCase()]&&!E?s.headers[R.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||E)return"";var R="";for(var B in s.headers)B!=="set-cookie"&&B!=="set-cookie2"&&(R+=B+": "+s.headers[B]+`\r
|
|
17
|
+
`)}scheduleStatusUpdate(e,t){let i=this.states.get(e);i&&i.status!==t&&i.pendingStatus!==t&&(i.pendingUpdate&&clearTimeout(i.pendingUpdate),i.pendingStatus=t,i.pendingUpdate=setTimeout(()=>{i.pendingStatus=null,this.emitStatus(e,t),i.pendingUpdate=null},hi.DEBOUNCE_MS))}emitStatus(e,t){let i=this.states.get(e);if(!i||i.status===t)return;i.status=t,i.lastUpdate=Date.now();let n;if(t==="waiting"){let s=this.detectPrompt(i.outputBuffer);n=s&&s.type!=="free-input"?s:i.pendingPrompt||s||void 0,i.emittedPromptKey=n?this.promptKey(n):null,i.lastSeenPromptKey=i.emittedPromptKey}else i.pendingPrompt=null,i.emittedPromptKey=null,i.lastSeenPromptKey=null,i.promptRefreshTimer&&(clearTimeout(i.promptRefreshTimer),i.promptRefreshTimer=null);this.onStatusChange(e,t,n)}promptKey(e){let t=(e.choices||[]).map(i=>`${i.key}=${i.label}`).join("\xA7");return`${e.type}|${e.question}|${t}`}schedulePromptRefresh(e){let t=this.states.get(e);t&&(t.promptRefreshTimer&&clearTimeout(t.promptRefreshTimer),t.promptRefreshTimer=setTimeout(()=>{let i=this.states.get(e);if(!i||(i.promptRefreshTimer=null,i.status!=="waiting"||Date.now()<i.resolveGraceUntil))return;let n=this.detectPrompt(i.outputBuffer),s=n&&n.type!=="free-input"?n:i.pendingPrompt;if(!s)return;let a=this.promptKey(s);a!==i.emittedPromptKey&&(i.emittedPromptKey=a,i.lastSeenPromptKey=a,this.onStatusChange(e,"waiting",s))},hi.PROMPT_REFRESH_MS))}resetWorkingTimeout(e,t){t.workingTimeout&&clearTimeout(t.workingTimeout),t.status==="working"&&(t.workingTimeout=setTimeout(()=>{let i=this.states.get(e);i&&i.status==="working"&&(this.analyzeOutput(i.outputBuffer)==="waiting"?this.emitStatus(e,"waiting"):this.onStatusChange(e,"working",void 0))},hi.WORKING_TIMEOUT_MS))}resolvePrompt(e){let t=this.states.get(e);t&&t.status==="waiting"&&(t.resolveGraceUntil=Date.now()+hi.RESOLVE_GRACE_MS,t.pendingPrompt=null,t.emittedPromptKey=null,t.lastSeenPromptKey=null,t.promptRefreshTimer&&(clearTimeout(t.promptRefreshTimer),t.promptRefreshTimer=null),t.outputBuffer="",this.scheduleStatusUpdate(e,"working"))}forceStatus(e,t){this.emitStatus(e,t)}resendWaitingPrompts(){for(let[e,t]of this.states){if(t.status!=="waiting")continue;let i=this.detectPrompt(t.outputBuffer),n=i&&i.type!=="free-input"?i:t.pendingPrompt||void 0;n&&this.onStatusChange(e,"waiting",n)}}getStatus(e){return this.states.get(e)?.status??null}dispose(){for(let e of this.states.keys())this.stopTracking(e)}};Sn.StatusDetector=ta;function Fg(r){for(let e=0;e<r.length;e++){let t=r.charCodeAt(e);if(t===27){let i=r[e+1];if(i==="["||i==="O"){for(e+=2;e<r.length&&!/[A-Za-z~]/.test(r[e]);)e++;continue}if(i==="]"){for(e+=2;e<r.length&&r.charCodeAt(e)!==7;)e++;continue}return!0}if(t===13||t===10||t===3||t>=32&&t!==127)return!0}return!1}});var vu=M((SE,bu)=>{var Mi=require("fs"),_u=require("url"),Dg=require("child_process").spawn;bu.exports=ra;ra.XMLHttpRequest=ra;function ra(r){"use strict";r=r||{};var e=this,t=require("http"),i=require("https"),n,s,a={},c=!1,u={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},d=Object.assign({},u),p=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","content-transfer-encoding","cookie","cookie2","date","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"],m=["TRACE","TRACK","CONNECT"],_=!1,E=!1,S=!1,T={};this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.readyState=this.UNSENT,this.onreadystatechange=null,this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),this.status=null,this.statusText=null;var z=function(R){return c||R&&p.indexOf(R.toLowerCase())===-1},ge=function(R){return R&&m.indexOf(R)===-1};this.open=function(R,B,re,K,U){if(this.abort(),E=!1,S=!1,!ge(R))throw new Error("SecurityError: Request method not allowed");a={method:R,url:B.toString(),async:typeof re!="boolean"?!0:re,user:K||null,password:U||null},ee(this.OPENED)},this.setDisableHeaderCheck=function(R){c=R},this.setRequestHeader=function(R,B){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!z(R))return console.warn('Refused to set unsafe header "'+R+'"'),!1;if(_)throw new Error("INVALID_STATE_ERR: send flag is true");return d[R]=B,!0},this.getResponseHeader=function(R){return typeof R=="string"&&this.readyState>this.OPENED&&s.headers[R.toLowerCase()]&&!E?s.headers[R.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||E)return"";var R="";for(var B in s.headers)B!=="set-cookie"&&B!=="set-cookie2"&&(R+=B+": "+s.headers[B]+`\r
|
|
18
18
|
`);return R.substr(0,R.length-2)},this.getRequestHeader=function(R){return typeof R=="string"&&d[R]?d[R]:""},this.send=function(R){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(_)throw new Error("INVALID_STATE_ERR: send has already been called");var B=!1,re=!1,K=_u.parse(a.url),U;switch(K.protocol){case"https:":B=!0;case"http:":U=K.hostname;break;case"file:":re=!0;break;case void 0:case"":U="localhost";break;default:throw new Error("Protocol not supported.")}if(re){if(a.method!=="GET")throw new Error("XMLHttpRequest: Only GET method is supported");if(a.async)Mi.readFile(unescape(K.pathname),function(A,P){A?e.handleError(A,A.errno||-1):(e.status=200,e.responseText=P.toString("utf8"),e.response=P,ee(e.DONE))});else try{this.response=Mi.readFileSync(unescape(K.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,ee(e.DONE)}catch(A){this.handleError(A,A.errno||-1)}return}var ye=K.port||(B?443:80),xe=K.pathname+(K.search?K.search:"");if(d.Host=U,B&&ye===443||ye===80||(d.Host+=":"+K.port),a.user){typeof a.password>"u"&&(a.password="");var ue=new Buffer(a.user+":"+a.password);d.Authorization="Basic "+ue.toString("base64")}if(a.method==="GET"||a.method==="HEAD")R=null;else if(R){d["Content-Length"]=Buffer.isBuffer(R)?R.length:Buffer.byteLength(R);var rt=Object.keys(d);rt.some(function(A){return A.toLowerCase()==="content-type"})||(d["Content-Type"]="text/plain;charset=UTF-8")}else a.method==="POST"&&(d["Content-Length"]=0);var Ee=r.agent||!1,Se={host:U,port:ye,path:xe,method:a.method,headers:d,agent:Ee};if(B&&(Se.pfx=r.pfx,Se.key=r.key,Se.passphrase=r.passphrase,Se.cert=r.cert,Se.ca=r.ca,Se.ciphers=r.ciphers,Se.rejectUnauthorized=r.rejectUnauthorized!==!1),E=!1,a.async){var ve=B?i.request:t.request;_=!0,e.dispatchEvent("readystatechange");var We=function(A){if(s=A,s.statusCode===302||s.statusCode===303||s.statusCode===307){a.url=s.headers.location;var P=_u.parse(a.url);U=P.hostname;var Z={hostname:P.hostname,port:P.port,path:P.path,method:s.statusCode===303?"GET":a.method,headers:d};B&&(Z.pfx=r.pfx,Z.key=r.key,Z.passphrase=r.passphrase,Z.cert=r.cert,Z.ca=r.ca,Z.ciphers=r.ciphers,Z.rejectUnauthorized=r.rejectUnauthorized!==!1),n=ve(Z,We).on("error",st),n.end();return}ee(e.HEADERS_RECEIVED),e.status=s.statusCode,s.on("data",function(Ne){if(Ne){var Xe=Buffer.from(Ne);e.response=Buffer.concat([e.response,Xe])}_&&ee(e.LOADING)}),s.on("end",function(){_&&(_=!1,ee(e.DONE),e.responseText=e.response.toString("utf8"))}),s.on("error",function(Ne){e.handleError(Ne)})},st=function(A){if(n.reusedSocket&&A.code==="ECONNRESET")return ve(Se,We).on("error",st);e.handleError(A)};n=ve(Se,We).on("error",st),r.autoUnref&&n.on("socket",A=>{A.unref()}),R&&n.write(R),n.end(),e.dispatchEvent("loadstart")}else{var Ze=".node-xmlhttprequest-content-"+process.pid,Te=".node-xmlhttprequest-sync-"+process.pid;Mi.writeFileSync(Te,"","utf8");for(var it="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(B?"s":"")+".request;var options = "+JSON.stringify(Se)+";var responseText = '';var responseData = Buffer.alloc(0);var req = doRequest(options, function(response) {response.on('data', function(chunk) { var data = Buffer.from(chunk); responseText += data.toString('utf8'); responseData = Buffer.concat([responseData, data]);});response.on('end', function() {fs.writeFileSync('"+Ze+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+Te+"');});response.on('error', function(error) {fs.writeFileSync('"+Ze+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Te+"');});}).on('error', function(error) {fs.writeFileSync('"+Ze+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Te+"');});"+(R?"req.write('"+JSON.stringify(R).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",ze=Dg(process.argv[0],["-e",it]),gt;Mi.existsSync(Te););if(e.responseText=Mi.readFileSync(Ze,"utf8"),ze.stdin.end(),Mi.unlinkSync(Ze),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var L=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(L,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var j=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));s={statusCode:e.status,headers:j.data.headers},e.responseText=j.data.text,e.response=Buffer.from(j.data.data,"base64"),ee(e.DONE,!0)}}},this.handleError=function(R,B){this.status=B||0,this.statusText=R,this.responseText=R.stack,E=!0,ee(this.DONE)},this.abort=function(){n&&(n.abort(),n=null),d=Object.assign({},u),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),E=S=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||_)&&this.readyState!==this.DONE&&(_=!1,ee(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(R,B){R in T||(T[R]=[]),T[R].push(B)},this.removeEventListener=function(R,B){R in T&&(T[R]=T[R].filter(function(re){return re!==B}))},this.dispatchEvent=function(R){if(typeof e["on"+R]=="function"&&(this.readyState===this.DONE&&a.async?setTimeout(function(){e["on"+R]()},0):e["on"+R]()),R in T)for(let B=0,re=T[R].length;B<re;B++)this.readyState===this.DONE?setTimeout(function(){T[R][B].call(e)},0):T[R][B].call(e)};var ee=function(R){if(!(e.readyState===R||e.readyState===e.UNSENT&&S)&&(e.readyState=R,(a.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let B;S?B="abort":E?B="error":B="load",e.dispatchEvent(B),e.dispatchEvent("loadend")}}}});var Ts=M(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.ERROR_PACKET=Wr.PACKET_TYPES_REVERSE=Wr.PACKET_TYPES=void 0;var sr=Object.create(null);Wr.PACKET_TYPES=sr;sr.open="0";sr.close="1";sr.ping="2";sr.pong="3";sr.message="4";sr.upgrade="5";sr.noop="6";var Eu=Object.create(null);Wr.PACKET_TYPES_REVERSE=Eu;Object.keys(sr).forEach(r=>{Eu[sr[r]]=r});var Bg={type:"error",data:"parser error"};Wr.ERROR_PACKET=Bg});var xu=M(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});Fi.encodePacket=void 0;Fi.encodePacketToBinary=Kg;var jg=Ts(),Ug=({type:r,data:e},t,i)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?i(t?e:"b"+wu(e,!0).toString("base64")):i(jg.PACKET_TYPES[r]+(e||""));Fi.encodePacket=Ug;var wu=(r,e)=>Buffer.isBuffer(r)||r instanceof Uint8Array&&!e?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength),ia;function Kg(r,e){if(r.data instanceof ArrayBuffer||ArrayBuffer.isView(r.data))return e(wu(r.data,!1));(0,Fi.encodePacket)(r,!0,t=>{ia||(ia=new TextEncoder),e(ia.encode(t))})}});var Tu=M(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.decodePacket=void 0;var Cs=Ts(),qg=(r,e)=>{if(typeof r!="string")return{type:"message",data:Su(r,e)};let t=r.charAt(0);if(t==="b"){let i=Buffer.from(r.substring(1),"base64");return{type:"message",data:Su(i,e)}}return Cs.PACKET_TYPES_REVERSE[t]?r.length>1?{type:Cs.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:Cs.PACKET_TYPES_REVERSE[t]}:Cs.ERROR_PACKET};ks.decodePacket=qg;var Su=(r,e)=>e==="arraybuffer"?r instanceof ArrayBuffer?r:Buffer.isBuffer(r)?r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength):r.buffer:Buffer.isBuffer(r)?r:Buffer.from(r)});var Di=M(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.decodePayload=vt.decodePacket=vt.encodePayload=vt.encodePacket=vt.protocol=void 0;vt.createPacketEncoderStream=Vg;vt.createPacketDecoderStream=zg;var sa=xu();Object.defineProperty(vt,"encodePacket",{enumerable:!0,get:function(){return sa.encodePacket}});var oa=Tu();Object.defineProperty(vt,"decodePacket",{enumerable:!0,get:function(){return oa.decodePacket}});var Cu=Ts(),ku="",Wg=(r,e)=>{let t=r.length,i=new Array(t),n=0;r.forEach((s,a)=>{(0,sa.encodePacket)(s,!1,c=>{i[a]=c,++n===t&&e(i.join(ku))})})};vt.encodePayload=Wg;var Hg=(r,e)=>{let t=r.split(ku),i=[];for(let n=0;n<t.length;n++){let s=(0,oa.decodePacket)(t[n],e);if(i.push(s),s.type==="error")break}return i};vt.decodePayload=Hg;function Vg(){return new TransformStream({transform(r,e){(0,sa.encodePacketToBinary)(r,t=>{let i=t.length,n;if(i<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,i);else if(i<65536){n=new Uint8Array(3);let s=new DataView(n.buffer);s.setUint8(0,126),s.setUint16(1,i)}else{n=new Uint8Array(9);let s=new DataView(n.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(i))}r.data&&typeof r.data!="string"&&(n[0]|=128),e.enqueue(n),e.enqueue(t)})}})}var na;function Os(r){return r.reduce((e,t)=>e+t.length,0)}function Ps(r,e){if(r[0].length===e)return r.shift();let t=new Uint8Array(e),i=0;for(let n=0;n<e;n++)t[n]=r[0][i++],i===r[0].length&&(r.shift(),i=0);return r.length&&i<r[0].length&&(r[0]=r[0].slice(i)),t}function zg(r,e){na||(na=new TextDecoder);let t=[],i=0,n=-1,s=!1;return new TransformStream({transform(a,c){for(t.push(a);;){if(i===0){if(Os(t)<1)break;let u=Ps(t,1);s=(u[0]&128)===128,n=u[0]&127,n<126?i=3:n===126?i=1:i=2}else if(i===1){if(Os(t)<2)break;let u=Ps(t,2);n=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),i=3}else if(i===2){if(Os(t)<8)break;let u=Ps(t,8),d=new DataView(u.buffer,u.byteOffset,u.length),p=d.getUint32(0);if(p>Math.pow(2,21)-1){c.enqueue(Cu.ERROR_PACKET);break}n=p*Math.pow(2,32)+d.getUint32(4),i=3}else{if(Os(t)<n)break;let u=Ps(t,n);c.enqueue((0,oa.decodePacket)(s?u:na.decode(u),e)),i=0}if(n===0||n>r){c.enqueue(Cu.ERROR_PACKET);break}}}})}vt.protocol=4});var di=M(Ou=>{Ou.Emitter=yt;function yt(r){if(r)return $g(r)}function $g(r){for(var e in yt.prototype)r[e]=yt.prototype[e];return r}yt.prototype.on=yt.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};yt.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};yt.prototype.off=yt.prototype.removeListener=yt.prototype.removeAllListeners=yt.prototype.removeEventListener=function(r,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+r];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var i,n=0;n<t.length;n++)if(i=t[n],i===e||i.fn===e){t.splice(n,1);break}return t.length===0&&delete this._callbacks["$"+r],this};yt.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],i=1;i<arguments.length;i++)e[i-1]=arguments[i];if(t){t=t.slice(0);for(var i=0,n=t.length;i<n;++i)t[i].apply(this,e)}return this};yt.prototype.emitReserved=yt.prototype.emit;yt.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};yt.prototype.hasListeners=function(r){return!!this.listeners(r).length}});var pi=M(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.CookieJar=Nt.defaultBinaryType=Nt.globalThisShim=Nt.nextTick=void 0;Nt.createCookieJar=Gg;Nt.parse=Pu;Nt.nextTick=process.nextTick;Nt.globalThisShim=global;Nt.defaultBinaryType="nodebuffer";function Gg(){return new Rs}function Pu(r){let e=r.split("; "),t=e[0].indexOf("=");if(t===-1)return;let i=e[0].substring(0,t).trim();if(!i.length)return;let n=e[0].substring(t+1).trim();n.charCodeAt(0)===34&&(n=n.slice(1,-1));let s={name:i,value:n};for(let a=1;a<e.length;a++){let c=e[a].split("=");if(c.length!==2)continue;let u=c[0].trim(),d=c[1].trim();switch(u){case"Expires":s.expires=new Date(d);break;case"Max-Age":let p=new Date;p.setUTCSeconds(p.getUTCSeconds()+parseInt(d,10)),s.expires=p;break;default:}}return s}var Rs=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let i=Pu(t);i&&this._cookies.set(i.name,i)})}get cookies(){let e=Date.now();return this._cookies.forEach((t,i)=>{var n;((n=t.expires)===null||n===void 0?void 0:n.getTime())<e&&this._cookies.delete(i)}),this._cookies.entries()}addCookies(e){let t=[];for(let[i,n]of this.cookies)t.push(`${i}=${n.value}`);t.length&&(e.setDisableHeaderCheck(!0),e.setRequestHeader("cookie",t.join("; ")))}appendCookies(e){for(let[t,i]of this.cookies)e.append("cookie",`${t}=${i.value}`)}};Nt.CookieJar=Rs});var gi=M(Bi=>{"use strict";Object.defineProperty(Bi,"__esModule",{value:!0});Bi.pick=Yg;Bi.installTimerFunctions=Zg;Bi.byteLength=em;Bi.randomString=rm;var Hr=pi();function Yg(r,...e){return e.reduce((t,i)=>(r.hasOwnProperty(i)&&(t[i]=r[i]),t),{})}var Xg=Hr.globalThisShim.setTimeout,Jg=Hr.globalThisShim.clearTimeout;function Zg(r,e){e.useNativeTimers?(r.setTimeoutFn=Xg.bind(Hr.globalThisShim),r.clearTimeoutFn=Jg.bind(Hr.globalThisShim)):(r.setTimeoutFn=Hr.globalThisShim.setTimeout.bind(Hr.globalThisShim),r.clearTimeoutFn=Hr.globalThisShim.clearTimeout.bind(Hr.globalThisShim))}var Qg=1.33;function em(r){return typeof r=="string"?tm(r):Math.ceil((r.byteLength||r.size)*Qg)}function tm(r){let e=0,t=0;for(let i=0,n=r.length;i<n;i++)e=r.charCodeAt(i),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(i++,t+=4);return t}function rm(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}});var aa=M(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});As.encode=im;As.decode=nm;function im(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function nm(r){let e={},t=r.split("&");for(let i=0,n=t.length;i<n;i++){let s=t[i].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}});var Au=M((LE,Ru)=>{var ji=1e3,Ui=ji*60,Ki=Ui*60,mi=Ki*24,sm=mi*7,om=mi*365.25;Ru.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return am(r);if(t==="number"&&isFinite(r))return e.long?fm(r):cm(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function am(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),i=(e[2]||"ms").toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return t*om;case"weeks":case"week":case"w":return t*sm;case"days":case"day":case"d":return t*mi;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Ki;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ui;case"seconds":case"second":case"secs":case"sec":case"s":return t*ji;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function cm(r){var e=Math.abs(r);return e>=mi?Math.round(r/mi)+"d":e>=Ki?Math.round(r/Ki)+"h":e>=Ui?Math.round(r/Ui)+"m":e>=ji?Math.round(r/ji)+"s":r+"ms"}function fm(r){var e=Math.abs(r);return e>=mi?Is(r,e,mi,"day"):e>=Ki?Is(r,e,Ki,"hour"):e>=Ui?Is(r,e,Ui,"minute"):e>=ji?Is(r,e,ji,"second"):r+" ms"}function Is(r,e,t,i){var n=e>=t*1.5;return Math.round(r/t)+" "+i+(n?"s":"")}});var ca=M((NE,Iu)=>{function um(r){t.debug=t,t.default=t,t.coerce=u,t.disable=a,t.enable=n,t.enabled=c,t.humanize=Au(),t.destroy=d,Object.keys(r).forEach(p=>{t[p]=r[p]}),t.names=[],t.skips=[],t.formatters={};function e(p){let m=0;for(let _=0;_<p.length;_++)m=(m<<5)-m+p.charCodeAt(_),m|=0;return t.colors[Math.abs(m)%t.colors.length]}t.selectColor=e;function t(p){let m,_=null,E,S;function T(...z){if(!T.enabled)return;let ge=T,ee=Number(new Date),R=ee-(m||ee);ge.diff=R,ge.prev=m,ge.curr=ee,m=ee,z[0]=t.coerce(z[0]),typeof z[0]!="string"&&z.unshift("%O");let B=0;z[0]=z[0].replace(/%([a-zA-Z%])/g,(K,U)=>{if(K==="%%")return"%";B++;let ye=t.formatters[U];if(typeof ye=="function"){let xe=z[B];K=ye.call(ge,xe),z.splice(B,1),B--}return K}),t.formatArgs.call(ge,z),(ge.log||t.log).apply(ge,z)}return T.namespace=p,T.useColors=t.useColors(),T.color=t.selectColor(p),T.extend=i,T.destroy=t.destroy,Object.defineProperty(T,"enabled",{enumerable:!0,configurable:!1,get:()=>_!==null?_:(E!==t.namespaces&&(E=t.namespaces,S=t.enabled(p)),S),set:z=>{_=z}}),typeof t.init=="function"&&t.init(T),T}function i(p,m){let _=t(this.namespace+(typeof m>"u"?":":m)+p);return _.log=this.log,_}function n(p){t.save(p),t.namespaces=p,t.names=[],t.skips=[];let m=(typeof p=="string"?p:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let _ of m)_[0]==="-"?t.skips.push(_.slice(1)):t.names.push(_)}function s(p,m){let _=0,E=0,S=-1,T=0;for(;_<p.length;)if(E<m.length&&(m[E]===p[_]||m[E]==="*"))m[E]==="*"?(S=E,T=_,E++):(_++,E++);else if(S!==-1)E=S+1,T++,_=T;else return!1;for(;E<m.length&&m[E]==="*";)E++;return E===m.length}function a(){let p=[...t.names,...t.skips.map(m=>"-"+m)].join(",");return t.enable(""),p}function c(p){for(let m of t.skips)if(s(p,m))return!1;for(let m of t.names)if(s(p,m))return!0;return!1}function u(p){return p instanceof Error?p.stack||p.message:p}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}Iu.exports=um});var Lu=M((Et,Ls)=>{Et.formatArgs=hm;Et.save=dm;Et.load=pm;Et.useColors=lm;Et.storage=gm();Et.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Et.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function lm(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function hm(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ls.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,i=0;r[0].replace(/%[a-zA-Z%]/g,n=>{n!=="%%"&&(t++,n==="%c"&&(i=t))}),r.splice(i,0,e)}Et.log=console.debug||console.log||(()=>{});function dm(r){try{r?Et.storage.setItem("debug",r):Et.storage.removeItem("debug")}catch{}}function pm(){let r;try{r=Et.storage.getItem("debug")||Et.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function gm(){try{return localStorage}catch{}}Ls.exports=ca()(Et);var{formatters:mm}=Ls.exports;mm.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Mu=M((ME,Nu)=>{"use strict";Nu.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",i=e.indexOf(t+r),n=e.indexOf("--");return i!==-1&&(n===-1||i<n)}});var Bu=M((FE,Du)=>{"use strict";var ym=require("os"),Fu=require("tty"),Mt=Mu(),{env:ot}=process,Vr;Mt("no-color")||Mt("no-colors")||Mt("color=false")||Mt("color=never")?Vr=0:(Mt("color")||Mt("colors")||Mt("color=true")||Mt("color=always"))&&(Vr=1);"FORCE_COLOR"in ot&&(ot.FORCE_COLOR==="true"?Vr=1:ot.FORCE_COLOR==="false"?Vr=0:Vr=ot.FORCE_COLOR.length===0?1:Math.min(parseInt(ot.FORCE_COLOR,10),3));function fa(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function ua(r,e){if(Vr===0)return 0;if(Mt("color=16m")||Mt("color=full")||Mt("color=truecolor"))return 3;if(Mt("color=256"))return 2;if(r&&!e&&Vr===void 0)return 0;let t=Vr||0;if(ot.TERM==="dumb")return t;if(process.platform==="win32"){let i=ym.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in ot)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(i=>i in ot)||ot.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in ot)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ot.TEAMCITY_VERSION)?1:0;if(ot.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in ot){let i=parseInt((ot.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ot.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ot.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ot.TERM)||"COLORTERM"in ot?1:t}function _m(r){let e=ua(r,r&&r.isTTY);return fa(e)}Du.exports={supportsColor:_m,stdout:fa(ua(!0,Fu.isatty(1))),stderr:fa(ua(!0,Fu.isatty(2)))}});var Uu=M((at,Ms)=>{var bm=require("tty"),Ns=require("util");at.init=Cm;at.log=xm;at.formatArgs=Em;at.save=Sm;at.load=Tm;at.useColors=vm;at.destroy=Ns.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");at.colors=[6,2,3,4,5,1];try{let r=Bu();r&&(r.stderr||r).level>=2&&(at.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}at.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(n,s)=>s.toUpperCase()),i=process.env[e];return/^(yes|on|true|enabled)$/i.test(i)?i=!0:/^(no|off|false|disabled)$/i.test(i)?i=!1:i==="null"?i=null:i=Number(i),r[t]=i,r},{});function vm(){return"colors"in at.inspectOpts?!!at.inspectOpts.colors:bm.isatty(process.stderr.fd)}function Em(r){let{namespace:e,useColors:t}=this;if(t){let i=this.color,n="\x1B[3"+(i<8?i:"8;5;"+i),s=` ${n};1m${e} \x1B[0m`;r[0]=s+r[0].split(`
|
|
19
19
|
`).join(`
|
|
20
20
|
`+s),r.push(n+"m+"+Ms.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=wm()+e+" "+r[0]}function wm(){return at.inspectOpts.hideDate?"":new Date().toISOString()+" "}function xm(...r){return process.stderr.write(Ns.formatWithOptions(at.inspectOpts,...r)+`
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
`+Object.keys(i).map(n=>`${n}: ${i[n]}`).join(`\r
|
|
26
26
|
`)+`\r
|
|
27
27
|
\r
|
|
28
|
-
`+t)}function Ei(r,e,t,i,n,s){if(r.listenerCount("wsClientError")){let a=new Error(n);Error.captureStackTrace(a,Ei),r.emit("wsClientError",a,t,e)}else Ln(t,i,n,s)}});var th=M((aw,eh)=>{"use strict";var Rr=Xs();Rr.createWebSocketStream=Hl();Rr.Server=Ql();Rr.Receiver=Ra();Rr.Sender=La();Rr.WebSocket=Rr;Rr.WebSocketServer=Rr.Server;eh.exports=Rr});var Ha=M(Yr=>{"use strict";var d_=Yr&&Yr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Yr,"__esModule",{value:!0});Yr.WS=Yr.BaseWS=void 0;var p_=Tn(),rh=gi(),g_=Di(),qa=pi(),m_=d_(Ft()),y_=(0,m_.default)("engine.io-client:websocket"),ih=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Zs=class extends p_.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,i=ih?{}:(0,rh.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,i)}catch(n){return this.emitReserved("error",n)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let i=e[t],n=t===e.length-1;(0,g_.encodePacket)(i,this.supportsBinary,s=>{try{this.doWrite(i,s)}catch{y_("websocket closed before onclose event")}n&&(0,qa.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=(0,rh.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}};Yr.BaseWS=Zs;var Ka=qa.globalThisShim.WebSocket||qa.globalThisShim.MozWebSocket,Wa=class extends Zs{createSocket(e,t,i){return ih?new Ka(e,t,i):t?new Ka(e,t):new Ka(e)}doWrite(e,t){this.ws.send(t)}};Yr.WS=Wa});var za=M(fr=>{"use strict";var __=fr&&fr.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),b_=fr&&fr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),v_=fr&&fr.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&__(e,r,t);return b_(e,r),e};Object.defineProperty(fr,"__esModule",{value:!0});fr.WS=void 0;var E_=v_(th()),w_=Ha(),Va=class extends w_.BaseWS{createSocket(e,t,i){var n;if(!((n=this.socket)===null||n===void 0)&&n._cookieJar){i.headers=i.headers||{},i.headers.cookie=typeof i.headers.cookie=="string"?[i.headers.cookie]:i.headers.cookie||[];for(let[s,a]of this.socket._cookieJar.cookies)i.headers.cookie.push(`${s}=${a.value}`)}return new E_.WebSocket(e,t,i)}doWrite(e,t){let i={};e.options&&(i.compress=e.options.compress),this.opts.perMessageDeflate&&(typeof t=="string"?Buffer.byteLength(t):t.length)<this.opts.perMessageDeflate.threshold&&(i.compress=!1),this.ws.send(t,i)}};fr.WS=Va});var Ga=M(Xi=>{"use strict";var x_=Xi&&Xi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xi,"__esModule",{value:!0});Xi.WT=void 0;var S_=Tn(),T_=pi(),nh=Di(),C_=x_(Ft()),Nn=(0,C_.default)("engine.io-client:webtransport"),$a=class extends S_.Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{Nn("transport closed gracefully"),this.onClose()}).catch(e=>{Nn("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=(0,nh.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),n=(0,nh.createPacketEncoderStream)();n.readable.pipeTo(e.writable),this._writer=n.writable.getWriter();let s=()=>{i.read().then(({done:c,value:u})=>{if(c){Nn("session is closed");return}Nn("received chunk: %o",u),this.onPacket(u),s()}).catch(c=>{Nn("an error occurred while reading: %s",c)})};s();let a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let i=e[t],n=t===e.length-1;this._writer.write(i).then(()=>{n&&(0,T_.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};Xi.WT=$a});var Ya=M(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});Qs.transports=void 0;var k_=ba(),O_=za(),P_=Ga();Qs.transports={websocket:O_.WS,webtransport:P_.WT,polling:k_.XHR}});var Ja=M(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.parse=I_;var R_=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,A_=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function I_(r){if(r.length>8e3)throw"URI too long";let e=r,t=r.indexOf("["),i=r.indexOf("]");t!=-1&&i!=-1&&(r=r.substring(0,t)+r.substring(t,i).replace(/:/g,";")+r.substring(i,r.length));let n=R_.exec(r||""),s={},a=14;for(;a--;)s[A_[a]]=n[a]||"";return t!=-1&&i!=-1&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=L_(s,s.path),s.queryKey=N_(s,s.query),s}function L_(r,e){let t=/\/{2,9}/g,i=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&i.splice(0,1),e.slice(-1)=="/"&&i.splice(i.length-1,1),i}function N_(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(i,n,s){n&&(t[n]=s)}),t}});var tc=M(ur=>{"use strict";var M_=ur&&ur.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ur,"__esModule",{value:!0});ur.Socket=ur.SocketWithUpgrade=ur.SocketWithoutUpgrade=void 0;var F_=Ya(),sh=gi(),D_=aa(),oh=Ja(),B_=di(),ah=Di(),Za=pi(),j_=M_(Ft()),De=(0,j_.default)("engine.io-client:socket"),Qa=typeof addEventListener=="function"&&typeof removeEventListener=="function",Mn=[];Qa&&addEventListener("offline",()=>{De("closing %d connection(s) because the network was lost",Mn.length),Mn.forEach(r=>r())},!1);var wi=class r extends B_.Emitter{constructor(e,t){if(super(),this.binaryType=Za.defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){let i=(0,oh.parse)(e);t.hostname=i.host,t.secure=i.protocol==="https"||i.protocol==="wss",t.port=i.port,i.query&&(t.query=i.query)}else t.host&&(t.hostname=(0,oh.parse)(t.host).host);(0,sh.installTimerFunctions)(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(i=>{let n=i.prototype.name;this.transports.push(n),this._transportsByName[n]=i}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=(0,D_.decode)(this.opts.query)),Qa&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(De("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Mn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Za.createCookieJar)()),this._open()}createTransport(e){De('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=ah.protocol,t.transport=e,this.id&&(t.sid=this.id);let i=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return De("options: %j",i),new this._transportsByName[e](i)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let e=this.opts.rememberUpgrade&&r.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){De("setting transport %s",e.name),this.transport&&(De("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){De("socket open"),this.readyState="open",r.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(De('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}else De('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();De("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let i=0;i<this.writeBuffer.length;i++){let n=this.writeBuffer[i].data;if(n&&(t+=(0,sh.byteLength)(n)),i>0&&t>this._maxPayload)return De("only send %d out of %d packets",i,this.writeBuffer.length),this.writeBuffer.slice(0,i);t+=2}return De("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(De("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,Za.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,i){return this._sendPacket("message",e,t,i),this}send(e,t,i){return this._sendPacket("message",e,t,i),this}_sendPacket(e,t,i,n){if(typeof t=="function"&&(n=t,t=void 0),typeof i=="function"&&(n=i,i=null),this.readyState==="closing"||this.readyState==="closed")return;i=i||{},i.compress=i.compress!==!1;let s={type:e,data:t,options:i};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),n&&this.once("flush",n),this.flush()}close(){let e=()=>{this._onClose("forced close"),De("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},i=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?i():e()}):this.upgrading?i():e()),this}_onError(e){if(De("socket error %j",e),r.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return De("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(De('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Qa&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let i=Mn.indexOf(this._offlineEventListener);i!==-1&&(De("removing listener for the 'offline' event"),Mn.splice(i,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};ur.SocketWithoutUpgrade=wi;wi.protocol=ah.protocol;var eo=class extends wi{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){De("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){De('probing transport "%s"',e);let t=this.createTransport(e),i=!1;wi.priorWebsocketSuccess=!1;let n=()=>{i||(De('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",m=>{if(!i)if(m.type==="pong"&&m.data==="probe"){if(De('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;wi.priorWebsocketSuccess=t.name==="websocket",De('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{i||this.readyState!=="closed"&&(De("changing transport and sending upgrade packet"),p(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{De('probe transport "%s" failed',e);let _=new Error("probe error");_.transport=t.name,this.emitReserved("upgradeError",_)}}))};function s(){i||(i=!0,p(),t.close(),t=null)}let a=m=>{let _=new Error("probe error: "+m);_.transport=t.name,s(),De('probe transport "%s" failed because of error: %s',e,m),this.emitReserved("upgradeError",_)};function c(){a("transport closed")}function u(){a("socket closed")}function d(m){t&&m.name!==t.name&&(De('"%s" works - aborting "%s"',m.name,t.name),s())}let p=()=>{t.removeListener("open",n),t.removeListener("error",a),t.removeListener("close",c),this.off("close",u),this.off("upgrading",d)};t.once("open",n),t.once("error",a),t.once("close",c),this.once("close",u),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{i||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let i=0;i<e.length;i++)~this.transports.indexOf(e[i])&&t.push(e[i]);return t}};ur.SocketWithUpgrade=eo;var ec=class extends eo{constructor(e,t={}){let i=typeof e=="object"?e:t;(!i.transports||i.transports&&typeof i.transports[0]=="string")&&(i.transports=(i.transports||["polling","websocket","webtransport"]).map(n=>F_.transports[n]).filter(n=>!!n)),super(e,i)}};ur.Socket=ec});var ch=M(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.Fetch=void 0;var U_=pa(),rc=class extends U_.Polling{doPoll(){this._fetch().then(e=>{if(!e.ok)return this.onError("fetch read error",e.status,e);e.text().then(t=>this.onData(t))}).catch(e=>{this.onError("fetch read error",e)})}doWrite(e,t){this._fetch(e).then(i=>{if(!i.ok)return this.onError("fetch write error",i.status,i);t()}).catch(i=>{this.onError("fetch write error",i)})}_fetch(e){var t;let i=e!==void 0,n=new Headers(this.opts.extraHeaders);return i&&n.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(n),fetch(this.uri(),{method:i?"POST":"GET",body:i?e:null,headers:n,credentials:this.opts.withCredentials?"include":"omit"}).then(s=>{var a;return(a=this.socket._cookieJar)===null||a===void 0||a.parseCookies(s.headers.getSetCookie()),s})}};to.Fetch=rc});var ro=M(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.WebTransport=Oe.WebSocket=Oe.NodeWebSocket=Oe.XHR=Oe.NodeXHR=Oe.Fetch=Oe.nextTick=Oe.parse=Oe.installTimerFunctions=Oe.transports=Oe.TransportError=Oe.Transport=Oe.protocol=Oe.SocketWithUpgrade=Oe.SocketWithoutUpgrade=Oe.Socket=void 0;var fh=tc();Object.defineProperty(Oe,"Socket",{enumerable:!0,get:function(){return fh.Socket}});var uh=tc();Object.defineProperty(Oe,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return uh.SocketWithoutUpgrade}});Object.defineProperty(Oe,"SocketWithUpgrade",{enumerable:!0,get:function(){return uh.SocketWithUpgrade}});Oe.protocol=fh.Socket.protocol;var lh=Tn();Object.defineProperty(Oe,"Transport",{enumerable:!0,get:function(){return lh.Transport}});Object.defineProperty(Oe,"TransportError",{enumerable:!0,get:function(){return lh.TransportError}});var K_=Ya();Object.defineProperty(Oe,"transports",{enumerable:!0,get:function(){return K_.transports}});var q_=gi();Object.defineProperty(Oe,"installTimerFunctions",{enumerable:!0,get:function(){return q_.installTimerFunctions}});var W_=Ja();Object.defineProperty(Oe,"parse",{enumerable:!0,get:function(){return W_.parse}});var H_=pi();Object.defineProperty(Oe,"nextTick",{enumerable:!0,get:function(){return H_.nextTick}});var V_=ch();Object.defineProperty(Oe,"Fetch",{enumerable:!0,get:function(){return V_.Fetch}});var z_=ba();Object.defineProperty(Oe,"NodeXHR",{enumerable:!0,get:function(){return z_.XHR}});var $_=ya();Object.defineProperty(Oe,"XHR",{enumerable:!0,get:function(){return $_.XHR}});var G_=za();Object.defineProperty(Oe,"NodeWebSocket",{enumerable:!0,get:function(){return G_.WS}});var Y_=Ha();Object.defineProperty(Oe,"WebSocket",{enumerable:!0,get:function(){return Y_.WS}});var X_=Ga();Object.defineProperty(Oe,"WebTransport",{enumerable:!0,get:function(){return X_.WT}})});var dh=M(Fn=>{"use strict";var J_=Fn&&Fn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fn,"__esModule",{value:!0});Fn.url=e0;var Z_=ro(),Q_=J_(Ft()),hh=(0,Q_.default)("socket.io-client:url");function e0(r,e="",t){let i=r;t=t||typeof location<"u"&&location,r==null&&(r=t.protocol+"//"+t.host),typeof r=="string"&&(r.charAt(0)==="/"&&(r.charAt(1)==="/"?r=t.protocol+r:r=t.host+r),/^(https?|wss?):\/\//.test(r)||(hh("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),hh("parse %s",r),i=(0,Z_.parse)(r)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";let s=i.host.indexOf(":")!==-1?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+s+":"+i.port+e,i.href=i.protocol+"://"+s+(t&&t.port===i.port?"":":"+i.port),i}});var ic=M(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.isBinary=gh;no.hasBinary=io;var t0=typeof ArrayBuffer=="function",r0=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,ph=Object.prototype.toString,i0=typeof Blob=="function"||typeof Blob<"u"&&ph.call(Blob)==="[object BlobConstructor]",n0=typeof File=="function"||typeof File<"u"&&ph.call(File)==="[object FileConstructor]";function gh(r){return t0&&(r instanceof ArrayBuffer||r0(r))||i0&&r instanceof Blob||n0&&r instanceof File}function io(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,i=r.length;t<i;t++)if(io(r[t]))return!0;return!1}if(gh(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return io(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&io(r[t]))return!0;return!1}});var mh=M(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.deconstructPacket=o0;so.reconstructPacket=a0;var s0=ic();function o0(r){let e=[],t=r.data,i=r;return i.data=nc(t,e),i.attachments=e.length,{packet:i,buffers:e}}function nc(r,e){if(!r)return r;if((0,s0.isBinary)(r)){let t={_placeholder:!0,num:e.length};return e.push(r),t}else if(Array.isArray(r)){let t=new Array(r.length);for(let i=0;i<r.length;i++)t[i]=nc(r[i],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){let t={};for(let i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=nc(r[i],e));return t}return r}function a0(r,e){return r.data=sc(r.data,e),delete r.attachments,r}function sc(r,e){if(!r)return r;if(r&&r._placeholder===!0){if(typeof r.num=="number"&&r.num>=0&&r.num<e.length)return e[r.num];throw new Error("illegal attachments")}else if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]=sc(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=sc(r[t],e));return r}});var ao=M(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.Decoder=zt.Encoder=zt.PacketType=zt.protocol=void 0;zt.isPacketValid=p0;var c0=di(),yh=mh(),_h=ic(),f0=Ft(),oc=(0,f0.default)("socket.io-parser"),bh=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];zt.protocol=5;var Fe;(function(r){r[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK"})(Fe||(zt.PacketType=Fe={}));var ac=class{constructor(e){this.replacer=e}encode(e){return oc("encoding packet %j",e),(e.type===Fe.EVENT||e.type===Fe.ACK)&&(0,_h.hasBinary)(e)?this.encodeAsBinary({type:e.type===Fe.EVENT?Fe.BINARY_EVENT:Fe.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Fe.BINARY_EVENT||e.type===Fe.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),oc("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,yh.deconstructPacket)(e),i=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(i),n}};zt.Encoder=ac;var cc=class r extends c0.Emitter{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);let i=t.type===Fe.BINARY_EVENT;i||t.type===Fe.BINARY_ACK?(t.type=i?Fe.EVENT:Fe.ACK,this.reconstructor=new fc(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,_h.isBinary)(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0,i={type:Number(e.charAt(0))};if(Fe[i.type]===void 0)throw new Error("unknown packet type "+i.type);if(i.type===Fe.BINARY_EVENT||i.type===Fe.BINARY_ACK){let s=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let a=e.substring(s,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");i.attachments=Number(a)}if(e.charAt(t+1)==="/"){let s=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););i.nsp=e.substring(s,t)}else i.nsp="/";let n=e.charAt(t+1);if(n!==""&&Number(n)==n){let s=t+1;for(;++t;){let a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}i.id=Number(e.substring(s,t+1))}if(e.charAt(++t)){let s=this.tryParse(e.substr(t));if(r.isPayloadValid(i.type,s))i.data=s;else throw new Error("invalid payload")}return oc("decoded %s as %j",e,i),i}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Fe.CONNECT:return oo(t);case Fe.DISCONNECT:return t===void 0;case Fe.CONNECT_ERROR:return typeof t=="string"||oo(t);case Fe.EVENT:case Fe.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&bh.indexOf(t[0])===-1);case Fe.ACK:case Fe.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};zt.Decoder=cc;var fc=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=(0,yh.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function u0(r){return typeof r=="string"}var l0=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function h0(r){return r===void 0||l0(r)}function oo(r){return Object.prototype.toString.call(r)==="[object Object]"}function d0(r,e){switch(r){case Fe.CONNECT:return e===void 0||oo(e);case Fe.DISCONNECT:return e===void 0;case Fe.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&bh.indexOf(e[0])===-1);case Fe.ACK:return Array.isArray(e);case Fe.CONNECT_ERROR:return typeof e=="string"||oo(e);default:return!1}}function p0(r){return u0(r.nsp)&&h0(r.id)&&d0(r.type,r.data)}});var lc=M(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.on=g0;function g0(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var dc=M(Ji=>{"use strict";var m0=Ji&&Ji.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ji,"__esModule",{value:!0});Ji.Socket=void 0;var $t=ao(),co=lc(),y0=di(),_0=m0(Ft()),et=(0,_0.default)("socket.io-client:socket"),b0=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),hc=class extends y0.Emitter{constructor(e,t,i){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,i&&i.auth&&(this.auth=i.auth),this._opts=Object.assign({},i),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[(0,co.on)(e,"open",this.onopen.bind(this)),(0,co.on)(e,"packet",this.onpacket.bind(this)),(0,co.on)(e,"error",this.onerror.bind(this)),(0,co.on)(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var i,n,s;if(b0.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let a={type:$t.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let p=this.ids++;et("emitting packet with ack id %d",p);let m=t.pop();this._registerAckCallback(p,m),a.id=p}let c=(n=(i=this.io.engine)===null||i===void 0?void 0:i.transport)===null||n===void 0?void 0:n.writable,u=this.connected&&!(!((s=this.io.engine)===null||s===void 0)&&s._hasPingExpired());return this.flags.volatile&&!c?et("discard packet as the transport is not currently writable"):u?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a),this.flags={},this}_registerAckCallback(e,t){var i;let n=(i=this.flags.timeout)!==null&&i!==void 0?i:this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let s=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&(et("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));et("event with ack id %d has timed out after %d ms",e,n),t.call(this,new Error("operation has timed out"))},n),a=(...c)=>{this.io.clearTimeoutFn(s),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((i,n)=>{let s=(a,c)=>a?n(a):i(c);s.withError=!0,t.push(s),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let i={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((n,...s)=>i!==this._queue[0]?et("packet [%d] already acknowledged",i.id):(n!==null?i.tryCount>this._opts.retries&&(et("packet [%d] is discarded after %d tries",i.id,i.tryCount),this._queue.shift(),t&&t(n)):(et("packet [%d] was successfully sent",i.id),this._queue.shift(),t&&t(null,...s)),i.pending=!1,this._drainQueue())),this._queue.push(i),this._drainQueue()}_drainQueue(e=!1){if(et("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){et("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,et("sending packet [%d] (try n\xB0%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){et("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:$t.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){et("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(i=>String(i.id)===e)){let i=this.acks[e];delete this.acks[e],i.withError&&i.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case $t.PacketType.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case $t.PacketType.EVENT:case $t.PacketType.BINARY_EVENT:this.onevent(e);break;case $t.PacketType.ACK:case $t.PacketType.BINARY_ACK:this.onack(e);break;case $t.PacketType.DISCONNECT:this.ondisconnect();break;case $t.PacketType.CONNECT_ERROR:this.destroy();let i=new Error(e.data.message);i.data=e.data.data,this.emitReserved("connect_error",i);break}}onevent(e){let t=e.data||[];et("emitting event %j",t),e.id!=null&&(et("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let i of t)i.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,i=!1;return function(...n){i||(i=!0,et("sending ack %j",n),t.packet({type:$t.PacketType.ACK,id:e,data:n}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){et("bad ack %s",e.id);return}delete this.acks[e.id],et("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){et("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){et("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(et("performing disconnect (%s)",this.nsp),this.packet({type:$t.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let i of t)i.apply(this,e.data)}}};Ji.Socket=hc});var vh=M(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.Backoff=Zi;function Zi(r){r=r||{},this.ms=r.min||100,this.max=r.max||1e4,this.factor=r.factor||2,this.jitter=r.jitter>0&&r.jitter<=1?r.jitter:0,this.attempts=0}Zi.prototype.duration=function(){var r=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*r);r=(Math.floor(e*10)&1)==0?r-t:r+t}return Math.min(r,this.max)|0};Zi.prototype.reset=function(){this.attempts=0};Zi.prototype.setMin=function(r){this.ms=r};Zi.prototype.setMax=function(r){this.max=r};Zi.prototype.setJitter=function(r){this.jitter=r}});var Eh=M(jt=>{"use strict";var v0=jt&&jt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),E0=jt&&jt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),w0=jt&&jt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&v0(e,r,t);return E0(e,r),e},x0=jt&&jt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(jt,"__esModule",{value:!0});jt.Manager=void 0;var gc=ro(),S0=dc(),T0=w0(ao()),xi=lc(),C0=vh(),k0=di(),O0=x0(Ft()),ft=(0,O0.default)("socket.io-client:manager"),mc=class extends k0.Emitter{constructor(e,t){var i;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,(0,gc.installTimerFunctions)(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((i=t.randomizationFactor)!==null&&i!==void 0?i:.5),this.backoff=new C0.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let n=t.parser||T0;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(ft("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;ft("opening %s",this.uri),this.engine=new gc.Socket(this.uri,this.opts);let t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;let n=(0,xi.on)(t,"open",function(){i.onopen(),e&&e()}),s=c=>{ft("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,xi.on)(t,"error",s);if(this._timeout!==!1){let c=this._timeout;ft("connect attempt will timeout after %d",c);let u=this.setTimeoutFn(()=>{ft("connect attempt timed out after %d",c),n(),s(new Error("timeout")),t.close()},c);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(n),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){ft("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,xi.on)(e,"ping",this.onping.bind(this)),(0,xi.on)(e,"data",this.ondata.bind(this)),(0,xi.on)(e,"error",this.onerror.bind(this)),(0,xi.on)(e,"close",this.onclose.bind(this)),(0,xi.on)(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){(0,gc.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){ft("error",e),this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new S0.Socket(this,e,t),this.nsps[e]=i),i}_destroy(e){let t=Object.keys(this.nsps);for(let i of t)if(this.nsps[i].active){ft("socket %s is still active, skipping close",i);return}this._close()}_packet(e){ft("writing packet %j",e);let t=this.encoder.encode(e);for(let i=0;i<t.length;i++)this.engine.write(t[i],e.options)}cleanup(){ft("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){ft("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var i;ft("closed due to %s",e),this.cleanup(),(i=this.engine)===null||i===void 0||i.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)ft("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();ft("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let i=this.setTimeoutFn(()=>{e.skipReconnect||(ft("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(n=>{n?(ft("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",n)):(ft("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};jt.Manager=mc});var Th=M((Be,Sh)=>{"use strict";var P0=Be&&Be.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Be,"__esModule",{value:!0});Be.WebTransport=Be.WebSocket=Be.NodeWebSocket=Be.XHR=Be.NodeXHR=Be.Fetch=Be.Socket=Be.Manager=Be.protocol=void 0;Be.io=Si;Be.connect=Si;Be.default=Si;var R0=dh(),fo=Eh();Object.defineProperty(Be,"Manager",{enumerable:!0,get:function(){return fo.Manager}});var xh=dc();Object.defineProperty(Be,"Socket",{enumerable:!0,get:function(){return xh.Socket}});var A0=P0(Ft()),wh=(0,A0.default)("socket.io-client"),Dn={};function Si(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,R0.url)(r,e.path||"/socket.io"),i=t.source,n=t.id,s=t.path,a=Dn[n]&&s in Dn[n].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||a,u;return c?(wh("ignoring socket cache for %s",i),u=new fo.Manager(i,e)):(Dn[n]||(wh("new io instance for %s",i),Dn[n]=new fo.Manager(i,e)),u=Dn[n]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(Si,{Manager:fo.Manager,Socket:xh.Socket,io:Si,connect:Si});var I0=ao();Object.defineProperty(Be,"protocol",{enumerable:!0,get:function(){return I0.protocol}});var Qi=ro();Object.defineProperty(Be,"Fetch",{enumerable:!0,get:function(){return Qi.Fetch}});Object.defineProperty(Be,"NodeXHR",{enumerable:!0,get:function(){return Qi.NodeXHR}});Object.defineProperty(Be,"XHR",{enumerable:!0,get:function(){return Qi.XHR}});Object.defineProperty(Be,"NodeWebSocket",{enumerable:!0,get:function(){return Qi.NodeWebSocket}});Object.defineProperty(Be,"WebSocket",{enumerable:!0,get:function(){return Qi.WebSocket}});Object.defineProperty(Be,"WebTransport",{enumerable:!0,get:function(){return Qi.WebTransport}});Sh.exports=Si});var _c=M(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.InputStreamReceiver=void 0;var L0=64,N0=30,M0=4,F0=256,D0=16,yc=class{streamId;lastAppliedSeq=0;cb;windowSize;ackThrottleMs;ackTimer=null;framesSinceAck=0;lastResendFrom=0;resendSuppressed=0;constructor(e,t,i={}){this.streamId=e,this.cb=t,this.windowSize=Math.max(1,i.windowSize??L0),this.ackThrottleMs=Math.max(0,i.ackThrottleMs??N0)}get appliedSeq(){return this.lastAppliedSeq}receive(e,t,i){if(e<=this.lastAppliedSeq){this.flushAck();return}if(e===this.lastAppliedSeq+1){try{this.cb.onApply(t,i)}catch{}this.lastAppliedSeq=e,this.scheduleAck();return}this.flushAck();let n=Math.max(this.windowSize*M0,F0);e-this.lastAppliedSeq>n||this.maybeResend(this.lastAppliedSeq+1)}maybeResend(e){if(e===this.lastResendFrom){if(++this.resendSuppressed<D0)return;this.resendSuppressed=0}else this.lastResendFrom=e,this.resendSuppressed=0;this.cb.onResend(e)}resumeState(){return{streamId:this.streamId,lastAckSeq:this.lastAppliedSeq}}dispose(){this.ackTimer&&(clearTimeout(this.ackTimer),this.ackTimer=null)}scheduleAck(){this.framesSinceAck++;let e=Math.max(1,Math.floor(this.windowSize/4));if(this.windowSize===1||this.framesSinceAck>=e){this.flushAck();return}this.ackTimer||(this.ackTimer=setTimeout(()=>this.flushAck(),this.ackThrottleMs))}flushAck(){this.ackTimer&&(clearTimeout(this.ackTimer),this.ackTimer=null),this.framesSinceAck=0,this.cb.onAck(this.lastAppliedSeq)}};uo.InputStreamReceiver=yc});var Ph=M(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.WebSocketService=void 0;var B0=Th(),Ch=Sr(),kh=fs(),Oh=os(),j0=_c(),bc=class{authService;cryptoService;config;logger;notification;deviceId;platform;extraCapabilities;socket=null;inputHandler=null;createTerminalHandler=null;getBufferHandler=null;redrawHandler=null;resizeHandler=null;reconnectHandlers=[];authFailureHandler=null;fileViewRequestHandler=null;fileListRequestHandler=null;fileDownloadRequestHandler=null;statusChangeHandler=null;agentNameSyncHandler=null;clientAttachedHandler=null;metaSessionEstablishedHandler=null;clientDetachedHandler=null;inputReceivers=new Map;terminalActiveCheck=null;MAX_INPUT_RECEIVERS=512;agentId=null;hasConnectedOnce=!1;isRemoteRename=!1;negotiatedCapabilities=[];HEARTBEAT_INTERVAL=3e4;HEARTBEAT_TIMEOUT=1e4;heartbeatTimer=null;pongTimer=null;lastPongTime=0;RESUME_WATCHDOG_INTERVAL=5e3;RESUME_WATCHDOG_THRESHOLD=15e3;resumeWatchdogTimer=null;resumeWatchdogExpectedAt=0;isManualDisconnect=!1;reconnectAttempts=0;reconnectTimer=null;networkCheckTimer=null;isOnline=!0;lastNetworkCheck=0;rekeyingTerminals=new Set;outputBuffer=new Map;OUTPUT_BUFFER_MAX_SIZE=1e3;invalidSessionSignalAt=new Map;INVALID_SESSION_SIGNAL_THROTTLE_MS=5e3;attachedClientCount=0;RECONNECT_BASE_DELAY=1e3;RECONNECT_MAX_DELAY=3e4;RECONNECT_JITTER=.2;NETWORK_CHECK_INTERVAL=5e3;constructor(e,t,i,n,s,a,c="vscode",u=[]){this.authService=e,this.cryptoService=t,this.config=i,this.logger=n,this.notification=s,this.deviceId=a,this.platform=c,this.extraCapabilities=u}async connect(){let e=await this.authService.getAccessToken();if(!e)throw new Error("No access token available");this.isManualDisconnect=!1,this.stopReconnect(),this.reconnectAttempts=0,this.agentId=await this.authService.getAgentId();let t=(0,kh.getWsUrl)(this.config);this.logger.info("Connecting to WebSocket",t),this.statusChangeHandler?.("connecting");let i=await this.cryptoService.getPublicKey();return new Promise((n,s)=>{let a=Array.from(new Set([...Ch.DEFAULT_CLIENT_CAPABILITIES,...this.extraCapabilities]));this.socket=(0,B0.io)(`${t}/agent`,{auth:{token:e,protocolVersion:Ch.PROTOCOL_VERSION,deviceId:this.deviceId,platform:this.platform,capabilities:a,publicKey:i},transports:["websocket"],reconnection:!1}),this.socket.on("connect",()=>{if(this.logger.info("WebSocket connected"),this.reconnectAttempts=0,this.statusChangeHandler?.("connected",this.agentId??void 0),this.startHeartbeat(),this.cryptoService.cleanupAllStaleSessions(),this.hasConnectedOnce){this.logger.info("Reconnected - triggering workspace re-registration");for(let c of this.reconnectHandlers)c()}else this.hasConnectedOnce=!0,n()}),this.socket.on("error",c=>{this.logger.error(`Server error [${c.code}]: ${c.message}`),c.code==="E401"&&(this.logger.warn("Auth failure (E401)"),this.authFailureHandler?.())}),this.socket.on("disconnect",c=>{this.logger.warn("WebSocket disconnected",c),this.stopHeartbeat(),this.statusChangeHandler?.("disconnected"),this.isManualDisconnect||(c==="transport close"?(this.logger.info("Transport close - attempting immediate reconnect"),this.attemptReconnect(!0)):this.scheduleReconnect())}),this.socket.on("protocol:info",c=>{this.logger.info("Protocol info received",c.protocolVersion),this.negotiatedCapabilities=c.negotiatedCapabilities,c.agentName&&this.config.getAgentName()!==c.agentName&&(this.isRemoteRename=!0,this.config.setAgentName(c.agentName).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(c.agentName),this.logger.info("Agent name synced from server",c.agentName))}),this.socket.on("pong",()=>{this.lastPongTime=Date.now(),this.clearPongTimeout(),this.logger.debug("Heartbeat pong received")}),this.socket.on("connect_error",c=>{this.logger.error("WebSocket connection error",c),this.statusChangeHandler?.("error"),this.hasConnectedOnce||s(c),this.scheduleReconnect()}),this.socket.on("terminal:input",c=>{this.handleTerminalInput(c)}),this.socket.on("crypto:keyExchange",async(c,u)=>{this.logger.info("Received key exchange request",c.terminalId,c.sessionId),this.rekeyingTerminals.add(c.terminalId),this.outputBuffer.set(c.terminalId,[]);try{if(await this.cryptoService.handleKeyExchange(c.terminalId,c.clientPublicKey,c.sessionId)){let p=await this.cryptoService.getPublicKey();u?.({success:!0,agentPublicKey:p||void 0}),this.flushOutputBuffer(c.terminalId)}else u?.({success:!1,error:"Key exchange failed"})}catch(d){this.logger.error("Key exchange error",d),u?.({success:!1,error:String(d)})}finally{this.rekeyingTerminals.delete(c.terminalId),this.outputBuffer.delete(c.terminalId)}}),this.socket.on("crypto:sessionCleanup",c=>{this.cryptoService.removeSession(c.terminalId,c.sessionId)}),this.socket.on("agent:keyExchangeRequest",async c=>{try{let u=await this.cryptoService.handleAgentKeyExchange(c.clientPublicKey,c.sessionId),d={agentId:c.agentId,sessionId:c.sessionId,ok:u,error:u?void 0:"Key exchange failed"};this.socket?.emit("agent:keyExchangeAck",d)}catch(u){this.logger.error("Agent key exchange error",u);let d={agentId:c.agentId,sessionId:c.sessionId,ok:!1,error:String(u)};this.socket?.emit("agent:keyExchangeAck",d)}}),this.socket.on("meta:keyExchange",async(c,u)=>{let{ok:d,isNew:p}=await this.cryptoService.handleMetaKeyExchange(c.clientIdentityPub),m=await this.cryptoService.getPublicKey()||void 0;u?.({ok:d,agentPublicKey:m}),d&&p&&this.metaSessionEstablishedHandler?.()}),this.socket.on("agent:sessionEnd",c=>{this.cryptoService.removeAgentSession(c.sessionId)}),this.socket.on("agent:renamed",c=>{this.logger.info("Agent renamed from web client",c.name),this.isRemoteRename=!0,this.config.setAgentName(c.name).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(c.name)}),this.socket.on("terminal:createRequest",c=>{this.createTerminalHandler?.(c.name)}),this.socket.on("terminal:getBuffer",(c,u)=>{if(!this.getBufferHandler){u?.({success:!1,error:"Buffer handler not set"});return}let d=this.getBufferHandler(c.terminalId);if(d===null){u?.({success:!1,error:"Terminal not found"});return}let p=this.cryptoService.encryptOutput(c.terminalId,d);if(!p){this.signalInvalidSession(void 0,c.terminalId),u?.({success:!1,error:"No E2E session"});return}u?.({success:!0,encrypted:p}),this.redrawHandler?.(c.terminalId)}),this.socket.on("terminal:resize",c=>{this.resizeHandler?.(c.terminalId,c.cols,c.rows)}),this.socket.on("workspace:clientAttached",c=>{this.attachedClientCount=c.clientCount,this.clientAttachedHandler?.(c)}),this.socket.on("workspace:clientDetached",c=>{this.attachedClientCount=c.clientCount,this.clientDetachedHandler?.(c)}),this.socket.on("file:view",c=>{this.fileViewRequestHandler?.(c.terminalId,c.request)}),this.socket.on("file:list",c=>{this.fileListRequestHandler?.(c.terminalId,c.request)}),this.socket.on("file:download:request",c=>{this.fileDownloadRequestHandler?.(c.terminalId,c.path,c.requestId)})})}disconnect(){this.isManualDisconnect=!0,this.hasConnectedOnce=!1,this.stopReconnect(),this.stopHeartbeat(),this.cryptoService.clearAllSessions(),this.socket&&(this.logger.info("Disconnecting WebSocket"),this.socket.disconnect(),this.socket=null)}softDisconnect(){this.stopReconnect(),this.stopHeartbeat(),this.socket&&(this.logger.info("Soft disconnecting WebSocket (for reconnect)"),this.socket.disconnect(),this.socket=null)}getStatus(){return{connected:this.socket?.connected??!1,agentId:this.agentId}}onInput(e){this.inputHandler=e}onCreateTerminalRequest(e){this.createTerminalHandler=e}onGetBufferRequest(e){this.getBufferHandler=e}onRedrawRequest(e){this.redrawHandler=e}onResizeRequest(e){this.resizeHandler=e}onReconnect(e){this.reconnectHandlers.push(e)}onAuthFailure(e){this.authFailureHandler=e}onFileViewRequest(e){this.fileViewRequestHandler=e}onFileListRequest(e){this.fileListRequestHandler=e}onFileDownloadRequest(e){this.fileDownloadRequestHandler=e}onStatusChange(e){this.statusChangeHandler=e}onAgentNameSync(e){this.agentNameSyncHandler=e}onClientAttached(e){this.clientAttachedHandler=e}onMetaSessionEstablished(e){this.metaSessionEstablishedHandler=e}onClientDetached(e){this.clientDetachedHandler=e}async registerWorkspace(e){return this.emit("workspace:register",e)}async unregisterWorkspace(e){await this.emit("workspace:unregister",{instanceId:e})}async terminalCreated(e){return this.emit("terminal:created",e)}async terminalClosed(e){this.cryptoService.removeSession(e.terminalId),await this.emit("terminal:closed",e)}terminalNotFound(e){this.socket?.emit("terminal:notFound",{terminalId:e})}sendPtyResized(e,t,i,n){this.socket?.connected&&this.socket.emit("agent:ptyResized",{instanceId:e,terminalId:t,cols:i,rows:n})}sendClaimControl(e,t,i,n){this.socket?.connected&&this.socket.emit("agent:claimControl",{instanceId:e,terminalId:t,cols:i,rows:n})}sendOutput(e,t,i){if(!this.socket?.connected)return;if(this.rekeyingTerminals.has(t)){let a=this.outputBuffer.get(t);a&&a.length<this.OUTPUT_BUFFER_MAX_SIZE&&a.push({instanceId:e,data:i});return}let n=this.cryptoService.encryptOutput(t,i);if(!n){this.attachedClientCount>0&&this.signalInvalidSession(e,t);return}let s={instanceId:e,terminalId:t,encrypted:n};this.socket?.emit("terminal:output",s)}flushOutputBuffer(e){let t=this.outputBuffer.get(e);if(!(!t||t.length===0)){this.logger.info("Flushing output buffer after rekey",e,String(t.length));for(let{instanceId:i,data:n}of t){let s=this.cryptoService.encryptOutput(e,n);if(!s){this.signalInvalidSession(i,e);continue}let a={instanceId:i,terminalId:e,encrypted:s};this.socket?.emit("terminal:output",a)}}}signalInvalidSession(e,t){let i=Date.now(),n=this.invalidSessionSignalAt.get(t)??0;i-n<this.INVALID_SESSION_SIGNAL_THROTTLE_MS||(this.invalidSessionSignalAt.set(t,i),this.logger.warn("E2E session invalid/missing \u2014 signaling clients to rekey",t),this.socket?.emit("crypto:invalidSession",{instanceId:e??this.instanceIdForTerminal(t),terminalId:t}))}instanceIdForTerminal(e){return this.inputReceivers.get(e)?.instanceId}async updateStatus(e){await this.emit("terminal:status",e)}sendTerminalEvent(e,t,i){let n={instanceId:e,terminalId:t,event:i};this.socket?.emit("terminal:event",n)}hasCapability(e){return this.negotiatedCapabilities.includes(e)}sendFileChangedEvent(e,t,i){let n={instanceId:e,terminalId:t,event:i};this.socket?.emit("file:changed",n)}sendFileListResponse(e,t){let i={instanceId:e,response:t};this.socket?.emit("file:list:response",i)}sendAgentRename(e){this.socket?.emit("agent:rename",{name:e})}isRemoteRenameInProgress(){return this.isRemoteRename}getSocket(){return this.socket}emit(e,t){let i=(0,Oh.generateCorrelationId)(),n=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:i}:t;return(0,Oh.runWithCorrelation)(i,()=>new Promise((s,a)=>{if(!this.socket?.connected){a(new Error("WebSocket not connected"));return}this.socket.emit(e,n,c=>{c.success?s(c):a(new Error(c.error||"Unknown error"))})}))}startHeartbeat(){this.stopHeartbeat(),this.lastPongTime=Date.now(),this.startResumeWatchdog(),this.heartbeatTimer=setInterval(()=>{if(!this.socket?.connected){this.stopHeartbeat();return}if(Date.now()-this.lastPongTime>this.HEARTBEAT_INTERVAL+this.HEARTBEAT_TIMEOUT){this.logger.warn("Heartbeat timeout"),this.socket.disconnect();return}this.socket.emit("ping"),this.pongTimer=setTimeout(()=>{this.logger.warn("Pong timeout - server not responding, forcing teardown + reconnect"),this.statusChangeHandler?.("error"),this.socket?.disconnect()},this.HEARTBEAT_TIMEOUT)},this.HEARTBEAT_INTERVAL)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.clearPongTimeout(),this.stopResumeWatchdog()}startResumeWatchdog(){this.stopResumeWatchdog(),this.resumeWatchdogExpectedAt=Date.now()+this.RESUME_WATCHDOG_INTERVAL,this.resumeWatchdogTimer=setTimeout(()=>this.onResumeWatchdogTick(),this.RESUME_WATCHDOG_INTERVAL)}onResumeWatchdogTick(){let e=Date.now(),t=e-this.resumeWatchdogExpectedAt;if(t>this.RESUME_WATCHDOG_THRESHOLD&&(this.logger.warn(`Resume detected (clock drift ${t}ms) - forcing liveness re-check`),!this.isManualDisconnect&&this.socket)){this.statusChangeHandler?.("error"),this.socket.disconnect();return}this.isManualDisconnect||(this.resumeWatchdogExpectedAt=e+this.RESUME_WATCHDOG_INTERVAL,this.resumeWatchdogTimer=setTimeout(()=>this.onResumeWatchdogTick(),this.RESUME_WATCHDOG_INTERVAL))}stopResumeWatchdog(){this.resumeWatchdogTimer&&(clearTimeout(this.resumeWatchdogTimer),this.resumeWatchdogTimer=null)}clearPongTimeout(){this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}handleTerminalInput(e){let t;if(e.encrypted){let i=this.cryptoService.decryptInput(e.terminalId,e.encrypted);if(!i){this.logger.error("Failed to decrypt terminal input",e.terminalId),this.signalInvalidSession(e.instanceId,e.terminalId);return}t=i}else if(e.data)t=Buffer.from(e.data,"base64").toString("utf8");else{this.logger.error("Invalid terminal input payload");return}if(e.streamId&&typeof e.seq=="number"){let i=this.getOrCreateInputReceiver(e.terminalId,e.streamId,e.instanceId,e.dbTerminalId);if(!i)return;i.receive(e.seq,t,e.paste);return}this.inputHandler?.(e.terminalId,t,e.dbTerminalId)}getOrCreateInputReceiver(e,t,i,n){let s=this.inputReceivers.get(e);if(this.terminalActiveCheck&&!this.terminalActiveCheck(e))return s&&this.disposeInputStream(e),null;if(s&&s.receiver.streamId===t)return n&&(s.routeId=n),i&&(s.instanceId=i),s.receiver;if(s&&s.receiver.dispose(),!s&&this.inputReceivers.size>=this.MAX_INPUT_RECEIVERS)return this.logger.error("inputReceivers map at cap, dropping frame",e),null;let a=new j0.InputStreamReceiver(t,{onApply:(c,u)=>this.inputHandler?.(e,c,this.routeIdFor(e),u),onAck:c=>this.sendInputAck(e,t,c),onResend:c=>this.sendInputResend(e,t,c)});return this.inputReceivers.set(e,{receiver:a,routeId:n??e,instanceId:i??""}),a}setTerminalActiveCheck(e){this.terminalActiveCheck=e}routeIdFor(e){return this.inputReceivers.get(e)?.routeId??e}sendInputAck(e,t,i){let n=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:ack",{instanceId:n,terminalId:e,streamId:t,ackSeq:i})}sendInputResend(e,t,i){let n=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:resend",{instanceId:n,terminalId:e,streamId:t,fromSeq:i})}sendInputResume(e){let t=this.inputReceivers.get(e);if(!t)return;let{streamId:i,lastAckSeq:n}=t.receiver.resumeState();this.socket?.emit("input:resume",{instanceId:t.instanceId,terminalId:e,streamId:i,lastAckSeq:n})}disposeInputStream(e){this.inputReceivers.get(e)?.receiver.dispose(),this.inputReceivers.delete(e)}hasE2ESession(e){return this.cryptoService.hasSession(e)}getReconnectDelay(){let e=Math.min(this.RECONNECT_BASE_DELAY*Math.pow(2,this.reconnectAttempts),this.RECONNECT_MAX_DELAY),t=1+(Math.random()*2-1)*this.RECONNECT_JITTER;return Math.floor(e*t)}scheduleReconnect(){if(this.isManualDisconnect)return;this.stopReconnect();let e=this.getReconnectDelay();if(this.logger.info("Scheduling reconnect",String(this.reconnectAttempts+1),"delay:",String(e)),!this.isOnline){this.statusChangeHandler?.("disconnected"),this.startNetworkCheck();return}this.statusChangeHandler?.("connecting"),this.reconnectTimer=setTimeout(()=>{this.attemptReconnect()},e)}async attemptReconnect(e=!1){if(this.isManualDisconnect||this.socket?.connected)return;let t=await this.authService.hasValidToken();if(!t){if(this.logger.info("Access token expired, attempting refresh"),!await this.authService.refreshAccessToken()){this.logger.info("Token refresh failed, stopping reconnect"),this.stopReconnect(),this.statusChangeHandler?.("disconnected"),this.notification.warn("Session expired. Please log in again."),this.authFailureHandler?.();return}t=!0}this.reconnectAttempts++;try{if(this.socket&&(this.socket.disconnect(),this.socket=null),!e&&!await this.checkNetwork()){this.isOnline=!1,this.scheduleReconnect();return}this.isOnline=!0,await this.connect(),this.reconnectAttempts=0}catch(i){this.logger.warn("Reconnect failed",i),this.statusChangeHandler?.("error"),this.scheduleReconnect()}}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopNetworkCheck()}async checkNetwork(){let e=Date.now();if(e-this.lastNetworkCheck<1e3)return this.isOnline;this.lastNetworkCheck=e;try{let t=`${(0,kh.getApiUrl)(this.config)}/health`,i=new AbortController,n=setTimeout(()=>i.abort(),5e3),s=await fetch(t,{method:"GET",signal:i.signal});return clearTimeout(n),this.logger.debug("Network check OK",String(s.status)),!0}catch{return this.logger.debug("Network check failed (offline)"),!1}}startNetworkCheck(){this.stopNetworkCheck(),this.networkCheckTimer=setInterval(async()=>{if(this.isManualDisconnect){this.stopNetworkCheck();return}if(this.socket?.connected){this.stopNetworkCheck();return}let e=await this.checkNetwork();e&&!this.isOnline?(this.logger.info("Network restored! Triggering immediate reconnect"),this.isOnline=!0,this.stopNetworkCheck(),this.reconnectAttempts=0,this.attemptReconnect()):e&&this.isOnline?(this.stopNetworkCheck(),this.attemptReconnect()):e||(this.isOnline=!1)},this.NETWORK_CHECK_INTERVAL)}stopNetworkCheck(){this.networkCheckTimer&&(clearInterval(this.networkCheckTimer),this.networkCheckTimer=null)}};lo.WebSocketService=bc});var Ah=M(lr=>{"use strict";var U0=lr&&lr.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),K0=lr&&lr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Ec=lr&&lr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&U0(t,e,i[n]);return K0(t,e),t}})();Object.defineProperty(lr,"__esModule",{value:!0});lr.FileTransferService=void 0;var ho=Ec(require("fs")),q0=Ec(require("path")),Rh=Ec(require("crypto")),je=Sr(),vc=class{socket=null;activeTransfers=new Map;instanceId="";logger;fallbackDir;cryptoService=null;constructor(e,t="/tmp"){this.logger=e,this.fallbackDir=t}setCrypto(e){this.cryptoService=e}attach(e,t){this.socket=e,this.instanceId=t,this.setupEventHandlers(),this.logger.info("FileTransferService attached")}detach(){this.socket=null;for(let[e]of this.activeTransfers)this.cancelTransfer(e,"Disconnected");this.logger.info("FileTransferService detached")}async sendFile(e,t,i,n,s){let a=ho.readFileSync(t),c=t.split("/").pop()||"file";return this.initAndSendChunks(e,a,c,{mimeType:this.getMimeType(c),requestId:s,onProgress:i,onComplete:n})}async sendBuffer(e,t,i,n,s){return this.initAndSendChunks(e,t,i,{mimeType:n,purpose:s?.purpose,viewMetadata:s?.viewMetadata,requestId:s?.requestId,onProgress:s?.onProgress,onComplete:s?.onComplete})}async initAndSendChunks(e,t,i,n){if(!this.socket)throw new Error("Socket not connected");let s=t.length,a=(0,je.calculateTotalChunks)(s),c=this.calculateChecksum(t),u=Rh.randomUUID(),d={id:u,terminalId:e,filename:i,size:s,totalChunks:a,direction:je.TransferDirection.DOWNLOAD,status:je.TransferStatus.PENDING,deliveredChunks:new Set,pendingChunks:new Map,checksum:c,checksumAlgorithm:"sha256",onProgress:n.onProgress?(m,_)=>n.onProgress(u,m,_):void 0,onComplete:n.onComplete?(m,_)=>n.onComplete(u,m,_):void 0,ackTimeouts:new Map};d.chunks=[];for(let m=0;m<a;m++){let _=m*je.CHUNK_SIZE,E=Math.min(_+je.CHUNK_SIZE,s);d.chunks.push(t.subarray(_,E))}this.activeTransfers.set(u,d);let p={transferId:u,terminalId:e,filename:i,size:s,totalChunks:a,mimeType:n.mimeType||"application/octet-stream",checksum:c,direction:je.TransferDirection.DOWNLOAD,instanceId:this.instanceId};return n.requestId&&(p.requestId=n.requestId),n.purpose&&(p.purpose=n.purpose),n.viewMetadata&&(p.viewMetadata=n.viewMetadata),new Promise((m,_)=>{this.socket.emit("file:init",p,E=>{E.accepted?(d.status=je.TransferStatus.ACTIVE,this.startSendingChunks(u),m(u)):(this.activeTransfers.delete(u),_(new Error(E.error||"Transfer rejected")))})})}async receiveFile(e,t,i,n,s,a,c,u="sha256",d,p){let m={id:e,terminalId:t,filename:i,filePath:c,size:n,totalChunks:s,direction:je.TransferDirection.UPLOAD,status:je.TransferStatus.ACTIVE,deliveredChunks:new Set,pendingChunks:new Map,chunks:new Array(s).fill(null),checksum:a,checksumAlgorithm:u,onProgress:d?(_,E)=>d(e,_,E):void 0,onComplete:p?(_,E)=>p(e,_,E):void 0,ackTimeouts:new Map};this.activeTransfers.set(e,m)}cancelTransfer(e,t){let i=this.activeTransfers.get(e);if(i){for(let n of i.ackTimeouts.values())clearTimeout(n);if(i.status=je.TransferStatus.CANCELLED,i.onComplete?.(!1,t),this.socket){let n={transferId:e,reason:t};this.socket.emit("file:cancel",n)}this.activeTransfers.delete(e)}}async resumeTransfer(e){let t=this.activeTransfers.get(e);!t||!this.socket||this.socket.emit("file:sync",{transferId:e},i=>{if(i.status===je.TransferStatus.EXPIRED){t.onComplete?.(!1,"Transfer expired"),this.activeTransfers.delete(e);return}if(i.deliveredChunks)for(let n of i.deliveredChunks)t.deliveredChunks.add(n);if(t.direction===je.TransferDirection.DOWNLOAD&&i.missingChunks){t.status=je.TransferStatus.ACTIVE;for(let n of i.missingChunks)this.sendChunk(t,n)}})}getTransferStatus(e){return this.activeTransfers.get(e)?.status??null}getTransferProgress(e){let t=this.activeTransfers.get(e);return t?{delivered:t.deliveredChunks.size,total:t.totalChunks}:null}setupEventHandlers(){this.socket&&(this.socket.on("file:chunk",e=>{this.handleIncomingChunk(e)}),this.socket.on("file:chunk:ack",e=>{this.handleChunkAck(e)}),this.socket.on("file:complete",e=>{this.handleComplete(e)}),this.socket.on("file:progress",e=>{this.handleProgress(e)}),this.socket.on("file:init",(e,t)=>{this.handleIncomingFileInit(e,t)}),this.socket.on("file:cancel",e=>{let t=this.activeTransfers.get(e.transferId);if(t){for(let i of t.ackTimeouts.values())clearTimeout(i);t.status=je.TransferStatus.CANCELLED,t.onComplete?.(!1,e.reason||"Cancelled by remote"),this.activeTransfers.delete(e.transferId)}}))}startSendingChunks(e){let t=this.activeTransfers.get(e);if(!(!t||!t.chunks))for(let i=0;i<Math.min(je.WINDOW_SIZE,t.totalChunks);i++)t.deliveredChunks.has(i)||this.sendChunk(t,i)}sendChunk(e,t){if(!this.socket||!e.chunks)return;let i=e.chunks[t];if(!i)return;let n=e.pendingChunks.get(t),s={seq:t,data:i,retries:n?n.retries:0,sentAt:Date.now()};e.pendingChunks.set(t,s);let a=this.cryptoService?.encryptFileChunk(e.terminalId,new Uint8Array(i.buffer,i.byteOffset,i.byteLength));if(!a){this.cancelTransfer(e.id,"No E2E session for file transfer");return}let c={transferId:e.id,seq:t,encrypted:a};this.socket.emit("file:chunk",c,d=>{d&&!d.success&&this.cancelTransfer(e.id,d.error||"Server rejected chunk")});let u=setTimeout(()=>{this.handleAckTimeout(e.id,t)},je.ACK_TIMEOUT_MS);e.ackTimeouts.set(t,u)}handleChunkAck(e){let t=this.activeTransfers.get(e.transferId);if(!t||t.status===je.TransferStatus.COMPLETED)return;let i=t.ackTimeouts.get(e.seq);i&&(clearTimeout(i),t.ackTimeouts.delete(e.seq)),t.deliveredChunks.add(e.seq),t.pendingChunks.delete(e.seq),t.onProgress?.(t.deliveredChunks.size,t.totalChunks);let n=e.seq+je.WINDOW_SIZE;n<t.totalChunks&&!t.deliveredChunks.has(n)&&this.sendChunk(t,n),t.deliveredChunks.size===t.totalChunks&&this.finishSending(t)}handleAckTimeout(e,t){let i=this.activeTransfers.get(e);if(!i)return;let n=i.pendingChunks.get(t);n&&(n.retries<je.MAX_RETRIES?(n.retries++,this.sendChunk(i,t)):this.cancelTransfer(e,"Max retries exceeded"))}finishSending(e){if(!this.socket)return;e.status=je.TransferStatus.COMPLETED;let t={transferId:e.id,checksum:e.checksum};this.socket.emit("file:end",t)}handleIncomingChunk(e){let t=this.activeTransfers.get(e.transferId);if(!t||!t.chunks)return;let i=e.encrypted?this.cryptoService?.decryptFileChunk(t.terminalId,e.encrypted):null;if(!i){this.cancelTransfer(e.transferId,"Chunk decryption failed (no E2E session?)");return}if(t.chunks[e.seq]=Buffer.from(i),t.deliveredChunks.add(e.seq),this.socket){let n={transferId:e.transferId,seq:e.seq};this.socket.emit("file:chunk:ack",n)}t.onProgress?.(t.deliveredChunks.size,t.totalChunks),t.deliveredChunks.size===t.totalChunks&&this.finishReceiving(t)}finishReceiving(e){if(!e.chunks||!e.filePath)return;let t=Buffer.concat(e.chunks);if(this.calculateChecksum(t,e.checksumAlgorithm)!==e.checksum){e.status=je.TransferStatus.FAILED,e.onComplete?.(!1,"Checksum mismatch"),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:"Checksum mismatch"});return}try{let n=q0.dirname(e.filePath);ho.existsSync(n)||ho.mkdirSync(n,{recursive:!0}),ho.writeFileSync(e.filePath,t),e.status=je.TransferStatus.COMPLETED,e.onComplete?.(!0),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!0})}catch(n){let s=n instanceof Error?n.message:String(n);e.status=je.TransferStatus.FAILED,e.onComplete?.(!1,`Failed to save file: ${s}`),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:`Failed to save file: ${s}`})}this.activeTransfers.delete(e.id)}handleComplete(e){let t=this.activeTransfers.get(e.transferId);if(t){e.success?(t.status=je.TransferStatus.COMPLETED,t.onComplete?.(!0)):(t.status=je.TransferStatus.FAILED,t.onComplete?.(!1,e.error));for(let i of t.ackTimeouts.values())clearTimeout(i);this.activeTransfers.delete(e.transferId)}}handleProgress(e){let t=this.activeTransfers.get(e.transferId);t&&t.onProgress?.(e.deliveredChunks,e.totalChunks)}handleIncomingFileInit(e,t){let n=`${e.targetPath||this.fallbackDir}/${e.filename}`;this.receiveFile(e.transferId,e.terminalId,e.filename,e.size,e.totalChunks,e.checksum,n,e.checksumAlgorithm||"sha256").then(()=>t({accepted:!0})).catch(s=>t({accepted:!1,error:s.message}))}calculateChecksum(e,t="sha256"){return t==="fnv1a"?this.fnv1aHash(e):Rh.createHash("sha256").update(e).digest("hex")}fnv1aHash(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e[n],t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0").repeat(8)}getMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{txt:"text/plain",json:"application/json",js:"application/javascript",ts:"application/typescript",html:"text/html",css:"text/css",md:"text/markdown",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[t||""]||"application/octet-stream"}};lr.FileTransferService=vc});var Oc=M((kw,mo)=>{function Nh(r){return Array.isArray(r)?r:[r]}var W0=void 0,xc="",Ih=" ",wc="\\",H0=/^\s+$/,V0=/(?:[^\\]|^)\\$/,z0=/^\\!/,$0=/^\\#/,G0=/\r?\n/g,Y0=/^\.{0,2}\/|^\.{1,2}$/,X0=/\/$/,en="/",Mh="node-ignore";typeof Symbol<"u"&&(Mh=Symbol.for("node-ignore"));var Fh=Mh,tn=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),J0=/([0-z])-([0-z])/g,Dh=()=>!1,Z0=r=>r.replace(J0,(e,t,i)=>t.charCodeAt(0)<=i.charCodeAt(0)?e:xc),Q0=r=>{let{length:e}=r;return r.slice(0,e-e%2)},eb=[[/^\uFEFF/,()=>xc],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?Ih:xc)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+Ih}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let i=t.replace(/\\\*/g,"[^\\/]*");return e+i}],[/\\\\\\(?=[$.|*+(){^])/g,()=>wc],[/\\\\/g,()=>wc],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,i,n)=>e===wc?`\\[${t}${Q0(i)}${n}`:n==="]"&&i.length%2===0?`[${Z0(t)}${i}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],tb=/(^|\\\/)?\\\*$/,Bn="regex",po="checkRegex",Lh="_",rb={[Bn](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[po](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},ib=r=>eb.reduce((e,[t,i])=>e.replace(t,i.bind(r)),r),go=r=>typeof r=="string",nb=r=>r&&go(r)&&!H0.test(r)&&!V0.test(r)&&r.indexOf("#")!==0,sb=r=>r.split(G0).filter(Boolean),Sc=class{constructor(e,t,i,n,s,a){this.pattern=e,this.mark=t,this.negative=s,tn(this,"body",i),tn(this,"ignoreCase",n),tn(this,"regexPrefix",a)}get regex(){let e=Lh+Bn;return this[e]?this[e]:this._make(Bn,e)}get checkRegex(){let e=Lh+po;return this[e]?this[e]:this._make(po,e)}_make(e,t){let i=this.regexPrefix.replace(tb,rb[e]),n=this.ignoreCase?new RegExp(i,"i"):new RegExp(i);return tn(this,t,n)}},ob=({pattern:r,mark:e},t)=>{let i=!1,n=r;n.indexOf("!")===0&&(i=!0,n=n.substr(1)),n=n.replace(z0,"!").replace($0,"#");let s=ib(n);return new Sc(r,e,n,t,i,s)},Tc=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[Fh]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(go(e)&&(e={pattern:e}),nb(e.pattern)){let t=ob(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,Nh(go(e)?sb(e):e).forEach(this._add,this),this._added}test(e,t,i){let n=!1,s=!1,a;this._rules.forEach(u=>{let{negative:d}=u;s===d&&n!==s||d&&!n&&!s&&!t||!u[i].test(e)||(n=!d,s=d,a=d?W0:u)});let c={ignored:n,unignored:s};return a&&(c.rule=a),c}},ab=(r,e)=>{throw new e(r)},Ar=(r,e,t)=>go(r)?r?Ar.isNotRelative(r)?t(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:t("path must not be empty",TypeError):t(`path must be a string, but got \`${e}\``,TypeError),Bh=r=>Y0.test(r);Ar.isNotRelative=Bh;Ar.convert=r=>r;var Cc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:i=!1}={}){tn(this,Fh,!0),this._rules=new Tc(t),this._strictPathCheck=!i,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,t,i,n){let s=e&&Ar.convert(e);return Ar(s,e,this._strictPathCheck?ab:Dh),this._t(s,t,i,n)}checkIgnore(e){if(!X0.test(e))return this.test(e);let t=e.split(en).filter(Boolean);if(t.pop(),t.length){let i=this._t(t.join(en)+en,this._testCache,!0,t);if(i.ignored)return i}return this._rules.test(e,!1,po)}_t(e,t,i,n){if(e in t)return t[e];if(n||(n=e.split(en).filter(Boolean)),n.pop(),!n.length)return t[e]=this._rules.test(e,i,Bn);let s=this._t(n.join(en)+en,t,i,n);return t[e]=s.ignored?s:this._rules.test(e,i,Bn)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return Nh(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},kc=r=>new Cc(r),cb=r=>Ar(r&&Ar.convert(r),r,Dh),jh=()=>{let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");Ar.convert=r;let e=/^[a-z]:\//i;Ar.isNotRelative=t=>e.test(t)||Bh(t)};typeof process<"u"&&process.platform==="win32"&&jh();mo.exports=kc;kc.default=kc;mo.exports.isPathValid=cb;tn(mo.exports,Symbol.for("setupWindows"),jh)});var Kh=M(Ut=>{"use strict";var fb=Ut&&Ut.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),ub=Ut&&Ut.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Uh=Ut&&Ut.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&fb(t,e,i[n]);return ub(t,e),t}})(),lb=Ut&&Ut.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ut,"__esModule",{value:!0});Ut.FileListService=void 0;var rn=Uh(require("path")),Pc=Uh(require("fs/promises")),hb=lb(Oc()),Rc=Sr(),db=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],Ac=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,hb.default)(),this.ignoreFilter.add(db),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=rn.join(this.workspaceRoot,".gitignore");try{let t=await Pc.readFile(e,"utf-8");this.ignoreFilter.add(t)}catch{}}onResponse(e){this.onResponseCallback=e}async handleListRequest(e){if(!this.workspaceRoot){this.sendResponse({requestId:e.requestId,path:e.path,entries:[],error:"No workspace root"});return}try{let t=this.resolvePath(e.path),i=await this.listDirectory(t,e.path);this.sendResponse({requestId:e.requestId,path:e.path,entries:i})}catch(t){this.logger.error("Failed to list directory",String(t)),this.sendResponse({requestId:e.requestId,path:e.path,entries:[],error:t instanceof Error?t.message:"Unknown error"})}}async listDirectory(e,t){let i=await Pc.readdir(e,{withFileTypes:!0}),n=[];for(let s of i){let a=t==="."||t===""?s.name:rn.join(t,s.name);if(this.shouldHide(a,s.isDirectory()))continue;let c=rn.join(e,s.name),u={name:s.name,path:a,type:s.isDirectory()?Rc.FileEntryType.DIRECTORY:Rc.FileEntryType.FILE};if(!s.isDirectory())try{let d=await Pc.stat(c);u.size=d.size,u.modified=d.mtime.toISOString()}catch{}n.push(u)}return n.sort((s,a)=>s.type!==a.type?s.type===Rc.FileEntryType.DIRECTORY?-1:1:s.name.localeCompare(a.name))}shouldHide(e,t){let i=e.split(rn.sep).join("/"),n=t?`${i}/`:i;return this.ignoreFilter.ignores(n)}resolvePath(e){if(!this.workspaceRoot)throw new Error("No workspace root");if(e==="."||e==="")return this.workspaceRoot;let t=rn.resolve(this.workspaceRoot,e);if(t!==this.workspaceRoot&&!t.startsWith(this.workspaceRoot+rn.sep))throw new Error("Path outside workspace");return t}sendResponse(e){this.onResponseCallback?.(e)}dispose(){this.onResponseCallback=null}};Ut.FileListService=Ac});var Wh=M(hr=>{"use strict";var pb=hr&&hr.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),gb=hr&&hr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),qh=hr&&hr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&pb(t,e,i[n]);return gb(t,e),t}})();Object.defineProperty(hr,"__esModule",{value:!0});hr.FileTrackerService=void 0;var Ic=qh(require("path")),Ti=qh(require("fs/promises")),mb=require("child_process"),yb=require("util"),Gt=Sr(),Lc=(0,yb.promisify)(mb.execFile),Nc={toolStart:/⏺\s*(Write|Edit|NotebookEdit)\s*\(\s*(?:file_path|notebook_path)\s*=\s*"([^"]+)"/,toolSuccess:/[✓✔]\s*(?:Wrote|Edited|Updated|Created)\s+([^\s\n]+)/,toolError:/[✗✘]\s*(?:Failed|Error)/i},Mc=class{trackedFiles=new Map;pendingToolCalls=new Map;outputBuffers=new Map;workspaceRoot;onFileChangedCallback=null;onFileViewTransferCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t}onFileChanged(e){this.onFileChangedCallback=e}onFileViewTransfer(e){this.onFileViewTransferCallback=e}async processOutput(e,t){let i=this.outputBuffers.get(e)||"";i+=t,i.length>10240&&(i=i.slice(-10240)),this.outputBuffers.set(e,i);try{await this.parseToolCalls(e,i)}catch(n){this.logger.error("Error parsing tool calls",n)}}async parseToolCalls(e,t){let i=this.stripAnsi(t),n=i.match(Nc.toolStart);if(n){let a=n[1],c=n[2],u=`${a}_${Date.now()}_${c}`;this.pendingToolCalls.has(u)||await this.handleToolStart(e,u,a,{file_path:c})}let s=i.match(Nc.toolSuccess);if(s){let a=s[1];for(let[c,u]of this.pendingToolCalls)if(u.filePath===a||a.endsWith(u.filePath)||u.filePath.endsWith(a)){await this.handleToolEnd(e,c,u.toolName,"success");break}}if(Nc.toolError.test(i))for(let[a,c]of this.pendingToolCalls)await this.handleToolEnd(e,a,c.toolName,"error")}stripAnsi(e){return e.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\x1b\][^\x07]*\x07/g,"").replace(/\x1b[()][AB012]/g,"").replace(/\x1b[=>]/g,"").replace(/\x1b[78DMEHc]/g,"")}async handleToolStart(e,t,i,n){if(!this.isFileModifyingTool(i))return;let s=this.extractFilePath(i,n);if(!s)return;let a=this.resolveFilePath(s),c={toolId:t,toolName:i,filePath:s,timestamp:new Date().toISOString()};this.pendingToolCalls.set(t,c);let u;try{u=await Ti.readFile(a,"utf-8")}catch{u=void 0}let d={path:s,changeType:u===void 0?Gt.FileChangeType.CREATE:Gt.FileChangeType.MODIFY,toolName:i,toolId:t,timestamp:c.timestamp,previousContent:u},p=this.trackedFiles.get(e)||[];p.push(d),this.trackedFiles.set(e,p)}async handleToolEnd(e,t,i,n){if(!this.isFileModifyingTool(i)||!this.pendingToolCalls.get(t))return;if(this.pendingToolCalls.delete(t),n==="error"){let p=this.trackedFiles.get(e)||[],m=p.findIndex(_=>_.toolId===t);m!==-1&&p.splice(m,1);return}let c=(this.trackedFiles.get(e)||[]).find(p=>p.toolId===t);if(!c)return;let u=this.resolveFilePath(c.path);try{let p=await Ti.stat(u);c.size=p.size}catch{c.changeType=Gt.FileChangeType.DELETE,c.size=void 0}let d={path:c.path,changeType:c.changeType,timestamp:new Date().toISOString(),source:"tool-call",toolName:c.toolName,toolId:c.toolId,size:c.size};this.onFileChangedCallback?.(e,d)}async handleViewRequest(e,t){let i=this.resolveFilePath(t.path),n=this.getViewableMimeType(t.path);if(n&&this.onFileViewTransferCallback){try{let a=await Ti.readFile(i),c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:n};this.onFileViewTransferCallback(e,Buffer.from(a),c)}catch(a){let c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:n,error:a instanceof Error?a.message:"Unknown error"};this.onFileViewTransferCallback(e,Buffer.alloc(0),c)}return}let s;try{t.type===Gt.FileViewType.CONTENT?s=await this.getFileContent(t,i):s=await this.getFileDiff(e,t,i)}catch(a){s={requestId:t.requestId,path:t.path,type:t.type,error:a instanceof Error?a.message:"Unknown error"}}if(this.onFileViewTransferCallback){let a={requestId:t.requestId,path:t.path,viewType:s.type===Gt.FileViewType.CONTENT?"content":"diff",language:s.language,truncated:s.truncated,error:s.error},c=Buffer.from(s.content||"","utf-8");this.onFileViewTransferCallback(e,c,a)}}getViewableMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf"}[t||""]||null}async getFileContent(e,t){let i=e.maxSize||1048576,n=await Ti.stat(t),s=await Ti.readFile(t,"utf-8"),a=!1,c=s;return s.length>i&&(c=s.slice(0,i),a=!0),{requestId:e.requestId,path:e.path,type:Gt.FileViewType.CONTENT,content:c,language:(0,Gt.getLanguageFromPath)(e.path),size:n.size,truncated:a}}async getFileDiff(e,t,i){let n=t.diffBase||Gt.DiffBase.GIT,s;return n===Gt.DiffBase.GIT?s=await this.getGitDiff(i):s=await this.getPreviousDiff(e,t.path,i),{requestId:t.requestId,path:t.path,type:Gt.FileViewType.DIFF,content:s,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await Lc("git",["diff","--cached","--",e],{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:i}=await Lc("git",["diff","--",e],{cwd:this.workspaceRoot});if(i.trim())return i;let{stdout:n}=await Lc("git",["status","--porcelain","--",e],{cwd:this.workspaceRoot});if(n.startsWith("??")||n.startsWith("A ")){let a=(await Ti.readFile(e,"utf-8")).split(`
|
|
28
|
+
`+t)}function Ei(r,e,t,i,n,s){if(r.listenerCount("wsClientError")){let a=new Error(n);Error.captureStackTrace(a,Ei),r.emit("wsClientError",a,t,e)}else Ln(t,i,n,s)}});var th=M((aw,eh)=>{"use strict";var Rr=Xs();Rr.createWebSocketStream=Hl();Rr.Server=Ql();Rr.Receiver=Ra();Rr.Sender=La();Rr.WebSocket=Rr;Rr.WebSocketServer=Rr.Server;eh.exports=Rr});var Ha=M(Yr=>{"use strict";var d_=Yr&&Yr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Yr,"__esModule",{value:!0});Yr.WS=Yr.BaseWS=void 0;var p_=Tn(),rh=gi(),g_=Di(),qa=pi(),m_=d_(Ft()),y_=(0,m_.default)("engine.io-client:websocket"),ih=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Zs=class extends p_.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,i=ih?{}:(0,rh.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,i)}catch(n){return this.emitReserved("error",n)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let i=e[t],n=t===e.length-1;(0,g_.encodePacket)(i,this.supportsBinary,s=>{try{this.doWrite(i,s)}catch{y_("websocket closed before onclose event")}n&&(0,qa.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=(0,rh.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}};Yr.BaseWS=Zs;var Ka=qa.globalThisShim.WebSocket||qa.globalThisShim.MozWebSocket,Wa=class extends Zs{createSocket(e,t,i){return ih?new Ka(e,t,i):t?new Ka(e,t):new Ka(e)}doWrite(e,t){this.ws.send(t)}};Yr.WS=Wa});var za=M(fr=>{"use strict";var __=fr&&fr.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),b_=fr&&fr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),v_=fr&&fr.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&__(e,r,t);return b_(e,r),e};Object.defineProperty(fr,"__esModule",{value:!0});fr.WS=void 0;var E_=v_(th()),w_=Ha(),Va=class extends w_.BaseWS{createSocket(e,t,i){var n;if(!((n=this.socket)===null||n===void 0)&&n._cookieJar){i.headers=i.headers||{},i.headers.cookie=typeof i.headers.cookie=="string"?[i.headers.cookie]:i.headers.cookie||[];for(let[s,a]of this.socket._cookieJar.cookies)i.headers.cookie.push(`${s}=${a.value}`)}return new E_.WebSocket(e,t,i)}doWrite(e,t){let i={};e.options&&(i.compress=e.options.compress),this.opts.perMessageDeflate&&(typeof t=="string"?Buffer.byteLength(t):t.length)<this.opts.perMessageDeflate.threshold&&(i.compress=!1),this.ws.send(t,i)}};fr.WS=Va});var Ga=M(Xi=>{"use strict";var x_=Xi&&Xi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xi,"__esModule",{value:!0});Xi.WT=void 0;var S_=Tn(),T_=pi(),nh=Di(),C_=x_(Ft()),Nn=(0,C_.default)("engine.io-client:webtransport"),$a=class extends S_.Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{Nn("transport closed gracefully"),this.onClose()}).catch(e=>{Nn("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=(0,nh.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),n=(0,nh.createPacketEncoderStream)();n.readable.pipeTo(e.writable),this._writer=n.writable.getWriter();let s=()=>{i.read().then(({done:c,value:u})=>{if(c){Nn("session is closed");return}Nn("received chunk: %o",u),this.onPacket(u),s()}).catch(c=>{Nn("an error occurred while reading: %s",c)})};s();let a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let i=e[t],n=t===e.length-1;this._writer.write(i).then(()=>{n&&(0,T_.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};Xi.WT=$a});var Ya=M(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});Qs.transports=void 0;var k_=ba(),O_=za(),P_=Ga();Qs.transports={websocket:O_.WS,webtransport:P_.WT,polling:k_.XHR}});var Ja=M(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.parse=I_;var R_=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,A_=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function I_(r){if(r.length>8e3)throw"URI too long";let e=r,t=r.indexOf("["),i=r.indexOf("]");t!=-1&&i!=-1&&(r=r.substring(0,t)+r.substring(t,i).replace(/:/g,";")+r.substring(i,r.length));let n=R_.exec(r||""),s={},a=14;for(;a--;)s[A_[a]]=n[a]||"";return t!=-1&&i!=-1&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=L_(s,s.path),s.queryKey=N_(s,s.query),s}function L_(r,e){let t=/\/{2,9}/g,i=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&i.splice(0,1),e.slice(-1)=="/"&&i.splice(i.length-1,1),i}function N_(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(i,n,s){n&&(t[n]=s)}),t}});var tc=M(ur=>{"use strict";var M_=ur&&ur.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ur,"__esModule",{value:!0});ur.Socket=ur.SocketWithUpgrade=ur.SocketWithoutUpgrade=void 0;var F_=Ya(),sh=gi(),D_=aa(),oh=Ja(),B_=di(),ah=Di(),Za=pi(),j_=M_(Ft()),De=(0,j_.default)("engine.io-client:socket"),Qa=typeof addEventListener=="function"&&typeof removeEventListener=="function",Mn=[];Qa&&addEventListener("offline",()=>{De("closing %d connection(s) because the network was lost",Mn.length),Mn.forEach(r=>r())},!1);var wi=class r extends B_.Emitter{constructor(e,t){if(super(),this.binaryType=Za.defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){let i=(0,oh.parse)(e);t.hostname=i.host,t.secure=i.protocol==="https"||i.protocol==="wss",t.port=i.port,i.query&&(t.query=i.query)}else t.host&&(t.hostname=(0,oh.parse)(t.host).host);(0,sh.installTimerFunctions)(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(i=>{let n=i.prototype.name;this.transports.push(n),this._transportsByName[n]=i}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=(0,D_.decode)(this.opts.query)),Qa&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(De("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Mn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Za.createCookieJar)()),this._open()}createTransport(e){De('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=ah.protocol,t.transport=e,this.id&&(t.sid=this.id);let i=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return De("options: %j",i),new this._transportsByName[e](i)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let e=this.opts.rememberUpgrade&&r.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){De("setting transport %s",e.name),this.transport&&(De("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){De("socket open"),this.readyState="open",r.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(De('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}else De('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();De("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let i=0;i<this.writeBuffer.length;i++){let n=this.writeBuffer[i].data;if(n&&(t+=(0,sh.byteLength)(n)),i>0&&t>this._maxPayload)return De("only send %d out of %d packets",i,this.writeBuffer.length),this.writeBuffer.slice(0,i);t+=2}return De("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(De("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,Za.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,i){return this._sendPacket("message",e,t,i),this}send(e,t,i){return this._sendPacket("message",e,t,i),this}_sendPacket(e,t,i,n){if(typeof t=="function"&&(n=t,t=void 0),typeof i=="function"&&(n=i,i=null),this.readyState==="closing"||this.readyState==="closed")return;i=i||{},i.compress=i.compress!==!1;let s={type:e,data:t,options:i};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),n&&this.once("flush",n),this.flush()}close(){let e=()=>{this._onClose("forced close"),De("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},i=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?i():e()}):this.upgrading?i():e()),this}_onError(e){if(De("socket error %j",e),r.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return De("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(De('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Qa&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let i=Mn.indexOf(this._offlineEventListener);i!==-1&&(De("removing listener for the 'offline' event"),Mn.splice(i,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};ur.SocketWithoutUpgrade=wi;wi.protocol=ah.protocol;var eo=class extends wi{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){De("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){De('probing transport "%s"',e);let t=this.createTransport(e),i=!1;wi.priorWebsocketSuccess=!1;let n=()=>{i||(De('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",m=>{if(!i)if(m.type==="pong"&&m.data==="probe"){if(De('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;wi.priorWebsocketSuccess=t.name==="websocket",De('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{i||this.readyState!=="closed"&&(De("changing transport and sending upgrade packet"),p(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{De('probe transport "%s" failed',e);let _=new Error("probe error");_.transport=t.name,this.emitReserved("upgradeError",_)}}))};function s(){i||(i=!0,p(),t.close(),t=null)}let a=m=>{let _=new Error("probe error: "+m);_.transport=t.name,s(),De('probe transport "%s" failed because of error: %s',e,m),this.emitReserved("upgradeError",_)};function c(){a("transport closed")}function u(){a("socket closed")}function d(m){t&&m.name!==t.name&&(De('"%s" works - aborting "%s"',m.name,t.name),s())}let p=()=>{t.removeListener("open",n),t.removeListener("error",a),t.removeListener("close",c),this.off("close",u),this.off("upgrading",d)};t.once("open",n),t.once("error",a),t.once("close",c),this.once("close",u),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{i||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let i=0;i<e.length;i++)~this.transports.indexOf(e[i])&&t.push(e[i]);return t}};ur.SocketWithUpgrade=eo;var ec=class extends eo{constructor(e,t={}){let i=typeof e=="object"?e:t;(!i.transports||i.transports&&typeof i.transports[0]=="string")&&(i.transports=(i.transports||["polling","websocket","webtransport"]).map(n=>F_.transports[n]).filter(n=>!!n)),super(e,i)}};ur.Socket=ec});var ch=M(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.Fetch=void 0;var U_=pa(),rc=class extends U_.Polling{doPoll(){this._fetch().then(e=>{if(!e.ok)return this.onError("fetch read error",e.status,e);e.text().then(t=>this.onData(t))}).catch(e=>{this.onError("fetch read error",e)})}doWrite(e,t){this._fetch(e).then(i=>{if(!i.ok)return this.onError("fetch write error",i.status,i);t()}).catch(i=>{this.onError("fetch write error",i)})}_fetch(e){var t;let i=e!==void 0,n=new Headers(this.opts.extraHeaders);return i&&n.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(n),fetch(this.uri(),{method:i?"POST":"GET",body:i?e:null,headers:n,credentials:this.opts.withCredentials?"include":"omit"}).then(s=>{var a;return(a=this.socket._cookieJar)===null||a===void 0||a.parseCookies(s.headers.getSetCookie()),s})}};to.Fetch=rc});var ro=M(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.WebTransport=Oe.WebSocket=Oe.NodeWebSocket=Oe.XHR=Oe.NodeXHR=Oe.Fetch=Oe.nextTick=Oe.parse=Oe.installTimerFunctions=Oe.transports=Oe.TransportError=Oe.Transport=Oe.protocol=Oe.SocketWithUpgrade=Oe.SocketWithoutUpgrade=Oe.Socket=void 0;var fh=tc();Object.defineProperty(Oe,"Socket",{enumerable:!0,get:function(){return fh.Socket}});var uh=tc();Object.defineProperty(Oe,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return uh.SocketWithoutUpgrade}});Object.defineProperty(Oe,"SocketWithUpgrade",{enumerable:!0,get:function(){return uh.SocketWithUpgrade}});Oe.protocol=fh.Socket.protocol;var lh=Tn();Object.defineProperty(Oe,"Transport",{enumerable:!0,get:function(){return lh.Transport}});Object.defineProperty(Oe,"TransportError",{enumerable:!0,get:function(){return lh.TransportError}});var K_=Ya();Object.defineProperty(Oe,"transports",{enumerable:!0,get:function(){return K_.transports}});var q_=gi();Object.defineProperty(Oe,"installTimerFunctions",{enumerable:!0,get:function(){return q_.installTimerFunctions}});var W_=Ja();Object.defineProperty(Oe,"parse",{enumerable:!0,get:function(){return W_.parse}});var H_=pi();Object.defineProperty(Oe,"nextTick",{enumerable:!0,get:function(){return H_.nextTick}});var V_=ch();Object.defineProperty(Oe,"Fetch",{enumerable:!0,get:function(){return V_.Fetch}});var z_=ba();Object.defineProperty(Oe,"NodeXHR",{enumerable:!0,get:function(){return z_.XHR}});var $_=ya();Object.defineProperty(Oe,"XHR",{enumerable:!0,get:function(){return $_.XHR}});var G_=za();Object.defineProperty(Oe,"NodeWebSocket",{enumerable:!0,get:function(){return G_.WS}});var Y_=Ha();Object.defineProperty(Oe,"WebSocket",{enumerable:!0,get:function(){return Y_.WS}});var X_=Ga();Object.defineProperty(Oe,"WebTransport",{enumerable:!0,get:function(){return X_.WT}})});var dh=M(Fn=>{"use strict";var J_=Fn&&Fn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fn,"__esModule",{value:!0});Fn.url=e0;var Z_=ro(),Q_=J_(Ft()),hh=(0,Q_.default)("socket.io-client:url");function e0(r,e="",t){let i=r;t=t||typeof location<"u"&&location,r==null&&(r=t.protocol+"//"+t.host),typeof r=="string"&&(r.charAt(0)==="/"&&(r.charAt(1)==="/"?r=t.protocol+r:r=t.host+r),/^(https?|wss?):\/\//.test(r)||(hh("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),hh("parse %s",r),i=(0,Z_.parse)(r)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";let s=i.host.indexOf(":")!==-1?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+s+":"+i.port+e,i.href=i.protocol+"://"+s+(t&&t.port===i.port?"":":"+i.port),i}});var ic=M(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.isBinary=gh;no.hasBinary=io;var t0=typeof ArrayBuffer=="function",r0=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,ph=Object.prototype.toString,i0=typeof Blob=="function"||typeof Blob<"u"&&ph.call(Blob)==="[object BlobConstructor]",n0=typeof File=="function"||typeof File<"u"&&ph.call(File)==="[object FileConstructor]";function gh(r){return t0&&(r instanceof ArrayBuffer||r0(r))||i0&&r instanceof Blob||n0&&r instanceof File}function io(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,i=r.length;t<i;t++)if(io(r[t]))return!0;return!1}if(gh(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return io(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&io(r[t]))return!0;return!1}});var mh=M(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.deconstructPacket=o0;so.reconstructPacket=a0;var s0=ic();function o0(r){let e=[],t=r.data,i=r;return i.data=nc(t,e),i.attachments=e.length,{packet:i,buffers:e}}function nc(r,e){if(!r)return r;if((0,s0.isBinary)(r)){let t={_placeholder:!0,num:e.length};return e.push(r),t}else if(Array.isArray(r)){let t=new Array(r.length);for(let i=0;i<r.length;i++)t[i]=nc(r[i],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){let t={};for(let i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=nc(r[i],e));return t}return r}function a0(r,e){return r.data=sc(r.data,e),delete r.attachments,r}function sc(r,e){if(!r)return r;if(r&&r._placeholder===!0){if(typeof r.num=="number"&&r.num>=0&&r.num<e.length)return e[r.num];throw new Error("illegal attachments")}else if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]=sc(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=sc(r[t],e));return r}});var ao=M(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.Decoder=zt.Encoder=zt.PacketType=zt.protocol=void 0;zt.isPacketValid=p0;var c0=di(),yh=mh(),_h=ic(),f0=Ft(),oc=(0,f0.default)("socket.io-parser"),bh=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];zt.protocol=5;var Fe;(function(r){r[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK"})(Fe||(zt.PacketType=Fe={}));var ac=class{constructor(e){this.replacer=e}encode(e){return oc("encoding packet %j",e),(e.type===Fe.EVENT||e.type===Fe.ACK)&&(0,_h.hasBinary)(e)?this.encodeAsBinary({type:e.type===Fe.EVENT?Fe.BINARY_EVENT:Fe.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Fe.BINARY_EVENT||e.type===Fe.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),oc("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,yh.deconstructPacket)(e),i=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(i),n}};zt.Encoder=ac;var cc=class r extends c0.Emitter{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);let i=t.type===Fe.BINARY_EVENT;i||t.type===Fe.BINARY_ACK?(t.type=i?Fe.EVENT:Fe.ACK,this.reconstructor=new fc(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,_h.isBinary)(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0,i={type:Number(e.charAt(0))};if(Fe[i.type]===void 0)throw new Error("unknown packet type "+i.type);if(i.type===Fe.BINARY_EVENT||i.type===Fe.BINARY_ACK){let s=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let a=e.substring(s,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");i.attachments=Number(a)}if(e.charAt(t+1)==="/"){let s=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););i.nsp=e.substring(s,t)}else i.nsp="/";let n=e.charAt(t+1);if(n!==""&&Number(n)==n){let s=t+1;for(;++t;){let a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}i.id=Number(e.substring(s,t+1))}if(e.charAt(++t)){let s=this.tryParse(e.substr(t));if(r.isPayloadValid(i.type,s))i.data=s;else throw new Error("invalid payload")}return oc("decoded %s as %j",e,i),i}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Fe.CONNECT:return oo(t);case Fe.DISCONNECT:return t===void 0;case Fe.CONNECT_ERROR:return typeof t=="string"||oo(t);case Fe.EVENT:case Fe.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&bh.indexOf(t[0])===-1);case Fe.ACK:case Fe.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};zt.Decoder=cc;var fc=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=(0,yh.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function u0(r){return typeof r=="string"}var l0=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function h0(r){return r===void 0||l0(r)}function oo(r){return Object.prototype.toString.call(r)==="[object Object]"}function d0(r,e){switch(r){case Fe.CONNECT:return e===void 0||oo(e);case Fe.DISCONNECT:return e===void 0;case Fe.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&bh.indexOf(e[0])===-1);case Fe.ACK:return Array.isArray(e);case Fe.CONNECT_ERROR:return typeof e=="string"||oo(e);default:return!1}}function p0(r){return u0(r.nsp)&&h0(r.id)&&d0(r.type,r.data)}});var lc=M(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.on=g0;function g0(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var dc=M(Ji=>{"use strict";var m0=Ji&&Ji.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ji,"__esModule",{value:!0});Ji.Socket=void 0;var $t=ao(),co=lc(),y0=di(),_0=m0(Ft()),et=(0,_0.default)("socket.io-client:socket"),b0=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),hc=class extends y0.Emitter{constructor(e,t,i){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,i&&i.auth&&(this.auth=i.auth),this._opts=Object.assign({},i),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[(0,co.on)(e,"open",this.onopen.bind(this)),(0,co.on)(e,"packet",this.onpacket.bind(this)),(0,co.on)(e,"error",this.onerror.bind(this)),(0,co.on)(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var i,n,s;if(b0.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let a={type:$t.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let p=this.ids++;et("emitting packet with ack id %d",p);let m=t.pop();this._registerAckCallback(p,m),a.id=p}let c=(n=(i=this.io.engine)===null||i===void 0?void 0:i.transport)===null||n===void 0?void 0:n.writable,u=this.connected&&!(!((s=this.io.engine)===null||s===void 0)&&s._hasPingExpired());return this.flags.volatile&&!c?et("discard packet as the transport is not currently writable"):u?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a),this.flags={},this}_registerAckCallback(e,t){var i;let n=(i=this.flags.timeout)!==null&&i!==void 0?i:this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let s=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&(et("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));et("event with ack id %d has timed out after %d ms",e,n),t.call(this,new Error("operation has timed out"))},n),a=(...c)=>{this.io.clearTimeoutFn(s),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((i,n)=>{let s=(a,c)=>a?n(a):i(c);s.withError=!0,t.push(s),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let i={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((n,...s)=>i!==this._queue[0]?et("packet [%d] already acknowledged",i.id):(n!==null?i.tryCount>this._opts.retries&&(et("packet [%d] is discarded after %d tries",i.id,i.tryCount),this._queue.shift(),t&&t(n)):(et("packet [%d] was successfully sent",i.id),this._queue.shift(),t&&t(null,...s)),i.pending=!1,this._drainQueue())),this._queue.push(i),this._drainQueue()}_drainQueue(e=!1){if(et("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){et("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,et("sending packet [%d] (try n\xB0%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){et("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:$t.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){et("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(i=>String(i.id)===e)){let i=this.acks[e];delete this.acks[e],i.withError&&i.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case $t.PacketType.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case $t.PacketType.EVENT:case $t.PacketType.BINARY_EVENT:this.onevent(e);break;case $t.PacketType.ACK:case $t.PacketType.BINARY_ACK:this.onack(e);break;case $t.PacketType.DISCONNECT:this.ondisconnect();break;case $t.PacketType.CONNECT_ERROR:this.destroy();let i=new Error(e.data.message);i.data=e.data.data,this.emitReserved("connect_error",i);break}}onevent(e){let t=e.data||[];et("emitting event %j",t),e.id!=null&&(et("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let i of t)i.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,i=!1;return function(...n){i||(i=!0,et("sending ack %j",n),t.packet({type:$t.PacketType.ACK,id:e,data:n}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){et("bad ack %s",e.id);return}delete this.acks[e.id],et("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){et("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){et("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(et("performing disconnect (%s)",this.nsp),this.packet({type:$t.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let i of t)i.apply(this,e.data)}}};Ji.Socket=hc});var vh=M(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});pc.Backoff=Zi;function Zi(r){r=r||{},this.ms=r.min||100,this.max=r.max||1e4,this.factor=r.factor||2,this.jitter=r.jitter>0&&r.jitter<=1?r.jitter:0,this.attempts=0}Zi.prototype.duration=function(){var r=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*r);r=(Math.floor(e*10)&1)==0?r-t:r+t}return Math.min(r,this.max)|0};Zi.prototype.reset=function(){this.attempts=0};Zi.prototype.setMin=function(r){this.ms=r};Zi.prototype.setMax=function(r){this.max=r};Zi.prototype.setJitter=function(r){this.jitter=r}});var Eh=M(jt=>{"use strict";var v0=jt&&jt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),E0=jt&&jt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),w0=jt&&jt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&v0(e,r,t);return E0(e,r),e},x0=jt&&jt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(jt,"__esModule",{value:!0});jt.Manager=void 0;var gc=ro(),S0=dc(),T0=w0(ao()),xi=lc(),C0=vh(),k0=di(),O0=x0(Ft()),ft=(0,O0.default)("socket.io-client:manager"),mc=class extends k0.Emitter{constructor(e,t){var i;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,(0,gc.installTimerFunctions)(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((i=t.randomizationFactor)!==null&&i!==void 0?i:.5),this.backoff=new C0.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let n=t.parser||T0;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(ft("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;ft("opening %s",this.uri),this.engine=new gc.Socket(this.uri,this.opts);let t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;let n=(0,xi.on)(t,"open",function(){i.onopen(),e&&e()}),s=c=>{ft("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,xi.on)(t,"error",s);if(this._timeout!==!1){let c=this._timeout;ft("connect attempt will timeout after %d",c);let u=this.setTimeoutFn(()=>{ft("connect attempt timed out after %d",c),n(),s(new Error("timeout")),t.close()},c);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(n),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){ft("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,xi.on)(e,"ping",this.onping.bind(this)),(0,xi.on)(e,"data",this.ondata.bind(this)),(0,xi.on)(e,"error",this.onerror.bind(this)),(0,xi.on)(e,"close",this.onclose.bind(this)),(0,xi.on)(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){(0,gc.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){ft("error",e),this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new S0.Socket(this,e,t),this.nsps[e]=i),i}_destroy(e){let t=Object.keys(this.nsps);for(let i of t)if(this.nsps[i].active){ft("socket %s is still active, skipping close",i);return}this._close()}_packet(e){ft("writing packet %j",e);let t=this.encoder.encode(e);for(let i=0;i<t.length;i++)this.engine.write(t[i],e.options)}cleanup(){ft("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){ft("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var i;ft("closed due to %s",e),this.cleanup(),(i=this.engine)===null||i===void 0||i.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)ft("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();ft("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let i=this.setTimeoutFn(()=>{e.skipReconnect||(ft("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(n=>{n?(ft("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",n)):(ft("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};jt.Manager=mc});var Th=M((Be,Sh)=>{"use strict";var P0=Be&&Be.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Be,"__esModule",{value:!0});Be.WebTransport=Be.WebSocket=Be.NodeWebSocket=Be.XHR=Be.NodeXHR=Be.Fetch=Be.Socket=Be.Manager=Be.protocol=void 0;Be.io=Si;Be.connect=Si;Be.default=Si;var R0=dh(),fo=Eh();Object.defineProperty(Be,"Manager",{enumerable:!0,get:function(){return fo.Manager}});var xh=dc();Object.defineProperty(Be,"Socket",{enumerable:!0,get:function(){return xh.Socket}});var A0=P0(Ft()),wh=(0,A0.default)("socket.io-client"),Dn={};function Si(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,R0.url)(r,e.path||"/socket.io"),i=t.source,n=t.id,s=t.path,a=Dn[n]&&s in Dn[n].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||a,u;return c?(wh("ignoring socket cache for %s",i),u=new fo.Manager(i,e)):(Dn[n]||(wh("new io instance for %s",i),Dn[n]=new fo.Manager(i,e)),u=Dn[n]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(Si,{Manager:fo.Manager,Socket:xh.Socket,io:Si,connect:Si});var I0=ao();Object.defineProperty(Be,"protocol",{enumerable:!0,get:function(){return I0.protocol}});var Qi=ro();Object.defineProperty(Be,"Fetch",{enumerable:!0,get:function(){return Qi.Fetch}});Object.defineProperty(Be,"NodeXHR",{enumerable:!0,get:function(){return Qi.NodeXHR}});Object.defineProperty(Be,"XHR",{enumerable:!0,get:function(){return Qi.XHR}});Object.defineProperty(Be,"NodeWebSocket",{enumerable:!0,get:function(){return Qi.NodeWebSocket}});Object.defineProperty(Be,"WebSocket",{enumerable:!0,get:function(){return Qi.WebSocket}});Object.defineProperty(Be,"WebTransport",{enumerable:!0,get:function(){return Qi.WebTransport}});Sh.exports=Si});var _c=M(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.InputStreamReceiver=void 0;var L0=64,N0=30,M0=4,F0=256,D0=16,yc=class{streamId;lastAppliedSeq=0;cb;windowSize;ackThrottleMs;ackTimer=null;framesSinceAck=0;lastResendFrom=0;resendSuppressed=0;constructor(e,t,i={}){this.streamId=e,this.cb=t,this.windowSize=Math.max(1,i.windowSize??L0),this.ackThrottleMs=Math.max(0,i.ackThrottleMs??N0)}get appliedSeq(){return this.lastAppliedSeq}receive(e,t,i){if(e<=this.lastAppliedSeq){this.flushAck();return}if(e===this.lastAppliedSeq+1){try{this.cb.onApply(t,i)}catch{}this.lastAppliedSeq=e,this.scheduleAck();return}this.flushAck();let n=Math.max(this.windowSize*M0,F0);e-this.lastAppliedSeq>n||this.maybeResend(this.lastAppliedSeq+1)}maybeResend(e){if(e===this.lastResendFrom){if(++this.resendSuppressed<D0)return;this.resendSuppressed=0}else this.lastResendFrom=e,this.resendSuppressed=0;this.cb.onResend(e)}resumeState(){return{streamId:this.streamId,lastAckSeq:this.lastAppliedSeq}}dispose(){this.ackTimer&&(clearTimeout(this.ackTimer),this.ackTimer=null)}scheduleAck(){this.framesSinceAck++;let e=Math.max(1,Math.floor(this.windowSize/4));if(this.windowSize===1||this.framesSinceAck>=e){this.flushAck();return}this.ackTimer||(this.ackTimer=setTimeout(()=>this.flushAck(),this.ackThrottleMs))}flushAck(){this.ackTimer&&(clearTimeout(this.ackTimer),this.ackTimer=null),this.framesSinceAck=0,this.cb.onAck(this.lastAppliedSeq)}};uo.InputStreamReceiver=yc});var Ph=M(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.WebSocketService=void 0;var B0=Th(),Ch=Sr(),kh=fs(),Oh=os(),j0=_c(),bc=class{authService;cryptoService;config;logger;notification;deviceId;platform;extraCapabilities;socket=null;inputHandler=null;createTerminalHandler=null;getBufferHandler=null;redrawHandler=null;resizeHandler=null;reconnectHandlers=[];authFailureHandler=null;fileViewRequestHandler=null;fileListRequestHandler=null;fileDownloadRequestHandler=null;statusChangeHandler=null;agentNameSyncHandler=null;clientAttachedHandler=null;metaSessionEstablishedHandler=null;clientDetachedHandler=null;inputReceivers=new Map;terminalActiveCheck=null;MAX_INPUT_RECEIVERS=512;agentId=null;hasConnectedOnce=!1;isRemoteRename=!1;negotiatedCapabilities=[];HEARTBEAT_INTERVAL=3e4;HEARTBEAT_TIMEOUT=1e4;heartbeatTimer=null;pongTimer=null;lastPongTime=0;RESUME_WATCHDOG_INTERVAL=5e3;RESUME_WATCHDOG_THRESHOLD=15e3;resumeWatchdogTimer=null;resumeWatchdogExpectedAt=0;isManualDisconnect=!1;reconnectAttempts=0;reconnectTimer=null;networkCheckTimer=null;isOnline=!0;lastNetworkCheck=0;rekeyingTerminals=new Set;outputBuffer=new Map;OUTPUT_BUFFER_MAX_SIZE=1e3;invalidSessionSignalAt=new Map;INVALID_SESSION_SIGNAL_THROTTLE_MS=5e3;attachedClientCount=0;RECONNECT_BASE_DELAY=1e3;RECONNECT_MAX_DELAY=3e4;RECONNECT_JITTER=.2;NETWORK_CHECK_INTERVAL=5e3;constructor(e,t,i,n,s,a,c="vscode",u=[]){this.authService=e,this.cryptoService=t,this.config=i,this.logger=n,this.notification=s,this.deviceId=a,this.platform=c,this.extraCapabilities=u}async connect(){let e=await this.authService.getAccessToken();if(!e)throw new Error("No access token available");this.isManualDisconnect=!1,this.stopReconnect(),this.reconnectAttempts=0,this.agentId=await this.authService.getAgentId();let t=(0,kh.getWsUrl)(this.config);this.logger.info("Connecting to WebSocket",t),this.statusChangeHandler?.("connecting");let i=await this.cryptoService.getPublicKey();return new Promise((n,s)=>{let a=Array.from(new Set([...Ch.DEFAULT_CLIENT_CAPABILITIES,...this.extraCapabilities]));this.socket=(0,B0.io)(`${t}/agent`,{auth:{token:e,protocolVersion:Ch.PROTOCOL_VERSION,deviceId:this.deviceId,platform:this.platform,capabilities:a,publicKey:i},transports:["websocket"],reconnection:!1}),this.socket.on("connect",()=>{if(this.logger.info("WebSocket connected"),this.reconnectAttempts=0,this.statusChangeHandler?.("connected",this.agentId??void 0),this.startHeartbeat(),this.cryptoService.cleanupAllStaleSessions(),this.hasConnectedOnce){this.logger.info("Reconnected - triggering workspace re-registration");for(let c of this.reconnectHandlers)c()}else this.hasConnectedOnce=!0,n()}),this.socket.on("error",c=>{this.logger.error(`Server error [${c.code}]: ${c.message}`),c.code==="E401"&&(this.logger.warn("Auth failure (E401)"),this.authFailureHandler?.())}),this.socket.on("disconnect",c=>{this.logger.warn("WebSocket disconnected",c),this.stopHeartbeat(),this.statusChangeHandler?.("disconnected"),this.isManualDisconnect||(c==="transport close"?(this.logger.info("Transport close - attempting immediate reconnect"),this.attemptReconnect(!0)):this.scheduleReconnect())}),this.socket.on("protocol:info",c=>{this.logger.info("Protocol info received",c.protocolVersion),this.negotiatedCapabilities=c.negotiatedCapabilities,c.agentName&&this.config.getAgentName()!==c.agentName&&(this.isRemoteRename=!0,this.config.setAgentName(c.agentName).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(c.agentName),this.logger.info("Agent name synced from server",c.agentName))}),this.socket.on("pong",()=>{this.lastPongTime=Date.now(),this.clearPongTimeout(),this.logger.debug("Heartbeat pong received")}),this.socket.on("connect_error",c=>{this.logger.error("WebSocket connection error",c),this.statusChangeHandler?.("error"),this.hasConnectedOnce||s(c),this.scheduleReconnect()}),this.socket.on("terminal:input",c=>{this.handleTerminalInput(c)}),this.socket.on("crypto:keyExchange",async(c,u)=>{this.logger.info("Received key exchange request",c.terminalId,c.sessionId),this.rekeyingTerminals.add(c.terminalId),this.outputBuffer.set(c.terminalId,[]);try{if(await this.cryptoService.handleKeyExchange(c.terminalId,c.clientPublicKey,c.sessionId)){let p=await this.cryptoService.getPublicKey();u?.({success:!0,agentPublicKey:p||void 0}),this.flushOutputBuffer(c.terminalId)}else u?.({success:!1,error:"Key exchange failed"})}catch(d){this.logger.error("Key exchange error",d),u?.({success:!1,error:String(d)})}finally{this.rekeyingTerminals.delete(c.terminalId),this.outputBuffer.delete(c.terminalId)}}),this.socket.on("crypto:sessionCleanup",c=>{this.cryptoService.removeSession(c.terminalId,c.sessionId)}),this.socket.on("agent:keyExchangeRequest",async c=>{try{let u=await this.cryptoService.handleAgentKeyExchange(c.clientPublicKey,c.sessionId),d={agentId:c.agentId,sessionId:c.sessionId,ok:u,error:u?void 0:"Key exchange failed"};this.socket?.emit("agent:keyExchangeAck",d)}catch(u){this.logger.error("Agent key exchange error",u);let d={agentId:c.agentId,sessionId:c.sessionId,ok:!1,error:String(u)};this.socket?.emit("agent:keyExchangeAck",d)}}),this.socket.on("meta:keyExchange",async(c,u)=>{let{ok:d,isNew:p}=await this.cryptoService.handleMetaKeyExchange(c.clientIdentityPub),m=await this.cryptoService.getPublicKey()||void 0;u?.({ok:d,agentPublicKey:m}),d&&this.metaSessionEstablishedHandler?.(p)}),this.socket.on("agent:sessionEnd",c=>{this.cryptoService.removeAgentSession(c.sessionId)}),this.socket.on("agent:renamed",c=>{this.logger.info("Agent renamed from web client",c.name),this.isRemoteRename=!0,this.config.setAgentName(c.name).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(c.name)}),this.socket.on("terminal:createRequest",c=>{this.createTerminalHandler?.(c.name)}),this.socket.on("terminal:getBuffer",(c,u)=>{if(!this.getBufferHandler){u?.({success:!1,error:"Buffer handler not set"});return}let d=this.getBufferHandler(c.terminalId);if(d===null){u?.({success:!1,error:"Terminal not found"});return}let p=this.cryptoService.encryptOutput(c.terminalId,d);if(!p){this.signalInvalidSession(void 0,c.terminalId),u?.({success:!1,error:"No E2E session"});return}u?.({success:!0,encrypted:p}),this.redrawHandler?.(c.terminalId)}),this.socket.on("terminal:resize",c=>{this.resizeHandler?.(c.terminalId,c.cols,c.rows)}),this.socket.on("workspace:clientAttached",c=>{this.attachedClientCount=c.clientCount,this.clientAttachedHandler?.(c)}),this.socket.on("workspace:clientDetached",c=>{this.attachedClientCount=c.clientCount,this.clientDetachedHandler?.(c)}),this.socket.on("file:view",c=>{this.fileViewRequestHandler?.(c.terminalId,c.request)}),this.socket.on("file:list",c=>{this.fileListRequestHandler?.(c.terminalId,c.request)}),this.socket.on("file:download:request",c=>{this.fileDownloadRequestHandler?.(c.terminalId,c.path,c.requestId)})})}disconnect(){this.isManualDisconnect=!0,this.hasConnectedOnce=!1,this.stopReconnect(),this.stopHeartbeat(),this.cryptoService.clearAllSessions(),this.socket&&(this.logger.info("Disconnecting WebSocket"),this.socket.disconnect(),this.socket=null)}softDisconnect(){this.stopReconnect(),this.stopHeartbeat(),this.socket&&(this.logger.info("Soft disconnecting WebSocket (for reconnect)"),this.socket.disconnect(),this.socket=null)}getStatus(){return{connected:this.socket?.connected??!1,agentId:this.agentId}}onInput(e){this.inputHandler=e}onCreateTerminalRequest(e){this.createTerminalHandler=e}onGetBufferRequest(e){this.getBufferHandler=e}onRedrawRequest(e){this.redrawHandler=e}onResizeRequest(e){this.resizeHandler=e}onReconnect(e){this.reconnectHandlers.push(e)}onAuthFailure(e){this.authFailureHandler=e}onFileViewRequest(e){this.fileViewRequestHandler=e}onFileListRequest(e){this.fileListRequestHandler=e}onFileDownloadRequest(e){this.fileDownloadRequestHandler=e}onStatusChange(e){this.statusChangeHandler=e}onAgentNameSync(e){this.agentNameSyncHandler=e}onClientAttached(e){this.clientAttachedHandler=e}onMetaSessionEstablished(e){this.metaSessionEstablishedHandler=e}onClientDetached(e){this.clientDetachedHandler=e}async registerWorkspace(e){return this.emit("workspace:register",e)}async unregisterWorkspace(e){await this.emit("workspace:unregister",{instanceId:e})}async terminalCreated(e){return this.emit("terminal:created",e)}async terminalClosed(e){this.cryptoService.removeSession(e.terminalId),await this.emit("terminal:closed",e)}terminalNotFound(e){this.socket?.emit("terminal:notFound",{terminalId:e})}sendPtyResized(e,t,i,n){this.socket?.connected&&this.socket.emit("agent:ptyResized",{instanceId:e,terminalId:t,cols:i,rows:n})}sendClaimControl(e,t,i,n){this.socket?.connected&&this.socket.emit("agent:claimControl",{instanceId:e,terminalId:t,cols:i,rows:n})}sendOutput(e,t,i){if(!this.socket?.connected)return;if(this.rekeyingTerminals.has(t)){let a=this.outputBuffer.get(t);a&&a.length<this.OUTPUT_BUFFER_MAX_SIZE&&a.push({instanceId:e,data:i});return}let n=this.cryptoService.encryptOutput(t,i);if(!n){this.attachedClientCount>0&&this.signalInvalidSession(e,t);return}let s={instanceId:e,terminalId:t,encrypted:n};this.socket?.emit("terminal:output",s)}flushOutputBuffer(e){let t=this.outputBuffer.get(e);if(!(!t||t.length===0)){this.logger.info("Flushing output buffer after rekey",e,String(t.length));for(let{instanceId:i,data:n}of t){let s=this.cryptoService.encryptOutput(e,n);if(!s){this.signalInvalidSession(i,e);continue}let a={instanceId:i,terminalId:e,encrypted:s};this.socket?.emit("terminal:output",a)}}}signalInvalidSession(e,t){let i=Date.now(),n=this.invalidSessionSignalAt.get(t)??0;i-n<this.INVALID_SESSION_SIGNAL_THROTTLE_MS||(this.invalidSessionSignalAt.set(t,i),this.logger.warn("E2E session invalid/missing \u2014 signaling clients to rekey",t),this.socket?.emit("crypto:invalidSession",{instanceId:e??this.instanceIdForTerminal(t),terminalId:t}))}instanceIdForTerminal(e){return this.inputReceivers.get(e)?.instanceId}async updateStatus(e){await this.emit("terminal:status",e)}sendTerminalEvent(e,t,i){let n={instanceId:e,terminalId:t,event:i};this.socket?.emit("terminal:event",n)}hasCapability(e){return this.negotiatedCapabilities.includes(e)}sendFileChangedEvent(e,t,i){let n={instanceId:e,terminalId:t,event:i};this.socket?.emit("file:changed",n)}sendFileListResponse(e,t){let i={instanceId:e,response:t};this.socket?.emit("file:list:response",i)}sendAgentRename(e){this.socket?.emit("agent:rename",{name:e})}isRemoteRenameInProgress(){return this.isRemoteRename}getSocket(){return this.socket}emit(e,t){let i=(0,Oh.generateCorrelationId)(),n=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:i}:t;return(0,Oh.runWithCorrelation)(i,()=>new Promise((s,a)=>{if(!this.socket?.connected){a(new Error("WebSocket not connected"));return}this.socket.emit(e,n,c=>{c.success?s(c):a(new Error(c.error||"Unknown error"))})}))}startHeartbeat(){this.stopHeartbeat(),this.lastPongTime=Date.now(),this.startResumeWatchdog(),this.heartbeatTimer=setInterval(()=>{if(!this.socket?.connected){this.stopHeartbeat();return}if(Date.now()-this.lastPongTime>this.HEARTBEAT_INTERVAL+this.HEARTBEAT_TIMEOUT){this.logger.warn("Heartbeat timeout"),this.socket.disconnect();return}this.socket.emit("ping"),this.pongTimer=setTimeout(()=>{this.logger.warn("Pong timeout - server not responding, forcing teardown + reconnect"),this.statusChangeHandler?.("error"),this.socket?.disconnect()},this.HEARTBEAT_TIMEOUT)},this.HEARTBEAT_INTERVAL)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.clearPongTimeout(),this.stopResumeWatchdog()}startResumeWatchdog(){this.stopResumeWatchdog(),this.resumeWatchdogExpectedAt=Date.now()+this.RESUME_WATCHDOG_INTERVAL,this.resumeWatchdogTimer=setTimeout(()=>this.onResumeWatchdogTick(),this.RESUME_WATCHDOG_INTERVAL)}onResumeWatchdogTick(){let e=Date.now(),t=e-this.resumeWatchdogExpectedAt;if(t>this.RESUME_WATCHDOG_THRESHOLD&&(this.logger.warn(`Resume detected (clock drift ${t}ms) - forcing liveness re-check`),!this.isManualDisconnect&&this.socket)){this.statusChangeHandler?.("error"),this.socket.disconnect();return}this.isManualDisconnect||(this.resumeWatchdogExpectedAt=e+this.RESUME_WATCHDOG_INTERVAL,this.resumeWatchdogTimer=setTimeout(()=>this.onResumeWatchdogTick(),this.RESUME_WATCHDOG_INTERVAL))}stopResumeWatchdog(){this.resumeWatchdogTimer&&(clearTimeout(this.resumeWatchdogTimer),this.resumeWatchdogTimer=null)}clearPongTimeout(){this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}handleTerminalInput(e){let t;if(e.encrypted){let i=this.cryptoService.decryptInput(e.terminalId,e.encrypted);if(!i){this.logger.error("Failed to decrypt terminal input",e.terminalId),this.signalInvalidSession(e.instanceId,e.terminalId);return}t=i}else if(e.data)t=Buffer.from(e.data,"base64").toString("utf8");else{this.logger.error("Invalid terminal input payload");return}if(e.streamId&&typeof e.seq=="number"){let i=this.getOrCreateInputReceiver(e.terminalId,e.streamId,e.instanceId,e.dbTerminalId);if(!i)return;i.receive(e.seq,t,e.paste);return}this.inputHandler?.(e.terminalId,t,e.dbTerminalId)}getOrCreateInputReceiver(e,t,i,n){let s=this.inputReceivers.get(e);if(this.terminalActiveCheck&&!this.terminalActiveCheck(e))return s&&this.disposeInputStream(e),null;if(s&&s.receiver.streamId===t)return n&&(s.routeId=n),i&&(s.instanceId=i),s.receiver;if(s&&s.receiver.dispose(),!s&&this.inputReceivers.size>=this.MAX_INPUT_RECEIVERS)return this.logger.error("inputReceivers map at cap, dropping frame",e),null;let a=new j0.InputStreamReceiver(t,{onApply:(c,u)=>this.inputHandler?.(e,c,this.routeIdFor(e),u),onAck:c=>this.sendInputAck(e,t,c),onResend:c=>this.sendInputResend(e,t,c)});return this.inputReceivers.set(e,{receiver:a,routeId:n??e,instanceId:i??""}),a}setTerminalActiveCheck(e){this.terminalActiveCheck=e}routeIdFor(e){return this.inputReceivers.get(e)?.routeId??e}sendInputAck(e,t,i){let n=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:ack",{instanceId:n,terminalId:e,streamId:t,ackSeq:i})}sendInputResend(e,t,i){let n=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:resend",{instanceId:n,terminalId:e,streamId:t,fromSeq:i})}sendInputResume(e){let t=this.inputReceivers.get(e);if(!t)return;let{streamId:i,lastAckSeq:n}=t.receiver.resumeState();this.socket?.emit("input:resume",{instanceId:t.instanceId,terminalId:e,streamId:i,lastAckSeq:n})}disposeInputStream(e){this.inputReceivers.get(e)?.receiver.dispose(),this.inputReceivers.delete(e)}hasE2ESession(e){return this.cryptoService.hasSession(e)}getReconnectDelay(){let e=Math.min(this.RECONNECT_BASE_DELAY*Math.pow(2,this.reconnectAttempts),this.RECONNECT_MAX_DELAY),t=1+(Math.random()*2-1)*this.RECONNECT_JITTER;return Math.floor(e*t)}scheduleReconnect(){if(this.isManualDisconnect)return;this.stopReconnect();let e=this.getReconnectDelay();if(this.logger.info("Scheduling reconnect",String(this.reconnectAttempts+1),"delay:",String(e)),!this.isOnline){this.statusChangeHandler?.("disconnected"),this.startNetworkCheck();return}this.statusChangeHandler?.("connecting"),this.reconnectTimer=setTimeout(()=>{this.attemptReconnect()},e)}async attemptReconnect(e=!1){if(this.isManualDisconnect||this.socket?.connected)return;let t=await this.authService.hasValidToken();if(!t){if(this.logger.info("Access token expired, attempting refresh"),!await this.authService.refreshAccessToken()){this.logger.info("Token refresh failed, stopping reconnect"),this.stopReconnect(),this.statusChangeHandler?.("disconnected"),this.notification.warn("Session expired. Please log in again."),this.authFailureHandler?.();return}t=!0}this.reconnectAttempts++;try{if(this.socket&&(this.socket.disconnect(),this.socket=null),!e&&!await this.checkNetwork()){this.isOnline=!1,this.scheduleReconnect();return}this.isOnline=!0,await this.connect(),this.reconnectAttempts=0}catch(i){this.logger.warn("Reconnect failed",i),this.statusChangeHandler?.("error"),this.scheduleReconnect()}}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopNetworkCheck()}async checkNetwork(){let e=Date.now();if(e-this.lastNetworkCheck<1e3)return this.isOnline;this.lastNetworkCheck=e;try{let t=`${(0,kh.getApiUrl)(this.config)}/health`,i=new AbortController,n=setTimeout(()=>i.abort(),5e3),s=await fetch(t,{method:"GET",signal:i.signal});return clearTimeout(n),this.logger.debug("Network check OK",String(s.status)),!0}catch{return this.logger.debug("Network check failed (offline)"),!1}}startNetworkCheck(){this.stopNetworkCheck(),this.networkCheckTimer=setInterval(async()=>{if(this.isManualDisconnect){this.stopNetworkCheck();return}if(this.socket?.connected){this.stopNetworkCheck();return}let e=await this.checkNetwork();e&&!this.isOnline?(this.logger.info("Network restored! Triggering immediate reconnect"),this.isOnline=!0,this.stopNetworkCheck(),this.reconnectAttempts=0,this.attemptReconnect()):e&&this.isOnline?(this.stopNetworkCheck(),this.attemptReconnect()):e||(this.isOnline=!1)},this.NETWORK_CHECK_INTERVAL)}stopNetworkCheck(){this.networkCheckTimer&&(clearInterval(this.networkCheckTimer),this.networkCheckTimer=null)}};lo.WebSocketService=bc});var Ah=M(lr=>{"use strict";var U0=lr&&lr.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),K0=lr&&lr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Ec=lr&&lr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&U0(t,e,i[n]);return K0(t,e),t}})();Object.defineProperty(lr,"__esModule",{value:!0});lr.FileTransferService=void 0;var ho=Ec(require("fs")),q0=Ec(require("path")),Rh=Ec(require("crypto")),je=Sr(),vc=class{socket=null;activeTransfers=new Map;instanceId="";logger;fallbackDir;cryptoService=null;constructor(e,t="/tmp"){this.logger=e,this.fallbackDir=t}setCrypto(e){this.cryptoService=e}attach(e,t){this.socket=e,this.instanceId=t,this.setupEventHandlers(),this.logger.info("FileTransferService attached")}detach(){this.socket=null;for(let[e]of this.activeTransfers)this.cancelTransfer(e,"Disconnected");this.logger.info("FileTransferService detached")}async sendFile(e,t,i,n,s){let a=ho.readFileSync(t),c=t.split("/").pop()||"file";return this.initAndSendChunks(e,a,c,{mimeType:this.getMimeType(c),requestId:s,onProgress:i,onComplete:n})}async sendBuffer(e,t,i,n,s){return this.initAndSendChunks(e,t,i,{mimeType:n,purpose:s?.purpose,viewMetadata:s?.viewMetadata,requestId:s?.requestId,onProgress:s?.onProgress,onComplete:s?.onComplete})}async initAndSendChunks(e,t,i,n){if(!this.socket)throw new Error("Socket not connected");let s=t.length,a=(0,je.calculateTotalChunks)(s),c=this.calculateChecksum(t),u=Rh.randomUUID(),d={id:u,terminalId:e,filename:i,size:s,totalChunks:a,direction:je.TransferDirection.DOWNLOAD,status:je.TransferStatus.PENDING,deliveredChunks:new Set,pendingChunks:new Map,checksum:c,checksumAlgorithm:"sha256",onProgress:n.onProgress?(m,_)=>n.onProgress(u,m,_):void 0,onComplete:n.onComplete?(m,_)=>n.onComplete(u,m,_):void 0,ackTimeouts:new Map};d.chunks=[];for(let m=0;m<a;m++){let _=m*je.CHUNK_SIZE,E=Math.min(_+je.CHUNK_SIZE,s);d.chunks.push(t.subarray(_,E))}this.activeTransfers.set(u,d);let p={transferId:u,terminalId:e,filename:i,size:s,totalChunks:a,mimeType:n.mimeType||"application/octet-stream",checksum:c,direction:je.TransferDirection.DOWNLOAD,instanceId:this.instanceId};return n.requestId&&(p.requestId=n.requestId),n.purpose&&(p.purpose=n.purpose),n.viewMetadata&&(p.viewMetadata=n.viewMetadata),new Promise((m,_)=>{this.socket.emit("file:init",p,E=>{E.accepted?(d.status=je.TransferStatus.ACTIVE,this.startSendingChunks(u),m(u)):(this.activeTransfers.delete(u),_(new Error(E.error||"Transfer rejected")))})})}async receiveFile(e,t,i,n,s,a,c,u="sha256",d,p){let m={id:e,terminalId:t,filename:i,filePath:c,size:n,totalChunks:s,direction:je.TransferDirection.UPLOAD,status:je.TransferStatus.ACTIVE,deliveredChunks:new Set,pendingChunks:new Map,chunks:new Array(s).fill(null),checksum:a,checksumAlgorithm:u,onProgress:d?(_,E)=>d(e,_,E):void 0,onComplete:p?(_,E)=>p(e,_,E):void 0,ackTimeouts:new Map};this.activeTransfers.set(e,m)}cancelTransfer(e,t){let i=this.activeTransfers.get(e);if(i){for(let n of i.ackTimeouts.values())clearTimeout(n);if(i.status=je.TransferStatus.CANCELLED,i.onComplete?.(!1,t),this.socket){let n={transferId:e,reason:t};this.socket.emit("file:cancel",n)}this.activeTransfers.delete(e)}}async resumeTransfer(e){let t=this.activeTransfers.get(e);!t||!this.socket||this.socket.emit("file:sync",{transferId:e},i=>{if(i.status===je.TransferStatus.EXPIRED){t.onComplete?.(!1,"Transfer expired"),this.activeTransfers.delete(e);return}if(i.deliveredChunks)for(let n of i.deliveredChunks)t.deliveredChunks.add(n);if(t.direction===je.TransferDirection.DOWNLOAD&&i.missingChunks){t.status=je.TransferStatus.ACTIVE;for(let n of i.missingChunks)this.sendChunk(t,n)}})}getTransferStatus(e){return this.activeTransfers.get(e)?.status??null}getTransferProgress(e){let t=this.activeTransfers.get(e);return t?{delivered:t.deliveredChunks.size,total:t.totalChunks}:null}setupEventHandlers(){this.socket&&(this.socket.on("file:chunk",e=>{this.handleIncomingChunk(e)}),this.socket.on("file:chunk:ack",e=>{this.handleChunkAck(e)}),this.socket.on("file:complete",e=>{this.handleComplete(e)}),this.socket.on("file:progress",e=>{this.handleProgress(e)}),this.socket.on("file:init",(e,t)=>{this.handleIncomingFileInit(e,t)}),this.socket.on("file:cancel",e=>{let t=this.activeTransfers.get(e.transferId);if(t){for(let i of t.ackTimeouts.values())clearTimeout(i);t.status=je.TransferStatus.CANCELLED,t.onComplete?.(!1,e.reason||"Cancelled by remote"),this.activeTransfers.delete(e.transferId)}}))}startSendingChunks(e){let t=this.activeTransfers.get(e);if(!(!t||!t.chunks))for(let i=0;i<Math.min(je.WINDOW_SIZE,t.totalChunks);i++)t.deliveredChunks.has(i)||this.sendChunk(t,i)}sendChunk(e,t){if(!this.socket||!e.chunks)return;let i=e.chunks[t];if(!i)return;let n=e.pendingChunks.get(t),s={seq:t,data:i,retries:n?n.retries:0,sentAt:Date.now()};e.pendingChunks.set(t,s);let a=this.cryptoService?.encryptFileChunk(e.terminalId,new Uint8Array(i.buffer,i.byteOffset,i.byteLength));if(!a){this.cancelTransfer(e.id,"No E2E session for file transfer");return}let c={transferId:e.id,seq:t,encrypted:a};this.socket.emit("file:chunk",c,d=>{d&&!d.success&&this.cancelTransfer(e.id,d.error||"Server rejected chunk")});let u=setTimeout(()=>{this.handleAckTimeout(e.id,t)},je.ACK_TIMEOUT_MS);e.ackTimeouts.set(t,u)}handleChunkAck(e){let t=this.activeTransfers.get(e.transferId);if(!t||t.status===je.TransferStatus.COMPLETED)return;let i=t.ackTimeouts.get(e.seq);i&&(clearTimeout(i),t.ackTimeouts.delete(e.seq)),t.deliveredChunks.add(e.seq),t.pendingChunks.delete(e.seq),t.onProgress?.(t.deliveredChunks.size,t.totalChunks);let n=e.seq+je.WINDOW_SIZE;n<t.totalChunks&&!t.deliveredChunks.has(n)&&this.sendChunk(t,n),t.deliveredChunks.size===t.totalChunks&&this.finishSending(t)}handleAckTimeout(e,t){let i=this.activeTransfers.get(e);if(!i)return;let n=i.pendingChunks.get(t);n&&(n.retries<je.MAX_RETRIES?(n.retries++,this.sendChunk(i,t)):this.cancelTransfer(e,"Max retries exceeded"))}finishSending(e){if(!this.socket)return;e.status=je.TransferStatus.COMPLETED;let t={transferId:e.id,checksum:e.checksum};this.socket.emit("file:end",t)}handleIncomingChunk(e){let t=this.activeTransfers.get(e.transferId);if(!t||!t.chunks)return;let i=e.encrypted?this.cryptoService?.decryptFileChunk(t.terminalId,e.encrypted):null;if(!i){this.cancelTransfer(e.transferId,"Chunk decryption failed (no E2E session?)");return}if(t.chunks[e.seq]=Buffer.from(i),t.deliveredChunks.add(e.seq),this.socket){let n={transferId:e.transferId,seq:e.seq};this.socket.emit("file:chunk:ack",n)}t.onProgress?.(t.deliveredChunks.size,t.totalChunks),t.deliveredChunks.size===t.totalChunks&&this.finishReceiving(t)}finishReceiving(e){if(!e.chunks||!e.filePath)return;let t=Buffer.concat(e.chunks);if(this.calculateChecksum(t,e.checksumAlgorithm)!==e.checksum){e.status=je.TransferStatus.FAILED,e.onComplete?.(!1,"Checksum mismatch"),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:"Checksum mismatch"});return}try{let n=q0.dirname(e.filePath);ho.existsSync(n)||ho.mkdirSync(n,{recursive:!0}),ho.writeFileSync(e.filePath,t),e.status=je.TransferStatus.COMPLETED,e.onComplete?.(!0),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!0})}catch(n){let s=n instanceof Error?n.message:String(n);e.status=je.TransferStatus.FAILED,e.onComplete?.(!1,`Failed to save file: ${s}`),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:`Failed to save file: ${s}`})}this.activeTransfers.delete(e.id)}handleComplete(e){let t=this.activeTransfers.get(e.transferId);if(t){e.success?(t.status=je.TransferStatus.COMPLETED,t.onComplete?.(!0)):(t.status=je.TransferStatus.FAILED,t.onComplete?.(!1,e.error));for(let i of t.ackTimeouts.values())clearTimeout(i);this.activeTransfers.delete(e.transferId)}}handleProgress(e){let t=this.activeTransfers.get(e.transferId);t&&t.onProgress?.(e.deliveredChunks,e.totalChunks)}handleIncomingFileInit(e,t){let n=`${e.targetPath||this.fallbackDir}/${e.filename}`;this.receiveFile(e.transferId,e.terminalId,e.filename,e.size,e.totalChunks,e.checksum,n,e.checksumAlgorithm||"sha256").then(()=>t({accepted:!0})).catch(s=>t({accepted:!1,error:s.message}))}calculateChecksum(e,t="sha256"){return t==="fnv1a"?this.fnv1aHash(e):Rh.createHash("sha256").update(e).digest("hex")}fnv1aHash(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e[n],t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0").repeat(8)}getMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{txt:"text/plain",json:"application/json",js:"application/javascript",ts:"application/typescript",html:"text/html",css:"text/css",md:"text/markdown",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[t||""]||"application/octet-stream"}};lr.FileTransferService=vc});var Oc=M((kw,mo)=>{function Nh(r){return Array.isArray(r)?r:[r]}var W0=void 0,xc="",Ih=" ",wc="\\",H0=/^\s+$/,V0=/(?:[^\\]|^)\\$/,z0=/^\\!/,$0=/^\\#/,G0=/\r?\n/g,Y0=/^\.{0,2}\/|^\.{1,2}$/,X0=/\/$/,en="/",Mh="node-ignore";typeof Symbol<"u"&&(Mh=Symbol.for("node-ignore"));var Fh=Mh,tn=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),J0=/([0-z])-([0-z])/g,Dh=()=>!1,Z0=r=>r.replace(J0,(e,t,i)=>t.charCodeAt(0)<=i.charCodeAt(0)?e:xc),Q0=r=>{let{length:e}=r;return r.slice(0,e-e%2)},eb=[[/^\uFEFF/,()=>xc],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?Ih:xc)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+Ih}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let i=t.replace(/\\\*/g,"[^\\/]*");return e+i}],[/\\\\\\(?=[$.|*+(){^])/g,()=>wc],[/\\\\/g,()=>wc],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,i,n)=>e===wc?`\\[${t}${Q0(i)}${n}`:n==="]"&&i.length%2===0?`[${Z0(t)}${i}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],tb=/(^|\\\/)?\\\*$/,Bn="regex",po="checkRegex",Lh="_",rb={[Bn](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[po](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},ib=r=>eb.reduce((e,[t,i])=>e.replace(t,i.bind(r)),r),go=r=>typeof r=="string",nb=r=>r&&go(r)&&!H0.test(r)&&!V0.test(r)&&r.indexOf("#")!==0,sb=r=>r.split(G0).filter(Boolean),Sc=class{constructor(e,t,i,n,s,a){this.pattern=e,this.mark=t,this.negative=s,tn(this,"body",i),tn(this,"ignoreCase",n),tn(this,"regexPrefix",a)}get regex(){let e=Lh+Bn;return this[e]?this[e]:this._make(Bn,e)}get checkRegex(){let e=Lh+po;return this[e]?this[e]:this._make(po,e)}_make(e,t){let i=this.regexPrefix.replace(tb,rb[e]),n=this.ignoreCase?new RegExp(i,"i"):new RegExp(i);return tn(this,t,n)}},ob=({pattern:r,mark:e},t)=>{let i=!1,n=r;n.indexOf("!")===0&&(i=!0,n=n.substr(1)),n=n.replace(z0,"!").replace($0,"#");let s=ib(n);return new Sc(r,e,n,t,i,s)},Tc=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[Fh]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(go(e)&&(e={pattern:e}),nb(e.pattern)){let t=ob(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,Nh(go(e)?sb(e):e).forEach(this._add,this),this._added}test(e,t,i){let n=!1,s=!1,a;this._rules.forEach(u=>{let{negative:d}=u;s===d&&n!==s||d&&!n&&!s&&!t||!u[i].test(e)||(n=!d,s=d,a=d?W0:u)});let c={ignored:n,unignored:s};return a&&(c.rule=a),c}},ab=(r,e)=>{throw new e(r)},Ar=(r,e,t)=>go(r)?r?Ar.isNotRelative(r)?t(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:t("path must not be empty",TypeError):t(`path must be a string, but got \`${e}\``,TypeError),Bh=r=>Y0.test(r);Ar.isNotRelative=Bh;Ar.convert=r=>r;var Cc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:i=!1}={}){tn(this,Fh,!0),this._rules=new Tc(t),this._strictPathCheck=!i,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,t,i,n){let s=e&&Ar.convert(e);return Ar(s,e,this._strictPathCheck?ab:Dh),this._t(s,t,i,n)}checkIgnore(e){if(!X0.test(e))return this.test(e);let t=e.split(en).filter(Boolean);if(t.pop(),t.length){let i=this._t(t.join(en)+en,this._testCache,!0,t);if(i.ignored)return i}return this._rules.test(e,!1,po)}_t(e,t,i,n){if(e in t)return t[e];if(n||(n=e.split(en).filter(Boolean)),n.pop(),!n.length)return t[e]=this._rules.test(e,i,Bn);let s=this._t(n.join(en)+en,t,i,n);return t[e]=s.ignored?s:this._rules.test(e,i,Bn)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return Nh(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},kc=r=>new Cc(r),cb=r=>Ar(r&&Ar.convert(r),r,Dh),jh=()=>{let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");Ar.convert=r;let e=/^[a-z]:\//i;Ar.isNotRelative=t=>e.test(t)||Bh(t)};typeof process<"u"&&process.platform==="win32"&&jh();mo.exports=kc;kc.default=kc;mo.exports.isPathValid=cb;tn(mo.exports,Symbol.for("setupWindows"),jh)});var Kh=M(Ut=>{"use strict";var fb=Ut&&Ut.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),ub=Ut&&Ut.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Uh=Ut&&Ut.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&fb(t,e,i[n]);return ub(t,e),t}})(),lb=Ut&&Ut.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ut,"__esModule",{value:!0});Ut.FileListService=void 0;var rn=Uh(require("path")),Pc=Uh(require("fs/promises")),hb=lb(Oc()),Rc=Sr(),db=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],Ac=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,hb.default)(),this.ignoreFilter.add(db),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=rn.join(this.workspaceRoot,".gitignore");try{let t=await Pc.readFile(e,"utf-8");this.ignoreFilter.add(t)}catch{}}onResponse(e){this.onResponseCallback=e}async handleListRequest(e){if(!this.workspaceRoot){this.sendResponse({requestId:e.requestId,path:e.path,entries:[],error:"No workspace root"});return}try{let t=this.resolvePath(e.path),i=await this.listDirectory(t,e.path);this.sendResponse({requestId:e.requestId,path:e.path,entries:i})}catch(t){this.logger.error("Failed to list directory",String(t)),this.sendResponse({requestId:e.requestId,path:e.path,entries:[],error:t instanceof Error?t.message:"Unknown error"})}}async listDirectory(e,t){let i=await Pc.readdir(e,{withFileTypes:!0}),n=[];for(let s of i){let a=t==="."||t===""?s.name:rn.join(t,s.name);if(this.shouldHide(a,s.isDirectory()))continue;let c=rn.join(e,s.name),u={name:s.name,path:a,type:s.isDirectory()?Rc.FileEntryType.DIRECTORY:Rc.FileEntryType.FILE};if(!s.isDirectory())try{let d=await Pc.stat(c);u.size=d.size,u.modified=d.mtime.toISOString()}catch{}n.push(u)}return n.sort((s,a)=>s.type!==a.type?s.type===Rc.FileEntryType.DIRECTORY?-1:1:s.name.localeCompare(a.name))}shouldHide(e,t){let i=e.split(rn.sep).join("/"),n=t?`${i}/`:i;return this.ignoreFilter.ignores(n)}resolvePath(e){if(!this.workspaceRoot)throw new Error("No workspace root");if(e==="."||e==="")return this.workspaceRoot;let t=rn.resolve(this.workspaceRoot,e);if(t!==this.workspaceRoot&&!t.startsWith(this.workspaceRoot+rn.sep))throw new Error("Path outside workspace");return t}sendResponse(e){this.onResponseCallback?.(e)}dispose(){this.onResponseCallback=null}};Ut.FileListService=Ac});var Wh=M(hr=>{"use strict";var pb=hr&&hr.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),gb=hr&&hr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),qh=hr&&hr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&pb(t,e,i[n]);return gb(t,e),t}})();Object.defineProperty(hr,"__esModule",{value:!0});hr.FileTrackerService=void 0;var Ic=qh(require("path")),Ti=qh(require("fs/promises")),mb=require("child_process"),yb=require("util"),Gt=Sr(),Lc=(0,yb.promisify)(mb.execFile),Nc={toolStart:/⏺\s*(Write|Edit|NotebookEdit)\s*\(\s*(?:file_path|notebook_path)\s*=\s*"([^"]+)"/,toolSuccess:/[✓✔]\s*(?:Wrote|Edited|Updated|Created)\s+([^\s\n]+)/,toolError:/[✗✘]\s*(?:Failed|Error)/i},Mc=class{trackedFiles=new Map;pendingToolCalls=new Map;outputBuffers=new Map;workspaceRoot;onFileChangedCallback=null;onFileViewTransferCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t}onFileChanged(e){this.onFileChangedCallback=e}onFileViewTransfer(e){this.onFileViewTransferCallback=e}async processOutput(e,t){let i=this.outputBuffers.get(e)||"";i+=t,i.length>10240&&(i=i.slice(-10240)),this.outputBuffers.set(e,i);try{await this.parseToolCalls(e,i)}catch(n){this.logger.error("Error parsing tool calls",n)}}async parseToolCalls(e,t){let i=this.stripAnsi(t),n=i.match(Nc.toolStart);if(n){let a=n[1],c=n[2],u=`${a}_${Date.now()}_${c}`;this.pendingToolCalls.has(u)||await this.handleToolStart(e,u,a,{file_path:c})}let s=i.match(Nc.toolSuccess);if(s){let a=s[1];for(let[c,u]of this.pendingToolCalls)if(u.filePath===a||a.endsWith(u.filePath)||u.filePath.endsWith(a)){await this.handleToolEnd(e,c,u.toolName,"success");break}}if(Nc.toolError.test(i))for(let[a,c]of this.pendingToolCalls)await this.handleToolEnd(e,a,c.toolName,"error")}stripAnsi(e){return e.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\x1b\][^\x07]*\x07/g,"").replace(/\x1b[()][AB012]/g,"").replace(/\x1b[=>]/g,"").replace(/\x1b[78DMEHc]/g,"")}async handleToolStart(e,t,i,n){if(!this.isFileModifyingTool(i))return;let s=this.extractFilePath(i,n);if(!s)return;let a=this.resolveFilePath(s),c={toolId:t,toolName:i,filePath:s,timestamp:new Date().toISOString()};this.pendingToolCalls.set(t,c);let u;try{u=await Ti.readFile(a,"utf-8")}catch{u=void 0}let d={path:s,changeType:u===void 0?Gt.FileChangeType.CREATE:Gt.FileChangeType.MODIFY,toolName:i,toolId:t,timestamp:c.timestamp,previousContent:u},p=this.trackedFiles.get(e)||[];p.push(d),this.trackedFiles.set(e,p)}async handleToolEnd(e,t,i,n){if(!this.isFileModifyingTool(i)||!this.pendingToolCalls.get(t))return;if(this.pendingToolCalls.delete(t),n==="error"){let p=this.trackedFiles.get(e)||[],m=p.findIndex(_=>_.toolId===t);m!==-1&&p.splice(m,1);return}let c=(this.trackedFiles.get(e)||[]).find(p=>p.toolId===t);if(!c)return;let u=this.resolveFilePath(c.path);try{let p=await Ti.stat(u);c.size=p.size}catch{c.changeType=Gt.FileChangeType.DELETE,c.size=void 0}let d={path:c.path,changeType:c.changeType,timestamp:new Date().toISOString(),source:"tool-call",toolName:c.toolName,toolId:c.toolId,size:c.size};this.onFileChangedCallback?.(e,d)}async handleViewRequest(e,t){let i=this.resolveFilePath(t.path),n=this.getViewableMimeType(t.path);if(n&&this.onFileViewTransferCallback){try{let a=await Ti.readFile(i),c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:n};this.onFileViewTransferCallback(e,Buffer.from(a),c)}catch(a){let c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:n,error:a instanceof Error?a.message:"Unknown error"};this.onFileViewTransferCallback(e,Buffer.alloc(0),c)}return}let s;try{t.type===Gt.FileViewType.CONTENT?s=await this.getFileContent(t,i):s=await this.getFileDiff(e,t,i)}catch(a){s={requestId:t.requestId,path:t.path,type:t.type,error:a instanceof Error?a.message:"Unknown error"}}if(this.onFileViewTransferCallback){let a={requestId:t.requestId,path:t.path,viewType:s.type===Gt.FileViewType.CONTENT?"content":"diff",language:s.language,truncated:s.truncated,error:s.error},c=Buffer.from(s.content||"","utf-8");this.onFileViewTransferCallback(e,c,a)}}getViewableMimeType(e){let t=e.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf"}[t||""]||null}async getFileContent(e,t){let i=e.maxSize||1048576,n=await Ti.stat(t),s=await Ti.readFile(t,"utf-8"),a=!1,c=s;return s.length>i&&(c=s.slice(0,i),a=!0),{requestId:e.requestId,path:e.path,type:Gt.FileViewType.CONTENT,content:c,language:(0,Gt.getLanguageFromPath)(e.path),size:n.size,truncated:a}}async getFileDiff(e,t,i){let n=t.diffBase||Gt.DiffBase.GIT,s;return n===Gt.DiffBase.GIT?s=await this.getGitDiff(i):s=await this.getPreviousDiff(e,t.path,i),{requestId:t.requestId,path:t.path,type:Gt.FileViewType.DIFF,content:s,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await Lc("git",["diff","--cached","--",e],{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:i}=await Lc("git",["diff","--",e],{cwd:this.workspaceRoot});if(i.trim())return i;let{stdout:n}=await Lc("git",["status","--porcelain","--",e],{cwd:this.workspaceRoot});if(n.startsWith("??")||n.startsWith("A ")){let a=(await Ti.readFile(e,"utf-8")).split(`
|
|
29
29
|
`),c=Ic.relative(this.workspaceRoot,e);return[`diff --git a/${c} b/${c}`,"new file mode 100644","--- /dev/null",`+++ b/${c}`,`@@ -0,0 +1,${a.length} @@`,...a.map(u=>`+${u}`)].join(`
|
|
30
30
|
`)}return"(no changes)"}catch{throw new Error("Git not available")}}async getPreviousDiff(e,t,i){let a=(this.trackedFiles.get(e)||[]).find(d=>d.path===t&&d.previousContent!==void 0)?.previousContent||"",c;try{c=await Ti.readFile(i,"utf-8")}catch{c=""}let u=(0,Gt.createSimpleDiff)(a,c,t);return this.diffContentToUnifiedText(u)}diffContentToUnifiedText(e){let t=[];t.push(`--- a/${e.path}`),t.push(`+++ b/${e.path}`);for(let i of e.hunks){t.push(`@@ -${i.oldStart},${i.oldLines} +${i.newStart},${i.newLines} @@`);for(let n of i.lines)switch(n.type){case"add":t.push(`+${n.content}`);break;case"remove":t.push(`-${n.content}`);break;case"context":t.push(` ${n.content}`);break}}return t.join(`
|
|
31
31
|
`)}clearTerminal(e){this.trackedFiles.delete(e),this.outputBuffers.delete(e)}getChangedFiles(e){return(this.trackedFiles.get(e)||[]).map(i=>({path:i.path,changeType:i.changeType,timestamp:i.timestamp,source:"tool-call",toolName:i.toolName,toolId:i.toolId,size:i.size}))}isFileModifyingTool(e){return["Write","Edit","NotebookEdit"].includes(e)}extractFilePath(e,t){return t?e==="Write"||e==="Edit"?t.file_path||null:e==="NotebookEdit"&&t.notebook_path||null:null}resolveFilePath(e){let t=this.workspaceRoot;if(!t)throw new Error("No workspace root configured");let i=Ic.resolve(t,e);if(i!==t&&!i.startsWith(t+Ic.sep))throw new Error("Path escapes workspace root");return i}dispose(){this.trackedFiles.clear(),this.pendingToolCalls.clear(),this.onFileChangedCallback=null,this.onFileViewTransferCallback=null}};hr.FileTrackerService=Mc});var Vh=M(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.InputStreamReceiver=tt.FileTrackerService=tt.FileListService=tt.FileTransferService=tt.WebSocketService=tt.isAnswerKeystroke=tt.StatusDetector=tt.AuthService=tt.CryptoService=void 0;var _b=gu();Object.defineProperty(tt,"CryptoService",{enumerable:!0,get:function(){return _b.CryptoService}});var bb=mu();Object.defineProperty(tt,"AuthService",{enumerable:!0,get:function(){return bb.AuthService}});var Hh=yu();Object.defineProperty(tt,"StatusDetector",{enumerable:!0,get:function(){return Hh.StatusDetector}});Object.defineProperty(tt,"isAnswerKeystroke",{enumerable:!0,get:function(){return Hh.isAnswerKeystroke}});var vb=Ph();Object.defineProperty(tt,"WebSocketService",{enumerable:!0,get:function(){return vb.WebSocketService}});var Eb=Ah();Object.defineProperty(tt,"FileTransferService",{enumerable:!0,get:function(){return Eb.FileTransferService}});var wb=Kh();Object.defineProperty(tt,"FileListService",{enumerable:!0,get:function(){return wb.FileListService}});var xb=Wh();Object.defineProperty(tt,"FileTrackerService",{enumerable:!0,get:function(){return xb.FileTrackerService}});var Sb=_c();Object.defineProperty(tt,"InputStreamReceiver",{enumerable:!0,get:function(){return Sb.InputStreamReceiver}})});var jn=M(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.FP_LABEL=X.KX_ACK_LABEL=X.KX_SIGN_LABEL=X.concatBytes=X.fingerprintShortHex=X.fingerprintIdentityKey=X.buildKxAckCanonical=X.buildKxCanonical=X.verifySessionKey=X.signSessionKey=X.identityPublicFromSecret=X.generateIdentityKeyPair=X.InputStreamReceiver=X.FileTrackerService=X.FileListService=X.FileTransferService=X.WebSocketService=X.isAnswerKeystroke=X.StatusDetector=X.AuthService=X.CryptoService=X.getCurrentCorrelationId=X.runWithCorrelation=X.generateCorrelationId=X.getWsUrl=X.getApiUrl=X.CircularBuffer=X.formatLogLine=X.shouldLog=X.LOG_LEVELS=void 0;var Fc=Lf();Object.defineProperty(X,"LOG_LEVELS",{enumerable:!0,get:function(){return Fc.LOG_LEVELS}});Object.defineProperty(X,"shouldLog",{enumerable:!0,get:function(){return Fc.shouldLog}});Object.defineProperty(X,"formatLogLine",{enumerable:!0,get:function(){return Fc.formatLogLine}});var nn=Ff();Object.defineProperty(X,"CircularBuffer",{enumerable:!0,get:function(){return nn.CircularBuffer}});Object.defineProperty(X,"getApiUrl",{enumerable:!0,get:function(){return nn.getApiUrl}});Object.defineProperty(X,"getWsUrl",{enumerable:!0,get:function(){return nn.getWsUrl}});Object.defineProperty(X,"generateCorrelationId",{enumerable:!0,get:function(){return nn.generateCorrelationId}});Object.defineProperty(X,"runWithCorrelation",{enumerable:!0,get:function(){return nn.runWithCorrelation}});Object.defineProperty(X,"getCurrentCorrelationId",{enumerable:!0,get:function(){return nn.getCurrentCorrelationId}});var Ir=Vh();Object.defineProperty(X,"CryptoService",{enumerable:!0,get:function(){return Ir.CryptoService}});Object.defineProperty(X,"AuthService",{enumerable:!0,get:function(){return Ir.AuthService}});Object.defineProperty(X,"StatusDetector",{enumerable:!0,get:function(){return Ir.StatusDetector}});Object.defineProperty(X,"isAnswerKeystroke",{enumerable:!0,get:function(){return Ir.isAnswerKeystroke}});Object.defineProperty(X,"WebSocketService",{enumerable:!0,get:function(){return Ir.WebSocketService}});Object.defineProperty(X,"FileTransferService",{enumerable:!0,get:function(){return Ir.FileTransferService}});Object.defineProperty(X,"FileListService",{enumerable:!0,get:function(){return Ir.FileListService}});Object.defineProperty(X,"FileTrackerService",{enumerable:!0,get:function(){return Ir.FileTrackerService}});Object.defineProperty(X,"InputStreamReceiver",{enumerable:!0,get:function(){return Ir.InputStreamReceiver}});var Kt=Zo();Object.defineProperty(X,"generateIdentityKeyPair",{enumerable:!0,get:function(){return Kt.generateIdentityKeyPair}});Object.defineProperty(X,"identityPublicFromSecret",{enumerable:!0,get:function(){return Kt.identityPublicFromSecret}});Object.defineProperty(X,"signSessionKey",{enumerable:!0,get:function(){return Kt.signSessionKey}});Object.defineProperty(X,"verifySessionKey",{enumerable:!0,get:function(){return Kt.verifySessionKey}});Object.defineProperty(X,"buildKxCanonical",{enumerable:!0,get:function(){return Kt.buildKxCanonical}});Object.defineProperty(X,"buildKxAckCanonical",{enumerable:!0,get:function(){return Kt.buildKxAckCanonical}});Object.defineProperty(X,"fingerprintIdentityKey",{enumerable:!0,get:function(){return Kt.fingerprintIdentityKey}});Object.defineProperty(X,"fingerprintShortHex",{enumerable:!0,get:function(){return Kt.fingerprintShortHex}});Object.defineProperty(X,"concatBytes",{enumerable:!0,get:function(){return Kt.concatBytes}});Object.defineProperty(X,"KX_SIGN_LABEL",{enumerable:!0,get:function(){return Kt.KX_SIGN_LABEL}});Object.defineProperty(X,"KX_ACK_LABEL",{enumerable:!0,get:function(){return Kt.KX_ACK_LABEL}});Object.defineProperty(X,"FP_LABEL",{enumerable:!0,get:function(){return Kt.FP_LABEL}})});var Uc=M((Kn,jc)=>{(function(r,e){typeof Kn=="object"&&typeof jc=="object"?jc.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof Kn=="object"?Kn["electron-machine-id"]=e(require("child_process"),require("crypto")):r["electron-machine-id"]=e(r.child_process,r.crypto)})(Kn,function(r,e){return(function(t){function i(s){if(n[s])return n[s].exports;var a=n[s]={exports:{},id:s,loaded:!1};return t[s].call(a.exports,a,a.exports,i),a.loaded=!0,a.exports}var n={};return i.m=t,i.c=n,i.p="",i(0)})([function(t,i,n){t.exports=n(34)},function(t,i,n){var s=n(29)("wks"),a=n(33),c=n(2).Symbol,u=typeof c=="function",d=t.exports=function(p){return s[p]||(s[p]=u&&c[p]||(u?c:a)("Symbol."+p))};d.store=s},function(t,i){var n=t.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=n)},function(t,i,n){var s=n(9);t.exports=function(a){if(!s(a))throw TypeError(a+" is not an object!");return a}},function(t,i,n){t.exports=!n(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(t,i,n){var s=n(12),a=n(17);t.exports=n(4)?function(c,u,d){return s.f(c,u,a(1,d))}:function(c,u,d){return c[u]=d,c}},function(t,i){var n=t.exports={version:"2.4.0"};typeof __e=="number"&&(__e=n)},function(t,i,n){var s=n(14);t.exports=function(a,c,u){if(s(a),c===void 0)return a;switch(u){case 1:return function(d){return a.call(c,d)};case 2:return function(d,p){return a.call(c,d,p)};case 3:return function(d,p,m){return a.call(c,d,p,m)}}return function(){return a.apply(c,arguments)}}},function(t,i){var n={}.hasOwnProperty;t.exports=function(s,a){return n.call(s,a)}},function(t,i){t.exports=function(n){return typeof n=="object"?n!==null:typeof n=="function"}},function(t,i){t.exports={}},function(t,i){var n={}.toString;t.exports=function(s){return n.call(s).slice(8,-1)}},function(t,i,n){var s=n(3),a=n(26),c=n(32),u=Object.defineProperty;i.f=n(4)?Object.defineProperty:function(d,p,m){if(s(d),p=c(p,!0),s(m),a)try{return u(d,p,m)}catch{}if("get"in m||"set"in m)throw TypeError("Accessors not supported!");return"value"in m&&(d[p]=m.value),d}},function(t,i,n){var s=n(42),a=n(15);t.exports=function(c){return s(a(c))}},function(t,i){t.exports=function(n){if(typeof n!="function")throw TypeError(n+" is not a function!");return n}},function(t,i){t.exports=function(n){if(n==null)throw TypeError("Can't call method on "+n);return n}},function(t,i,n){var s=n(9),a=n(2).document,c=s(a)&&s(a.createElement);t.exports=function(u){return c?a.createElement(u):{}}},function(t,i){t.exports=function(n,s){return{enumerable:!(1&n),configurable:!(2&n),writable:!(4&n),value:s}}},function(t,i,n){var s=n(12).f,a=n(8),c=n(1)("toStringTag");t.exports=function(u,d,p){u&&!a(u=p?u:u.prototype,c)&&s(u,c,{configurable:!0,value:d})}},function(t,i,n){var s=n(29)("keys"),a=n(33);t.exports=function(c){return s[c]||(s[c]=a(c))}},function(t,i){var n=Math.ceil,s=Math.floor;t.exports=function(a){return isNaN(a=+a)?0:(a>0?s:n)(a)}},function(t,i,n){var s=n(11),a=n(1)("toStringTag"),c=s((function(){return arguments})())=="Arguments",u=function(d,p){try{return d[p]}catch{}};t.exports=function(d){var p,m,_;return d===void 0?"Undefined":d===null?"Null":typeof(m=u(p=Object(d),a))=="string"?m:c?s(p):(_=s(p))=="Object"&&typeof p.callee=="function"?"Arguments":_}},function(t,i){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,i,n){var s=n(2),a=n(6),c=n(7),u=n(5),d="prototype",p=function(m,_,E){var S,T,z,ge=m&p.F,ee=m&p.G,R=m&p.S,B=m&p.P,re=m&p.B,K=m&p.W,U=ee?a:a[_]||(a[_]={}),ye=U[d],xe=ee?s:R?s[_]:(s[_]||{})[d];ee&&(E=_);for(S in E)T=!ge&&xe&&xe[S]!==void 0,T&&S in U||(z=T?xe[S]:E[S],U[S]=ee&&typeof xe[S]!="function"?E[S]:re&&T?c(z,s):K&&xe[S]==z?(function(ue){var rt=function(Ee,Se,ve){if(this instanceof ue){switch(arguments.length){case 0:return new ue;case 1:return new ue(Ee);case 2:return new ue(Ee,Se)}return new ue(Ee,Se,ve)}return ue.apply(this,arguments)};return rt[d]=ue[d],rt})(z):B&&typeof z=="function"?c(Function.call,z):z,B&&((U.virtual||(U.virtual={}))[S]=z,m&p.R&&ye&&!ye[S]&&u(ye,S,z)))};p.F=1,p.G=2,p.S=4,p.P=8,p.B=16,p.W=32,p.U=64,p.R=128,t.exports=p},function(t,i){t.exports=function(n){try{return!!n()}catch{return!0}}},function(t,i,n){t.exports=n(2).document&&document.documentElement},function(t,i,n){t.exports=!n(4)&&!n(24)(function(){return Object.defineProperty(n(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(t,i,n){"use strict";var s=n(28),a=n(23),c=n(57),u=n(5),d=n(8),p=n(10),m=n(45),_=n(18),E=n(52),S=n(1)("iterator"),T=!([].keys&&"next"in[].keys()),z="@@iterator",ge="keys",ee="values",R=function(){return this};t.exports=function(B,re,K,U,ye,xe,ue){m(K,re,U);var rt,Ee,Se,ve=function(j){if(!T&&j in Te)return Te[j];switch(j){case ge:return function(){return new K(this,j)};case ee:return function(){return new K(this,j)}}return function(){return new K(this,j)}},We=re+" Iterator",st=ye==ee,Ze=!1,Te=B.prototype,it=Te[S]||Te[z]||ye&&Te[ye],ze=it||ve(ye),gt=ye?st?ve("entries"):ze:void 0,L=re=="Array"&&Te.entries||it;if(L&&(Se=E(L.call(new B)),Se!==Object.prototype&&(_(Se,We,!0),s||d(Se,S)||u(Se,S,R))),st&&it&&it.name!==ee&&(Ze=!0,ze=function(){return it.call(this)}),s&&!ue||!T&&!Ze&&Te[S]||u(Te,S,ze),p[re]=ze,p[We]=R,ye)if(rt={values:st?ze:ve(ee),keys:xe?ze:ve(ge),entries:gt},ue)for(Ee in rt)Ee in Te||c(Te,Ee,rt[Ee]);else a(a.P+a.F*(T||Ze),re,rt);return rt}},function(t,i){t.exports=!0},function(t,i,n){var s=n(2),a="__core-js_shared__",c=s[a]||(s[a]={});t.exports=function(u){return c[u]||(c[u]={})}},function(t,i,n){var s,a,c,u=n(7),d=n(41),p=n(25),m=n(16),_=n(2),E=_.process,S=_.setImmediate,T=_.clearImmediate,z=_.MessageChannel,ge=0,ee={},R="onreadystatechange",B=function(){var K=+this;if(ee.hasOwnProperty(K)){var U=ee[K];delete ee[K],U()}},re=function(K){B.call(K.data)};S&&T||(S=function(K){for(var U=[],ye=1;arguments.length>ye;)U.push(arguments[ye++]);return ee[++ge]=function(){d(typeof K=="function"?K:Function(K),U)},s(ge),ge},T=function(K){delete ee[K]},n(11)(E)=="process"?s=function(K){E.nextTick(u(B,K,1))}:z?(a=new z,c=a.port2,a.port1.onmessage=re,s=u(c.postMessage,c,1)):_.addEventListener&&typeof postMessage=="function"&&!_.importScripts?(s=function(K){_.postMessage(K+"","*")},_.addEventListener("message",re,!1)):s=R in m("script")?function(K){p.appendChild(m("script"))[R]=function(){p.removeChild(this),B.call(K)}}:function(K){setTimeout(u(B,K,1),0)}),t.exports={set:S,clear:T}},function(t,i,n){var s=n(20),a=Math.min;t.exports=function(c){return c>0?a(s(c),9007199254740991):0}},function(t,i,n){var s=n(9);t.exports=function(a,c){if(!s(a))return a;var u,d;if(c&&typeof(u=a.toString)=="function"&&!s(d=u.call(a))||typeof(u=a.valueOf)=="function"&&!s(d=u.call(a))||!c&&typeof(u=a.toString)=="function"&&!s(d=u.call(a)))return d;throw TypeError("Can't convert object to primitive value")}},function(t,i){var n=0,s=Math.random();t.exports=function(a){return"Symbol(".concat(a===void 0?"":a,")_",(++n+s).toString(36))}},function(t,i,n){"use strict";function s(R){return R&&R.__esModule?R:{default:R}}function a(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function c(R){return(0,S.createHash)("sha256").update(R).digest("hex")}function u(R){switch(z){case"darwin":return R.split("IOPlatformUUID")[1].split(`
|
|
@@ -50,7 +50,7 @@ tell application "System Events" to get value of property list item "CFBundleNam
|
|
|
50
50
|
`),await No(ge,a,i)||process.exit(1),ee=!0);let R;try{let{machineIdSync:P}=await Promise.resolve().then(()=>fe(Uc()));R=P()}catch{R=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}let B,re=new ut.StatusDetector((P,Z,Ne)=>{if(!U.getStatus().connected)return;let Xe=B;B=Z,U.updateStatus({instanceId:ue,terminalId:P,status:Z,encryptedPrompt:Ne&&T.encryptPromptInfo(Ne)||void 0}).catch(()=>{});let lt=rp(Z,Xe,Ne);lt&&U.sendTerminalEvent(ue,P,lt)}),K=p?[np.Capability.MULTI_VIEWER_RENDER]:[],U=new ut.WebSocketService(ge,T,t,i,s,R,"cli",K);p&&i.info("Multi-viewer rendering capability advertised");let ye=!1;U.onStatusChange(P=>{if(P==="connected"){if(ye)i.info("Reconnected to termiq.io");else{let Z=p?" (multi-viewer mode)":"";process.stderr.write(`Connected to termiq.io${Z}
|
|
51
51
|
`),ye=!0}m.update({online:!0})}else P==="disconnected"?(i.info("Disconnected from termiq.io (will retry)"),m.update({online:!1})):P==="error"&&(i.warn("Connection degraded (no server response) \u2014 reconnecting"),m.update({online:!1}))}),U.onAuthFailure(()=>{process.stderr.write(`Session expired. Please run "termiq login" again.
|
|
52
52
|
`),A(),process.exit(1)});try{await U.connect()}catch(P){process.stderr.write(`Connection failed: ${P instanceof Error?P.message:String(P)}
|
|
53
|
-
`),process.exit(1)}let xe=ip.basename(c),ue=`cli_${Date.now()}`,rt=T.encryptWorkspaceInfo({name:xe,path:c});await U.registerWorkspace({instanceId:ue,encryptedInfo:rt||void 0});let Ee=new xo(i);p&&Ee.setMultiViewerMode(!0),Ee.setPreWriteHook(P=>m.inspectPtyOutput(P));let Se=null;Ee.setOnResize((P,Z)=>{m.update({ptyCols:P,ptyRows:Z}),p&&Se&&U.sendPtyResized(ue,Se,P,Z)}),Ee.setOnLocalClaim((P,Z)=>{p&&Se&&U.sendClaimControl(ue,Se,P,Z)});let ve=Ee.spawn(c,m.reservedRows()),We=`CLI: ${xe}`,st=process.env.SHELL||"/bin/bash",Ze=T.encryptTerminalInfo({name:We,command:st,cwd:c});await U.terminalCreated({instanceId:ue,terminalId:ve,encryptedInfo:Ze||void 0,streamId:Ee.getStreamId()??void 0}),Se=ve,p&&U.sendPtyResized(ue,ve,Ee.getPtyCols(),Ee.getPtyRows());let Te=new ut.FileTransferService(i);Te.setCrypto(T);let it=new ut.FileTrackerService(i,c),ze=new ut.FileListService(i,c),gt=u?new Io(i,c):null,L=U.getSocket();L&&Te.attach(L,ue),it.onFileChanged((P,Z)=>{U.sendFileChangedEvent(ue,P,Z)}),it.onFileViewTransfer(async(P,Z,Ne)=>{try{await Te.sendBuffer(P,Z,Ne.path.split("/").pop()||"view",Ne.mimeType||"text/plain",{purpose:"view",viewMetadata:Ne})}catch(Xe){i.error("File view transfer failed",Xe)}}),U.onFileViewRequest((P,Z)=>{it.handleViewRequest(P,Z)}),U.onFileListRequest((P,Z)=>{ze.handleListRequest(Z)}),ze.onResponse(P=>{U.sendFileListResponse(ue,P)}),U.onFileDownloadRequest(async(P,Z,Ne)=>{try{await Te.sendFile(P,Z,void 0,void 0,Ne)}catch(Xe){i.error("File download failed",Xe)}}),gt&&(gt.onFileChanged(P=>{U.sendFileChangedEvent(ue,ve,P)}),gt.start()),re.startTracking(ve),Ee.setOnOutput(P=>{U.sendOutput(ue,ve,P),re.processOutput(ve,P),it.processOutput(ve,P)}),Ee.setOnLocalInput(P=>{(0,ut.isAnswerKeystroke)(P)&&re.resolvePrompt(ve)}),U.onInput((P,Z,Ne,Xe)=>{P===ve&&((0,ut.isAnswerKeystroke)(Z)&&re.resolvePrompt(ve),Ee.write(Z,Xe))}),U.setTerminalActiveCheck(P=>P===ve&&Ee.isAlive()),U.onResizeRequest((P,Z,Ne)=>{P===ve&&(i.info("Remote resize received",{terminalId:P,cols:Z,rows:Ne}),Ee.resize(Z,Ne))}),U.onClientAttached(({clientCount:P})=>{Ee.setSigwinchEnabled(!1),m.update({viewerCount:P}),U.sendInputResume(ve)}),U.onClientDetached(({clientCount:P})=>{P===0&&Ee.setSigwinchEnabled(!0),m.update({viewerCount:P})}),U.onGetBufferRequest(P=>P===ve?Ee.getBuffer():null),U.onRedrawRequest(P=>{P===ve&&Ee.redrawNoResize()});async function j(){let P=T.encryptWorkspaceInfo({name:xe,path:c});await U.registerWorkspace({instanceId:ue,encryptedInfo:P||void 0});let Z=T.encryptTerminalInfo({name:We,command:st,cwd:c});await U.terminalCreated({instanceId:ue,terminalId:ve,encryptedInfo:Z||void 0,streamId:Ee.getStreamId()??void 0})}U.onMetaSessionEstablished(
|
|
53
|
+
`),process.exit(1)}let xe=ip.basename(c),ue=`cli_${Date.now()}`,rt=T.encryptWorkspaceInfo({name:xe,path:c});await U.registerWorkspace({instanceId:ue,encryptedInfo:rt||void 0});let Ee=new xo(i);p&&Ee.setMultiViewerMode(!0),Ee.setPreWriteHook(P=>m.inspectPtyOutput(P));let Se=null;Ee.setOnResize((P,Z)=>{m.update({ptyCols:P,ptyRows:Z}),p&&Se&&U.sendPtyResized(ue,Se,P,Z)}),Ee.setOnLocalClaim((P,Z)=>{p&&Se&&U.sendClaimControl(ue,Se,P,Z)});let ve=Ee.spawn(c,m.reservedRows()),We=`CLI: ${xe}`,st=process.env.SHELL||"/bin/bash",Ze=T.encryptTerminalInfo({name:We,command:st,cwd:c});await U.terminalCreated({instanceId:ue,terminalId:ve,encryptedInfo:Ze||void 0,streamId:Ee.getStreamId()??void 0}),Se=ve,p&&U.sendPtyResized(ue,ve,Ee.getPtyCols(),Ee.getPtyRows());let Te=new ut.FileTransferService(i);Te.setCrypto(T);let it=new ut.FileTrackerService(i,c),ze=new ut.FileListService(i,c),gt=u?new Io(i,c):null,L=U.getSocket();L&&Te.attach(L,ue),it.onFileChanged((P,Z)=>{U.sendFileChangedEvent(ue,P,Z)}),it.onFileViewTransfer(async(P,Z,Ne)=>{try{await Te.sendBuffer(P,Z,Ne.path.split("/").pop()||"view",Ne.mimeType||"text/plain",{purpose:"view",viewMetadata:Ne})}catch(Xe){i.error("File view transfer failed",Xe)}}),U.onFileViewRequest((P,Z)=>{it.handleViewRequest(P,Z)}),U.onFileListRequest((P,Z)=>{ze.handleListRequest(Z)}),ze.onResponse(P=>{U.sendFileListResponse(ue,P)}),U.onFileDownloadRequest(async(P,Z,Ne)=>{try{await Te.sendFile(P,Z,void 0,void 0,Ne)}catch(Xe){i.error("File download failed",Xe)}}),gt&&(gt.onFileChanged(P=>{U.sendFileChangedEvent(ue,ve,P)}),gt.start()),re.startTracking(ve),Ee.setOnOutput(P=>{U.sendOutput(ue,ve,P),re.processOutput(ve,P),it.processOutput(ve,P)}),Ee.setOnLocalInput(P=>{(0,ut.isAnswerKeystroke)(P)&&re.resolvePrompt(ve)}),U.onInput((P,Z,Ne,Xe)=>{P===ve&&((0,ut.isAnswerKeystroke)(Z)&&re.resolvePrompt(ve),Ee.write(Z,Xe))}),U.setTerminalActiveCheck(P=>P===ve&&Ee.isAlive()),U.onResizeRequest((P,Z,Ne)=>{P===ve&&(i.info("Remote resize received",{terminalId:P,cols:Z,rows:Ne}),Ee.resize(Z,Ne))}),U.onClientAttached(({clientCount:P})=>{Ee.setSigwinchEnabled(!1),m.update({viewerCount:P}),U.sendInputResume(ve)}),U.onClientDetached(({clientCount:P})=>{P===0&&Ee.setSigwinchEnabled(!0),m.update({viewerCount:P})}),U.onGetBufferRequest(P=>P===ve?Ee.getBuffer():null),U.onRedrawRequest(P=>{P===ve&&Ee.redrawNoResize()});async function j(){let P=T.encryptWorkspaceInfo({name:xe,path:c});await U.registerWorkspace({instanceId:ue,encryptedInfo:P||void 0});let Z=T.encryptTerminalInfo({name:We,command:st,cwd:c});await U.terminalCreated({instanceId:ue,terminalId:ve,encryptedInfo:Z||void 0,streamId:Ee.getStreamId()??void 0})}U.onMetaSessionEstablished(P=>{P&&j().catch(Z=>{i.error("Failed to re-register metadata after meta session",Z)}),re.resendWaitingPrompts()}),U.onReconnect(async()=>{try{await j();let P=U.getSocket();P&&Te.attach(P,ue)}catch(P){i.error("Failed to re-register on reconnect",P)}});function A(){gt?.dispose(),Te.detach(),it.dispose(),ze.dispose(),re.stopTracking(ve),re.dispose(),U.disposeInputStream(ve),U.terminalClosed({instanceId:ue,terminalId:ve}).catch(()=>{}),U.unregisterWorkspace(ue).catch(()=>{}),U.disconnect(),Ee.dispose()}Ee.setOnExit(()=>{m.disable(),process.stderr.write(`Session ended.
|
|
54
54
|
`),A(),process.exit(0)}),process.on("SIGINT",()=>{m.disable(),process.stderr.write(`Session ended.
|
|
55
55
|
`),A(),process.exit(0)}),process.on("SIGTERM",()=>{m.disable(),process.stderr.write(`Session ended.
|
|
56
56
|
`),A(),process.exit(0)})}async function op(r){await r.logout(),process.stderr.write(`Logged out.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@termiq/cli",
|
|
3
|
-
"version": "3.18.
|
|
3
|
+
"version": "3.18.3",
|
|
4
4
|
"description": "Run Claude Code, Gemini CLI, or any shell over SSH/CI and control it from your phone — push on done/waiting/error, answer Y/n from the notification. End-to-end encrypted.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"terminal",
|