@termiq/cli 3.43.1 → 3.44.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +28 -28
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -1,38 +1,38 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var _p=Object.create;var $o=Object.defineProperty;var vp=Object.getOwnPropertyDescriptor;var bp=Object.getOwnPropertyNames;var Ep=Object.getPrototypeOf,wp=Object.prototype.hasOwnProperty;var qt=(r,e)=>()=>(r&&(e=r(r=0)),e);var M=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),xp=(r,e)=>{for(var t in e)$o(r,t,{get:e[t],enumerable:!0})},Sp=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of bp(e))!wp.call(r,n)&&n!==t&&$o(r,n,{get:()=>e[n],enumerable:!(i=vp(e,n))||i.enumerable});return r};var fe=(r,e,t)=>(t=r!=null?_p(Ep(r)):{},Sp(e||!r||!r.__esModule?$o(t,"default",{value:r,enumerable:!0}):t,r));var as=M(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.generateCorrelationId=kp;yn.runWithCorrelation=Op;yn.getCurrentCorrelationId=Pp;var Cp=require("async_hooks");function kp(){let r=new Uint8Array(4),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(r);else for(let t=0;t<4;t++)r[t]=Math.floor(Math.random()*256);return"c-"+Array.from(r,t=>t.toString(16).padStart(2,"0")).join("")}var Af=new Cp.AsyncLocalStorage;function Op(r,e){return Af.run(r,e)}function Pp(){return Af.getStore()}});var Lf=M(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});Ii.LOG_LEVELS=void 0;Ii.shouldLog=Ap;Ii.formatLogLine=Ip;var Rp=as();Ii.LOG_LEVELS=["silent","error","warn","info","debug"];var If={silent:0,error:1,warn:2,info:3,debug:4};function Ap(r,e){return If[r]<=If[e]}function Ip(r,e,t,i){let n={ts:new Date().toISOString(),level:r,src:e,msg:t},s=(0,Rp.getCurrentCorrelationId)();s&&(n.cid=s);let a=i;a.length>0&&typeof a[0]=="object"&&a[0]!==null&&!(a[0]instanceof Error)&&!Array.isArray(a[0])&&(n.ctx=a[0],a=a.slice(1));let c=[...a].reverse().find(u=>u instanceof Error);c&&(n.err={message:c.message,stack:c.stack,name:c.name},a=a.filter(u=>u!==c)),a.length>0&&(n.args=a);try{return JSON.stringify(n)}catch{return JSON.stringify({ts:n.ts,level:r,src:e,msg:t,_unserializable:!0})}}});var Nf=M(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});Dr.formatLogLine=Dr.shouldLog=Dr.LOG_LEVELS=void 0;var Go=Lf();Object.defineProperty(Dr,"LOG_LEVELS",{enumerable:!0,get:function(){return Go.LOG_LEVELS}});Object.defineProperty(Dr,"shouldLog",{enumerable:!0,get:function(){return Go.shouldLog}});Object.defineProperty(Dr,"formatLogLine",{enumerable:!0,get:function(){return Go.formatLogLine}})});var Mf=M(cs=>{"use strict";Object.defineProperty(cs,"__esModule",{value:!0});cs.CircularBuffer=void 0;var Yo=class{buffer=[];totalSize=0;maxSize;constructor(e=100){this.maxSize=e*1024}append(e){for(this.buffer.push(e),this.totalSize+=e.length;this.totalSize>this.maxSize&&this.buffer.length>1;){let t=this.buffer.shift();t&&(this.totalSize-=t.length)}}getContent(){return this.buffer.join("")}getLastBytes(e){let t=this.getContent();return t.length<=e?t:t.slice(-e)}getSize(){return this.totalSize}clear(){this.buffer=[],this.totalSize=0}};cs.CircularBuffer=Yo});var us=M(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});fs.getApiUrl=Lp;fs.getWsUrl=Np;function Lp(r){return`${r.getServerUrl()}/api`}function Np(r){let e=r.getServerUrl();return e.startsWith("https://")?e.replace(/^https:\/\//,"wss://"):e.replace(/^http:\/\//,"ws://")}});var Df=M(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.getCurrentCorrelationId=vt.runWithCorrelation=vt.generateCorrelationId=vt.getWsUrl=vt.getApiUrl=vt.CircularBuffer=void 0;var Mp=Mf();Object.defineProperty(vt,"CircularBuffer",{enumerable:!0,get:function(){return Mp.CircularBuffer}});var Ff=us();Object.defineProperty(vt,"getApiUrl",{enumerable:!0,get:function(){return Ff.getApiUrl}});Object.defineProperty(vt,"getWsUrl",{enumerable:!0,get:function(){return Ff.getWsUrl}});var Xo=as();Object.defineProperty(vt,"generateCorrelationId",{enumerable:!0,get:function(){return Xo.generateCorrelationId}});Object.defineProperty(vt,"runWithCorrelation",{enumerable:!0,get:function(){return Xo.runWithCorrelation}});Object.defineProperty(vt,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Xo.getCurrentCorrelationId}})});var jf=M(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0})});var Kf=M(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0})});var qf=M(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});ls.PLAN_LIMITS=void 0;ls.PLAN_LIMITS={free:{maxAgents:1,maxTerminals:2,maxTeamMembers:1,historyDays:1},basic:{maxAgents:3,maxTerminals:10,maxTeamMembers:1,historyDays:7},pro:{maxAgents:10,maxTerminals:50,maxTeamMembers:5,historyDays:30}}});var Hf=M(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0})});var Vf=M(Zt=>{"use strict";var Fp=Zt&&Zt.__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]})),hs=Zt&&Zt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Fp(e,r,t)};Object.defineProperty(Zt,"__esModule",{value:!0});hs(jf(),Zt);hs(Kf(),Zt);hs(qf(),Zt);hs(Hf(),Zt)});var zf=M(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.API_VERSION=It.WS_NAMESPACES=It.TIMEOUTS=It.STATUS_PATTERNS=It.TERMINAL_STATUSES=void 0;It.TERMINAL_STATUSES={idle:{label:"Idle",color:"gray",icon:"\u25CF"},working:{label:"Working",color:"blue",icon:"\u27F3"},waiting:{label:"Awaiting input",color:"orange",icon:"\u26A0"},completed:{label:"Completed",color:"green",icon:"\u2713"},error:{label:"Error",color:"red",icon:"\u2715"},offline:{label:"Offline",color:"black",icon:"\u26AB"}};It.STATUS_PATTERNS={idle:[/[❯$]\s*$/,/>\s*$/],waiting:[/\[Y\/n\]/i,/\(y\/N\)/i,/Continue\?/i,/proceed\?/i],completed:[/✓/,/Done/,/Completed/,/Success/],error:[/Error/,/Failed/,/✕/,/Exception/]};It.TIMEOUTS={HEARTBEAT_INTERVAL:3e4,OFFLINE_THRESHOLD:6e4,DEVICE_CODE_EXPIRY:9e5,DEVICE_CODE_POLL_INTERVAL:5e3};It.WS_NAMESPACES={AGENT:"/agent",CLIENT:"/client"};It.API_VERSION="v1"});var $f=M(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});ds.isMultiRecipientPayload=Dp;ds.isEncryptedPayload=Bp;function Dp(r){return typeof r=="object"&&r!==null&&"v"in r&&r.v===2&&"recipients"in r&&Array.isArray(r.recipients)}function Bp(r){if(typeof r!="object"||r===null||!("encrypted"in r))return!1;let e=r.encrypted;if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.v=="number"&&typeof t.sid=="string"&&typeof t.n=="string"&&typeof t.c=="string"}});var Jo=M(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.KX_SIG_VERSION=Qt.KX_FINGERPRINT_LABEL=Qt.KX_ACK_LABEL=Qt.KX_SIGN_LABEL=void 0;Qt.KX_SIGN_LABEL="termiq-kx-v1";Qt.KX_ACK_LABEL="termiq-kxack-v1";Qt.KX_FINGERPRINT_LABEL="termiq-fp-v1";Qt.KX_SIG_VERSION=1});var _n=M((sE,ps)=>{(function(r){"use strict";var e=function(f){var h,l=new Float64Array(16);if(f)for(h=0;h<f.length;h++)l[h]=f[h];return l},t=function(){throw new Error("no PRNG")},i=new Uint8Array(16),n=new Uint8Array(32);n[0]=9;var s=e(),a=e([1]),c=e([56129,1]),u=e([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),d=e([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),p=e([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),m=e([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),_=e([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function E(f,h,l,o){f[h]=l>>24&255,f[h+1]=l>>16&255,f[h+2]=l>>8&255,f[h+3]=l&255,f[h+4]=o>>24&255,f[h+5]=o>>16&255,f[h+6]=o>>8&255,f[h+7]=o&255}function S(f,h,l,o,g){var v,b=0;for(v=0;v<g;v++)b|=f[h+v]^l[o+v];return(1&b-1>>>8)-1}function T(f,h,l,o){return S(f,h,l,o,16)}function z(f,h,l,o){return S(f,h,l,o,32)}function ge(f,h,l,o){for(var g=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,v=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,b=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,k=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,D=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,J=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,W=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,Pe=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,V=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,ne=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,se=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,he=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,le=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,oe=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,ce=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ae=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,$=g,Q=v,H=b,G=k,Y=D,q=J,w=W,x=Pe,I=V,C=ne,O=se,F=he,ie=le,de=oe,me=ce,pe=ae,y,ve=0;ve<20;ve+=2)y=$+ie|0,Y^=y<<7|y>>>25,y=Y+$|0,I^=y<<9|y>>>23,y=I+Y|0,ie^=y<<13|y>>>19,y=ie+I|0,$^=y<<18|y>>>14,y=q+Q|0,C^=y<<7|y>>>25,y=C+q|0,de^=y<<9|y>>>23,y=de+C|0,Q^=y<<13|y>>>19,y=Q+de|0,q^=y<<18|y>>>14,y=O+w|0,me^=y<<7|y>>>25,y=me+O|0,H^=y<<9|y>>>23,y=H+me|0,w^=y<<13|y>>>19,y=w+H|0,O^=y<<18|y>>>14,y=pe+F|0,G^=y<<7|y>>>25,y=G+pe|0,x^=y<<9|y>>>23,y=x+G|0,F^=y<<13|y>>>19,y=F+x|0,pe^=y<<18|y>>>14,y=$+G|0,Q^=y<<7|y>>>25,y=Q+$|0,H^=y<<9|y>>>23,y=H+Q|0,G^=y<<13|y>>>19,y=G+H|0,$^=y<<18|y>>>14,y=q+Y|0,w^=y<<7|y>>>25,y=w+q|0,x^=y<<9|y>>>23,y=x+w|0,Y^=y<<13|y>>>19,y=Y+x|0,q^=y<<18|y>>>14,y=O+C|0,F^=y<<7|y>>>25,y=F+O|0,I^=y<<9|y>>>23,y=I+F|0,C^=y<<13|y>>>19,y=C+I|0,O^=y<<18|y>>>14,y=pe+me|0,ie^=y<<7|y>>>25,y=ie+pe|0,de^=y<<9|y>>>23,y=de+ie|0,me^=y<<13|y>>>19,y=me+de|0,pe^=y<<18|y>>>14;$=$+g|0,Q=Q+v|0,H=H+b|0,G=G+k|0,Y=Y+D|0,q=q+J|0,w=w+W|0,x=x+Pe|0,I=I+V|0,C=C+ne|0,O=O+se|0,F=F+he|0,ie=ie+le|0,de=de+oe|0,me=me+ce|0,pe=pe+ae|0,f[0]=$>>>0&255,f[1]=$>>>8&255,f[2]=$>>>16&255,f[3]=$>>>24&255,f[4]=Q>>>0&255,f[5]=Q>>>8&255,f[6]=Q>>>16&255,f[7]=Q>>>24&255,f[8]=H>>>0&255,f[9]=H>>>8&255,f[10]=H>>>16&255,f[11]=H>>>24&255,f[12]=G>>>0&255,f[13]=G>>>8&255,f[14]=G>>>16&255,f[15]=G>>>24&255,f[16]=Y>>>0&255,f[17]=Y>>>8&255,f[18]=Y>>>16&255,f[19]=Y>>>24&255,f[20]=q>>>0&255,f[21]=q>>>8&255,f[22]=q>>>16&255,f[23]=q>>>24&255,f[24]=w>>>0&255,f[25]=w>>>8&255,f[26]=w>>>16&255,f[27]=w>>>24&255,f[28]=x>>>0&255,f[29]=x>>>8&255,f[30]=x>>>16&255,f[31]=x>>>24&255,f[32]=I>>>0&255,f[33]=I>>>8&255,f[34]=I>>>16&255,f[35]=I>>>24&255,f[36]=C>>>0&255,f[37]=C>>>8&255,f[38]=C>>>16&255,f[39]=C>>>24&255,f[40]=O>>>0&255,f[41]=O>>>8&255,f[42]=O>>>16&255,f[43]=O>>>24&255,f[44]=F>>>0&255,f[45]=F>>>8&255,f[46]=F>>>16&255,f[47]=F>>>24&255,f[48]=ie>>>0&255,f[49]=ie>>>8&255,f[50]=ie>>>16&255,f[51]=ie>>>24&255,f[52]=de>>>0&255,f[53]=de>>>8&255,f[54]=de>>>16&255,f[55]=de>>>24&255,f[56]=me>>>0&255,f[57]=me>>>8&255,f[58]=me>>>16&255,f[59]=me>>>24&255,f[60]=pe>>>0&255,f[61]=pe>>>8&255,f[62]=pe>>>16&255,f[63]=pe>>>24&255}function ee(f,h,l,o){for(var g=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,v=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,b=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,k=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,D=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,J=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,W=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,Pe=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,V=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,ne=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,se=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,he=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,le=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,oe=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,ce=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ae=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,$=g,Q=v,H=b,G=k,Y=D,q=J,w=W,x=Pe,I=V,C=ne,O=se,F=he,ie=le,de=oe,me=ce,pe=ae,y,ve=0;ve<20;ve+=2)y=$+ie|0,Y^=y<<7|y>>>25,y=Y+$|0,I^=y<<9|y>>>23,y=I+Y|0,ie^=y<<13|y>>>19,y=ie+I|0,$^=y<<18|y>>>14,y=q+Q|0,C^=y<<7|y>>>25,y=C+q|0,de^=y<<9|y>>>23,y=de+C|0,Q^=y<<13|y>>>19,y=Q+de|0,q^=y<<18|y>>>14,y=O+w|0,me^=y<<7|y>>>25,y=me+O|0,H^=y<<9|y>>>23,y=H+me|0,w^=y<<13|y>>>19,y=w+H|0,O^=y<<18|y>>>14,y=pe+F|0,G^=y<<7|y>>>25,y=G+pe|0,x^=y<<9|y>>>23,y=x+G|0,F^=y<<13|y>>>19,y=F+x|0,pe^=y<<18|y>>>14,y=$+G|0,Q^=y<<7|y>>>25,y=Q+$|0,H^=y<<9|y>>>23,y=H+Q|0,G^=y<<13|y>>>19,y=G+H|0,$^=y<<18|y>>>14,y=q+Y|0,w^=y<<7|y>>>25,y=w+q|0,x^=y<<9|y>>>23,y=x+w|0,Y^=y<<13|y>>>19,y=Y+x|0,q^=y<<18|y>>>14,y=O+C|0,F^=y<<7|y>>>25,y=F+O|0,I^=y<<9|y>>>23,y=I+F|0,C^=y<<13|y>>>19,y=C+I|0,O^=y<<18|y>>>14,y=pe+me|0,ie^=y<<7|y>>>25,y=ie+pe|0,de^=y<<9|y>>>23,y=de+ie|0,me^=y<<13|y>>>19,y=me+de|0,pe^=y<<18|y>>>14;f[0]=$>>>0&255,f[1]=$>>>8&255,f[2]=$>>>16&255,f[3]=$>>>24&255,f[4]=q>>>0&255,f[5]=q>>>8&255,f[6]=q>>>16&255,f[7]=q>>>24&255,f[8]=O>>>0&255,f[9]=O>>>8&255,f[10]=O>>>16&255,f[11]=O>>>24&255,f[12]=pe>>>0&255,f[13]=pe>>>8&255,f[14]=pe>>>16&255,f[15]=pe>>>24&255,f[16]=w>>>0&255,f[17]=w>>>8&255,f[18]=w>>>16&255,f[19]=w>>>24&255,f[20]=x>>>0&255,f[21]=x>>>8&255,f[22]=x>>>16&255,f[23]=x>>>24&255,f[24]=I>>>0&255,f[25]=I>>>8&255,f[26]=I>>>16&255,f[27]=I>>>24&255,f[28]=C>>>0&255,f[29]=C>>>8&255,f[30]=C>>>16&255,f[31]=C>>>24&255}function R(f,h,l,o){ge(f,h,l,o)}function B(f,h,l,o){ee(f,h,l,o)}var re=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function K(f,h,l,o,g,v,b){var k=new Uint8Array(16),D=new Uint8Array(64),J,W;for(W=0;W<16;W++)k[W]=0;for(W=0;W<8;W++)k[W]=v[W];for(;g>=64;){for(R(D,k,b,re),W=0;W<64;W++)f[h+W]=l[o+W]^D[W];for(J=1,W=8;W<16;W++)J=J+(k[W]&255)|0,k[W]=J&255,J>>>=8;g-=64,h+=64,o+=64}if(g>0)for(R(D,k,b,re),W=0;W<g;W++)f[h+W]=l[o+W]^D[W];return 0}function U(f,h,l,o,g){var v=new Uint8Array(16),b=new Uint8Array(64),k,D;for(D=0;D<16;D++)v[D]=0;for(D=0;D<8;D++)v[D]=o[D];for(;l>=64;){for(R(b,v,g,re),D=0;D<64;D++)f[h+D]=b[D];for(k=1,D=8;D<16;D++)k=k+(v[D]&255)|0,v[D]=k&255,k>>>=8;l-=64,h+=64}if(l>0)for(R(b,v,g,re),D=0;D<l;D++)f[h+D]=b[D];return 0}function ye(f,h,l,o,g){var v=new Uint8Array(32);B(v,o,g,re);for(var b=new Uint8Array(8),k=0;k<8;k++)b[k]=o[k+16];return U(f,h,l,b,v)}function xe(f,h,l,o,g,v,b){var k=new Uint8Array(32);B(k,v,b,re);for(var D=new Uint8Array(8),J=0;J<8;J++)D[J]=v[J+16];return K(f,h,l,o,g,D,k)}var ue=function(f){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var h,l,o,g,v,b,k,D;h=f[0]&255|(f[1]&255)<<8,this.r[0]=h&8191,l=f[2]&255|(f[3]&255)<<8,this.r[1]=(h>>>13|l<<3)&8191,o=f[4]&255|(f[5]&255)<<8,this.r[2]=(l>>>10|o<<6)&7939,g=f[6]&255|(f[7]&255)<<8,this.r[3]=(o>>>7|g<<9)&8191,v=f[8]&255|(f[9]&255)<<8,this.r[4]=(g>>>4|v<<12)&255,this.r[5]=v>>>1&8190,b=f[10]&255|(f[11]&255)<<8,this.r[6]=(v>>>14|b<<2)&8191,k=f[12]&255|(f[13]&255)<<8,this.r[7]=(b>>>11|k<<5)&8065,D=f[14]&255|(f[15]&255)<<8,this.r[8]=(k>>>8|D<<8)&8191,this.r[9]=D>>>5&127,this.pad[0]=f[16]&255|(f[17]&255)<<8,this.pad[1]=f[18]&255|(f[19]&255)<<8,this.pad[2]=f[20]&255|(f[21]&255)<<8,this.pad[3]=f[22]&255|(f[23]&255)<<8,this.pad[4]=f[24]&255|(f[25]&255)<<8,this.pad[5]=f[26]&255|(f[27]&255)<<8,this.pad[6]=f[28]&255|(f[29]&255)<<8,this.pad[7]=f[30]&255|(f[31]&255)<<8};ue.prototype.blocks=function(f,h,l){for(var o=this.fin?0:2048,g,v,b,k,D,J,W,Pe,V,ne,se,he,le,oe,ce,ae,$,Q,H,G=this.h[0],Y=this.h[1],q=this.h[2],w=this.h[3],x=this.h[4],I=this.h[5],C=this.h[6],O=this.h[7],F=this.h[8],ie=this.h[9],de=this.r[0],me=this.r[1],pe=this.r[2],y=this.r[3],ve=this.r[4],Re=this.r[5],Ae=this.r[6],_e=this.r[7],Ce=this.r[8],ke=this.r[9];l>=16;)g=f[h+0]&255|(f[h+1]&255)<<8,G+=g&8191,v=f[h+2]&255|(f[h+3]&255)<<8,Y+=(g>>>13|v<<3)&8191,b=f[h+4]&255|(f[h+5]&255)<<8,q+=(v>>>10|b<<6)&8191,k=f[h+6]&255|(f[h+7]&255)<<8,w+=(b>>>7|k<<9)&8191,D=f[h+8]&255|(f[h+9]&255)<<8,x+=(k>>>4|D<<12)&8191,I+=D>>>1&8191,J=f[h+10]&255|(f[h+11]&255)<<8,C+=(D>>>14|J<<2)&8191,W=f[h+12]&255|(f[h+13]&255)<<8,O+=(J>>>11|W<<5)&8191,Pe=f[h+14]&255|(f[h+15]&255)<<8,F+=(W>>>8|Pe<<8)&8191,ie+=Pe>>>5|o,V=0,ne=V,ne+=G*de,ne+=Y*(5*ke),ne+=q*(5*Ce),ne+=w*(5*_e),ne+=x*(5*Ae),V=ne>>>13,ne&=8191,ne+=I*(5*Re),ne+=C*(5*ve),ne+=O*(5*y),ne+=F*(5*pe),ne+=ie*(5*me),V+=ne>>>13,ne&=8191,se=V,se+=G*me,se+=Y*de,se+=q*(5*ke),se+=w*(5*Ce),se+=x*(5*_e),V=se>>>13,se&=8191,se+=I*(5*Ae),se+=C*(5*Re),se+=O*(5*ve),se+=F*(5*y),se+=ie*(5*pe),V+=se>>>13,se&=8191,he=V,he+=G*pe,he+=Y*me,he+=q*de,he+=w*(5*ke),he+=x*(5*Ce),V=he>>>13,he&=8191,he+=I*(5*_e),he+=C*(5*Ae),he+=O*(5*Re),he+=F*(5*ve),he+=ie*(5*y),V+=he>>>13,he&=8191,le=V,le+=G*y,le+=Y*pe,le+=q*me,le+=w*de,le+=x*(5*ke),V=le>>>13,le&=8191,le+=I*(5*Ce),le+=C*(5*_e),le+=O*(5*Ae),le+=F*(5*Re),le+=ie*(5*ve),V+=le>>>13,le&=8191,oe=V,oe+=G*ve,oe+=Y*y,oe+=q*pe,oe+=w*me,oe+=x*de,V=oe>>>13,oe&=8191,oe+=I*(5*ke),oe+=C*(5*Ce),oe+=O*(5*_e),oe+=F*(5*Ae),oe+=ie*(5*Re),V+=oe>>>13,oe&=8191,ce=V,ce+=G*Re,ce+=Y*ve,ce+=q*y,ce+=w*pe,ce+=x*me,V=ce>>>13,ce&=8191,ce+=I*de,ce+=C*(5*ke),ce+=O*(5*Ce),ce+=F*(5*_e),ce+=ie*(5*Ae),V+=ce>>>13,ce&=8191,ae=V,ae+=G*Ae,ae+=Y*Re,ae+=q*ve,ae+=w*y,ae+=x*pe,V=ae>>>13,ae&=8191,ae+=I*me,ae+=C*de,ae+=O*(5*ke),ae+=F*(5*Ce),ae+=ie*(5*_e),V+=ae>>>13,ae&=8191,$=V,$+=G*_e,$+=Y*Ae,$+=q*Re,$+=w*ve,$+=x*y,V=$>>>13,$&=8191,$+=I*pe,$+=C*me,$+=O*de,$+=F*(5*ke),$+=ie*(5*Ce),V+=$>>>13,$&=8191,Q=V,Q+=G*Ce,Q+=Y*_e,Q+=q*Ae,Q+=w*Re,Q+=x*ve,V=Q>>>13,Q&=8191,Q+=I*y,Q+=C*pe,Q+=O*me,Q+=F*de,Q+=ie*(5*ke),V+=Q>>>13,Q&=8191,H=V,H+=G*ke,H+=Y*Ce,H+=q*_e,H+=w*Ae,H+=x*Re,V=H>>>13,H&=8191,H+=I*ve,H+=C*y,H+=O*pe,H+=F*me,H+=ie*de,V+=H>>>13,H&=8191,V=(V<<2)+V|0,V=V+ne|0,ne=V&8191,V=V>>>13,se+=V,G=ne,Y=se,q=he,w=le,x=oe,I=ce,C=ae,O=$,F=Q,ie=H,h+=16,l-=16;this.h[0]=G,this.h[1]=Y,this.h[2]=q,this.h[3]=w,this.h[4]=x,this.h[5]=I,this.h[6]=C,this.h[7]=O,this.h[8]=F,this.h[9]=ie},ue.prototype.finish=function(f,h){var l=new Uint16Array(10),o,g,v,b;if(this.leftover){for(b=this.leftover,this.buffer[b++]=1;b<16;b++)this.buffer[b]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(o=this.h[1]>>>13,this.h[1]&=8191,b=2;b<10;b++)this.h[b]+=o,o=this.h[b]>>>13,this.h[b]&=8191;for(this.h[0]+=o*5,o=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=o,o=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=o,l[0]=this.h[0]+5,o=l[0]>>>13,l[0]&=8191,b=1;b<10;b++)l[b]=this.h[b]+o,o=l[b]>>>13,l[b]&=8191;for(l[9]-=8192,g=(o^1)-1,b=0;b<10;b++)l[b]&=g;for(g=~g,b=0;b<10;b++)this.h[b]=this.h[b]&g|l[b];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,v=this.h[0]+this.pad[0],this.h[0]=v&65535,b=1;b<8;b++)v=(this.h[b]+this.pad[b]|0)+(v>>>16)|0,this.h[b]=v&65535;f[h+0]=this.h[0]>>>0&255,f[h+1]=this.h[0]>>>8&255,f[h+2]=this.h[1]>>>0&255,f[h+3]=this.h[1]>>>8&255,f[h+4]=this.h[2]>>>0&255,f[h+5]=this.h[2]>>>8&255,f[h+6]=this.h[3]>>>0&255,f[h+7]=this.h[3]>>>8&255,f[h+8]=this.h[4]>>>0&255,f[h+9]=this.h[4]>>>8&255,f[h+10]=this.h[5]>>>0&255,f[h+11]=this.h[5]>>>8&255,f[h+12]=this.h[6]>>>0&255,f[h+13]=this.h[6]>>>8&255,f[h+14]=this.h[7]>>>0&255,f[h+15]=this.h[7]>>>8&255},ue.prototype.update=function(f,h,l){var o,g;if(this.leftover){for(g=16-this.leftover,g>l&&(g=l),o=0;o<g;o++)this.buffer[this.leftover+o]=f[h+o];if(l-=g,h+=g,this.leftover+=g,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(l>=16&&(g=l-l%16,this.blocks(f,h,g),h+=g,l-=g),l){for(o=0;o<l;o++)this.buffer[this.leftover+o]=f[h+o];this.leftover+=l}};function rt(f,h,l,o,g,v){var b=new ue(v);return b.update(l,o,g),b.finish(f,h),0}function Ee(f,h,l,o,g,v){var b=new Uint8Array(16);return rt(b,0,l,o,g,v),T(f,h,b,0)}function Se(f,h,l,o,g){var v;if(l<32)return-1;for(xe(f,0,h,0,l,o,g),rt(f,16,f,32,l-32,f),v=0;v<16;v++)f[v]=0;return 0}function be(f,h,l,o,g){var v,b=new Uint8Array(32);if(l<32||(ye(b,0,32,o,g),Ee(h,16,h,32,l-32,b)!==0))return-1;for(xe(f,0,h,0,l,o,g),v=0;v<32;v++)f[v]=0;return 0}function We(f,h){var l;for(l=0;l<16;l++)f[l]=h[l]|0}function st(f){var h,l,o=1;for(h=0;h<16;h++)l=f[h]+o+65535,o=Math.floor(l/65536),f[h]=l-o*65536;f[0]+=o-1+37*(o-1)}function Ze(f,h,l){for(var o,g=~(l-1),v=0;v<16;v++)o=g&(f[v]^h[v]),f[v]^=o,h[v]^=o}function Te(f,h){var l,o,g,v=e(),b=e();for(l=0;l<16;l++)b[l]=h[l];for(st(b),st(b),st(b),o=0;o<2;o++){for(v[0]=b[0]-65517,l=1;l<15;l++)v[l]=b[l]-65535-(v[l-1]>>16&1),v[l-1]&=65535;v[15]=b[15]-32767-(v[14]>>16&1),g=v[15]>>16&1,v[14]&=65535,Ze(b,v,1-g)}for(l=0;l<16;l++)f[2*l]=b[l]&255,f[2*l+1]=b[l]>>8}function it(f,h){var l=new Uint8Array(32),o=new Uint8Array(32);return Te(l,f),Te(o,h),z(l,0,o,0)}function ze(f){var h=new Uint8Array(32);return Te(h,f),h[0]&1}function gt(f,h){var l;for(l=0;l<16;l++)f[l]=h[2*l]+(h[2*l+1]<<8);f[15]&=32767}function L(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]+l[o]}function j(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]-l[o]}function A(f,h,l){var o,g,v=0,b=0,k=0,D=0,J=0,W=0,Pe=0,V=0,ne=0,se=0,he=0,le=0,oe=0,ce=0,ae=0,$=0,Q=0,H=0,G=0,Y=0,q=0,w=0,x=0,I=0,C=0,O=0,F=0,ie=0,de=0,me=0,pe=0,y=l[0],ve=l[1],Re=l[2],Ae=l[3],_e=l[4],Ce=l[5],ke=l[6],Je=l[7],Me=l[8],$e=l[9],Ge=l[10],Ye=l[11],nt=l[12],ht=l[13],dt=l[14],pt=l[15];o=h[0],v+=o*y,b+=o*ve,k+=o*Re,D+=o*Ae,J+=o*_e,W+=o*Ce,Pe+=o*ke,V+=o*Je,ne+=o*Me,se+=o*$e,he+=o*Ge,le+=o*Ye,oe+=o*nt,ce+=o*ht,ae+=o*dt,$+=o*pt,o=h[1],b+=o*y,k+=o*ve,D+=o*Re,J+=o*Ae,W+=o*_e,Pe+=o*Ce,V+=o*ke,ne+=o*Je,se+=o*Me,he+=o*$e,le+=o*Ge,oe+=o*Ye,ce+=o*nt,ae+=o*ht,$+=o*dt,Q+=o*pt,o=h[2],k+=o*y,D+=o*ve,J+=o*Re,W+=o*Ae,Pe+=o*_e,V+=o*Ce,ne+=o*ke,se+=o*Je,he+=o*Me,le+=o*$e,oe+=o*Ge,ce+=o*Ye,ae+=o*nt,$+=o*ht,Q+=o*dt,H+=o*pt,o=h[3],D+=o*y,J+=o*ve,W+=o*Re,Pe+=o*Ae,V+=o*_e,ne+=o*Ce,se+=o*ke,he+=o*Je,le+=o*Me,oe+=o*$e,ce+=o*Ge,ae+=o*Ye,$+=o*nt,Q+=o*ht,H+=o*dt,G+=o*pt,o=h[4],J+=o*y,W+=o*ve,Pe+=o*Re,V+=o*Ae,ne+=o*_e,se+=o*Ce,he+=o*ke,le+=o*Je,oe+=o*Me,ce+=o*$e,ae+=o*Ge,$+=o*Ye,Q+=o*nt,H+=o*ht,G+=o*dt,Y+=o*pt,o=h[5],W+=o*y,Pe+=o*ve,V+=o*Re,ne+=o*Ae,se+=o*_e,he+=o*Ce,le+=o*ke,oe+=o*Je,ce+=o*Me,ae+=o*$e,$+=o*Ge,Q+=o*Ye,H+=o*nt,G+=o*ht,Y+=o*dt,q+=o*pt,o=h[6],Pe+=o*y,V+=o*ve,ne+=o*Re,se+=o*Ae,he+=o*_e,le+=o*Ce,oe+=o*ke,ce+=o*Je,ae+=o*Me,$+=o*$e,Q+=o*Ge,H+=o*Ye,G+=o*nt,Y+=o*ht,q+=o*dt,w+=o*pt,o=h[7],V+=o*y,ne+=o*ve,se+=o*Re,he+=o*Ae,le+=o*_e,oe+=o*Ce,ce+=o*ke,ae+=o*Je,$+=o*Me,Q+=o*$e,H+=o*Ge,G+=o*Ye,Y+=o*nt,q+=o*ht,w+=o*dt,x+=o*pt,o=h[8],ne+=o*y,se+=o*ve,he+=o*Re,le+=o*Ae,oe+=o*_e,ce+=o*Ce,ae+=o*ke,$+=o*Je,Q+=o*Me,H+=o*$e,G+=o*Ge,Y+=o*Ye,q+=o*nt,w+=o*ht,x+=o*dt,I+=o*pt,o=h[9],se+=o*y,he+=o*ve,le+=o*Re,oe+=o*Ae,ce+=o*_e,ae+=o*Ce,$+=o*ke,Q+=o*Je,H+=o*Me,G+=o*$e,Y+=o*Ge,q+=o*Ye,w+=o*nt,x+=o*ht,I+=o*dt,C+=o*pt,o=h[10],he+=o*y,le+=o*ve,oe+=o*Re,ce+=o*Ae,ae+=o*_e,$+=o*Ce,Q+=o*ke,H+=o*Je,G+=o*Me,Y+=o*$e,q+=o*Ge,w+=o*Ye,x+=o*nt,I+=o*ht,C+=o*dt,O+=o*pt,o=h[11],le+=o*y,oe+=o*ve,ce+=o*Re,ae+=o*Ae,$+=o*_e,Q+=o*Ce,H+=o*ke,G+=o*Je,Y+=o*Me,q+=o*$e,w+=o*Ge,x+=o*Ye,I+=o*nt,C+=o*ht,O+=o*dt,F+=o*pt,o=h[12],oe+=o*y,ce+=o*ve,ae+=o*Re,$+=o*Ae,Q+=o*_e,H+=o*Ce,G+=o*ke,Y+=o*Je,q+=o*Me,w+=o*$e,x+=o*Ge,I+=o*Ye,C+=o*nt,O+=o*ht,F+=o*dt,ie+=o*pt,o=h[13],ce+=o*y,ae+=o*ve,$+=o*Re,Q+=o*Ae,H+=o*_e,G+=o*Ce,Y+=o*ke,q+=o*Je,w+=o*Me,x+=o*$e,I+=o*Ge,C+=o*Ye,O+=o*nt,F+=o*ht,ie+=o*dt,de+=o*pt,o=h[14],ae+=o*y,$+=o*ve,Q+=o*Re,H+=o*Ae,G+=o*_e,Y+=o*Ce,q+=o*ke,w+=o*Je,x+=o*Me,I+=o*$e,C+=o*Ge,O+=o*Ye,F+=o*nt,ie+=o*ht,de+=o*dt,me+=o*pt,o=h[15],$+=o*y,Q+=o*ve,H+=o*Re,G+=o*Ae,Y+=o*_e,q+=o*Ce,w+=o*ke,x+=o*Je,I+=o*Me,C+=o*$e,O+=o*Ge,F+=o*Ye,ie+=o*nt,de+=o*ht,me+=o*dt,pe+=o*pt,v+=38*Q,b+=38*H,k+=38*G,D+=38*Y,J+=38*q,W+=38*w,Pe+=38*x,V+=38*I,ne+=38*C,se+=38*O,he+=38*F,le+=38*ie,oe+=38*de,ce+=38*me,ae+=38*pe,g=1,o=v+g+65535,g=Math.floor(o/65536),v=o-g*65536,o=b+g+65535,g=Math.floor(o/65536),b=o-g*65536,o=k+g+65535,g=Math.floor(o/65536),k=o-g*65536,o=D+g+65535,g=Math.floor(o/65536),D=o-g*65536,o=J+g+65535,g=Math.floor(o/65536),J=o-g*65536,o=W+g+65535,g=Math.floor(o/65536),W=o-g*65536,o=Pe+g+65535,g=Math.floor(o/65536),Pe=o-g*65536,o=V+g+65535,g=Math.floor(o/65536),V=o-g*65536,o=ne+g+65535,g=Math.floor(o/65536),ne=o-g*65536,o=se+g+65535,g=Math.floor(o/65536),se=o-g*65536,o=he+g+65535,g=Math.floor(o/65536),he=o-g*65536,o=le+g+65535,g=Math.floor(o/65536),le=o-g*65536,o=oe+g+65535,g=Math.floor(o/65536),oe=o-g*65536,o=ce+g+65535,g=Math.floor(o/65536),ce=o-g*65536,o=ae+g+65535,g=Math.floor(o/65536),ae=o-g*65536,o=$+g+65535,g=Math.floor(o/65536),$=o-g*65536,v+=g-1+37*(g-1),g=1,o=v+g+65535,g=Math.floor(o/65536),v=o-g*65536,o=b+g+65535,g=Math.floor(o/65536),b=o-g*65536,o=k+g+65535,g=Math.floor(o/65536),k=o-g*65536,o=D+g+65535,g=Math.floor(o/65536),D=o-g*65536,o=J+g+65535,g=Math.floor(o/65536),J=o-g*65536,o=W+g+65535,g=Math.floor(o/65536),W=o-g*65536,o=Pe+g+65535,g=Math.floor(o/65536),Pe=o-g*65536,o=V+g+65535,g=Math.floor(o/65536),V=o-g*65536,o=ne+g+65535,g=Math.floor(o/65536),ne=o-g*65536,o=se+g+65535,g=Math.floor(o/65536),se=o-g*65536,o=he+g+65535,g=Math.floor(o/65536),he=o-g*65536,o=le+g+65535,g=Math.floor(o/65536),le=o-g*65536,o=oe+g+65535,g=Math.floor(o/65536),oe=o-g*65536,o=ce+g+65535,g=Math.floor(o/65536),ce=o-g*65536,o=ae+g+65535,g=Math.floor(o/65536),ae=o-g*65536,o=$+g+65535,g=Math.floor(o/65536),$=o-g*65536,v+=g-1+37*(g-1),f[0]=v,f[1]=b,f[2]=k,f[3]=D,f[4]=J,f[5]=W,f[6]=Pe,f[7]=V,f[8]=ne,f[9]=se,f[10]=he,f[11]=le,f[12]=oe,f[13]=ce,f[14]=ae,f[15]=$}function P(f,h){A(f,h,h)}function Z(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=253;o>=0;o--)P(l,l),o!==2&&o!==4&&A(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function Ne(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=250;o>=0;o--)P(l,l),o!==1&&A(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function Xe(f,h,l){var o=new Uint8Array(32),g=new Float64Array(80),v,b,k=e(),D=e(),J=e(),W=e(),Pe=e(),V=e();for(b=0;b<31;b++)o[b]=h[b];for(o[31]=h[31]&127|64,o[0]&=248,gt(g,l),b=0;b<16;b++)D[b]=g[b],W[b]=k[b]=J[b]=0;for(k[0]=W[0]=1,b=254;b>=0;--b)v=o[b>>>3]>>>(b&7)&1,Ze(k,D,v),Ze(J,W,v),L(Pe,k,J),j(k,k,J),L(J,D,W),j(D,D,W),P(W,Pe),P(V,k),A(k,J,k),A(J,D,Pe),L(Pe,k,J),j(k,k,J),P(D,k),j(J,W,V),A(k,J,c),L(k,k,W),A(J,J,k),A(k,W,V),A(W,D,g),P(D,Pe),Ze(k,D,v),Ze(J,W,v);for(b=0;b<16;b++)g[b+16]=k[b],g[b+32]=J[b],g[b+48]=D[b],g[b+64]=W[b];var ne=g.subarray(32),se=g.subarray(16);return Z(ne,ne),A(se,se,ne),Te(f,se),0}function lt(f,h){return Xe(f,h,n)}function wt(f,h){return t(h,32),lt(f,h)}function mr(f,h,l){var o=new Uint8Array(32);return Xe(o,l,h),B(f,i,o,re)}var Mr=Se,ii=be;function Fr(f,h,l,o,g,v){var b=new Uint8Array(32);return mr(b,g,v),Mr(f,h,l,o,b)}function Pi(f,h,l,o,g,v){var b=new Uint8Array(32);return mr(b,g,v),ii(f,h,l,o,b)}var Jn=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function xf(f,h,l,o){for(var g=new Int32Array(16),v=new Int32Array(16),b,k,D,J,W,Pe,V,ne,se,he,le,oe,ce,ae,$,Q,H,G,Y,q,w,x,I,C,O,F,ie=f[0],de=f[1],me=f[2],pe=f[3],y=f[4],ve=f[5],Re=f[6],Ae=f[7],_e=h[0],Ce=h[1],ke=h[2],Je=h[3],Me=h[4],$e=h[5],Ge=h[6],Ye=h[7],nt=0;o>=128;){for(Y=0;Y<16;Y++)q=8*Y+nt,g[Y]=l[q+0]<<24|l[q+1]<<16|l[q+2]<<8|l[q+3],v[Y]=l[q+4]<<24|l[q+5]<<16|l[q+6]<<8|l[q+7];for(Y=0;Y<80;Y++)if(b=ie,k=de,D=me,J=pe,W=y,Pe=ve,V=Re,ne=Ae,se=_e,he=Ce,le=ke,oe=Je,ce=Me,ae=$e,$=Ge,Q=Ye,w=Ae,x=Ye,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=(y>>>14|Me<<18)^(y>>>18|Me<<14)^(Me>>>9|y<<23),x=(Me>>>14|y<<18)^(Me>>>18|y<<14)^(y>>>9|Me<<23),I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,w=y&ve^~y&Re,x=Me&$e^~Me&Ge,I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,w=Jn[Y*2],x=Jn[Y*2+1],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,w=g[Y%16],x=v[Y%16],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,H=O&65535|F<<16,G=I&65535|C<<16,w=H,x=G,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=(ie>>>28|_e<<4)^(_e>>>2|ie<<30)^(_e>>>7|ie<<25),x=(_e>>>28|ie<<4)^(ie>>>2|_e<<30)^(ie>>>7|_e<<25),I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,w=ie&de^ie&me^de&me,x=_e&Ce^_e&ke^Ce&ke,I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,ne=O&65535|F<<16,Q=I&65535|C<<16,w=J,x=oe,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=H,x=G,I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,J=O&65535|F<<16,oe=I&65535|C<<16,de=b,me=k,pe=D,y=J,ve=W,Re=Pe,Ae=V,ie=ne,Ce=se,ke=he,Je=le,Me=oe,$e=ce,Ge=ae,Ye=$,_e=Q,Y%16===15)for(q=0;q<16;q++)w=g[q],x=v[q],I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=g[(q+9)%16],x=v[(q+9)%16],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,H=g[(q+1)%16],G=v[(q+1)%16],w=(H>>>1|G<<31)^(H>>>8|G<<24)^H>>>7,x=(G>>>1|H<<31)^(G>>>8|H<<24)^(G>>>7|H<<25),I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,H=g[(q+14)%16],G=v[(q+14)%16],w=(H>>>19|G<<13)^(G>>>29|H<<3)^H>>>6,x=(G>>>19|H<<13)^(H>>>29|G<<3)^(G>>>6|H<<26),I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,g[q]=O&65535|F<<16,v[q]=I&65535|C<<16;w=ie,x=_e,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[0],x=h[0],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[0]=ie=O&65535|F<<16,h[0]=_e=I&65535|C<<16,w=de,x=Ce,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[1],x=h[1],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[1]=de=O&65535|F<<16,h[1]=Ce=I&65535|C<<16,w=me,x=ke,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[2],x=h[2],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[2]=me=O&65535|F<<16,h[2]=ke=I&65535|C<<16,w=pe,x=Je,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[3],x=h[3],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[3]=pe=O&65535|F<<16,h[3]=Je=I&65535|C<<16,w=y,x=Me,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[4],x=h[4],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[4]=y=O&65535|F<<16,h[4]=Me=I&65535|C<<16,w=ve,x=$e,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[5],x=h[5],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[5]=ve=O&65535|F<<16,h[5]=$e=I&65535|C<<16,w=Re,x=Ge,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[6],x=h[6],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[6]=Re=O&65535|F<<16,h[6]=Ge=I&65535|C<<16,w=Ae,x=Ye,I=x&65535,C=x>>>16,O=w&65535,F=w>>>16,w=f[7],x=h[7],I+=x&65535,C+=x>>>16,O+=w&65535,F+=w>>>16,C+=I>>>16,O+=C>>>16,F+=O>>>16,f[7]=Ae=O&65535|F<<16,h[7]=Ye=I&65535|C<<16,nt+=128,o-=128}return o}function ni(f,h,l){var o=new Int32Array(8),g=new Int32Array(8),v=new Uint8Array(256),b,k=l;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,g[0]=4089235720,g[1]=2227873595,g[2]=4271175723,g[3]=1595750129,g[4]=2917565137,g[5]=725511199,g[6]=4215389547,g[7]=327033209,xf(o,g,h,l),l%=128,b=0;b<l;b++)v[b]=h[k-l+b];for(v[l]=128,l=256-128*(l<112?1:0),v[l-9]=0,E(v,l-8,k/536870912|0,k<<3),xf(o,g,v,l),b=0;b<8;b++)E(f,8*b,o[b],g[b]);return 0}function Zn(f,h){var l=e(),o=e(),g=e(),v=e(),b=e(),k=e(),D=e(),J=e(),W=e();j(l,f[1],f[0]),j(W,h[1],h[0]),A(l,l,W),L(o,f[0],f[1]),L(W,h[0],h[1]),A(o,o,W),A(g,f[3],h[3]),A(g,g,d),A(v,f[2],h[2]),L(v,v,v),j(b,o,l),j(k,v,g),L(D,v,g),L(J,o,l),A(f[0],b,k),A(f[1],J,D),A(f[2],D,k),A(f[3],b,J)}function Sf(f,h,l){var o;for(o=0;o<4;o++)Ze(f[o],h[o],l)}function Do(f,h){var l=e(),o=e(),g=e();Z(g,h[2]),A(l,h[0],g),A(o,h[1],g),Te(f,o),f[31]^=ze(l)<<7}function Bo(f,h,l){var o,g;for(We(f[0],s),We(f[1],a),We(f[2],a),We(f[3],s),g=255;g>=0;--g)o=l[g/8|0]>>(g&7)&1,Sf(f,h,o),Zn(h,f),Zn(f,f),Sf(f,h,o)}function Qn(f,h){var l=[e(),e(),e(),e()];We(l[0],p),We(l[1],m),We(l[2],a),A(l[3],p,m),Bo(f,l,h)}function jo(f,h,l){var o=new Uint8Array(64),g=[e(),e(),e(),e()],v;for(l||t(h,32),ni(o,h,32),o[0]&=248,o[31]&=127,o[31]|=64,Qn(g,o),Do(f,g),v=0;v<32;v++)h[v+32]=f[v];return 0}var es=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function Uo(f,h){var l,o,g,v;for(o=63;o>=32;--o){for(l=0,g=o-32,v=o-12;g<v;++g)h[g]+=l-16*h[o]*es[g-(o-32)],l=Math.floor((h[g]+128)/256),h[g]-=l*256;h[g]+=l,h[o]=0}for(l=0,g=0;g<32;g++)h[g]+=l-(h[31]>>4)*es[g],l=h[g]>>8,h[g]&=255;for(g=0;g<32;g++)h[g]-=l*es[g];for(o=0;o<32;o++)h[o+1]+=h[o]>>8,f[o]=h[o]&255}function Ko(f){var h=new Float64Array(64),l;for(l=0;l<64;l++)h[l]=f[l];for(l=0;l<64;l++)f[l]=0;Uo(f,h)}function Tf(f,h,l,o){var g=new Uint8Array(64),v=new Uint8Array(64),b=new Uint8Array(64),k,D,J=new Float64Array(64),W=[e(),e(),e(),e()];ni(g,o,32),g[0]&=248,g[31]&=127,g[31]|=64;var Pe=l+64;for(k=0;k<l;k++)f[64+k]=h[k];for(k=0;k<32;k++)f[32+k]=g[32+k];for(ni(b,f.subarray(32),l+32),Ko(b),Qn(W,b),Do(f,W),k=32;k<64;k++)f[k]=o[k];for(ni(v,f,l+64),Ko(v),k=0;k<64;k++)J[k]=0;for(k=0;k<32;k++)J[k]=b[k];for(k=0;k<32;k++)for(D=0;D<32;D++)J[k+D]+=v[k]*g[D];return Uo(f.subarray(32),J),Pe}function pp(f,h){var l=e(),o=e(),g=e(),v=e(),b=e(),k=e(),D=e();return We(f[2],a),gt(f[1],h),P(g,f[1]),A(v,g,u),j(g,g,f[2]),L(v,f[2],v),P(b,v),P(k,b),A(D,k,b),A(l,D,g),A(l,l,v),Ne(l,l),A(l,l,g),A(l,l,v),A(l,l,v),A(f[0],l,v),P(o,f[0]),A(o,o,v),it(o,g)&&A(f[0],f[0],_),P(o,f[0]),A(o,o,v),it(o,g)?-1:(ze(f[0])===h[31]>>7&&j(f[0],s,f[0]),A(f[3],f[0],f[1]),0)}function qo(f,h,l,o){var g,v=new Uint8Array(32),b=new Uint8Array(64),k=[e(),e(),e(),e()],D=[e(),e(),e(),e()];if(l<64||pp(D,o))return-1;for(g=0;g<l;g++)f[g]=h[g];for(g=0;g<32;g++)f[g+32]=o[g];if(ni(b,f,l),Ko(b),Bo(k,D,b),Qn(D,h.subarray(32)),Zn(k,D),Do(v,k),l-=64,z(h,0,v,0)){for(g=0;g<l;g++)f[g]=0;return-1}for(g=0;g<l;g++)f[g]=h[g+64];return l}var Wo=32,ts=24,ln=32,Ri=16,hn=32,rs=32,dn=32,pn=32,Ho=32,Cf=ts,gp=ln,mp=Ri,yr=64,si=32,Ai=64,Vo=32,zo=64;r.lowlevel={crypto_core_hsalsa20:B,crypto_stream_xor:xe,crypto_stream:ye,crypto_stream_salsa20_xor:K,crypto_stream_salsa20:U,crypto_onetimeauth:rt,crypto_onetimeauth_verify:Ee,crypto_verify_16:T,crypto_verify_32:z,crypto_secretbox:Se,crypto_secretbox_open:be,crypto_scalarmult:Xe,crypto_scalarmult_base:lt,crypto_box_beforenm:mr,crypto_box_afternm:Mr,crypto_box:Fr,crypto_box_open:Pi,crypto_box_keypair:wt,crypto_hash:ni,crypto_sign:Tf,crypto_sign_keypair:jo,crypto_sign_open:qo,crypto_secretbox_KEYBYTES:Wo,crypto_secretbox_NONCEBYTES:ts,crypto_secretbox_ZEROBYTES:ln,crypto_secretbox_BOXZEROBYTES:Ri,crypto_scalarmult_BYTES:hn,crypto_scalarmult_SCALARBYTES:rs,crypto_box_PUBLICKEYBYTES:dn,crypto_box_SECRETKEYBYTES:pn,crypto_box_BEFORENMBYTES:Ho,crypto_box_NONCEBYTES:Cf,crypto_box_ZEROBYTES:gp,crypto_box_BOXZEROBYTES:mp,crypto_sign_BYTES:yr,crypto_sign_PUBLICKEYBYTES:si,crypto_sign_SECRETKEYBYTES:Ai,crypto_sign_SEEDBYTES:Vo,crypto_hash_BYTES:zo,gf:e,D:u,L:es,pack25519:Te,unpack25519:gt,M:A,A:L,S:P,Z:j,pow2523:Ne,add:Zn,set25519:We,modL:Uo,scalarmult:Bo,scalarbase:Qn};function kf(f,h){if(f.length!==Wo)throw new Error("bad key size");if(h.length!==ts)throw new Error("bad nonce size")}function yp(f,h){if(f.length!==dn)throw new Error("bad public key size");if(h.length!==pn)throw new Error("bad secret key size")}function xt(){for(var f=0;f<arguments.length;f++)if(!(arguments[f]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function Of(f){for(var h=0;h<f.length;h++)f[h]=0}r.randomBytes=function(f){var h=new Uint8Array(f);return t(h,f),h},r.secretbox=function(f,h,l){xt(f,h,l),kf(l,h);for(var o=new Uint8Array(ln+f.length),g=new Uint8Array(o.length),v=0;v<f.length;v++)o[v+ln]=f[v];return Se(g,o,o.length,h,l),g.subarray(Ri)},r.secretbox.open=function(f,h,l){xt(f,h,l),kf(l,h);for(var o=new Uint8Array(Ri+f.length),g=new Uint8Array(o.length),v=0;v<f.length;v++)o[v+Ri]=f[v];return o.length<32||be(g,o,o.length,h,l)!==0?null:g.subarray(ln)},r.secretbox.keyLength=Wo,r.secretbox.nonceLength=ts,r.secretbox.overheadLength=Ri,r.scalarMult=function(f,h){if(xt(f,h),f.length!==rs)throw new Error("bad n size");if(h.length!==hn)throw new Error("bad p size");var l=new Uint8Array(hn);return Xe(l,f,h),l},r.scalarMult.base=function(f){if(xt(f),f.length!==rs)throw new Error("bad n size");var h=new Uint8Array(hn);return lt(h,f),h},r.scalarMult.scalarLength=rs,r.scalarMult.groupElementLength=hn,r.box=function(f,h,l,o){var g=r.box.before(l,o);return r.secretbox(f,h,g)},r.box.before=function(f,h){xt(f,h),yp(f,h);var l=new Uint8Array(Ho);return mr(l,f,h),l},r.box.after=r.secretbox,r.box.open=function(f,h,l,o){var g=r.box.before(l,o);return r.secretbox.open(f,h,g)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var f=new Uint8Array(dn),h=new Uint8Array(pn);return wt(f,h),{publicKey:f,secretKey:h}},r.box.keyPair.fromSecretKey=function(f){if(xt(f),f.length!==pn)throw new Error("bad secret key size");var h=new Uint8Array(dn);return lt(h,f),{publicKey:h,secretKey:new Uint8Array(f)}},r.box.publicKeyLength=dn,r.box.secretKeyLength=pn,r.box.sharedKeyLength=Ho,r.box.nonceLength=Cf,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(f,h){if(xt(f,h),h.length!==Ai)throw new Error("bad secret key size");var l=new Uint8Array(yr+f.length);return Tf(l,f,f.length,h),l},r.sign.open=function(f,h){if(xt(f,h),h.length!==si)throw new Error("bad public key size");var l=new Uint8Array(f.length),o=qo(l,f,f.length,h);if(o<0)return null;for(var g=new Uint8Array(o),v=0;v<g.length;v++)g[v]=l[v];return g},r.sign.detached=function(f,h){for(var l=r.sign(f,h),o=new Uint8Array(yr),g=0;g<o.length;g++)o[g]=l[g];return o},r.sign.detached.verify=function(f,h,l){if(xt(f,h,l),h.length!==yr)throw new Error("bad signature size");if(l.length!==si)throw new Error("bad public key size");var o=new Uint8Array(yr+f.length),g=new Uint8Array(yr+f.length),v;for(v=0;v<yr;v++)o[v]=h[v];for(v=0;v<f.length;v++)o[v+yr]=f[v];return qo(g,o,o.length,l)>=0},r.sign.keyPair=function(){var f=new Uint8Array(si),h=new Uint8Array(Ai);return jo(f,h),{publicKey:f,secretKey:h}},r.sign.keyPair.fromSecretKey=function(f){if(xt(f),f.length!==Ai)throw new Error("bad secret key size");for(var h=new Uint8Array(si),l=0;l<h.length;l++)h[l]=f[32+l];return{publicKey:h,secretKey:new Uint8Array(f)}},r.sign.keyPair.fromSeed=function(f){if(xt(f),f.length!==Vo)throw new Error("bad seed size");for(var h=new Uint8Array(si),l=new Uint8Array(Ai),o=0;o<32;o++)l[o]=f[o];return jo(h,l,!0),{publicKey:h,secretKey:l}},r.sign.publicKeyLength=si,r.sign.secretKeyLength=Ai,r.sign.seedLength=Vo,r.sign.signatureLength=yr,r.hash=function(f){xt(f);var h=new Uint8Array(zo);return ni(h,f,f.length),h},r.hash.hashLength=zo,r.verify=function(f,h){return xt(f,h),f.length===0||h.length===0||f.length!==h.length?!1:S(f,0,h,0,f.length)===0},r.setPRNG=function(f){t=f},(function(){var f=typeof self<"u"?self.crypto||self.msCrypto:null;if(f&&f.getRandomValues){var h=65536;r.setPRNG(function(l,o){var g,v=new Uint8Array(o);for(g=0;g<o;g+=h)f.getRandomValues(v.subarray(g,g+Math.min(o-g,h)));for(g=0;g<o;g++)l[g]=v[g];Of(v)})}else typeof require<"u"&&(f=require("crypto"),f&&f.randomBytes&&r.setPRNG(function(l,o){var g,v=f.randomBytes(o);for(g=0;g<o;g++)l[g]=v[g];Of(v)}))})()})(typeof ps<"u"&&ps.exports?ps.exports:self.nacl=self.nacl||{})});var vn=M((Gf,gs)=>{(function(r,e){"use strict";typeof gs<"u"&&gs.exports?gs.exports=e():(r.nacl||(r.nacl={}),r.nacl.util=e())})(Gf,function(){"use strict";var r={};function e(t){if(!/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(t))throw new TypeError("invalid encoding")}return r.decodeUTF8=function(t){if(typeof t!="string")throw new TypeError("expected string");var i,n=unescape(encodeURIComponent(t)),s=new Uint8Array(n.length);for(i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s},r.encodeUTF8=function(t){var i,n=[];for(i=0;i<t.length;i++)n.push(String.fromCharCode(t[i]));return decodeURIComponent(escape(n.join("")))},typeof atob>"u"?typeof Buffer.from<"u"?(r.encodeBase64=function(t){return Buffer.from(t).toString("base64")},r.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(Buffer.from(t,"base64"),0))}):(r.encodeBase64=function(t){return new Buffer(t).toString("base64")},r.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(new Buffer(t,"base64"),0))}):(r.encodeBase64=function(t){var i,n=[],s=t.length;for(i=0;i<s;i++)n.push(String.fromCharCode(t[i]));return btoa(n.join(""))},r.decodeBase64=function(t){e(t);var i,n=atob(t),s=new Uint8Array(n.length);for(i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}),r})});var Yf=M(Tt=>{"use strict";var jp=Tt&&Tt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Tt,"__esModule",{value:!0});Tt.concatBytes=bn;Tt.generateIdentityKeyPair=Up;Tt.identityPublicFromSecret=Kp;Tt.signSessionKey=qp;Tt.verifySessionKey=Wp;Tt.buildKxCanonical=Hp;Tt.buildKxAckCanonical=Vp;Tt.fingerprintIdentityKey=zp;Tt.fingerprintShortHex=$p;var er=jp(_n()),St=vn(),ms=Jo();function bn(...r){let e=0;for(let n of r)e+=n.length;let t=new Uint8Array(e),i=0;for(let n of r)t.set(n,i),i+=n.length;return t}function Up(){let r=er.default.sign.keyPair();return{identityPublicKey:(0,St.encodeBase64)(r.publicKey),identitySecretKey:(0,St.encodeBase64)(r.secretKey)}}function Kp(r){let e=(0,St.decodeBase64)(r);if(e.length!==er.default.sign.secretKeyLength)throw new Error("bad identity secret key length");let t=er.default.sign.keyPair.fromSecretKey(e);return(0,St.encodeBase64)(t.publicKey)}function qp(r,e){let t=(0,St.decodeBase64)(e);if(t.length!==er.default.sign.secretKeyLength)throw new Error("bad identity secret key length");return(0,St.encodeBase64)(er.default.sign.detached(r,t))}function Wp(r,e,t){try{let i=(0,St.decodeBase64)(e),n=(0,St.decodeBase64)(t);return n.length!==er.default.sign.publicKeyLength||i.length!==er.default.sign.signatureLength?!1:er.default.sign.detached.verify(r,i,n)}catch{return!1}}var oi=new Uint8Array([0]);function Hp(r){let e=new TextEncoder,t=e.encode(ms.KX_SIGN_LABEL),i=e.encode(r.agentId),n=e.encode(String(r.keyVersion)),s=(0,St.decodeBase64)(r.boxPublicKey);return bn(t,oi,i,oi,n,oi,s)}function Vp(r){let e=new TextEncoder;return bn(e.encode(ms.KX_ACK_LABEL),oi,e.encode(r.agentId),oi,e.encode(String(r.keyVersion)),oi,(0,St.decodeBase64)(r.boxPublicKey),oi,(0,St.decodeBase64)(r.boundClientKey))}function zp(r){let e=(0,St.decodeBase64)(r),t=bn(new TextEncoder().encode(ms.KX_FINGERPRINT_LABEL),e),i=er.default.hash(t),n=[];for(let s=0;s<12;s++){let a=s*5,u=(((i[a]<<24>>>0)+(i[a+1]<<16)+(i[a+2]<<8)+i[a+3]^i[a+4])>>>0)%1e5;n.push(String(u).padStart(5,"0"))}return n.join(" ")}function $p(r){let e=(0,St.decodeBase64)(r),t=bn(new TextEncoder().encode(ms.KX_FINGERPRINT_LABEL),e),i=er.default.hash(t).slice(0,8);return Array.from(i).map(n=>n.toString(16).padStart(2,"0")).join(":").toUpperCase()}});var Xf=M(jr=>{"use strict";var Gp=jr&&jr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(jr,"__esModule",{value:!0});jr.encrypt=Yp;jr.decrypt=Xp;jr.encryptBinary=Jp;jr.decryptBinary=Zp;var br=Gp(_n()),Br=vn();function Yp(r,e,t){let i=br.default.randomBytes(br.default.secretbox.nonceLength),n=new TextEncoder().encode(r),s=br.default.secretbox(n,i,e);return{v:1,sid:t,n:(0,Br.encodeBase64)(i),c:(0,Br.encodeBase64)(s)}}function Xp(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Br.decodeBase64)(r.n),i=(0,Br.decodeBase64)(r.c);if(t.length!==br.default.secretbox.nonceLength)throw new Error(`Invalid nonce length: ${t.length}`);let n=br.default.secretbox.open(i,t,e);if(!n)throw new Error("Decryption failed: invalid ciphertext or wrong key");return new TextDecoder().decode(n)}function Jp(r,e,t){let i=br.default.randomBytes(br.default.secretbox.nonceLength),n=br.default.secretbox(r,i,e);return{v:1,sid:t,n:(0,Br.encodeBase64)(i),c:(0,Br.encodeBase64)(n)}}function Zp(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Br.decodeBase64)(r.n),i=(0,Br.decodeBase64)(r.c),n=br.default.secretbox.open(i,t,e);if(!n)throw new Error("Decryption failed: invalid ciphertext or wrong key");return n}});var Jf=M(Wt=>{"use strict";var Qp=Wt&&Wt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Wt,"__esModule",{value:!0});Wt.generateKeyPair=eg;Wt.deriveSharedSecret=tg;Wt.deriveMetaSid=rg;Wt.isValidPublicKey=ig;Wt.clearKey=ng;Wt.keyToBase64=sg;Wt.base64ToKey=og;var Li=Qp(_n()),tr=vn();function eg(){let r=Li.default.box.keyPair();return{publicKey:(0,tr.encodeBase64)(r.publicKey),secretKey:(0,tr.encodeBase64)(r.secretKey)}}function tg(r,e){let t=(0,tr.decodeBase64)(r),i=(0,tr.decodeBase64)(e);if(t.length!==Li.default.box.publicKeyLength)throw new Error(`Invalid public key length: ${t.length}`);if(i.length!==Li.default.box.secretKeyLength)throw new Error(`Invalid secret key length: ${i.length}`);return Li.default.box.before(t,i)}function rg(r,e){let t=new TextEncoder().encode("termiq-meta-v1"),i=(0,tr.decodeBase64)(r),n=(0,tr.decodeBase64)(e),s=new Uint8Array(t.length+i.length+n.length);return s.set(t,0),s.set(i,t.length),s.set(n,t.length+i.length),(0,tr.encodeBase64)(Li.default.hash(s).slice(0,32))}function ig(r){try{return(0,tr.decodeBase64)(r).length===Li.default.box.publicKeyLength}catch{return!1}}function ng(r){r.fill(0)}function sg(r){return(0,tr.encodeBase64)(r)}function og(r){return(0,tr.decodeBase64)(r)}});var Qf=M(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.base64ToKey=te.keyToBase64=te.clearKey=te.isValidPublicKey=te.deriveMetaSid=te.deriveSharedSecret=te.generateKeyPair=te.decryptBinary=te.encryptBinary=te.decrypt=te.encrypt=te.concatBytes=te.fingerprintShortHex=te.fingerprintIdentityKey=te.buildKxAckCanonical=te.buildKxCanonical=te.verifySessionKey=te.signSessionKey=te.identityPublicFromSecret=te.generateIdentityKeyPair=te.KX_SIG_VERSION=te.KX_FINGERPRINT_LABEL=te.KX_ACK_LABEL=te.KX_SIGN_LABEL=te.isMultiRecipientPayload=te.isEncryptedPayload=void 0;var Zf=$f();Object.defineProperty(te,"isEncryptedPayload",{enumerable:!0,get:function(){return Zf.isEncryptedPayload}});Object.defineProperty(te,"isMultiRecipientPayload",{enumerable:!0,get:function(){return Zf.isMultiRecipientPayload}});var ys=Jo();Object.defineProperty(te,"KX_SIGN_LABEL",{enumerable:!0,get:function(){return ys.KX_SIGN_LABEL}});Object.defineProperty(te,"KX_ACK_LABEL",{enumerable:!0,get:function(){return ys.KX_ACK_LABEL}});Object.defineProperty(te,"KX_FINGERPRINT_LABEL",{enumerable:!0,get:function(){return ys.KX_FINGERPRINT_LABEL}});Object.defineProperty(te,"KX_SIG_VERSION",{enumerable:!0,get:function(){return ys.KX_SIG_VERSION}});var Er=Yf();Object.defineProperty(te,"generateIdentityKeyPair",{enumerable:!0,get:function(){return Er.generateIdentityKeyPair}});Object.defineProperty(te,"identityPublicFromSecret",{enumerable:!0,get:function(){return Er.identityPublicFromSecret}});Object.defineProperty(te,"signSessionKey",{enumerable:!0,get:function(){return Er.signSessionKey}});Object.defineProperty(te,"verifySessionKey",{enumerable:!0,get:function(){return Er.verifySessionKey}});Object.defineProperty(te,"buildKxCanonical",{enumerable:!0,get:function(){return Er.buildKxCanonical}});Object.defineProperty(te,"buildKxAckCanonical",{enumerable:!0,get:function(){return Er.buildKxAckCanonical}});Object.defineProperty(te,"fingerprintIdentityKey",{enumerable:!0,get:function(){return Er.fingerprintIdentityKey}});Object.defineProperty(te,"fingerprintShortHex",{enumerable:!0,get:function(){return Er.fingerprintShortHex}});Object.defineProperty(te,"concatBytes",{enumerable:!0,get:function(){return Er.concatBytes}});var _s=Xf();Object.defineProperty(te,"encrypt",{enumerable:!0,get:function(){return _s.encrypt}});Object.defineProperty(te,"decrypt",{enumerable:!0,get:function(){return _s.decrypt}});Object.defineProperty(te,"encryptBinary",{enumerable:!0,get:function(){return _s.encryptBinary}});Object.defineProperty(te,"decryptBinary",{enumerable:!0,get:function(){return _s.decryptBinary}});var ai=Jf();Object.defineProperty(te,"generateKeyPair",{enumerable:!0,get:function(){return ai.generateKeyPair}});Object.defineProperty(te,"deriveSharedSecret",{enumerable:!0,get:function(){return ai.deriveSharedSecret}});Object.defineProperty(te,"deriveMetaSid",{enumerable:!0,get:function(){return ai.deriveMetaSid}});Object.defineProperty(te,"isValidPublicKey",{enumerable:!0,get:function(){return ai.isValidPublicKey}});Object.defineProperty(te,"clearKey",{enumerable:!0,get:function(){return ai.clearKey}});Object.defineProperty(te,"keyToBase64",{enumerable:!0,get:function(){return ai.keyToBase64}});Object.defineProperty(te,"base64ToKey",{enumerable:!0,get:function(){return ai.base64ToKey}})});var eu=M(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.MIN_CLIENT_VERSION=Ct.PROTOCOL_VERSION_MINOR=Ct.PROTOCOL_VERSION_MAJOR=Ct.PROTOCOL_VERSION=void 0;Ct.isCompatibleVersion=ag;Ct.compareVersions=cg;Ct.PROTOCOL_VERSION="2.1";Ct.PROTOCOL_VERSION_MAJOR=2;Ct.PROTOCOL_VERSION_MINOR=1;Ct.MIN_CLIENT_VERSION="2.0";function ag(r){let[e]=r.split(".").map(Number);return e===Ct.PROTOCOL_VERSION_MAJOR}function cg(r,e){let[t,i]=r.split(".").map(Number),[n,s]=e.split(".").map(Number);return t!==n?t<n?-1:1:i!==s?i<s?-1:1:0}});var tu=M(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.SERVER_CAPABILITIES=rr.DEFAULT_CLIENT_CAPABILITIES=rr.Capability=void 0;rr.hasCapability=fg;rr.negotiateCapabilities=ug;var Ni;(function(r){r.FILE_TRANSFER="file-transfer",r.RELIABLE_MESSAGING="reliable-messaging",r.COMPRESSION="compression",r.E2E_ENCRYPTION="e2e-encryption",r.PRIORITY_QUEUES="priority-queues",r.OFFLINE_QUEUE="offline-queue",r.MULTI_DEVICE="multi-device",r.TERMINAL_EVENTS="terminal-events",r.E2E_PRIVACY="e2e-privacy",r.RELIABLE_INPUT="reliable-input",r.MULTI_VIEWER_RENDER="multi-viewer-render"})(Ni||(rr.Capability=Ni={}));rr.DEFAULT_CLIENT_CAPABILITIES=[Ni.E2E_ENCRYPTION,Ni.TERMINAL_EVENTS,Ni.RELIABLE_INPUT];rr.SERVER_CAPABILITIES=Object.values(Ni);function fg(r,e){return r.includes(e)}function ug(r,e){return r.filter(t=>e.includes(t))}});var ru=M(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.DEFAULT_PRIORITY=wr.PRIORITY_NAMES=wr.Priority=void 0;wr.comparePriority=lg;var ci;(function(r){r[r.CRITICAL=0]="CRITICAL",r[r.HIGH=1]="HIGH",r[r.NORMAL=2]="NORMAL",r[r.LOW=3]="LOW"})(ci||(wr.Priority=ci={}));wr.PRIORITY_NAMES={[ci.CRITICAL]:"CRITICAL",[ci.HIGH]:"HIGH",[ci.NORMAL]:"NORMAL",[ci.LOW]:"LOW"};wr.DEFAULT_PRIORITY=ci.NORMAL;function lg(r,e){return r-e}});var iu=M(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.DEFAULT_RELIABILITY=ir.RELIABILITY_NAMES=ir.Reliability=void 0;ir.requiresAck=hg;ir.requiresBuffer=dg;var Ur;(function(r){r[r.FIRE_FORGET=0]="FIRE_FORGET",r[r.BUFFERED=1]="BUFFERED",r[r.GUARANTEED=2]="GUARANTEED"})(Ur||(ir.Reliability=Ur={}));ir.RELIABILITY_NAMES={[Ur.FIRE_FORGET]:"FIRE_FORGET",[Ur.BUFFERED]:"BUFFERED",[Ur.GUARANTEED]:"GUARANTEED"};ir.DEFAULT_RELIABILITY=Ur.FIRE_FORGET;function hg(r){return r===Ur.GUARANTEED}function dg(r){return r>=Ur.BUFFERED}});var nu=M(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.createMessage=pg;function pg(r,e,t={}){return{id:crypto.randomUUID(),type:r,payload:e,priority:t.priority??2,reliability:t.reliability??0,seq:t.seq,timestamp:new Date().toISOString()}}});var su=M(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.TerminalEventType=void 0;fi.deriveStatusFromEvent=gg;fi.shouldTriggerPushNotification=mg;fi.getPushNotificationMessage=yg;var mt;(function(r){r.SESSION_START="session_start",r.SESSION_END="session_end",r.MESSAGE="message",r.TOOL_START="tool_start",r.TOOL_END="tool_end",r.WAITING_INPUT="waiting_input",r.ERROR="error"})(mt||(fi.TerminalEventType=mt={}));function gg(r){switch(r.type){case mt.SESSION_START:case mt.TOOL_START:case mt.MESSAGE:return"working";case mt.WAITING_INPUT:return"waiting";case mt.SESSION_END:return r.status==="success"?"completed":"error";case mt.ERROR:return r.severity==="fatal"?"error":"working";case mt.TOOL_END:return r.status==="error"?"error":"working";default:return"idle"}}function mg(r){switch(r.type){case mt.WAITING_INPUT:return!0;case mt.SESSION_END:return!0;case mt.ERROR:return r.severity!=="warning";default:return!1}}function yg(r,e){switch(r.type){case mt.WAITING_INPUT:return{title:`${e}: Input Required`,body:r.question.slice(0,100)};case mt.SESSION_END:{let t=r;return t.status==="success"?{title:`${e}: Task Completed`,body:t.summary||"Session finished successfully"}:{title:`${e}: Task Failed`,body:t.summary||"Session ended with error"}}case mt.ERROR:{let t=r;return t.severity==="warning"?null:{title:`${e}: Error`,body:t.message.slice(0,100)}}default:return null}}});var cu=M(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.TransferDirection=Ue.TransferStatus=Ue.CHUNK_TTL_SECONDS=Ue.TRANSFER_TTL_SECONDS=Ue.MAX_RETRIES=Ue.ACK_TIMEOUT_MS=Ue.WINDOW_SIZE=Ue.DEFAULT_MAX_FILE_SIZE=Ue.CHUNK_SIZE=void 0;Ue.calculateTotalChunks=_g;Ue.getMissingChunks=vg;Ue.isTransferComplete=bg;Ue.CHUNK_SIZE=64*1024;Ue.DEFAULT_MAX_FILE_SIZE=100*1024*1024;Ue.WINDOW_SIZE=10;Ue.ACK_TIMEOUT_MS=3e4;Ue.MAX_RETRIES=3;Ue.TRANSFER_TTL_SECONDS=1440*60;Ue.CHUNK_TTL_SECONDS=1440*60;var ou;(function(r){r.PENDING="pending",r.ACTIVE="active",r.PAUSED="paused",r.COMPLETED="completed",r.FAILED="failed",r.CANCELLED="cancelled",r.EXPIRED="expired"})(ou||(Ue.TransferStatus=ou={}));var au;(function(r){r.DOWNLOAD="download",r.UPLOAD="upload"})(au||(Ue.TransferDirection=au={}));function _g(r,e=Ue.CHUNK_SIZE){return Math.ceil(r/e)}function vg(r,e){let t=new Set(e),i=[];for(let n=0;n<r;n++)t.has(n)||i.push(n);return i}function bg(r,e){return e.length===r}});var fu=M(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.ERROR_MESSAGES=xr.ErrorCode=void 0;xr.createError=Eg;xr.isRetryableError=wg;var Ie;(function(r){r.AUTH_FAILED="E001",r.TOKEN_EXPIRED="E002",r.TOKEN_INVALID="E003",r.NOT_FOUND="E011",r.ALREADY_EXISTS="E012",r.ACCESS_DENIED="E021",r.FORBIDDEN="E022",r.RATE_LIMITED="E031",r.TOO_MANY_CONNECTIONS="E032",r.QUOTA_EXCEEDED="E041",r.FILE_TOO_LARGE="E042",r.QUEUE_FULL="E043",r.TRANSFERS_LIMIT="E044",r.TRANSFER_FAILED="E051",r.TRANSFER_EXPIRED="E052",r.TRANSFER_CANCELLED="E053",r.CHECKSUM_MISMATCH="E054",r.CHUNK_MISSING="E055",r.INVALID_MESSAGE="E061",r.UNSUPPORTED_VERSION="E062",r.CAPABILITY_REQUIRED="E063",r.INVALID_STATE="E071",r.TIMEOUT="E072",r.CONNECTION_LOST="E073",r.INTERNAL_ERROR="E091",r.SERVICE_UNAVAILABLE="E092"})(Ie||(xr.ErrorCode=Ie={}));xr.ERROR_MESSAGES={[Ie.AUTH_FAILED]:"Authentication failed",[Ie.TOKEN_EXPIRED]:"Token expired",[Ie.TOKEN_INVALID]:"Invalid token",[Ie.NOT_FOUND]:"Resource not found",[Ie.ALREADY_EXISTS]:"Resource already exists",[Ie.ACCESS_DENIED]:"Access denied",[Ie.FORBIDDEN]:"Operation forbidden",[Ie.RATE_LIMITED]:"Rate limit exceeded",[Ie.TOO_MANY_CONNECTIONS]:"Too many connections",[Ie.QUOTA_EXCEEDED]:"Plan quota exceeded",[Ie.FILE_TOO_LARGE]:"File size exceeds limit",[Ie.QUEUE_FULL]:"Message queue is full",[Ie.TRANSFERS_LIMIT]:"Daily transfers limit reached",[Ie.TRANSFER_FAILED]:"File transfer failed",[Ie.TRANSFER_EXPIRED]:"Transfer expired",[Ie.TRANSFER_CANCELLED]:"Transfer cancelled",[Ie.CHECKSUM_MISMATCH]:"File checksum mismatch",[Ie.CHUNK_MISSING]:"Chunk missing or corrupted",[Ie.INVALID_MESSAGE]:"Invalid message format",[Ie.UNSUPPORTED_VERSION]:"Unsupported protocol version",[Ie.CAPABILITY_REQUIRED]:"Required capability not supported",[Ie.INVALID_STATE]:"Invalid state for this operation",[Ie.TIMEOUT]:"Operation timed out",[Ie.CONNECTION_LOST]:"Connection lost",[Ie.INTERNAL_ERROR]:"Internal server error",[Ie.SERVICE_UNAVAILABLE]:"Service temporarily unavailable"};function Eg(r,e={}){return{code:r,message:e.message||xr.ERROR_MESSAGES[r],details:e.details,retryable:e.retryable??!1,retryAfter:e.retryAfter}}function wg(r){return[Ie.RATE_LIMITED,Ie.TIMEOUT,Ie.CONNECTION_LOST,Ie.SERVICE_UNAVAILABLE].includes(r)}});var du=M(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.FileEntryType=kt.DiffBase=kt.FileViewType=kt.FileChangeType=void 0;kt.getLanguageFromPath=xg;kt.parseUnifiedDiff=Sg;kt.createSimpleDiff=Tg;var Kr;(function(r){r.CREATE="create",r.MODIFY="modify",r.DELETE="delete"})(Kr||(kt.FileChangeType=Kr={}));var uu;(function(r){r.CONTENT="content",r.DIFF="diff"})(uu||(kt.FileViewType=uu={}));var lu;(function(r){r.GIT="git",r.PREVIOUS="previous"})(lu||(kt.DiffBase=lu={}));function xg(r){let e=r.split(".").pop()?.toLowerCase(),t={js:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",mjs:"javascript",cjs:"javascript",html:"html",htm:"html",css:"css",scss:"scss",sass:"scss",less:"less",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",toml:"toml",md:"markdown",mdx:"markdown",env:"plaintext",gitignore:"plaintext",dockerignore:"plaintext",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",py:"python",pyw:"python",pyi:"python",go:"go",rs:"rust",java:"java",kt:"kotlin",kts:"kotlin",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",sql:"sql",graphql:"graphql",gql:"graphql",prisma:"prisma",dockerfile:"dockerfile"},i=r.split("/").pop()?.toLowerCase()||"";return{dockerfile:"dockerfile",makefile:"makefile",".gitignore":"plaintext",".env":"plaintext",".env.local":"plaintext",".env.development":"plaintext",".env.production":"plaintext"}[i]||t[e||""]||"plaintext"}function Sg(r,e){let t=r.split(`
|
|
3
|
-
`),i=[],n=0,s=0,a=null,c=0,u=0;for(let p of t){if(p.startsWith("diff ")||p.startsWith("index ")||p.startsWith("---")||p.startsWith("+++"))continue;let m=p.match(/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@/);if(m){a&&i.push(a);let _=parseInt(m[1],10),
|
|
2
|
+
"use strict";var _p=Object.create;var $o=Object.defineProperty;var bp=Object.getOwnPropertyDescriptor;var Ep=Object.getOwnPropertyNames;var vp=Object.getPrototypeOf,wp=Object.prototype.hasOwnProperty;var qt=(r,e)=>()=>(r&&(e=r(r=0)),e);var M=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Sp=(r,e)=>{for(var t in e)$o(r,t,{get:e[t],enumerable:!0})},xp=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ep(e))!wp.call(r,n)&&n!==t&&$o(r,n,{get:()=>e[n],enumerable:!(i=bp(e,n))||i.enumerable});return r};var de=(r,e,t)=>(t=r!=null?_p(vp(r)):{},xp(e||!r||!r.__esModule?$o(t,"default",{value:r,enumerable:!0}):t,r));var as=M(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.generateCorrelationId=kp;yn.runWithCorrelation=Op;yn.getCurrentCorrelationId=Pp;var Cp=require("async_hooks");function kp(){let r=new Uint8Array(4),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(r);else for(let t=0;t<4;t++)r[t]=Math.floor(Math.random()*256);return"c-"+Array.from(r,t=>t.toString(16).padStart(2,"0")).join("")}var Af=new Cp.AsyncLocalStorage;function Op(r,e){return Af.run(r,e)}function Pp(){return Af.getStore()}});var Lf=M(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});Ii.LOG_LEVELS=void 0;Ii.shouldLog=Ap;Ii.formatLogLine=Ip;var Rp=as();Ii.LOG_LEVELS=["silent","error","warn","info","debug"];var If={silent:0,error:1,warn:2,info:3,debug:4};function Ap(r,e){return If[r]<=If[e]}function Ip(r,e,t,i){let n={ts:new Date().toISOString(),level:r,src:e,msg:t},s=(0,Rp.getCurrentCorrelationId)();s&&(n.cid=s);let a=i;a.length>0&&typeof a[0]=="object"&&a[0]!==null&&!(a[0]instanceof Error)&&!Array.isArray(a[0])&&(n.ctx=a[0],a=a.slice(1));let c=[...a].reverse().find(u=>u instanceof Error);c&&(n.err={message:c.message,stack:c.stack,name:c.name},a=a.filter(u=>u!==c)),a.length>0&&(n.args=a);try{return JSON.stringify(n)}catch{return JSON.stringify({ts:n.ts,level:r,src:e,msg:t,_unserializable:!0})}}});var Nf=M(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});Dr.formatLogLine=Dr.shouldLog=Dr.LOG_LEVELS=void 0;var Go=Lf();Object.defineProperty(Dr,"LOG_LEVELS",{enumerable:!0,get:function(){return Go.LOG_LEVELS}});Object.defineProperty(Dr,"shouldLog",{enumerable:!0,get:function(){return Go.shouldLog}});Object.defineProperty(Dr,"formatLogLine",{enumerable:!0,get:function(){return Go.formatLogLine}})});var Mf=M(cs=>{"use strict";Object.defineProperty(cs,"__esModule",{value:!0});cs.CircularBuffer=void 0;var Yo=class{buffer=[];totalSize=0;maxSize;constructor(e=100){this.maxSize=e*1024}append(e){for(this.buffer.push(e),this.totalSize+=e.length;this.totalSize>this.maxSize&&this.buffer.length>1;){let t=this.buffer.shift();t&&(this.totalSize-=t.length)}}getContent(){return this.buffer.join("")}getLastBytes(e){let t=this.getContent();return t.length<=e?t:t.slice(-e)}getSize(){return this.totalSize}clear(){this.buffer=[],this.totalSize=0}};cs.CircularBuffer=Yo});var us=M(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});fs.getApiUrl=Lp;fs.getWsUrl=Np;function Lp(r){return`${r.getServerUrl()}/api`}function Np(r){let e=r.getServerUrl();return e.startsWith("https://")?e.replace(/^https:\/\//,"wss://"):e.replace(/^http:\/\//,"ws://")}});var Df=M(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.getCurrentCorrelationId=Et.runWithCorrelation=Et.generateCorrelationId=Et.getWsUrl=Et.getApiUrl=Et.CircularBuffer=void 0;var Mp=Mf();Object.defineProperty(Et,"CircularBuffer",{enumerable:!0,get:function(){return Mp.CircularBuffer}});var Ff=us();Object.defineProperty(Et,"getApiUrl",{enumerable:!0,get:function(){return Ff.getApiUrl}});Object.defineProperty(Et,"getWsUrl",{enumerable:!0,get:function(){return Ff.getWsUrl}});var Xo=as();Object.defineProperty(Et,"generateCorrelationId",{enumerable:!0,get:function(){return Xo.generateCorrelationId}});Object.defineProperty(Et,"runWithCorrelation",{enumerable:!0,get:function(){return Xo.runWithCorrelation}});Object.defineProperty(Et,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Xo.getCurrentCorrelationId}})});var jf=M(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0})});var Kf=M(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0})});var qf=M(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});ls.PLAN_LIMITS=void 0;ls.PLAN_LIMITS={free:{maxAgents:1,maxTerminals:2,maxTeamMembers:1,historyDays:1},basic:{maxAgents:3,maxTerminals:10,maxTeamMembers:1,historyDays:7},pro:{maxAgents:10,maxTerminals:50,maxTeamMembers:5,historyDays:30}}});var Hf=M(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0})});var Vf=M(Zt=>{"use strict";var Fp=Zt&&Zt.__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]})),hs=Zt&&Zt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Fp(e,r,t)};Object.defineProperty(Zt,"__esModule",{value:!0});hs(jf(),Zt);hs(Kf(),Zt);hs(qf(),Zt);hs(Hf(),Zt)});var zf=M(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.API_VERSION=It.WS_NAMESPACES=It.TIMEOUTS=It.STATUS_PATTERNS=It.TERMINAL_STATUSES=void 0;It.TERMINAL_STATUSES={idle:{label:"Idle",color:"gray",icon:"\u25CF"},working:{label:"Working",color:"blue",icon:"\u27F3"},waiting:{label:"Awaiting input",color:"orange",icon:"\u26A0"},completed:{label:"Completed",color:"green",icon:"\u2713"},error:{label:"Error",color:"red",icon:"\u2715"},offline:{label:"Offline",color:"black",icon:"\u26AB"}};It.STATUS_PATTERNS={idle:[/[❯$]\s*$/,/>\s*$/],waiting:[/\[Y\/n\]/i,/\(y\/N\)/i,/Continue\?/i,/proceed\?/i],completed:[/✓/,/Done/,/Completed/,/Success/],error:[/Error/,/Failed/,/✕/,/Exception/]};It.TIMEOUTS={HEARTBEAT_INTERVAL:3e4,OFFLINE_THRESHOLD:6e4,DEVICE_CODE_EXPIRY:9e5,DEVICE_CODE_POLL_INTERVAL:5e3};It.WS_NAMESPACES={AGENT:"/agent",CLIENT:"/client"};It.API_VERSION="v1"});var $f=M(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});ds.isMultiRecipientPayload=Dp;ds.isEncryptedPayload=Bp;function Dp(r){return typeof r=="object"&&r!==null&&"v"in r&&r.v===2&&"recipients"in r&&Array.isArray(r.recipients)}function Bp(r){if(typeof r!="object"||r===null||!("encrypted"in r))return!1;let e=r.encrypted;if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.v=="number"&&typeof t.sid=="string"&&typeof t.n=="string"&&typeof t.c=="string"}});var Jo=M(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.KX_SIG_VERSION=Qt.KX_FINGERPRINT_LABEL=Qt.KX_ACK_LABEL=Qt.KX_SIGN_LABEL=void 0;Qt.KX_SIGN_LABEL="termiq-kx-v1";Qt.KX_ACK_LABEL="termiq-kxack-v1";Qt.KX_FINGERPRINT_LABEL="termiq-fp-v1";Qt.KX_SIG_VERSION=1});var _n=M((sv,ps)=>{(function(r){"use strict";var e=function(f){var h,l=new Float64Array(16);if(f)for(h=0;h<f.length;h++)l[h]=f[h];return l},t=function(){throw new Error("no PRNG")},i=new Uint8Array(16),n=new Uint8Array(32);n[0]=9;var s=e(),a=e([1]),c=e([56129,1]),u=e([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),d=e([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),p=e([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),m=e([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),_=e([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function v(f,h,l,o){f[h]=l>>24&255,f[h+1]=l>>16&255,f[h+2]=l>>8&255,f[h+3]=l&255,f[h+4]=o>>24&255,f[h+5]=o>>16&255,f[h+6]=o>>8&255,f[h+7]=o&255}function T(f,h,l,o,g){var b,E=0;for(b=0;b<g;b++)E|=f[h+b]^l[o+b];return(1&E-1>>>8)-1}function x(f,h,l,o){return T(f,h,l,o,16)}function H(f,h,l,o){return T(f,h,l,o,32)}function oe(f,h,l,o){for(var g=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,b=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,E=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,O=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,D=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,Z=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,W=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,Pe=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,z=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,ae=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,ce=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,ge=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,pe=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,fe=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,le=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ue=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,$=g,ee=b,V=E,G=O,Y=D,q=Z,w=W,S=Pe,I=z,C=ae,P=ce,F=ge,ie=pe,me=fe,Ee=le,ye=ue,y,Se=0;Se<20;Se+=2)y=$+ie|0,Y^=y<<7|y>>>25,y=Y+$|0,I^=y<<9|y>>>23,y=I+Y|0,ie^=y<<13|y>>>19,y=ie+I|0,$^=y<<18|y>>>14,y=q+ee|0,C^=y<<7|y>>>25,y=C+q|0,me^=y<<9|y>>>23,y=me+C|0,ee^=y<<13|y>>>19,y=ee+me|0,q^=y<<18|y>>>14,y=P+w|0,Ee^=y<<7|y>>>25,y=Ee+P|0,V^=y<<9|y>>>23,y=V+Ee|0,w^=y<<13|y>>>19,y=w+V|0,P^=y<<18|y>>>14,y=ye+F|0,G^=y<<7|y>>>25,y=G+ye|0,S^=y<<9|y>>>23,y=S+G|0,F^=y<<13|y>>>19,y=F+S|0,ye^=y<<18|y>>>14,y=$+G|0,ee^=y<<7|y>>>25,y=ee+$|0,V^=y<<9|y>>>23,y=V+ee|0,G^=y<<13|y>>>19,y=G+V|0,$^=y<<18|y>>>14,y=q+Y|0,w^=y<<7|y>>>25,y=w+q|0,S^=y<<9|y>>>23,y=S+w|0,Y^=y<<13|y>>>19,y=Y+S|0,q^=y<<18|y>>>14,y=P+C|0,F^=y<<7|y>>>25,y=F+P|0,I^=y<<9|y>>>23,y=I+F|0,C^=y<<13|y>>>19,y=C+I|0,P^=y<<18|y>>>14,y=ye+Ee|0,ie^=y<<7|y>>>25,y=ie+ye|0,me^=y<<9|y>>>23,y=me+ie|0,Ee^=y<<13|y>>>19,y=Ee+me|0,ye^=y<<18|y>>>14;$=$+g|0,ee=ee+b|0,V=V+E|0,G=G+O|0,Y=Y+D|0,q=q+Z|0,w=w+W|0,S=S+Pe|0,I=I+z|0,C=C+ae|0,P=P+ce|0,F=F+ge|0,ie=ie+pe|0,me=me+fe|0,Ee=Ee+le|0,ye=ye+ue|0,f[0]=$>>>0&255,f[1]=$>>>8&255,f[2]=$>>>16&255,f[3]=$>>>24&255,f[4]=ee>>>0&255,f[5]=ee>>>8&255,f[6]=ee>>>16&255,f[7]=ee>>>24&255,f[8]=V>>>0&255,f[9]=V>>>8&255,f[10]=V>>>16&255,f[11]=V>>>24&255,f[12]=G>>>0&255,f[13]=G>>>8&255,f[14]=G>>>16&255,f[15]=G>>>24&255,f[16]=Y>>>0&255,f[17]=Y>>>8&255,f[18]=Y>>>16&255,f[19]=Y>>>24&255,f[20]=q>>>0&255,f[21]=q>>>8&255,f[22]=q>>>16&255,f[23]=q>>>24&255,f[24]=w>>>0&255,f[25]=w>>>8&255,f[26]=w>>>16&255,f[27]=w>>>24&255,f[28]=S>>>0&255,f[29]=S>>>8&255,f[30]=S>>>16&255,f[31]=S>>>24&255,f[32]=I>>>0&255,f[33]=I>>>8&255,f[34]=I>>>16&255,f[35]=I>>>24&255,f[36]=C>>>0&255,f[37]=C>>>8&255,f[38]=C>>>16&255,f[39]=C>>>24&255,f[40]=P>>>0&255,f[41]=P>>>8&255,f[42]=P>>>16&255,f[43]=P>>>24&255,f[44]=F>>>0&255,f[45]=F>>>8&255,f[46]=F>>>16&255,f[47]=F>>>24&255,f[48]=ie>>>0&255,f[49]=ie>>>8&255,f[50]=ie>>>16&255,f[51]=ie>>>24&255,f[52]=me>>>0&255,f[53]=me>>>8&255,f[54]=me>>>16&255,f[55]=me>>>24&255,f[56]=Ee>>>0&255,f[57]=Ee>>>8&255,f[58]=Ee>>>16&255,f[59]=Ee>>>24&255,f[60]=ye>>>0&255,f[61]=ye>>>8&255,f[62]=ye>>>16&255,f[63]=ye>>>24&255}function J(f,h,l,o){for(var g=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,b=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,E=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,O=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,D=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,Z=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,W=h[0]&255|(h[1]&255)<<8|(h[2]&255)<<16|(h[3]&255)<<24,Pe=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,z=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,ae=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,ce=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,ge=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,pe=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,fe=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,le=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ue=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,$=g,ee=b,V=E,G=O,Y=D,q=Z,w=W,S=Pe,I=z,C=ae,P=ce,F=ge,ie=pe,me=fe,Ee=le,ye=ue,y,Se=0;Se<20;Se+=2)y=$+ie|0,Y^=y<<7|y>>>25,y=Y+$|0,I^=y<<9|y>>>23,y=I+Y|0,ie^=y<<13|y>>>19,y=ie+I|0,$^=y<<18|y>>>14,y=q+ee|0,C^=y<<7|y>>>25,y=C+q|0,me^=y<<9|y>>>23,y=me+C|0,ee^=y<<13|y>>>19,y=ee+me|0,q^=y<<18|y>>>14,y=P+w|0,Ee^=y<<7|y>>>25,y=Ee+P|0,V^=y<<9|y>>>23,y=V+Ee|0,w^=y<<13|y>>>19,y=w+V|0,P^=y<<18|y>>>14,y=ye+F|0,G^=y<<7|y>>>25,y=G+ye|0,S^=y<<9|y>>>23,y=S+G|0,F^=y<<13|y>>>19,y=F+S|0,ye^=y<<18|y>>>14,y=$+G|0,ee^=y<<7|y>>>25,y=ee+$|0,V^=y<<9|y>>>23,y=V+ee|0,G^=y<<13|y>>>19,y=G+V|0,$^=y<<18|y>>>14,y=q+Y|0,w^=y<<7|y>>>25,y=w+q|0,S^=y<<9|y>>>23,y=S+w|0,Y^=y<<13|y>>>19,y=Y+S|0,q^=y<<18|y>>>14,y=P+C|0,F^=y<<7|y>>>25,y=F+P|0,I^=y<<9|y>>>23,y=I+F|0,C^=y<<13|y>>>19,y=C+I|0,P^=y<<18|y>>>14,y=ye+Ee|0,ie^=y<<7|y>>>25,y=ie+ye|0,me^=y<<9|y>>>23,y=me+ie|0,Ee^=y<<13|y>>>19,y=Ee+me|0,ye^=y<<18|y>>>14;f[0]=$>>>0&255,f[1]=$>>>8&255,f[2]=$>>>16&255,f[3]=$>>>24&255,f[4]=q>>>0&255,f[5]=q>>>8&255,f[6]=q>>>16&255,f[7]=q>>>24&255,f[8]=P>>>0&255,f[9]=P>>>8&255,f[10]=P>>>16&255,f[11]=P>>>24&255,f[12]=ye>>>0&255,f[13]=ye>>>8&255,f[14]=ye>>>16&255,f[15]=ye>>>24&255,f[16]=w>>>0&255,f[17]=w>>>8&255,f[18]=w>>>16&255,f[19]=w>>>24&255,f[20]=S>>>0&255,f[21]=S>>>8&255,f[22]=S>>>16&255,f[23]=S>>>24&255,f[24]=I>>>0&255,f[25]=I>>>8&255,f[26]=I>>>16&255,f[27]=I>>>24&255,f[28]=C>>>0&255,f[29]=C>>>8&255,f[30]=C>>>16&255,f[31]=C>>>24&255}function k(f,h,l,o){oe(f,h,l,o)}function B(f,h,l,o){J(f,h,l,o)}var te=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function j(f,h,l,o,g,b,E){var O=new Uint8Array(16),D=new Uint8Array(64),Z,W;for(W=0;W<16;W++)O[W]=0;for(W=0;W<8;W++)O[W]=b[W];for(;g>=64;){for(k(D,O,E,te),W=0;W<64;W++)f[h+W]=l[o+W]^D[W];for(Z=1,W=8;W<16;W++)Z=Z+(O[W]&255)|0,O[W]=Z&255,Z>>>=8;g-=64,h+=64,o+=64}if(g>0)for(k(D,O,E,te),W=0;W<g;W++)f[h+W]=l[o+W]^D[W];return 0}function U(f,h,l,o,g){var b=new Uint8Array(16),E=new Uint8Array(64),O,D;for(D=0;D<16;D++)b[D]=0;for(D=0;D<8;D++)b[D]=o[D];for(;l>=64;){for(k(E,b,g,te),D=0;D<64;D++)f[h+D]=E[D];for(O=1,D=8;D<16;D++)O=O+(b[D]&255)|0,b[D]=O&255,O>>>=8;l-=64,h+=64}if(l>0)for(k(E,b,g,te),D=0;D<l;D++)f[h+D]=E[D];return 0}function ne(f,h,l,o,g){var b=new Uint8Array(32);B(b,o,g,te);for(var E=new Uint8Array(8),O=0;O<8;O++)E[O]=o[O+16];return U(f,h,l,E,b)}function _e(f,h,l,o,g,b,E){var O=new Uint8Array(32);B(O,b,E,te);for(var D=new Uint8Array(8),Z=0;Z<8;Z++)D[Z]=b[Z+16];return j(f,h,l,o,g,D,O)}var se=function(f){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var h,l,o,g,b,E,O,D;h=f[0]&255|(f[1]&255)<<8,this.r[0]=h&8191,l=f[2]&255|(f[3]&255)<<8,this.r[1]=(h>>>13|l<<3)&8191,o=f[4]&255|(f[5]&255)<<8,this.r[2]=(l>>>10|o<<6)&7939,g=f[6]&255|(f[7]&255)<<8,this.r[3]=(o>>>7|g<<9)&8191,b=f[8]&255|(f[9]&255)<<8,this.r[4]=(g>>>4|b<<12)&255,this.r[5]=b>>>1&8190,E=f[10]&255|(f[11]&255)<<8,this.r[6]=(b>>>14|E<<2)&8191,O=f[12]&255|(f[13]&255)<<8,this.r[7]=(E>>>11|O<<5)&8065,D=f[14]&255|(f[15]&255)<<8,this.r[8]=(O>>>8|D<<8)&8191,this.r[9]=D>>>5&127,this.pad[0]=f[16]&255|(f[17]&255)<<8,this.pad[1]=f[18]&255|(f[19]&255)<<8,this.pad[2]=f[20]&255|(f[21]&255)<<8,this.pad[3]=f[22]&255|(f[23]&255)<<8,this.pad[4]=f[24]&255|(f[25]&255)<<8,this.pad[5]=f[26]&255|(f[27]&255)<<8,this.pad[6]=f[28]&255|(f[29]&255)<<8,this.pad[7]=f[30]&255|(f[31]&255)<<8};se.prototype.blocks=function(f,h,l){for(var o=this.fin?0:2048,g,b,E,O,D,Z,W,Pe,z,ae,ce,ge,pe,fe,le,ue,$,ee,V,G=this.h[0],Y=this.h[1],q=this.h[2],w=this.h[3],S=this.h[4],I=this.h[5],C=this.h[6],P=this.h[7],F=this.h[8],ie=this.h[9],me=this.r[0],Ee=this.r[1],ye=this.r[2],y=this.r[3],Se=this.r[4],Re=this.r[5],Ae=this.r[6],we=this.r[7],Ce=this.r[8],ke=this.r[9];l>=16;)g=f[h+0]&255|(f[h+1]&255)<<8,G+=g&8191,b=f[h+2]&255|(f[h+3]&255)<<8,Y+=(g>>>13|b<<3)&8191,E=f[h+4]&255|(f[h+5]&255)<<8,q+=(b>>>10|E<<6)&8191,O=f[h+6]&255|(f[h+7]&255)<<8,w+=(E>>>7|O<<9)&8191,D=f[h+8]&255|(f[h+9]&255)<<8,S+=(O>>>4|D<<12)&8191,I+=D>>>1&8191,Z=f[h+10]&255|(f[h+11]&255)<<8,C+=(D>>>14|Z<<2)&8191,W=f[h+12]&255|(f[h+13]&255)<<8,P+=(Z>>>11|W<<5)&8191,Pe=f[h+14]&255|(f[h+15]&255)<<8,F+=(W>>>8|Pe<<8)&8191,ie+=Pe>>>5|o,z=0,ae=z,ae+=G*me,ae+=Y*(5*ke),ae+=q*(5*Ce),ae+=w*(5*we),ae+=S*(5*Ae),z=ae>>>13,ae&=8191,ae+=I*(5*Re),ae+=C*(5*Se),ae+=P*(5*y),ae+=F*(5*ye),ae+=ie*(5*Ee),z+=ae>>>13,ae&=8191,ce=z,ce+=G*Ee,ce+=Y*me,ce+=q*(5*ke),ce+=w*(5*Ce),ce+=S*(5*we),z=ce>>>13,ce&=8191,ce+=I*(5*Ae),ce+=C*(5*Re),ce+=P*(5*Se),ce+=F*(5*y),ce+=ie*(5*ye),z+=ce>>>13,ce&=8191,ge=z,ge+=G*ye,ge+=Y*Ee,ge+=q*me,ge+=w*(5*ke),ge+=S*(5*Ce),z=ge>>>13,ge&=8191,ge+=I*(5*we),ge+=C*(5*Ae),ge+=P*(5*Re),ge+=F*(5*Se),ge+=ie*(5*y),z+=ge>>>13,ge&=8191,pe=z,pe+=G*y,pe+=Y*ye,pe+=q*Ee,pe+=w*me,pe+=S*(5*ke),z=pe>>>13,pe&=8191,pe+=I*(5*Ce),pe+=C*(5*we),pe+=P*(5*Ae),pe+=F*(5*Re),pe+=ie*(5*Se),z+=pe>>>13,pe&=8191,fe=z,fe+=G*Se,fe+=Y*y,fe+=q*ye,fe+=w*Ee,fe+=S*me,z=fe>>>13,fe&=8191,fe+=I*(5*ke),fe+=C*(5*Ce),fe+=P*(5*we),fe+=F*(5*Ae),fe+=ie*(5*Re),z+=fe>>>13,fe&=8191,le=z,le+=G*Re,le+=Y*Se,le+=q*y,le+=w*ye,le+=S*Ee,z=le>>>13,le&=8191,le+=I*me,le+=C*(5*ke),le+=P*(5*Ce),le+=F*(5*we),le+=ie*(5*Ae),z+=le>>>13,le&=8191,ue=z,ue+=G*Ae,ue+=Y*Re,ue+=q*Se,ue+=w*y,ue+=S*ye,z=ue>>>13,ue&=8191,ue+=I*Ee,ue+=C*me,ue+=P*(5*ke),ue+=F*(5*Ce),ue+=ie*(5*we),z+=ue>>>13,ue&=8191,$=z,$+=G*we,$+=Y*Ae,$+=q*Re,$+=w*Se,$+=S*y,z=$>>>13,$&=8191,$+=I*ye,$+=C*Ee,$+=P*me,$+=F*(5*ke),$+=ie*(5*Ce),z+=$>>>13,$&=8191,ee=z,ee+=G*Ce,ee+=Y*we,ee+=q*Ae,ee+=w*Re,ee+=S*Se,z=ee>>>13,ee&=8191,ee+=I*y,ee+=C*ye,ee+=P*Ee,ee+=F*me,ee+=ie*(5*ke),z+=ee>>>13,ee&=8191,V=z,V+=G*ke,V+=Y*Ce,V+=q*we,V+=w*Ae,V+=S*Re,z=V>>>13,V&=8191,V+=I*Se,V+=C*y,V+=P*ye,V+=F*Ee,V+=ie*me,z+=V>>>13,V&=8191,z=(z<<2)+z|0,z=z+ae|0,ae=z&8191,z=z>>>13,ce+=z,G=ae,Y=ce,q=ge,w=pe,S=fe,I=le,C=ue,P=$,F=ee,ie=V,h+=16,l-=16;this.h[0]=G,this.h[1]=Y,this.h[2]=q,this.h[3]=w,this.h[4]=S,this.h[5]=I,this.h[6]=C,this.h[7]=P,this.h[8]=F,this.h[9]=ie},se.prototype.finish=function(f,h){var l=new Uint16Array(10),o,g,b,E;if(this.leftover){for(E=this.leftover,this.buffer[E++]=1;E<16;E++)this.buffer[E]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(o=this.h[1]>>>13,this.h[1]&=8191,E=2;E<10;E++)this.h[E]+=o,o=this.h[E]>>>13,this.h[E]&=8191;for(this.h[0]+=o*5,o=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=o,o=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=o,l[0]=this.h[0]+5,o=l[0]>>>13,l[0]&=8191,E=1;E<10;E++)l[E]=this.h[E]+o,o=l[E]>>>13,l[E]&=8191;for(l[9]-=8192,g=(o^1)-1,E=0;E<10;E++)l[E]&=g;for(g=~g,E=0;E<10;E++)this.h[E]=this.h[E]&g|l[E];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,b=this.h[0]+this.pad[0],this.h[0]=b&65535,E=1;E<8;E++)b=(this.h[E]+this.pad[E]|0)+(b>>>16)|0,this.h[E]=b&65535;f[h+0]=this.h[0]>>>0&255,f[h+1]=this.h[0]>>>8&255,f[h+2]=this.h[1]>>>0&255,f[h+3]=this.h[1]>>>8&255,f[h+4]=this.h[2]>>>0&255,f[h+5]=this.h[2]>>>8&255,f[h+6]=this.h[3]>>>0&255,f[h+7]=this.h[3]>>>8&255,f[h+8]=this.h[4]>>>0&255,f[h+9]=this.h[4]>>>8&255,f[h+10]=this.h[5]>>>0&255,f[h+11]=this.h[5]>>>8&255,f[h+12]=this.h[6]>>>0&255,f[h+13]=this.h[6]>>>8&255,f[h+14]=this.h[7]>>>0&255,f[h+15]=this.h[7]>>>8&255},se.prototype.update=function(f,h,l){var o,g;if(this.leftover){for(g=16-this.leftover,g>l&&(g=l),o=0;o<g;o++)this.buffer[this.leftover+o]=f[h+o];if(l-=g,h+=g,this.leftover+=g,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(l>=16&&(g=l-l%16,this.blocks(f,h,g),h+=g,l-=g),l){for(o=0;o<l;o++)this.buffer[this.leftover+o]=f[h+o];this.leftover+=l}};function ze(f,h,l,o,g,b){var E=new se(b);return E.update(l,o,g),E.finish(f,h),0}function ve(f,h,l,o,g,b){var E=new Uint8Array(16);return ze(E,0,l,o,g,b),x(f,h,E,0)}function be(f,h,l,o,g){var b;if(l<32)return-1;for(_e(f,0,h,0,l,o,g),ze(f,16,f,32,l-32,f),b=0;b<16;b++)f[b]=0;return 0}function he(f,h,l,o,g){var b,E=new Uint8Array(32);if(l<32||(ne(E,0,32,o,g),ve(h,16,h,32,l-32,E)!==0))return-1;for(_e(f,0,h,0,l,o,g),b=0;b<32;b++)f[b]=0;return 0}function We(f,h){var l;for(l=0;l<16;l++)f[l]=h[l]|0}function ot(f){var h,l,o=1;for(h=0;h<16;h++)l=f[h]+o+65535,o=Math.floor(l/65536),f[h]=l-o*65536;f[0]+=o-1+37*(o-1)}function Qe(f,h,l){for(var o,g=~(l-1),b=0;b<16;b++)o=g&(f[b]^h[b]),f[b]^=o,h[b]^=o}function Te(f,h){var l,o,g,b=e(),E=e();for(l=0;l<16;l++)E[l]=h[l];for(ot(E),ot(E),ot(E),o=0;o<2;o++){for(b[0]=E[0]-65517,l=1;l<15;l++)b[l]=E[l]-65535-(b[l-1]>>16&1),b[l-1]&=65535;b[15]=E[15]-32767-(b[14]>>16&1),g=b[15]>>16&1,b[14]&=65535,Qe(E,b,1-g)}for(l=0;l<16;l++)f[2*l]=E[l]&255,f[2*l+1]=E[l]>>8}function it(f,h){var l=new Uint8Array(32),o=new Uint8Array(32);return Te(l,f),Te(o,h),H(l,0,o,0)}function $e(f){var h=new Uint8Array(32);return Te(h,f),h[0]&1}function mt(f,h){var l;for(l=0;l<16;l++)f[l]=h[2*l]+(h[2*l+1]<<8);f[15]&=32767}function L(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]+l[o]}function K(f,h,l){for(var o=0;o<16;o++)f[o]=h[o]-l[o]}function A(f,h,l){var o,g,b=0,E=0,O=0,D=0,Z=0,W=0,Pe=0,z=0,ae=0,ce=0,ge=0,pe=0,fe=0,le=0,ue=0,$=0,ee=0,V=0,G=0,Y=0,q=0,w=0,S=0,I=0,C=0,P=0,F=0,ie=0,me=0,Ee=0,ye=0,y=l[0],Se=l[1],Re=l[2],Ae=l[3],we=l[4],Ce=l[5],ke=l[6],Ze=l[7],Me=l[8],Ge=l[9],Ye=l[10],Xe=l[11],st=l[12],dt=l[13],pt=l[14],gt=l[15];o=h[0],b+=o*y,E+=o*Se,O+=o*Re,D+=o*Ae,Z+=o*we,W+=o*Ce,Pe+=o*ke,z+=o*Ze,ae+=o*Me,ce+=o*Ge,ge+=o*Ye,pe+=o*Xe,fe+=o*st,le+=o*dt,ue+=o*pt,$+=o*gt,o=h[1],E+=o*y,O+=o*Se,D+=o*Re,Z+=o*Ae,W+=o*we,Pe+=o*Ce,z+=o*ke,ae+=o*Ze,ce+=o*Me,ge+=o*Ge,pe+=o*Ye,fe+=o*Xe,le+=o*st,ue+=o*dt,$+=o*pt,ee+=o*gt,o=h[2],O+=o*y,D+=o*Se,Z+=o*Re,W+=o*Ae,Pe+=o*we,z+=o*Ce,ae+=o*ke,ce+=o*Ze,ge+=o*Me,pe+=o*Ge,fe+=o*Ye,le+=o*Xe,ue+=o*st,$+=o*dt,ee+=o*pt,V+=o*gt,o=h[3],D+=o*y,Z+=o*Se,W+=o*Re,Pe+=o*Ae,z+=o*we,ae+=o*Ce,ce+=o*ke,ge+=o*Ze,pe+=o*Me,fe+=o*Ge,le+=o*Ye,ue+=o*Xe,$+=o*st,ee+=o*dt,V+=o*pt,G+=o*gt,o=h[4],Z+=o*y,W+=o*Se,Pe+=o*Re,z+=o*Ae,ae+=o*we,ce+=o*Ce,ge+=o*ke,pe+=o*Ze,fe+=o*Me,le+=o*Ge,ue+=o*Ye,$+=o*Xe,ee+=o*st,V+=o*dt,G+=o*pt,Y+=o*gt,o=h[5],W+=o*y,Pe+=o*Se,z+=o*Re,ae+=o*Ae,ce+=o*we,ge+=o*Ce,pe+=o*ke,fe+=o*Ze,le+=o*Me,ue+=o*Ge,$+=o*Ye,ee+=o*Xe,V+=o*st,G+=o*dt,Y+=o*pt,q+=o*gt,o=h[6],Pe+=o*y,z+=o*Se,ae+=o*Re,ce+=o*Ae,ge+=o*we,pe+=o*Ce,fe+=o*ke,le+=o*Ze,ue+=o*Me,$+=o*Ge,ee+=o*Ye,V+=o*Xe,G+=o*st,Y+=o*dt,q+=o*pt,w+=o*gt,o=h[7],z+=o*y,ae+=o*Se,ce+=o*Re,ge+=o*Ae,pe+=o*we,fe+=o*Ce,le+=o*ke,ue+=o*Ze,$+=o*Me,ee+=o*Ge,V+=o*Ye,G+=o*Xe,Y+=o*st,q+=o*dt,w+=o*pt,S+=o*gt,o=h[8],ae+=o*y,ce+=o*Se,ge+=o*Re,pe+=o*Ae,fe+=o*we,le+=o*Ce,ue+=o*ke,$+=o*Ze,ee+=o*Me,V+=o*Ge,G+=o*Ye,Y+=o*Xe,q+=o*st,w+=o*dt,S+=o*pt,I+=o*gt,o=h[9],ce+=o*y,ge+=o*Se,pe+=o*Re,fe+=o*Ae,le+=o*we,ue+=o*Ce,$+=o*ke,ee+=o*Ze,V+=o*Me,G+=o*Ge,Y+=o*Ye,q+=o*Xe,w+=o*st,S+=o*dt,I+=o*pt,C+=o*gt,o=h[10],ge+=o*y,pe+=o*Se,fe+=o*Re,le+=o*Ae,ue+=o*we,$+=o*Ce,ee+=o*ke,V+=o*Ze,G+=o*Me,Y+=o*Ge,q+=o*Ye,w+=o*Xe,S+=o*st,I+=o*dt,C+=o*pt,P+=o*gt,o=h[11],pe+=o*y,fe+=o*Se,le+=o*Re,ue+=o*Ae,$+=o*we,ee+=o*Ce,V+=o*ke,G+=o*Ze,Y+=o*Me,q+=o*Ge,w+=o*Ye,S+=o*Xe,I+=o*st,C+=o*dt,P+=o*pt,F+=o*gt,o=h[12],fe+=o*y,le+=o*Se,ue+=o*Re,$+=o*Ae,ee+=o*we,V+=o*Ce,G+=o*ke,Y+=o*Ze,q+=o*Me,w+=o*Ge,S+=o*Ye,I+=o*Xe,C+=o*st,P+=o*dt,F+=o*pt,ie+=o*gt,o=h[13],le+=o*y,ue+=o*Se,$+=o*Re,ee+=o*Ae,V+=o*we,G+=o*Ce,Y+=o*ke,q+=o*Ze,w+=o*Me,S+=o*Ge,I+=o*Ye,C+=o*Xe,P+=o*st,F+=o*dt,ie+=o*pt,me+=o*gt,o=h[14],ue+=o*y,$+=o*Se,ee+=o*Re,V+=o*Ae,G+=o*we,Y+=o*Ce,q+=o*ke,w+=o*Ze,S+=o*Me,I+=o*Ge,C+=o*Ye,P+=o*Xe,F+=o*st,ie+=o*dt,me+=o*pt,Ee+=o*gt,o=h[15],$+=o*y,ee+=o*Se,V+=o*Re,G+=o*Ae,Y+=o*we,q+=o*Ce,w+=o*ke,S+=o*Ze,I+=o*Me,C+=o*Ge,P+=o*Ye,F+=o*Xe,ie+=o*st,me+=o*dt,Ee+=o*pt,ye+=o*gt,b+=38*ee,E+=38*V,O+=38*G,D+=38*Y,Z+=38*q,W+=38*w,Pe+=38*S,z+=38*I,ae+=38*C,ce+=38*P,ge+=38*F,pe+=38*ie,fe+=38*me,le+=38*Ee,ue+=38*ye,g=1,o=b+g+65535,g=Math.floor(o/65536),b=o-g*65536,o=E+g+65535,g=Math.floor(o/65536),E=o-g*65536,o=O+g+65535,g=Math.floor(o/65536),O=o-g*65536,o=D+g+65535,g=Math.floor(o/65536),D=o-g*65536,o=Z+g+65535,g=Math.floor(o/65536),Z=o-g*65536,o=W+g+65535,g=Math.floor(o/65536),W=o-g*65536,o=Pe+g+65535,g=Math.floor(o/65536),Pe=o-g*65536,o=z+g+65535,g=Math.floor(o/65536),z=o-g*65536,o=ae+g+65535,g=Math.floor(o/65536),ae=o-g*65536,o=ce+g+65535,g=Math.floor(o/65536),ce=o-g*65536,o=ge+g+65535,g=Math.floor(o/65536),ge=o-g*65536,o=pe+g+65535,g=Math.floor(o/65536),pe=o-g*65536,o=fe+g+65535,g=Math.floor(o/65536),fe=o-g*65536,o=le+g+65535,g=Math.floor(o/65536),le=o-g*65536,o=ue+g+65535,g=Math.floor(o/65536),ue=o-g*65536,o=$+g+65535,g=Math.floor(o/65536),$=o-g*65536,b+=g-1+37*(g-1),g=1,o=b+g+65535,g=Math.floor(o/65536),b=o-g*65536,o=E+g+65535,g=Math.floor(o/65536),E=o-g*65536,o=O+g+65535,g=Math.floor(o/65536),O=o-g*65536,o=D+g+65535,g=Math.floor(o/65536),D=o-g*65536,o=Z+g+65535,g=Math.floor(o/65536),Z=o-g*65536,o=W+g+65535,g=Math.floor(o/65536),W=o-g*65536,o=Pe+g+65535,g=Math.floor(o/65536),Pe=o-g*65536,o=z+g+65535,g=Math.floor(o/65536),z=o-g*65536,o=ae+g+65535,g=Math.floor(o/65536),ae=o-g*65536,o=ce+g+65535,g=Math.floor(o/65536),ce=o-g*65536,o=ge+g+65535,g=Math.floor(o/65536),ge=o-g*65536,o=pe+g+65535,g=Math.floor(o/65536),pe=o-g*65536,o=fe+g+65535,g=Math.floor(o/65536),fe=o-g*65536,o=le+g+65535,g=Math.floor(o/65536),le=o-g*65536,o=ue+g+65535,g=Math.floor(o/65536),ue=o-g*65536,o=$+g+65535,g=Math.floor(o/65536),$=o-g*65536,b+=g-1+37*(g-1),f[0]=b,f[1]=E,f[2]=O,f[3]=D,f[4]=Z,f[5]=W,f[6]=Pe,f[7]=z,f[8]=ae,f[9]=ce,f[10]=ge,f[11]=pe,f[12]=fe,f[13]=le,f[14]=ue,f[15]=$}function R(f,h){A(f,h,h)}function Q(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=253;o>=0;o--)R(l,l),o!==2&&o!==4&&A(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function Ne(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=250;o>=0;o--)R(l,l),o!==1&&A(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function Je(f,h,l){var o=new Uint8Array(32),g=new Float64Array(80),b,E,O=e(),D=e(),Z=e(),W=e(),Pe=e(),z=e();for(E=0;E<31;E++)o[E]=h[E];for(o[31]=h[31]&127|64,o[0]&=248,mt(g,l),E=0;E<16;E++)D[E]=g[E],W[E]=O[E]=Z[E]=0;for(O[0]=W[0]=1,E=254;E>=0;--E)b=o[E>>>3]>>>(E&7)&1,Qe(O,D,b),Qe(Z,W,b),L(Pe,O,Z),K(O,O,Z),L(Z,D,W),K(D,D,W),R(W,Pe),R(z,O),A(O,Z,O),A(Z,D,Pe),L(Pe,O,Z),K(O,O,Z),R(D,O),K(Z,W,z),A(O,Z,c),L(O,O,W),A(Z,Z,O),A(O,W,z),A(W,D,g),R(D,Pe),Qe(O,D,b),Qe(Z,W,b);for(E=0;E<16;E++)g[E+16]=O[E],g[E+32]=Z[E],g[E+48]=D[E],g[E+64]=W[E];var ae=g.subarray(32),ce=g.subarray(16);return Q(ae,ae),A(ce,ce,ae),Te(f,ce),0}function nt(f,h){return Je(f,h,n)}function ht(f,h){return t(h,32),nt(f,h)}function mr(f,h,l){var o=new Uint8Array(32);return Je(o,l,h),B(f,i,o,te)}var Mr=be,ii=he;function Fr(f,h,l,o,g,b){var E=new Uint8Array(32);return mr(E,g,b),Mr(f,h,l,o,E)}function Pi(f,h,l,o,g,b){var E=new Uint8Array(32);return mr(E,g,b),ii(f,h,l,o,E)}var Jn=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function Sf(f,h,l,o){for(var g=new Int32Array(16),b=new Int32Array(16),E,O,D,Z,W,Pe,z,ae,ce,ge,pe,fe,le,ue,$,ee,V,G,Y,q,w,S,I,C,P,F,ie=f[0],me=f[1],Ee=f[2],ye=f[3],y=f[4],Se=f[5],Re=f[6],Ae=f[7],we=h[0],Ce=h[1],ke=h[2],Ze=h[3],Me=h[4],Ge=h[5],Ye=h[6],Xe=h[7],st=0;o>=128;){for(Y=0;Y<16;Y++)q=8*Y+st,g[Y]=l[q+0]<<24|l[q+1]<<16|l[q+2]<<8|l[q+3],b[Y]=l[q+4]<<24|l[q+5]<<16|l[q+6]<<8|l[q+7];for(Y=0;Y<80;Y++)if(E=ie,O=me,D=Ee,Z=ye,W=y,Pe=Se,z=Re,ae=Ae,ce=we,ge=Ce,pe=ke,fe=Ze,le=Me,ue=Ge,$=Ye,ee=Xe,w=Ae,S=Xe,I=S&65535,C=S>>>16,P=w&65535,F=w>>>16,w=(y>>>14|Me<<18)^(y>>>18|Me<<14)^(Me>>>9|y<<23),S=(Me>>>14|y<<18)^(Me>>>18|y<<14)^(y>>>9|Me<<23),I+=S&65535,C+=S>>>16,P+=w&65535,F+=w>>>16,w=y&Se^~y&Re,S=Me&Ge^~Me&Ye,I+=S&65535,C+=S>>>16,P+=w&65535,F+=w>>>16,w=Jn[Y*2],S=Jn[Y*2+1],I+=S&65535,C+=S>>>16,P+=w&65535,F+=w>>>16,w=g[Y%16],S=b[Y%16],I+=S&65535,C+=S>>>16,P+=w&65535,F+=w>>>16,C+=I>>>16,P+=C>>>16,F+=P>>>16,V=P&65535|F<<16,G=I&65535|C<<16,w=V,S=G,I=S&65535,C=S>>>16,P=w&65535,F=w>>>16,w=(ie>>>28|we<<4)^(we>>>2|ie<<30)^(we>>>7|ie<<25),S=(we>>>28|ie<<4)^(ie>>>2|we<<30)^(ie>>>7|we<<25),I+=S&65535,C+=S>>>16,P+=w&65535,F+=w>>>16,w=ie&me^ie&Ee^me&Ee,S=we&Ce^we&ke^Ce&ke,I+=S&65535,C+=S>>>16,P+=w&65535,F+=w>>>16,C+=I>>>16,P+=C>>>16,F+=P>>>16,ae=P&65535|F<<16,ee=I&65535|C<<16,w=Z,S=fe,I=S&65535,C=S>>>16,P=w&65535,F=w>>>16,w=V,S=G,I+=S&65535,C+=S>>>16,P+=w&65535,F+=w>>>16,C+=I>>>16,P+=C>>>16,F+=P>>>16,Z=P&65535|F<<16,fe=I&65535|C<<16,me=E,Ee=O,ye=D,y=Z,Se=W,Re=Pe,Ae=z,ie=ae,Ce=ce,ke=ge,Ze=pe,Me=fe,Ge=le,Ye=ue,Xe=$,we=ee,Y%16===15)for(q=0;q<16;q++)w=g[q],S=b[q],I=S&65535,C=S>>>16,P=w&65535,F=w>>>16,w=g[(q+9)%16],S=b[(q+9)%16],I+=S&65535,C+=S>>>16,P+=w&65535,F+=w>>>16,V=g[(q+1)%16],G=b[(q+1)%16],w=(V>>>1|G<<31)^(V>>>8|G<<24)^V>>>7,S=(G>>>1|V<<31)^(G>>>8|V<<24)^(G>>>7|V<<25),I+=S&65535,C+=S>>>16,P+=w&65535,F+=w>>>16,V=g[(q+14)%16],G=b[(q+14)%16],w=(V>>>19|G<<13)^(G>>>29|V<<3)^V>>>6,S=(G>>>19|V<<13)^(V>>>29|G<<3)^(G>>>6|V<<26),I+=S&65535,C+=S>>>16,P+=w&65535,F+=w>>>16,C+=I>>>16,P+=C>>>16,F+=P>>>16,g[q]=P&65535|F<<16,b[q]=I&65535|C<<16;w=ie,S=we,I=S&65535,C=S>>>16,P=w&65535,F=w>>>16,w=f[0],S=h[0],I+=S&65535,C+=S>>>16,P+=w&65535,F+=w>>>16,C+=I>>>16,P+=C>>>16,F+=P>>>16,f[0]=ie=P&65535|F<<16,h[0]=we=I&65535|C<<16,w=me,S=Ce,I=S&65535,C=S>>>16,P=w&65535,F=w>>>16,w=f[1],S=h[1],I+=S&65535,C+=S>>>16,P+=w&65535,F+=w>>>16,C+=I>>>16,P+=C>>>16,F+=P>>>16,f[1]=me=P&65535|F<<16,h[1]=Ce=I&65535|C<<16,w=Ee,S=ke,I=S&65535,C=S>>>16,P=w&65535,F=w>>>16,w=f[2],S=h[2],I+=S&65535,C+=S>>>16,P+=w&65535,F+=w>>>16,C+=I>>>16,P+=C>>>16,F+=P>>>16,f[2]=Ee=P&65535|F<<16,h[2]=ke=I&65535|C<<16,w=ye,S=Ze,I=S&65535,C=S>>>16,P=w&65535,F=w>>>16,w=f[3],S=h[3],I+=S&65535,C+=S>>>16,P+=w&65535,F+=w>>>16,C+=I>>>16,P+=C>>>16,F+=P>>>16,f[3]=ye=P&65535|F<<16,h[3]=Ze=I&65535|C<<16,w=y,S=Me,I=S&65535,C=S>>>16,P=w&65535,F=w>>>16,w=f[4],S=h[4],I+=S&65535,C+=S>>>16,P+=w&65535,F+=w>>>16,C+=I>>>16,P+=C>>>16,F+=P>>>16,f[4]=y=P&65535|F<<16,h[4]=Me=I&65535|C<<16,w=Se,S=Ge,I=S&65535,C=S>>>16,P=w&65535,F=w>>>16,w=f[5],S=h[5],I+=S&65535,C+=S>>>16,P+=w&65535,F+=w>>>16,C+=I>>>16,P+=C>>>16,F+=P>>>16,f[5]=Se=P&65535|F<<16,h[5]=Ge=I&65535|C<<16,w=Re,S=Ye,I=S&65535,C=S>>>16,P=w&65535,F=w>>>16,w=f[6],S=h[6],I+=S&65535,C+=S>>>16,P+=w&65535,F+=w>>>16,C+=I>>>16,P+=C>>>16,F+=P>>>16,f[6]=Re=P&65535|F<<16,h[6]=Ye=I&65535|C<<16,w=Ae,S=Xe,I=S&65535,C=S>>>16,P=w&65535,F=w>>>16,w=f[7],S=h[7],I+=S&65535,C+=S>>>16,P+=w&65535,F+=w>>>16,C+=I>>>16,P+=C>>>16,F+=P>>>16,f[7]=Ae=P&65535|F<<16,h[7]=Xe=I&65535|C<<16,st+=128,o-=128}return o}function ni(f,h,l){var o=new Int32Array(8),g=new Int32Array(8),b=new Uint8Array(256),E,O=l;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,g[0]=4089235720,g[1]=2227873595,g[2]=4271175723,g[3]=1595750129,g[4]=2917565137,g[5]=725511199,g[6]=4215389547,g[7]=327033209,Sf(o,g,h,l),l%=128,E=0;E<l;E++)b[E]=h[O-l+E];for(b[l]=128,l=256-128*(l<112?1:0),b[l-9]=0,v(b,l-8,O/536870912|0,O<<3),Sf(o,g,b,l),E=0;E<8;E++)v(f,8*E,o[E],g[E]);return 0}function Zn(f,h){var l=e(),o=e(),g=e(),b=e(),E=e(),O=e(),D=e(),Z=e(),W=e();K(l,f[1],f[0]),K(W,h[1],h[0]),A(l,l,W),L(o,f[0],f[1]),L(W,h[0],h[1]),A(o,o,W),A(g,f[3],h[3]),A(g,g,d),A(b,f[2],h[2]),L(b,b,b),K(E,o,l),K(O,b,g),L(D,b,g),L(Z,o,l),A(f[0],E,O),A(f[1],Z,D),A(f[2],D,O),A(f[3],E,Z)}function xf(f,h,l){var o;for(o=0;o<4;o++)Qe(f[o],h[o],l)}function Do(f,h){var l=e(),o=e(),g=e();Q(g,h[2]),A(l,h[0],g),A(o,h[1],g),Te(f,o),f[31]^=$e(l)<<7}function Bo(f,h,l){var o,g;for(We(f[0],s),We(f[1],a),We(f[2],a),We(f[3],s),g=255;g>=0;--g)o=l[g/8|0]>>(g&7)&1,xf(f,h,o),Zn(h,f),Zn(f,f),xf(f,h,o)}function Qn(f,h){var l=[e(),e(),e(),e()];We(l[0],p),We(l[1],m),We(l[2],a),A(l[3],p,m),Bo(f,l,h)}function jo(f,h,l){var o=new Uint8Array(64),g=[e(),e(),e(),e()],b;for(l||t(h,32),ni(o,h,32),o[0]&=248,o[31]&=127,o[31]|=64,Qn(g,o),Do(f,g),b=0;b<32;b++)h[b+32]=f[b];return 0}var es=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function Uo(f,h){var l,o,g,b;for(o=63;o>=32;--o){for(l=0,g=o-32,b=o-12;g<b;++g)h[g]+=l-16*h[o]*es[g-(o-32)],l=Math.floor((h[g]+128)/256),h[g]-=l*256;h[g]+=l,h[o]=0}for(l=0,g=0;g<32;g++)h[g]+=l-(h[31]>>4)*es[g],l=h[g]>>8,h[g]&=255;for(g=0;g<32;g++)h[g]-=l*es[g];for(o=0;o<32;o++)h[o+1]+=h[o]>>8,f[o]=h[o]&255}function Ko(f){var h=new Float64Array(64),l;for(l=0;l<64;l++)h[l]=f[l];for(l=0;l<64;l++)f[l]=0;Uo(f,h)}function Tf(f,h,l,o){var g=new Uint8Array(64),b=new Uint8Array(64),E=new Uint8Array(64),O,D,Z=new Float64Array(64),W=[e(),e(),e(),e()];ni(g,o,32),g[0]&=248,g[31]&=127,g[31]|=64;var Pe=l+64;for(O=0;O<l;O++)f[64+O]=h[O];for(O=0;O<32;O++)f[32+O]=g[32+O];for(ni(E,f.subarray(32),l+32),Ko(E),Qn(W,E),Do(f,W),O=32;O<64;O++)f[O]=o[O];for(ni(b,f,l+64),Ko(b),O=0;O<64;O++)Z[O]=0;for(O=0;O<32;O++)Z[O]=E[O];for(O=0;O<32;O++)for(D=0;D<32;D++)Z[O+D]+=b[O]*g[D];return Uo(f.subarray(32),Z),Pe}function pp(f,h){var l=e(),o=e(),g=e(),b=e(),E=e(),O=e(),D=e();return We(f[2],a),mt(f[1],h),R(g,f[1]),A(b,g,u),K(g,g,f[2]),L(b,f[2],b),R(E,b),R(O,E),A(D,O,E),A(l,D,g),A(l,l,b),Ne(l,l),A(l,l,g),A(l,l,b),A(l,l,b),A(f[0],l,b),R(o,f[0]),A(o,o,b),it(o,g)&&A(f[0],f[0],_),R(o,f[0]),A(o,o,b),it(o,g)?-1:($e(f[0])===h[31]>>7&&K(f[0],s,f[0]),A(f[3],f[0],f[1]),0)}function qo(f,h,l,o){var g,b=new Uint8Array(32),E=new Uint8Array(64),O=[e(),e(),e(),e()],D=[e(),e(),e(),e()];if(l<64||pp(D,o))return-1;for(g=0;g<l;g++)f[g]=h[g];for(g=0;g<32;g++)f[g+32]=o[g];if(ni(E,f,l),Ko(E),Bo(O,D,E),Qn(D,h.subarray(32)),Zn(O,D),Do(b,O),l-=64,H(h,0,b,0)){for(g=0;g<l;g++)f[g]=0;return-1}for(g=0;g<l;g++)f[g]=h[g+64];return l}var Wo=32,ts=24,ln=32,Ri=16,hn=32,rs=32,dn=32,pn=32,Ho=32,Cf=ts,gp=ln,mp=Ri,yr=64,si=32,Ai=64,Vo=32,zo=64;r.lowlevel={crypto_core_hsalsa20:B,crypto_stream_xor:_e,crypto_stream:ne,crypto_stream_salsa20_xor:j,crypto_stream_salsa20:U,crypto_onetimeauth:ze,crypto_onetimeauth_verify:ve,crypto_verify_16:x,crypto_verify_32:H,crypto_secretbox:be,crypto_secretbox_open:he,crypto_scalarmult:Je,crypto_scalarmult_base:nt,crypto_box_beforenm:mr,crypto_box_afternm:Mr,crypto_box:Fr,crypto_box_open:Pi,crypto_box_keypair:ht,crypto_hash:ni,crypto_sign:Tf,crypto_sign_keypair:jo,crypto_sign_open:qo,crypto_secretbox_KEYBYTES:Wo,crypto_secretbox_NONCEBYTES:ts,crypto_secretbox_ZEROBYTES:ln,crypto_secretbox_BOXZEROBYTES:Ri,crypto_scalarmult_BYTES:hn,crypto_scalarmult_SCALARBYTES:rs,crypto_box_PUBLICKEYBYTES:dn,crypto_box_SECRETKEYBYTES:pn,crypto_box_BEFORENMBYTES:Ho,crypto_box_NONCEBYTES:Cf,crypto_box_ZEROBYTES:gp,crypto_box_BOXZEROBYTES:mp,crypto_sign_BYTES:yr,crypto_sign_PUBLICKEYBYTES:si,crypto_sign_SECRETKEYBYTES:Ai,crypto_sign_SEEDBYTES:Vo,crypto_hash_BYTES:zo,gf:e,D:u,L:es,pack25519:Te,unpack25519:mt,M:A,A:L,S:R,Z:K,pow2523:Ne,add:Zn,set25519:We,modL:Uo,scalarmult:Bo,scalarbase:Qn};function kf(f,h){if(f.length!==Wo)throw new Error("bad key size");if(h.length!==ts)throw new Error("bad nonce size")}function yp(f,h){if(f.length!==dn)throw new Error("bad public key size");if(h.length!==pn)throw new Error("bad secret key size")}function St(){for(var f=0;f<arguments.length;f++)if(!(arguments[f]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function Of(f){for(var h=0;h<f.length;h++)f[h]=0}r.randomBytes=function(f){var h=new Uint8Array(f);return t(h,f),h},r.secretbox=function(f,h,l){St(f,h,l),kf(l,h);for(var o=new Uint8Array(ln+f.length),g=new Uint8Array(o.length),b=0;b<f.length;b++)o[b+ln]=f[b];return be(g,o,o.length,h,l),g.subarray(Ri)},r.secretbox.open=function(f,h,l){St(f,h,l),kf(l,h);for(var o=new Uint8Array(Ri+f.length),g=new Uint8Array(o.length),b=0;b<f.length;b++)o[b+Ri]=f[b];return o.length<32||he(g,o,o.length,h,l)!==0?null:g.subarray(ln)},r.secretbox.keyLength=Wo,r.secretbox.nonceLength=ts,r.secretbox.overheadLength=Ri,r.scalarMult=function(f,h){if(St(f,h),f.length!==rs)throw new Error("bad n size");if(h.length!==hn)throw new Error("bad p size");var l=new Uint8Array(hn);return Je(l,f,h),l},r.scalarMult.base=function(f){if(St(f),f.length!==rs)throw new Error("bad n size");var h=new Uint8Array(hn);return nt(h,f),h},r.scalarMult.scalarLength=rs,r.scalarMult.groupElementLength=hn,r.box=function(f,h,l,o){var g=r.box.before(l,o);return r.secretbox(f,h,g)},r.box.before=function(f,h){St(f,h),yp(f,h);var l=new Uint8Array(Ho);return mr(l,f,h),l},r.box.after=r.secretbox,r.box.open=function(f,h,l,o){var g=r.box.before(l,o);return r.secretbox.open(f,h,g)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var f=new Uint8Array(dn),h=new Uint8Array(pn);return ht(f,h),{publicKey:f,secretKey:h}},r.box.keyPair.fromSecretKey=function(f){if(St(f),f.length!==pn)throw new Error("bad secret key size");var h=new Uint8Array(dn);return nt(h,f),{publicKey:h,secretKey:new Uint8Array(f)}},r.box.publicKeyLength=dn,r.box.secretKeyLength=pn,r.box.sharedKeyLength=Ho,r.box.nonceLength=Cf,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(f,h){if(St(f,h),h.length!==Ai)throw new Error("bad secret key size");var l=new Uint8Array(yr+f.length);return Tf(l,f,f.length,h),l},r.sign.open=function(f,h){if(St(f,h),h.length!==si)throw new Error("bad public key size");var l=new Uint8Array(f.length),o=qo(l,f,f.length,h);if(o<0)return null;for(var g=new Uint8Array(o),b=0;b<g.length;b++)g[b]=l[b];return g},r.sign.detached=function(f,h){for(var l=r.sign(f,h),o=new Uint8Array(yr),g=0;g<o.length;g++)o[g]=l[g];return o},r.sign.detached.verify=function(f,h,l){if(St(f,h,l),h.length!==yr)throw new Error("bad signature size");if(l.length!==si)throw new Error("bad public key size");var o=new Uint8Array(yr+f.length),g=new Uint8Array(yr+f.length),b;for(b=0;b<yr;b++)o[b]=h[b];for(b=0;b<f.length;b++)o[b+yr]=f[b];return qo(g,o,o.length,l)>=0},r.sign.keyPair=function(){var f=new Uint8Array(si),h=new Uint8Array(Ai);return jo(f,h),{publicKey:f,secretKey:h}},r.sign.keyPair.fromSecretKey=function(f){if(St(f),f.length!==Ai)throw new Error("bad secret key size");for(var h=new Uint8Array(si),l=0;l<h.length;l++)h[l]=f[32+l];return{publicKey:h,secretKey:new Uint8Array(f)}},r.sign.keyPair.fromSeed=function(f){if(St(f),f.length!==Vo)throw new Error("bad seed size");for(var h=new Uint8Array(si),l=new Uint8Array(Ai),o=0;o<32;o++)l[o]=f[o];return jo(h,l,!0),{publicKey:h,secretKey:l}},r.sign.publicKeyLength=si,r.sign.secretKeyLength=Ai,r.sign.seedLength=Vo,r.sign.signatureLength=yr,r.hash=function(f){St(f);var h=new Uint8Array(zo);return ni(h,f,f.length),h},r.hash.hashLength=zo,r.verify=function(f,h){return St(f,h),f.length===0||h.length===0||f.length!==h.length?!1:T(f,0,h,0,f.length)===0},r.setPRNG=function(f){t=f},(function(){var f=typeof self<"u"?self.crypto||self.msCrypto:null;if(f&&f.getRandomValues){var h=65536;r.setPRNG(function(l,o){var g,b=new Uint8Array(o);for(g=0;g<o;g+=h)f.getRandomValues(b.subarray(g,g+Math.min(o-g,h)));for(g=0;g<o;g++)l[g]=b[g];Of(b)})}else typeof require<"u"&&(f=require("crypto"),f&&f.randomBytes&&r.setPRNG(function(l,o){var g,b=f.randomBytes(o);for(g=0;g<o;g++)l[g]=b[g];Of(b)}))})()})(typeof ps<"u"&&ps.exports?ps.exports:self.nacl=self.nacl||{})});var bn=M((Gf,gs)=>{(function(r,e){"use strict";typeof gs<"u"&&gs.exports?gs.exports=e():(r.nacl||(r.nacl={}),r.nacl.util=e())})(Gf,function(){"use strict";var r={};function e(t){if(!/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(t))throw new TypeError("invalid encoding")}return r.decodeUTF8=function(t){if(typeof t!="string")throw new TypeError("expected string");var i,n=unescape(encodeURIComponent(t)),s=new Uint8Array(n.length);for(i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s},r.encodeUTF8=function(t){var i,n=[];for(i=0;i<t.length;i++)n.push(String.fromCharCode(t[i]));return decodeURIComponent(escape(n.join("")))},typeof atob>"u"?typeof Buffer.from<"u"?(r.encodeBase64=function(t){return Buffer.from(t).toString("base64")},r.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(Buffer.from(t,"base64"),0))}):(r.encodeBase64=function(t){return new Buffer(t).toString("base64")},r.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(new Buffer(t,"base64"),0))}):(r.encodeBase64=function(t){var i,n=[],s=t.length;for(i=0;i<s;i++)n.push(String.fromCharCode(t[i]));return btoa(n.join(""))},r.decodeBase64=function(t){e(t);var i,n=atob(t),s=new Uint8Array(n.length);for(i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}),r})});var Yf=M(Tt=>{"use strict";var jp=Tt&&Tt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Tt,"__esModule",{value:!0});Tt.concatBytes=En;Tt.generateIdentityKeyPair=Up;Tt.identityPublicFromSecret=Kp;Tt.signSessionKey=qp;Tt.verifySessionKey=Wp;Tt.buildKxCanonical=Hp;Tt.buildKxAckCanonical=Vp;Tt.fingerprintIdentityKey=zp;Tt.fingerprintShortHex=$p;var er=jp(_n()),xt=bn(),ms=Jo();function En(...r){let e=0;for(let n of r)e+=n.length;let t=new Uint8Array(e),i=0;for(let n of r)t.set(n,i),i+=n.length;return t}function Up(){let r=er.default.sign.keyPair();return{identityPublicKey:(0,xt.encodeBase64)(r.publicKey),identitySecretKey:(0,xt.encodeBase64)(r.secretKey)}}function Kp(r){let e=(0,xt.decodeBase64)(r);if(e.length!==er.default.sign.secretKeyLength)throw new Error("bad identity secret key length");let t=er.default.sign.keyPair.fromSecretKey(e);return(0,xt.encodeBase64)(t.publicKey)}function qp(r,e){let t=(0,xt.decodeBase64)(e);if(t.length!==er.default.sign.secretKeyLength)throw new Error("bad identity secret key length");return(0,xt.encodeBase64)(er.default.sign.detached(r,t))}function Wp(r,e,t){try{let i=(0,xt.decodeBase64)(e),n=(0,xt.decodeBase64)(t);return n.length!==er.default.sign.publicKeyLength||i.length!==er.default.sign.signatureLength?!1:er.default.sign.detached.verify(r,i,n)}catch{return!1}}var oi=new Uint8Array([0]);function Hp(r){let e=new TextEncoder,t=e.encode(ms.KX_SIGN_LABEL),i=e.encode(r.agentId),n=e.encode(String(r.keyVersion)),s=(0,xt.decodeBase64)(r.boxPublicKey);return En(t,oi,i,oi,n,oi,s)}function Vp(r){let e=new TextEncoder;return En(e.encode(ms.KX_ACK_LABEL),oi,e.encode(r.agentId),oi,e.encode(String(r.keyVersion)),oi,(0,xt.decodeBase64)(r.boxPublicKey),oi,(0,xt.decodeBase64)(r.boundClientKey))}function zp(r){let e=(0,xt.decodeBase64)(r),t=En(new TextEncoder().encode(ms.KX_FINGERPRINT_LABEL),e),i=er.default.hash(t),n=[];for(let s=0;s<12;s++){let a=s*5,u=(((i[a]<<24>>>0)+(i[a+1]<<16)+(i[a+2]<<8)+i[a+3]^i[a+4])>>>0)%1e5;n.push(String(u).padStart(5,"0"))}return n.join(" ")}function $p(r){let e=(0,xt.decodeBase64)(r),t=En(new TextEncoder().encode(ms.KX_FINGERPRINT_LABEL),e),i=er.default.hash(t).slice(0,8);return Array.from(i).map(n=>n.toString(16).padStart(2,"0")).join(":").toUpperCase()}});var Xf=M(jr=>{"use strict";var Gp=jr&&jr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(jr,"__esModule",{value:!0});jr.encrypt=Yp;jr.decrypt=Xp;jr.encryptBinary=Jp;jr.decryptBinary=Zp;var Er=Gp(_n()),Br=bn();function Yp(r,e,t){let i=Er.default.randomBytes(Er.default.secretbox.nonceLength),n=new TextEncoder().encode(r),s=Er.default.secretbox(n,i,e);return{v:1,sid:t,n:(0,Br.encodeBase64)(i),c:(0,Br.encodeBase64)(s)}}function Xp(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Br.decodeBase64)(r.n),i=(0,Br.decodeBase64)(r.c);if(t.length!==Er.default.secretbox.nonceLength)throw new Error(`Invalid nonce length: ${t.length}`);let n=Er.default.secretbox.open(i,t,e);if(!n)throw new Error("Decryption failed: invalid ciphertext or wrong key");return new TextDecoder().decode(n)}function Jp(r,e,t){let i=Er.default.randomBytes(Er.default.secretbox.nonceLength),n=Er.default.secretbox(r,i,e);return{v:1,sid:t,n:(0,Br.encodeBase64)(i),c:(0,Br.encodeBase64)(n)}}function Zp(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,Br.decodeBase64)(r.n),i=(0,Br.decodeBase64)(r.c),n=Er.default.secretbox.open(i,t,e);if(!n)throw new Error("Decryption failed: invalid ciphertext or wrong key");return n}});var Jf=M(Wt=>{"use strict";var Qp=Wt&&Wt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Wt,"__esModule",{value:!0});Wt.generateKeyPair=eg;Wt.deriveSharedSecret=tg;Wt.deriveMetaSid=rg;Wt.isValidPublicKey=ig;Wt.clearKey=ng;Wt.keyToBase64=sg;Wt.base64ToKey=og;var Li=Qp(_n()),tr=bn();function eg(){let r=Li.default.box.keyPair();return{publicKey:(0,tr.encodeBase64)(r.publicKey),secretKey:(0,tr.encodeBase64)(r.secretKey)}}function tg(r,e){let t=(0,tr.decodeBase64)(r),i=(0,tr.decodeBase64)(e);if(t.length!==Li.default.box.publicKeyLength)throw new Error(`Invalid public key length: ${t.length}`);if(i.length!==Li.default.box.secretKeyLength)throw new Error(`Invalid secret key length: ${i.length}`);return Li.default.box.before(t,i)}function rg(r,e){let t=new TextEncoder().encode("termiq-meta-v1"),i=(0,tr.decodeBase64)(r),n=(0,tr.decodeBase64)(e),s=new Uint8Array(t.length+i.length+n.length);return s.set(t,0),s.set(i,t.length),s.set(n,t.length+i.length),(0,tr.encodeBase64)(Li.default.hash(s).slice(0,32))}function ig(r){try{return(0,tr.decodeBase64)(r).length===Li.default.box.publicKeyLength}catch{return!1}}function ng(r){r.fill(0)}function sg(r){return(0,tr.encodeBase64)(r)}function og(r){return(0,tr.decodeBase64)(r)}});var Qf=M(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.base64ToKey=re.keyToBase64=re.clearKey=re.isValidPublicKey=re.deriveMetaSid=re.deriveSharedSecret=re.generateKeyPair=re.decryptBinary=re.encryptBinary=re.decrypt=re.encrypt=re.concatBytes=re.fingerprintShortHex=re.fingerprintIdentityKey=re.buildKxAckCanonical=re.buildKxCanonical=re.verifySessionKey=re.signSessionKey=re.identityPublicFromSecret=re.generateIdentityKeyPair=re.KX_SIG_VERSION=re.KX_FINGERPRINT_LABEL=re.KX_ACK_LABEL=re.KX_SIGN_LABEL=re.isMultiRecipientPayload=re.isEncryptedPayload=void 0;var Zf=$f();Object.defineProperty(re,"isEncryptedPayload",{enumerable:!0,get:function(){return Zf.isEncryptedPayload}});Object.defineProperty(re,"isMultiRecipientPayload",{enumerable:!0,get:function(){return Zf.isMultiRecipientPayload}});var ys=Jo();Object.defineProperty(re,"KX_SIGN_LABEL",{enumerable:!0,get:function(){return ys.KX_SIGN_LABEL}});Object.defineProperty(re,"KX_ACK_LABEL",{enumerable:!0,get:function(){return ys.KX_ACK_LABEL}});Object.defineProperty(re,"KX_FINGERPRINT_LABEL",{enumerable:!0,get:function(){return ys.KX_FINGERPRINT_LABEL}});Object.defineProperty(re,"KX_SIG_VERSION",{enumerable:!0,get:function(){return ys.KX_SIG_VERSION}});var vr=Yf();Object.defineProperty(re,"generateIdentityKeyPair",{enumerable:!0,get:function(){return vr.generateIdentityKeyPair}});Object.defineProperty(re,"identityPublicFromSecret",{enumerable:!0,get:function(){return vr.identityPublicFromSecret}});Object.defineProperty(re,"signSessionKey",{enumerable:!0,get:function(){return vr.signSessionKey}});Object.defineProperty(re,"verifySessionKey",{enumerable:!0,get:function(){return vr.verifySessionKey}});Object.defineProperty(re,"buildKxCanonical",{enumerable:!0,get:function(){return vr.buildKxCanonical}});Object.defineProperty(re,"buildKxAckCanonical",{enumerable:!0,get:function(){return vr.buildKxAckCanonical}});Object.defineProperty(re,"fingerprintIdentityKey",{enumerable:!0,get:function(){return vr.fingerprintIdentityKey}});Object.defineProperty(re,"fingerprintShortHex",{enumerable:!0,get:function(){return vr.fingerprintShortHex}});Object.defineProperty(re,"concatBytes",{enumerable:!0,get:function(){return vr.concatBytes}});var _s=Xf();Object.defineProperty(re,"encrypt",{enumerable:!0,get:function(){return _s.encrypt}});Object.defineProperty(re,"decrypt",{enumerable:!0,get:function(){return _s.decrypt}});Object.defineProperty(re,"encryptBinary",{enumerable:!0,get:function(){return _s.encryptBinary}});Object.defineProperty(re,"decryptBinary",{enumerable:!0,get:function(){return _s.decryptBinary}});var ai=Jf();Object.defineProperty(re,"generateKeyPair",{enumerable:!0,get:function(){return ai.generateKeyPair}});Object.defineProperty(re,"deriveSharedSecret",{enumerable:!0,get:function(){return ai.deriveSharedSecret}});Object.defineProperty(re,"deriveMetaSid",{enumerable:!0,get:function(){return ai.deriveMetaSid}});Object.defineProperty(re,"isValidPublicKey",{enumerable:!0,get:function(){return ai.isValidPublicKey}});Object.defineProperty(re,"clearKey",{enumerable:!0,get:function(){return ai.clearKey}});Object.defineProperty(re,"keyToBase64",{enumerable:!0,get:function(){return ai.keyToBase64}});Object.defineProperty(re,"base64ToKey",{enumerable:!0,get:function(){return ai.base64ToKey}})});var eu=M(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.MIN_CLIENT_VERSION=Ct.PROTOCOL_VERSION_MINOR=Ct.PROTOCOL_VERSION_MAJOR=Ct.PROTOCOL_VERSION=void 0;Ct.isCompatibleVersion=ag;Ct.compareVersions=cg;Ct.PROTOCOL_VERSION="2.1";Ct.PROTOCOL_VERSION_MAJOR=2;Ct.PROTOCOL_VERSION_MINOR=1;Ct.MIN_CLIENT_VERSION="2.0";function ag(r){let[e]=r.split(".").map(Number);return e===Ct.PROTOCOL_VERSION_MAJOR}function cg(r,e){let[t,i]=r.split(".").map(Number),[n,s]=e.split(".").map(Number);return t!==n?t<n?-1:1:i!==s?i<s?-1:1:0}});var tu=M(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.SERVER_CAPABILITIES=rr.DEFAULT_CLIENT_CAPABILITIES=rr.Capability=void 0;rr.hasCapability=fg;rr.negotiateCapabilities=ug;var Ni;(function(r){r.FILE_TRANSFER="file-transfer",r.RELIABLE_MESSAGING="reliable-messaging",r.COMPRESSION="compression",r.E2E_ENCRYPTION="e2e-encryption",r.PRIORITY_QUEUES="priority-queues",r.OFFLINE_QUEUE="offline-queue",r.MULTI_DEVICE="multi-device",r.TERMINAL_EVENTS="terminal-events",r.E2E_PRIVACY="e2e-privacy",r.RELIABLE_INPUT="reliable-input",r.MULTI_VIEWER_RENDER="multi-viewer-render"})(Ni||(rr.Capability=Ni={}));rr.DEFAULT_CLIENT_CAPABILITIES=[Ni.E2E_ENCRYPTION,Ni.TERMINAL_EVENTS,Ni.RELIABLE_INPUT];rr.SERVER_CAPABILITIES=Object.values(Ni);function fg(r,e){return r.includes(e)}function ug(r,e){return r.filter(t=>e.includes(t))}});var ru=M(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.DEFAULT_PRIORITY=wr.PRIORITY_NAMES=wr.Priority=void 0;wr.comparePriority=lg;var ci;(function(r){r[r.CRITICAL=0]="CRITICAL",r[r.HIGH=1]="HIGH",r[r.NORMAL=2]="NORMAL",r[r.LOW=3]="LOW"})(ci||(wr.Priority=ci={}));wr.PRIORITY_NAMES={[ci.CRITICAL]:"CRITICAL",[ci.HIGH]:"HIGH",[ci.NORMAL]:"NORMAL",[ci.LOW]:"LOW"};wr.DEFAULT_PRIORITY=ci.NORMAL;function lg(r,e){return r-e}});var iu=M(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.DEFAULT_RELIABILITY=ir.RELIABILITY_NAMES=ir.Reliability=void 0;ir.requiresAck=hg;ir.requiresBuffer=dg;var Ur;(function(r){r[r.FIRE_FORGET=0]="FIRE_FORGET",r[r.BUFFERED=1]="BUFFERED",r[r.GUARANTEED=2]="GUARANTEED"})(Ur||(ir.Reliability=Ur={}));ir.RELIABILITY_NAMES={[Ur.FIRE_FORGET]:"FIRE_FORGET",[Ur.BUFFERED]:"BUFFERED",[Ur.GUARANTEED]:"GUARANTEED"};ir.DEFAULT_RELIABILITY=Ur.FIRE_FORGET;function hg(r){return r===Ur.GUARANTEED}function dg(r){return r>=Ur.BUFFERED}});var nu=M(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.createMessage=pg;function pg(r,e,t={}){return{id:crypto.randomUUID(),type:r,payload:e,priority:t.priority??2,reliability:t.reliability??0,seq:t.seq,timestamp:new Date().toISOString()}}});var su=M(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.TerminalEventType=void 0;fi.deriveStatusFromEvent=gg;fi.shouldTriggerPushNotification=mg;fi.getPushNotificationMessage=yg;var yt;(function(r){r.SESSION_START="session_start",r.SESSION_END="session_end",r.MESSAGE="message",r.TOOL_START="tool_start",r.TOOL_END="tool_end",r.WAITING_INPUT="waiting_input",r.ERROR="error"})(yt||(fi.TerminalEventType=yt={}));function gg(r){switch(r.type){case yt.SESSION_START:case yt.TOOL_START:case yt.MESSAGE:return"working";case yt.WAITING_INPUT:return"waiting";case yt.SESSION_END:return r.status==="success"?"completed":"error";case yt.ERROR:return r.severity==="fatal"?"error":"working";case yt.TOOL_END:return r.status==="error"?"error":"working";default:return"idle"}}function mg(r){switch(r.type){case yt.WAITING_INPUT:return!0;case yt.SESSION_END:return!0;case yt.ERROR:return r.severity!=="warning";default:return!1}}function yg(r,e){switch(r.type){case yt.WAITING_INPUT:return{title:`${e}: Input Required`,body:r.question.slice(0,100)};case yt.SESSION_END:{let t=r;return t.status==="success"?{title:`${e}: Task Completed`,body:t.summary||"Session finished successfully"}:{title:`${e}: Task Failed`,body:t.summary||"Session ended with error"}}case yt.ERROR:{let t=r;return t.severity==="warning"?null:{title:`${e}: Error`,body:t.message.slice(0,100)}}default:return null}}});var cu=M(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.TransferDirection=Ue.TransferStatus=Ue.CHUNK_TTL_SECONDS=Ue.TRANSFER_TTL_SECONDS=Ue.MAX_RETRIES=Ue.ACK_TIMEOUT_MS=Ue.WINDOW_SIZE=Ue.DEFAULT_MAX_FILE_SIZE=Ue.CHUNK_SIZE=void 0;Ue.calculateTotalChunks=_g;Ue.getMissingChunks=bg;Ue.isTransferComplete=Eg;Ue.CHUNK_SIZE=64*1024;Ue.DEFAULT_MAX_FILE_SIZE=100*1024*1024;Ue.WINDOW_SIZE=10;Ue.ACK_TIMEOUT_MS=3e4;Ue.MAX_RETRIES=3;Ue.TRANSFER_TTL_SECONDS=1440*60;Ue.CHUNK_TTL_SECONDS=1440*60;var ou;(function(r){r.PENDING="pending",r.ACTIVE="active",r.PAUSED="paused",r.COMPLETED="completed",r.FAILED="failed",r.CANCELLED="cancelled",r.EXPIRED="expired"})(ou||(Ue.TransferStatus=ou={}));var au;(function(r){r.DOWNLOAD="download",r.UPLOAD="upload"})(au||(Ue.TransferDirection=au={}));function _g(r,e=Ue.CHUNK_SIZE){return Math.ceil(r/e)}function bg(r,e){let t=new Set(e),i=[];for(let n=0;n<r;n++)t.has(n)||i.push(n);return i}function Eg(r,e){return e.length===r}});var fu=M(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.ERROR_MESSAGES=Sr.ErrorCode=void 0;Sr.createError=vg;Sr.isRetryableError=wg;var Ie;(function(r){r.AUTH_FAILED="E001",r.TOKEN_EXPIRED="E002",r.TOKEN_INVALID="E003",r.NOT_FOUND="E011",r.ALREADY_EXISTS="E012",r.ACCESS_DENIED="E021",r.FORBIDDEN="E022",r.RATE_LIMITED="E031",r.TOO_MANY_CONNECTIONS="E032",r.QUOTA_EXCEEDED="E041",r.FILE_TOO_LARGE="E042",r.QUEUE_FULL="E043",r.TRANSFERS_LIMIT="E044",r.TRANSFER_FAILED="E051",r.TRANSFER_EXPIRED="E052",r.TRANSFER_CANCELLED="E053",r.CHECKSUM_MISMATCH="E054",r.CHUNK_MISSING="E055",r.INVALID_MESSAGE="E061",r.UNSUPPORTED_VERSION="E062",r.CAPABILITY_REQUIRED="E063",r.INVALID_STATE="E071",r.TIMEOUT="E072",r.CONNECTION_LOST="E073",r.INTERNAL_ERROR="E091",r.SERVICE_UNAVAILABLE="E092"})(Ie||(Sr.ErrorCode=Ie={}));Sr.ERROR_MESSAGES={[Ie.AUTH_FAILED]:"Authentication failed",[Ie.TOKEN_EXPIRED]:"Token expired",[Ie.TOKEN_INVALID]:"Invalid token",[Ie.NOT_FOUND]:"Resource not found",[Ie.ALREADY_EXISTS]:"Resource already exists",[Ie.ACCESS_DENIED]:"Access denied",[Ie.FORBIDDEN]:"Operation forbidden",[Ie.RATE_LIMITED]:"Rate limit exceeded",[Ie.TOO_MANY_CONNECTIONS]:"Too many connections",[Ie.QUOTA_EXCEEDED]:"Plan quota exceeded",[Ie.FILE_TOO_LARGE]:"File size exceeds limit",[Ie.QUEUE_FULL]:"Message queue is full",[Ie.TRANSFERS_LIMIT]:"Daily transfers limit reached",[Ie.TRANSFER_FAILED]:"File transfer failed",[Ie.TRANSFER_EXPIRED]:"Transfer expired",[Ie.TRANSFER_CANCELLED]:"Transfer cancelled",[Ie.CHECKSUM_MISMATCH]:"File checksum mismatch",[Ie.CHUNK_MISSING]:"Chunk missing or corrupted",[Ie.INVALID_MESSAGE]:"Invalid message format",[Ie.UNSUPPORTED_VERSION]:"Unsupported protocol version",[Ie.CAPABILITY_REQUIRED]:"Required capability not supported",[Ie.INVALID_STATE]:"Invalid state for this operation",[Ie.TIMEOUT]:"Operation timed out",[Ie.CONNECTION_LOST]:"Connection lost",[Ie.INTERNAL_ERROR]:"Internal server error",[Ie.SERVICE_UNAVAILABLE]:"Service temporarily unavailable"};function vg(r,e={}){return{code:r,message:e.message||Sr.ERROR_MESSAGES[r],details:e.details,retryable:e.retryable??!1,retryAfter:e.retryAfter}}function wg(r){return[Ie.RATE_LIMITED,Ie.TIMEOUT,Ie.CONNECTION_LOST,Ie.SERVICE_UNAVAILABLE].includes(r)}});var du=M(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.FileEntryType=kt.DiffBase=kt.FileViewType=kt.FileChangeType=void 0;kt.getLanguageFromPath=Sg;kt.parseUnifiedDiff=xg;kt.createSimpleDiff=Tg;var Kr;(function(r){r.CREATE="create",r.MODIFY="modify",r.DELETE="delete"})(Kr||(kt.FileChangeType=Kr={}));var uu;(function(r){r.CONTENT="content",r.DIFF="diff"})(uu||(kt.FileViewType=uu={}));var lu;(function(r){r.GIT="git",r.PREVIOUS="previous"})(lu||(kt.DiffBase=lu={}));function Sg(r){let e=r.split(".").pop()?.toLowerCase(),t={js:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",mjs:"javascript",cjs:"javascript",html:"html",htm:"html",css:"css",scss:"scss",sass:"scss",less:"less",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",toml:"toml",md:"markdown",mdx:"markdown",env:"plaintext",gitignore:"plaintext",dockerignore:"plaintext",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",py:"python",pyw:"python",pyi:"python",go:"go",rs:"rust",java:"java",kt:"kotlin",kts:"kotlin",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",sql:"sql",graphql:"graphql",gql:"graphql",prisma:"prisma",dockerfile:"dockerfile"},i=r.split("/").pop()?.toLowerCase()||"";return{dockerfile:"dockerfile",makefile:"makefile",".gitignore":"plaintext",".env":"plaintext",".env.local":"plaintext",".env.development":"plaintext",".env.production":"plaintext"}[i]||t[e||""]||"plaintext"}function xg(r,e){let t=r.split(`
|
|
3
|
+
`),i=[],n=0,s=0,a=null,c=0,u=0;for(let p of t){if(p.startsWith("diff ")||p.startsWith("index ")||p.startsWith("---")||p.startsWith("+++"))continue;let m=p.match(/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@/);if(m){a&&i.push(a);let _=parseInt(m[1],10),v=parseInt(m[2]||"1",10),T=parseInt(m[3],10),x=parseInt(m[4]||"1",10);a={oldStart:_,oldLines:v,newStart:T,newLines:x,lines:[]},c=_,u=T;continue}a&&(p.startsWith("+")?(a.lines.push({type:"add",content:p.slice(1),oldLineNumber:null,newLineNumber:u++}),n++):p.startsWith("-")?(a.lines.push({type:"remove",content:p.slice(1),oldLineNumber:c++,newLineNumber:null}),s++):(p.startsWith(" ")||p==="")&&a.lines.push({type:"context",content:p.startsWith(" ")?p.slice(1):p,oldLineNumber:c++,newLineNumber:u++}))}a&&i.push(a);let d;return s===0&&n>0&&i.length===1&&i[0].oldLines===0?d=Kr.CREATE:n===0&&s>0&&i.length===1&&i[0].newLines===0?d=Kr.DELETE:d=Kr.MODIFY,{path:e,changeType:d,hunks:i,additions:n,deletions:s,isBinary:!1}}function Tg(r,e,t){let i=r.split(`
|
|
4
4
|
`),n=e.split(`
|
|
5
|
-
`),s=[],a=0,c=0,u=Math.max(i.length,n.length);for(let p=0;p<u;p++){let m=i[p],_=n[p];m===_?m!==void 0&&s.push({type:"context",content:m,oldLineNumber:p+1,newLineNumber:p+1}):(m!==void 0&&(s.push({type:"remove",content:m,oldLineNumber:p+1,newLineNumber:null}),c++),_!==void 0&&(s.push({type:"add",content:_,oldLineNumber:null,newLineNumber:p+1}),a++))}let d;return r===""?d=Kr.CREATE:e===""?d=Kr.DELETE:d=Kr.MODIFY,{path:t,changeType:d,hunks:[{oldStart:1,oldLines:i.length,newStart:1,newLines:n.length,lines:s}],additions:a,deletions:c,isBinary:!1}}var hu;(function(r){r.FILE="file",r.DIRECTORY="directory"})(hu||(kt.FileEntryType=hu={}))});var pu=M(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.createSimpleDiff=N.parseUnifiedDiff=N.getLanguageFromPath=N.FileEntryType=N.DiffBase=N.FileViewType=N.FileChangeType=N.isRetryableError=N.createError=N.ERROR_MESSAGES=N.ErrorCode=N.isTransferComplete=N.getMissingChunks=N.calculateTotalChunks=N.TransferDirection=N.TransferStatus=N.CHUNK_TTL_SECONDS=N.TRANSFER_TTL_SECONDS=N.MAX_RETRIES=N.ACK_TIMEOUT_MS=N.WINDOW_SIZE=N.DEFAULT_MAX_FILE_SIZE=N.CHUNK_SIZE=N.getPushNotificationMessage=N.shouldTriggerPushNotification=N.deriveStatusFromEvent=N.TerminalEventType=N.createMessage=N.requiresBuffer=N.requiresAck=N.DEFAULT_RELIABILITY=N.RELIABILITY_NAMES=N.Reliability=N.comparePriority=N.DEFAULT_PRIORITY=N.PRIORITY_NAMES=N.Priority=N.negotiateCapabilities=N.hasCapability=N.SERVER_CAPABILITIES=N.DEFAULT_CLIENT_CAPABILITIES=N.Capability=N.compareVersions=N.isCompatibleVersion=N.MIN_CLIENT_VERSION=N.PROTOCOL_VERSION_MINOR=N.PROTOCOL_VERSION_MAJOR=N.PROTOCOL_VERSION=void 0;var Mi=eu();Object.defineProperty(N,"PROTOCOL_VERSION",{enumerable:!0,get:function(){return Mi.PROTOCOL_VERSION}});Object.defineProperty(N,"PROTOCOL_VERSION_MAJOR",{enumerable:!0,get:function(){return Mi.PROTOCOL_VERSION_MAJOR}});Object.defineProperty(N,"PROTOCOL_VERSION_MINOR",{enumerable:!0,get:function(){return Mi.PROTOCOL_VERSION_MINOR}});Object.defineProperty(N,"MIN_CLIENT_VERSION",{enumerable:!0,get:function(){return Mi.MIN_CLIENT_VERSION}});Object.defineProperty(N,"isCompatibleVersion",{enumerable:!0,get:function(){return Mi.isCompatibleVersion}});Object.defineProperty(N,"compareVersions",{enumerable:!0,get:function(){return Mi.compareVersions}});var En=tu();Object.defineProperty(N,"Capability",{enumerable:!0,get:function(){return En.Capability}});Object.defineProperty(N,"DEFAULT_CLIENT_CAPABILITIES",{enumerable:!0,get:function(){return En.DEFAULT_CLIENT_CAPABILITIES}});Object.defineProperty(N,"SERVER_CAPABILITIES",{enumerable:!0,get:function(){return En.SERVER_CAPABILITIES}});Object.defineProperty(N,"hasCapability",{enumerable:!0,get:function(){return En.hasCapability}});Object.defineProperty(N,"negotiateCapabilities",{enumerable:!0,get:function(){return En.negotiateCapabilities}});var vs=ru();Object.defineProperty(N,"Priority",{enumerable:!0,get:function(){return vs.Priority}});Object.defineProperty(N,"PRIORITY_NAMES",{enumerable:!0,get:function(){return vs.PRIORITY_NAMES}});Object.defineProperty(N,"DEFAULT_PRIORITY",{enumerable:!0,get:function(){return vs.DEFAULT_PRIORITY}});Object.defineProperty(N,"comparePriority",{enumerable:!0,get:function(){return vs.comparePriority}});var wn=iu();Object.defineProperty(N,"Reliability",{enumerable:!0,get:function(){return wn.Reliability}});Object.defineProperty(N,"RELIABILITY_NAMES",{enumerable:!0,get:function(){return wn.RELIABILITY_NAMES}});Object.defineProperty(N,"DEFAULT_RELIABILITY",{enumerable:!0,get:function(){return wn.DEFAULT_RELIABILITY}});Object.defineProperty(N,"requiresAck",{enumerable:!0,get:function(){return wn.requiresAck}});Object.defineProperty(N,"requiresBuffer",{enumerable:!0,get:function(){return wn.requiresBuffer}});var Cg=nu();Object.defineProperty(N,"createMessage",{enumerable:!0,get:function(){return Cg.createMessage}});var bs=su();Object.defineProperty(N,"TerminalEventType",{enumerable:!0,get:function(){return bs.TerminalEventType}});Object.defineProperty(N,"deriveStatusFromEvent",{enumerable:!0,get:function(){return bs.deriveStatusFromEvent}});Object.defineProperty(N,"shouldTriggerPushNotification",{enumerable:!0,get:function(){return bs.shouldTriggerPushNotification}});Object.defineProperty(N,"getPushNotificationMessage",{enumerable:!0,get:function(){return bs.getPushNotificationMessage}});var Lt=cu();Object.defineProperty(N,"CHUNK_SIZE",{enumerable:!0,get:function(){return Lt.CHUNK_SIZE}});Object.defineProperty(N,"DEFAULT_MAX_FILE_SIZE",{enumerable:!0,get:function(){return Lt.DEFAULT_MAX_FILE_SIZE}});Object.defineProperty(N,"WINDOW_SIZE",{enumerable:!0,get:function(){return Lt.WINDOW_SIZE}});Object.defineProperty(N,"ACK_TIMEOUT_MS",{enumerable:!0,get:function(){return Lt.ACK_TIMEOUT_MS}});Object.defineProperty(N,"MAX_RETRIES",{enumerable:!0,get:function(){return Lt.MAX_RETRIES}});Object.defineProperty(N,"TRANSFER_TTL_SECONDS",{enumerable:!0,get:function(){return Lt.TRANSFER_TTL_SECONDS}});Object.defineProperty(N,"CHUNK_TTL_SECONDS",{enumerable:!0,get:function(){return Lt.CHUNK_TTL_SECONDS}});Object.defineProperty(N,"TransferStatus",{enumerable:!0,get:function(){return Lt.TransferStatus}});Object.defineProperty(N,"TransferDirection",{enumerable:!0,get:function(){return Lt.TransferDirection}});Object.defineProperty(N,"calculateTotalChunks",{enumerable:!0,get:function(){return Lt.calculateTotalChunks}});Object.defineProperty(N,"getMissingChunks",{enumerable:!0,get:function(){return Lt.getMissingChunks}});Object.defineProperty(N,"isTransferComplete",{enumerable:!0,get:function(){return Lt.isTransferComplete}});var Es=fu();Object.defineProperty(N,"ErrorCode",{enumerable:!0,get:function(){return Es.ErrorCode}});Object.defineProperty(N,"ERROR_MESSAGES",{enumerable:!0,get:function(){return Es.ERROR_MESSAGES}});Object.defineProperty(N,"createError",{enumerable:!0,get:function(){return Es.createError}});Object.defineProperty(N,"isRetryableError",{enumerable:!0,get:function(){return Es.isRetryableError}});var ui=du();Object.defineProperty(N,"FileChangeType",{enumerable:!0,get:function(){return ui.FileChangeType}});Object.defineProperty(N,"FileViewType",{enumerable:!0,get:function(){return ui.FileViewType}});Object.defineProperty(N,"DiffBase",{enumerable:!0,get:function(){return ui.DiffBase}});Object.defineProperty(N,"FileEntryType",{enumerable:!0,get:function(){return ui.FileEntryType}});Object.defineProperty(N,"getLanguageFromPath",{enumerable:!0,get:function(){return ui.getLanguageFromPath}});Object.defineProperty(N,"parseUnifiedDiff",{enumerable:!0,get:function(){return ui.parseUnifiedDiff}});Object.defineProperty(N,"createSimpleDiff",{enumerable:!0,get:function(){return ui.createSimpleDiff}})});var Sr=M(nr=>{"use strict";var kg=nr&&nr.__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]})),ws=nr&&nr.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&kg(e,r,t)};Object.defineProperty(nr,"__esModule",{value:!0});ws(Vf(),nr);ws(zf(),nr);ws(Qf(),nr);ws(pu(),nr)});var Qo=M(He=>{"use strict";var Og=He&&He.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(He,"__esModule",{value:!0});He.FP_LABEL=He.KX_ACK_LABEL=He.KX_SIGN_LABEL=void 0;He.concatBytes=xn;He.generateIdentityKeyPair=Pg;He.identityPublicFromSecret=Rg;He.signSessionKey=Ag;He.verifySessionKey=Ig;He.buildKxCanonical=Lg;He.buildKxAckCanonical=Ng;He.fingerprintIdentityKey=Mg;He.fingerprintShortHex=Fg;var sr=Og(_n()),Ot=vn();He.KX_SIGN_LABEL="termiq-kx-v1";He.KX_ACK_LABEL="termiq-kxack-v1";He.FP_LABEL="termiq-fp-v1";function xn(...r){let e=0;for(let n of r)e+=n.length;let t=new Uint8Array(e),i=0;for(let n of r)t.set(n,i),i+=n.length;return t}function Pg(){let r=sr.default.sign.keyPair();return{identityPublicKey:(0,Ot.encodeBase64)(r.publicKey),identitySecretKey:(0,Ot.encodeBase64)(r.secretKey)}}function Rg(r){let e=(0,Ot.decodeBase64)(r);if(e.length!==sr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");let t=sr.default.sign.keyPair.fromSecretKey(e);return(0,Ot.encodeBase64)(t.publicKey)}function Ag(r,e){let t=(0,Ot.decodeBase64)(e);if(t.length!==sr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");return(0,Ot.encodeBase64)(sr.default.sign.detached(r,t))}function Ig(r,e,t){try{let i=(0,Ot.decodeBase64)(e),n=(0,Ot.decodeBase64)(t);return n.length!==sr.default.sign.publicKeyLength||i.length!==sr.default.sign.signatureLength?!1:sr.default.sign.detached.verify(r,i,n)}catch{return!1}}var li=new Uint8Array([0]);function Lg(r){let e=new TextEncoder,t=e.encode(He.KX_SIGN_LABEL),i=e.encode(r.agentId),n=e.encode(String(r.keyVersion)),s=(0,Ot.decodeBase64)(r.boxPublicKey);return xn(t,li,i,li,n,li,s)}function Ng(r){let e=new TextEncoder;return xn(e.encode(He.KX_ACK_LABEL),li,e.encode(r.agentId),li,e.encode(String(r.keyVersion)),li,(0,Ot.decodeBase64)(r.boxPublicKey),li,(0,Ot.decodeBase64)(r.boundClientKey))}function Mg(r){let e=(0,Ot.decodeBase64)(r),t=xn(new TextEncoder().encode(He.FP_LABEL),e),i=sr.default.hash(t),n=[];for(let s=0;s<12;s++){let a=s*5,u=(((i[a]<<24>>>0)+(i[a+1]<<16)+(i[a+2]<<8)+i[a+3]^i[a+4])>>>0)%1e5;n.push(String(u).padStart(5,"0"))}return n.join(" ")}function Fg(r){let e=(0,Ot.decodeBase64)(r),t=xn(new TextEncoder().encode(He.FP_LABEL),e),i=sr.default.hash(t).slice(0,8);return Array.from(i).map(n=>n.toString(16).padStart(2,"0")).join(":").toUpperCase()}});var mu=M(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});xs.CryptoService=void 0;var Qe=Sr(),qr=Qo(),Dg=3600*1e3,gu=10,ea=class{storage;logger;sessions=new Map;agentSessions=new Map;metaSessions=new Map;keyPair=null;identityKeyPair=null;publicKeyKey;secretKeyKey;keyVersionKey;identityPublicKeyKey;identitySecretKeyKey;constructor(e,t,i,n){this.storage=e,this.logger=t;let s=`termiq.${i}.${n}`;this.publicKeyKey=`${s}.crypto.publicKey`,this.secretKeyKey=`${s}.crypto.secretKey`,this.keyVersionKey=`${s}.crypto.keyVersion`,this.identityPublicKeyKey=`${s}.crypto.identityPublicKey`,this.identitySecretKeyKey=`${s}.crypto.identitySecretKey`,this.logger.info("CryptoService namespace",i,n)}async initialize(){let e=await this.storage.get(this.publicKeyKey),t=await this.storage.get(this.secretKeyKey);e&&t?(this.keyPair={publicKey:e,secretKey:t},this.logger.info("Loaded existing box key pair")):await this.generateBoxKeyPair(),await this.ensureIdentityKeyPair()}async generateBoxKeyPair(){this.logger.info("Generating new box key pair"),this.keyPair=(0,Qe.generateKeyPair)(),await this.storage.set(this.publicKeyKey,this.keyPair.publicKey),await this.storage.set(this.secretKeyKey,this.keyPair.secretKey);let e=await this.getKeyVersion();return await this.storage.set(this.keyVersionKey,String(e+1)),this.logger.info("Box key pair generated and stored"),this.keyPair}async generateIdentityKeyPair(){return this.generateBoxKeyPair()}async ensureIdentityKeyPair(){if(this.identityKeyPair)return this.identityKeyPair;let e=await this.storage.get(this.identitySecretKeyKey),t=await this.storage.get(this.identityPublicKeyKey);return e?(t||(t=(0,qr.identityPublicFromSecret)(e),await this.storage.set(this.identityPublicKeyKey,t)),this.identityKeyPair={identityPublicKey:t,identitySecretKey:e},this.logger.info("Loaded existing identity (Ed25519) key pair"),this.identityKeyPair):(this.logger.info("Generating new identity (Ed25519) key pair"),this.identityKeyPair=(0,qr.generateIdentityKeyPair)(),await this.storage.set(this.identityPublicKeyKey,this.identityKeyPair.identityPublicKey),await this.storage.set(this.identitySecretKeyKey,this.identityKeyPair.identitySecretKey),this.logger.info("Identity (Ed25519) key pair generated and stored"),this.identityKeyPair)}async getIdentityPublicKey(){return(await this.ensureIdentityKeyPair()).identityPublicKey}async getPublicKey(){return this.keyPair?this.keyPair.publicKey:await this.storage.get(this.publicKeyKey)||null}async getKeyVersion(){let e=await this.storage.get(this.keyVersionKey);return e?parseInt(e,10):1}async getSignedAgentKey(e){if(!this.keyPair&&(await this.initialize(),!this.keyPair))return this.logger.error("No box key pair available for signing"),null;let t=await this.ensureIdentityKeyPair(),i=await this.getKeyVersion(),n=this.keyPair.publicKey,s=(0,qr.buildKxCanonical)({agentId:e,keyVersion:i,boxPublicKey:n}),a=(0,qr.signSessionKey)(s,t.identitySecretKey);return{boxPublicKey:n,identityPublicKey:t.identityPublicKey,keyVersion:i,signature:a,sigVersion:1}}async signKeyExchangeAck(e,t){if(!this.keyPair&&(await this.initialize(),!this.keyPair))return this.logger.error("No box key pair available for ACK signing"),null;let i=await this.ensureIdentityKeyPair(),n=await this.getKeyVersion(),s=(0,qr.buildKxAckCanonical)({agentId:e,keyVersion:n,boxPublicKey:this.keyPair.publicKey,boundClientKey:t});return(0,qr.signSessionKey)(s,i.identitySecretKey)}async getSafetyNumber(){let e=await this.ensureIdentityKeyPair();return(0,qr.fingerprintIdentityKey)(e.identityPublicKey)}async getShortFingerprint(){let e=await this.ensureIdentityKeyPair();return(0,qr.fingerprintShortHex)(e.identityPublicKey)}async handleKeyExchange(e,t,i){if(!this.keyPair&&(this.logger.warn("Key pair missing, attempting re-initialization"),await this.initialize(),!this.keyPair))return this.logger.error("No identity key pair available after re-initialization"),!1;this.logger.info("Starting key exchange",e,i);try{let n=this.sessions.get(e);n||(n=new Map,this.sessions.set(e,n));let s=(0,Qe.deriveSharedSecret)(t,this.keyPair.secretKey),a={terminalId:e,clientPublicKey:t,sharedSecret:s,createdAt:Date.now(),sessionId:i};return n.set(i,a),this.logger.info("Key exchange completed",e,i,"total:",n.size),!0}catch(n){return this.logger.error("Key exchange failed",n),!1}}encryptOutput(e,t){let i=this.sessions.get(e);if(!i||i.size===0)return null;try{if(i.size===1){let s=i.values().next().value;return s?(0,Qe.encrypt)(t,s.sharedSecret,s.sessionId):null}let n=[];for(let s of i.values()){let a=(0,Qe.encrypt)(t,s.sharedSecret,s.sessionId);n.push({sid:a.sid,n:a.n,c:a.c})}return{v:2,recipients:n}}catch(n){return this.logger.error("Encryption failed",n),null}}decryptInput(e,t){let i=this.sessions.get(e);if(!i)return this.logger.error("No sessions for terminal",e),null;let n=i.get(t.sid);if(!n)return this.logger.error("No session for sessionId",t.sid),null;try{return(0,Qe.decrypt)(t,n.sharedSecret)}catch(s){return this.logger.error("Decryption failed",s),null}}encryptFileChunk(e,t){let i=this.sessions.get(e);if(!i||i.size===0)return null;let n=null;for(let s of i.values())(!n||s.createdAt>n.createdAt)&&(n=s);if(!n)return null;try{return(0,Qe.encryptBinary)(t,n.sharedSecret,n.sessionId)}catch(s){return this.logger.error("File chunk encryption failed",s),null}}decryptFileChunk(e,t){let i=this.sessions.get(e)?.get(t.sid);if(!i)return this.logger.error("No session for file chunk",e,t.sid),null;try{return(0,Qe.decryptBinary)(t,i.sharedSecret)}catch(n){return this.logger.error("File chunk decryption failed",n),null}}hasSession(e){let t=this.sessions.get(e);return t!==void 0&&t.size>0}removeSession(e,t){let i=this.sessions.get(e);if(i)if(t){let n=i.get(t);n&&((0,Qe.clearKey)(n.sharedSecret),i.delete(t),this.logger.info("Session removed",e,t)),i.size===0&&this.sessions.delete(e)}else{for(let n of i.values())(0,Qe.clearKey)(n.sharedSecret);this.sessions.delete(e),this.logger.debug("All sessions removed for terminal",e)}}clearAllSessions(){for(let e of this.sessions.values())for(let t of e.values())(0,Qe.clearKey)(t.sharedSecret);this.sessions.clear(),this.logger.debug("All sessions cleared")}cleanupStaleSessions(e){let t=this.sessions.get(e);if(!t||t.size===0)return;let i=Date.now(),n=[];for(let[s,a]of t)i-a.createdAt>Dg&&n.push(s);for(let s of n){let a=t.get(s);a&&((0,Qe.clearKey)(a.sharedSecret),t.delete(s),this.logger.info("Session expired (TTL)",e,s,`age:${Math.round((i-a.createdAt)/1e3)}s`))}if(t.size>gu){let a=Array.from(t.entries()).sort((c,u)=>c[1].createdAt-u[1].createdAt).slice(0,t.size-gu);for(let[,c]of a)(0,Qe.clearKey)(c.sharedSecret),t.delete(c.sessionId)}t.size===0&&this.sessions.delete(e)}cleanupAllStaleSessions(){for(let e of this.sessions.keys())this.cleanupStaleSessions(e)}getSessionInfo(){let e=[];for(let[t,i]of this.sessions.entries())for(let n of i.values())e.push({terminalId:t,createdAt:n.createdAt,sessionId:n.sessionId});return e}async handleAgentKeyExchange(e,t){if(!this.keyPair&&(this.logger.warn("Key pair missing for agent key exchange"),await this.initialize(),!this.keyPair))return this.logger.error("No identity key pair available for agent key exchange"),!1;try{let i=this.agentSessions.get(t);i&&(this.logger.info("Rekeying existing agent session",t),(0,Qe.clearKey)(i.sharedSecret));let n=(0,Qe.deriveSharedSecret)(e,this.keyPair.secretKey),s={sessionId:t,clientPublicKey:e,sharedSecret:n,createdAt:Date.now()};return this.agentSessions.set(t,s),this.logger.info("Agent key exchange completed",t,"total:",this.agentSessions.size),!0}catch(i){return this.logger.error("Agent key exchange failed",i),!1}}removeAgentSession(e){let t=this.agentSessions.get(e);t&&((0,Qe.clearKey)(t.sharedSecret),this.agentSessions.delete(e),this.logger.info("Agent session removed",e))}hasAgentSessions(){return this.agentSessions.size>0}async handleMetaKeyExchange(e){if(!this.keyPair&&(await this.initialize(),!this.keyPair))return{ok:!1,isNew:!1};try{let t=!this.metaSessions.has(e),i=(0,Qe.deriveSharedSecret)(e,this.keyPair.secretKey),n=(0,Qe.deriveMetaSid)(this.keyPair.publicKey,e);return this.metaSessions.set(e,{clientIdentityPub:e,sharedSecret:i,sidMeta:n}),this.logger.info("Meta key exchange completed",n,"isNew:",t,"total:",this.metaSessions.size),{ok:!0,isNew:t}}catch(t){return this.logger.error("Meta key exchange failed",t),{ok:!1,isNew:!1}}}hasMetaSession(){return this.metaSessions.size>0}encryptWorkspaceInfo(e){let t=this.encryptForMeta(JSON.stringify(e));return t?{encrypted:t}:null}encryptTerminalInfo(e){let t=this.encryptForMeta(JSON.stringify(e));return t?{encrypted:t}:null}encryptPromptInfo(e){let t=this.encryptForMeta(JSON.stringify(e));return t?{encrypted:t}:null}encryptForMeta(e){if(this.metaSessions.size===0)return null;try{if(this.metaSessions.size===1){let i=this.metaSessions.values().next().value;return i?(0,Qe.encrypt)(e,i.sharedSecret,i.sidMeta):null}let t=[];for(let i of this.metaSessions.values()){let n=(0,Qe.encrypt)(e,i.sharedSecret,i.sidMeta);t.push({sid:n.sid,n:n.n,c:n.c})}return{v:2,recipients:t}}catch(t){return this.logger.error("Meta encryption failed",t),null}}clearAllAgentSessions(){for(let e of this.agentSessions.values())(0,Qe.clearKey)(e.sharedSecret);this.agentSessions.clear(),this.logger.debug("All agent sessions cleared")}async deleteKeys(){await this.storage.delete(this.publicKeyKey),await this.storage.delete(this.secretKeyKey),await this.storage.delete(this.keyVersionKey),await this.storage.delete(this.identityPublicKeyKey),await this.storage.delete(this.identitySecretKeyKey),this.keyPair=null,this.identityKeyPair=null,this.clearAllSessions(),this.clearAllAgentSessions(),this.logger.info("All crypto keys deleted")}};xs.CryptoService=ea});var yu=M(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.AuthService=void 0;var Sn=us(),ta=class{storage;cryptoService;machineId;config;logger;notification;browser;pollingAbortController=null;tokenKey;refreshTokenKey;agentIdKey;constructor(e,t,i,n,s,a,c,u,d){this.storage=e,this.cryptoService=t,this.machineId=i,this.config=n,this.logger=s,this.notification=a,this.browser=c;let p=`termiq.${u}.${d}`;this.tokenKey=`${p}.accessToken`,this.refreshTokenKey=`${p}.refreshToken`,this.agentIdKey=`${p}.agentId`,this.logger.info("AuthService namespace",u,d)}cancelPolling(){this.pollingAbortController&&(this.logger.info("Cancelling active polling"),this.pollingAbortController.abort(),this.pollingAbortController=null)}async startDeviceCodeFlow(){this.cancelPolling();let e=(0,Sn.getApiUrl)(this.config),t=await this.machineId.getMachineId(),i=this.machineId.getMachineName(),n=await this.cryptoService.getPublicKey();n||(await this.cryptoService.generateIdentityKeyPair(),n=await this.cryptoService.getPublicKey()),this.logger.info("Starting device code flow",t,i);let s=await fetch(`${e}/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machineId:t,machineName:i,publicKey:n})});if(!s.ok){let a=await s.text();throw new Error(`Failed to get device code: ${a}`)}return s.json()}async pollForToken(e){this.cancelPolling();let t=(0,Sn.getApiUrl)(this.config),i=5e3,n=60;this.pollingAbortController=new AbortController;let s=this.pollingAbortController.signal;this.logger.info("Starting token polling");for(let a=0;a<n;a++){if(s.aborted)return this.logger.info("Polling was cancelled"),null;if(await this.sleep(i),s.aborted)return this.logger.info("Polling was cancelled"),null;try{let c=await fetch(`${t}/auth/device/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:e}),signal:s});if(!c.ok){if(c.status===403)try{let d=await c.json();if(d.error==="AGENT_LIMIT_EXCEEDED")return this.logger.warn("Agent limit exceeded",String(d.current),"/",String(d.max)),this.notification.warn(`Agent limit reached (${d.current}/${d.max}). Upgrade your plan to add more devices.`),null}catch{}this.logger.warn("Poll request failed",String(c.status));continue}let u=await c.json();if(u.status==="success"&&u.accessToken)return this.logger.info("Token received successfully"),this.pollingAbortController=null,await this.saveTokens(u),u;if(u.status==="expired")return this.logger.warn("Device code expired"),null;if(u.status==="limit_exceeded")return this.logger.warn("Agent limit exceeded",String(u.current),"/",String(u.max)),this.notification.warn(`Agent limit reached (${u.current}/${u.max}). Remove an old agent or upgrade your plan.`),null;this.logger.debug("Token pending, continuing poll",String(a))}catch(c){if(s.aborted)return this.logger.info("Polling was cancelled"),null;let u=c instanceof Error?c.message:String(c);this.logger.warn(`Poll error: ${u}`)}}return this.logger.warn("Polling timed out"),this.pollingAbortController=null,null}async loginWithApiKey(e){let t=(0,Sn.getApiUrl)(this.config),i=await this.machineId.getMachineId(),n=this.machineId.getMachineName(),s=await this.cryptoService.getPublicKey();s||(await this.cryptoService.generateIdentityKeyPair(),s=await this.cryptoService.getPublicKey()),this.logger.info("Logging in with API key");try{let a=await fetch(`${t}/auth/api-key/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e,machineId:i,machineName:n,publicKey:s})});if(!a.ok){let u=await a.text();return this.logger.error("API key login failed",u),!1}let c=await a.json();return c.accessToken?(await this.saveTokens(c),this.logger.info("API key login successful"),!0):!1}catch(a){return this.logger.error("API key login error",a),!1}}async hasValidToken(){let e=await this.storage.get(this.tokenKey);if(!e)return!1;try{let i=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()).exp*1e3;return Date.now()<i}catch{return!1}}async getAccessToken(){return await this.storage.get(this.tokenKey)||null}async getAgentId(){return await this.storage.get(this.agentIdKey)||null}async refreshAccessToken(){let e=await this.storage.get(this.refreshTokenKey);if(!e)return this.logger.debug("No refresh token available"),null;let t=(0,Sn.getApiUrl)(this.config);try{this.logger.info("Refreshing access token");let i=await fetch(`${t}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!i.ok)return this.logger.warn("Token refresh failed",String(i.status)),i.status===401&&await this.storage.delete(this.refreshTokenKey),null;let n=await i.json();return await this.storage.set(this.tokenKey,n.accessToken),await this.storage.set(this.refreshTokenKey,n.refreshToken),this.logger.info("Access token refreshed successfully"),n.accessToken}catch(i){return this.logger.warn("Token refresh error",i),null}}async logout(){this.logger.info("Logging out"),this.cancelPolling(),await this.storage.delete(this.tokenKey),await this.storage.delete(this.refreshTokenKey),await this.storage.delete(this.agentIdKey),await this.cryptoService.deleteKeys()}async saveTokens(e){e.accessToken&&await this.storage.set(this.tokenKey,e.accessToken),e.refreshToken&&await this.storage.set(this.refreshTokenKey,e.refreshToken),e.agentId&&await this.storage.set(this.agentIdKey,e.agentId)}async getLimits(){let e=await this.getAccessToken();if(!e)return this.logger.warn("Cannot fetch limits: no access token"),null;let t=(0,Sn.getApiUrl)(this.config);try{let i=await fetch(`${t}/users/me/limits`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});return i.ok?await i.json():(this.logger.error("Failed to fetch limits",String(i.status)),null)}catch(i){let n=i instanceof Error?i.message:String(i);return this.logger.error(`Error fetching limits: ${n}`),null}}async openUrl(e){await this.browser.openUrl(e)}async canCreateTerminal(){let e=await this.getLimits();return e?e.terminals.unlimited?{allowed:!0,limits:e}:e.terminals.current>=e.terminals.max?{allowed:!1,reason:`Terminal limit reached (${e.terminals.current}/${e.terminals.max}). Upgrade your plan to create more terminals.`,limits:e}:{allowed:!0,limits:e}:{allowed:!0}}sleep(e){return new Promise(t=>setTimeout(t,e))}};Ss.AuthService=ta});var _u=M(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.StatusDetector=void 0;Tn.isAnswerKeystroke=Bg;var Ts={working:[/✶/,/⠋|⠙|⠹|⠸|⠼|⠴|⠦|⠧|⠇|⠏/],idle:[/[❯$#>]\s*$/,/^\s*\d+\s*[❯$#>]\s*$/,/\(base\)\s*[❯$#>]\s*$/,/\)\s*[❯$#>]\s*$/],waiting:[/\[y\/n\]\s*$/i,/\[y\/N\]\s*$/i,/\(y\/n\)\s*$/i,/\(yes\/no\)\s*$/i,/press enter to continue\s*$/i,/press any key\s*$/i,/\[enter\]\s*$/i],completed:[/✓\s*(Done|Complete|Success|Finished)/i,/\[done\]/i,/\[success\]/i,/completed successfully/i,/Build succeeded/i,/All tests passed/i],error:[/✕\s*(Error|Failed|Failure)/i,/\[error\]/i,/\[failed\]/i,/Error:/i,/Exception:/i,/FATAL:/i,/Build failed/i,/Tests failed/i,/command not found/i,/Permission denied/i,/No such file or directory/i]},hi={IDLE_TIMEOUT_MS:5e3,DEBOUNCE_MS:500,BUFFER_SIZE:16e3,WORKING_TIMEOUT_MS:3e4,RESOLVE_GRACE_MS:1500,PROMPT_REFRESH_MS:450},ra=class r{states=new Map;onStatusChange;constructor(e){this.onStatusChange=e}startTracking(e){if(this.states.has(e))return;let t={status:"idle",lastUpdate:Date.now(),lastOutput:Date.now(),outputBuffer:"",pendingUpdate:null,pendingStatus:null,pendingPrompt:null,emittedPromptKey:null,lastSeenPromptKey:null,promptRefreshTimer:null,resolveGraceUntil:0,workingTimeout:null};this.states.set(e,t),this.emitStatus(e,"idle")}stopTracking(e){let t=this.states.get(e);t&&(t.pendingUpdate&&clearTimeout(t.pendingUpdate),t.workingTimeout&&clearTimeout(t.workingTimeout),t.promptRefreshTimer&&clearTimeout(t.promptRefreshTimer)),this.states.delete(e)}processOutput(e,t){let i=this.states.get(e);if(!i)return;i.lastOutput=Date.now(),i.outputBuffer+=t,i.outputBuffer.length>hi.BUFFER_SIZE&&(i.outputBuffer=i.outputBuffer.slice(-hi.BUFFER_SIZE));let n=Date.now()<i.resolveGraceUntil,s=!1;if(!n){let a=this.detectPrompt(i.outputBuffer);if(a&&a.type!=="free-input"&&this.isPromptActive(i.outputBuffer)&&(s=!0,i.pendingPrompt=a,i.status==="waiting")){let c=this.promptKey(a);c!==i.lastSeenPromptKey&&(i.lastSeenPromptKey=c,this.schedulePromptRefresh(e))}}if(s)this.scheduleStatusUpdate(e,"waiting");else if(i.status==="waiting"&&!n){let a=this.analyzeOutput(i.outputBuffer);(a==="completed"||a==="error")&&this.scheduleStatusUpdate(e,a)}else{let a=this.analyzeOutput(i.outputBuffer);a&&this.scheduleStatusUpdate(e,a)}this.resetWorkingTimeout(e,i)}isPromptActive(e){let i=this.normalizeBuffer(this.stripAnsi(e)).split(`
|
|
5
|
+
`),s=[],a=0,c=0,u=Math.max(i.length,n.length);for(let p=0;p<u;p++){let m=i[p],_=n[p];m===_?m!==void 0&&s.push({type:"context",content:m,oldLineNumber:p+1,newLineNumber:p+1}):(m!==void 0&&(s.push({type:"remove",content:m,oldLineNumber:p+1,newLineNumber:null}),c++),_!==void 0&&(s.push({type:"add",content:_,oldLineNumber:null,newLineNumber:p+1}),a++))}let d;return r===""?d=Kr.CREATE:e===""?d=Kr.DELETE:d=Kr.MODIFY,{path:t,changeType:d,hunks:[{oldStart:1,oldLines:i.length,newStart:1,newLines:n.length,lines:s}],additions:a,deletions:c,isBinary:!1}}var hu;(function(r){r.FILE="file",r.DIRECTORY="directory"})(hu||(kt.FileEntryType=hu={}))});var pu=M(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.createSimpleDiff=N.parseUnifiedDiff=N.getLanguageFromPath=N.FileEntryType=N.DiffBase=N.FileViewType=N.FileChangeType=N.isRetryableError=N.createError=N.ERROR_MESSAGES=N.ErrorCode=N.isTransferComplete=N.getMissingChunks=N.calculateTotalChunks=N.TransferDirection=N.TransferStatus=N.CHUNK_TTL_SECONDS=N.TRANSFER_TTL_SECONDS=N.MAX_RETRIES=N.ACK_TIMEOUT_MS=N.WINDOW_SIZE=N.DEFAULT_MAX_FILE_SIZE=N.CHUNK_SIZE=N.getPushNotificationMessage=N.shouldTriggerPushNotification=N.deriveStatusFromEvent=N.TerminalEventType=N.createMessage=N.requiresBuffer=N.requiresAck=N.DEFAULT_RELIABILITY=N.RELIABILITY_NAMES=N.Reliability=N.comparePriority=N.DEFAULT_PRIORITY=N.PRIORITY_NAMES=N.Priority=N.negotiateCapabilities=N.hasCapability=N.SERVER_CAPABILITIES=N.DEFAULT_CLIENT_CAPABILITIES=N.Capability=N.compareVersions=N.isCompatibleVersion=N.MIN_CLIENT_VERSION=N.PROTOCOL_VERSION_MINOR=N.PROTOCOL_VERSION_MAJOR=N.PROTOCOL_VERSION=void 0;var Mi=eu();Object.defineProperty(N,"PROTOCOL_VERSION",{enumerable:!0,get:function(){return Mi.PROTOCOL_VERSION}});Object.defineProperty(N,"PROTOCOL_VERSION_MAJOR",{enumerable:!0,get:function(){return Mi.PROTOCOL_VERSION_MAJOR}});Object.defineProperty(N,"PROTOCOL_VERSION_MINOR",{enumerable:!0,get:function(){return Mi.PROTOCOL_VERSION_MINOR}});Object.defineProperty(N,"MIN_CLIENT_VERSION",{enumerable:!0,get:function(){return Mi.MIN_CLIENT_VERSION}});Object.defineProperty(N,"isCompatibleVersion",{enumerable:!0,get:function(){return Mi.isCompatibleVersion}});Object.defineProperty(N,"compareVersions",{enumerable:!0,get:function(){return Mi.compareVersions}});var vn=tu();Object.defineProperty(N,"Capability",{enumerable:!0,get:function(){return vn.Capability}});Object.defineProperty(N,"DEFAULT_CLIENT_CAPABILITIES",{enumerable:!0,get:function(){return vn.DEFAULT_CLIENT_CAPABILITIES}});Object.defineProperty(N,"SERVER_CAPABILITIES",{enumerable:!0,get:function(){return vn.SERVER_CAPABILITIES}});Object.defineProperty(N,"hasCapability",{enumerable:!0,get:function(){return vn.hasCapability}});Object.defineProperty(N,"negotiateCapabilities",{enumerable:!0,get:function(){return vn.negotiateCapabilities}});var bs=ru();Object.defineProperty(N,"Priority",{enumerable:!0,get:function(){return bs.Priority}});Object.defineProperty(N,"PRIORITY_NAMES",{enumerable:!0,get:function(){return bs.PRIORITY_NAMES}});Object.defineProperty(N,"DEFAULT_PRIORITY",{enumerable:!0,get:function(){return bs.DEFAULT_PRIORITY}});Object.defineProperty(N,"comparePriority",{enumerable:!0,get:function(){return bs.comparePriority}});var wn=iu();Object.defineProperty(N,"Reliability",{enumerable:!0,get:function(){return wn.Reliability}});Object.defineProperty(N,"RELIABILITY_NAMES",{enumerable:!0,get:function(){return wn.RELIABILITY_NAMES}});Object.defineProperty(N,"DEFAULT_RELIABILITY",{enumerable:!0,get:function(){return wn.DEFAULT_RELIABILITY}});Object.defineProperty(N,"requiresAck",{enumerable:!0,get:function(){return wn.requiresAck}});Object.defineProperty(N,"requiresBuffer",{enumerable:!0,get:function(){return wn.requiresBuffer}});var Cg=nu();Object.defineProperty(N,"createMessage",{enumerable:!0,get:function(){return Cg.createMessage}});var Es=su();Object.defineProperty(N,"TerminalEventType",{enumerable:!0,get:function(){return Es.TerminalEventType}});Object.defineProperty(N,"deriveStatusFromEvent",{enumerable:!0,get:function(){return Es.deriveStatusFromEvent}});Object.defineProperty(N,"shouldTriggerPushNotification",{enumerable:!0,get:function(){return Es.shouldTriggerPushNotification}});Object.defineProperty(N,"getPushNotificationMessage",{enumerable:!0,get:function(){return Es.getPushNotificationMessage}});var Lt=cu();Object.defineProperty(N,"CHUNK_SIZE",{enumerable:!0,get:function(){return Lt.CHUNK_SIZE}});Object.defineProperty(N,"DEFAULT_MAX_FILE_SIZE",{enumerable:!0,get:function(){return Lt.DEFAULT_MAX_FILE_SIZE}});Object.defineProperty(N,"WINDOW_SIZE",{enumerable:!0,get:function(){return Lt.WINDOW_SIZE}});Object.defineProperty(N,"ACK_TIMEOUT_MS",{enumerable:!0,get:function(){return Lt.ACK_TIMEOUT_MS}});Object.defineProperty(N,"MAX_RETRIES",{enumerable:!0,get:function(){return Lt.MAX_RETRIES}});Object.defineProperty(N,"TRANSFER_TTL_SECONDS",{enumerable:!0,get:function(){return Lt.TRANSFER_TTL_SECONDS}});Object.defineProperty(N,"CHUNK_TTL_SECONDS",{enumerable:!0,get:function(){return Lt.CHUNK_TTL_SECONDS}});Object.defineProperty(N,"TransferStatus",{enumerable:!0,get:function(){return Lt.TransferStatus}});Object.defineProperty(N,"TransferDirection",{enumerable:!0,get:function(){return Lt.TransferDirection}});Object.defineProperty(N,"calculateTotalChunks",{enumerable:!0,get:function(){return Lt.calculateTotalChunks}});Object.defineProperty(N,"getMissingChunks",{enumerable:!0,get:function(){return Lt.getMissingChunks}});Object.defineProperty(N,"isTransferComplete",{enumerable:!0,get:function(){return Lt.isTransferComplete}});var vs=fu();Object.defineProperty(N,"ErrorCode",{enumerable:!0,get:function(){return vs.ErrorCode}});Object.defineProperty(N,"ERROR_MESSAGES",{enumerable:!0,get:function(){return vs.ERROR_MESSAGES}});Object.defineProperty(N,"createError",{enumerable:!0,get:function(){return vs.createError}});Object.defineProperty(N,"isRetryableError",{enumerable:!0,get:function(){return vs.isRetryableError}});var ui=du();Object.defineProperty(N,"FileChangeType",{enumerable:!0,get:function(){return ui.FileChangeType}});Object.defineProperty(N,"FileViewType",{enumerable:!0,get:function(){return ui.FileViewType}});Object.defineProperty(N,"DiffBase",{enumerable:!0,get:function(){return ui.DiffBase}});Object.defineProperty(N,"FileEntryType",{enumerable:!0,get:function(){return ui.FileEntryType}});Object.defineProperty(N,"getLanguageFromPath",{enumerable:!0,get:function(){return ui.getLanguageFromPath}});Object.defineProperty(N,"parseUnifiedDiff",{enumerable:!0,get:function(){return ui.parseUnifiedDiff}});Object.defineProperty(N,"createSimpleDiff",{enumerable:!0,get:function(){return ui.createSimpleDiff}})});var xr=M(nr=>{"use strict";var kg=nr&&nr.__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]})),ws=nr&&nr.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&kg(e,r,t)};Object.defineProperty(nr,"__esModule",{value:!0});ws(Vf(),nr);ws(zf(),nr);ws(Qf(),nr);ws(pu(),nr)});var Qo=M(He=>{"use strict";var Og=He&&He.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(He,"__esModule",{value:!0});He.FP_LABEL=He.KX_ACK_LABEL=He.KX_SIGN_LABEL=void 0;He.concatBytes=Sn;He.generateIdentityKeyPair=Pg;He.identityPublicFromSecret=Rg;He.signSessionKey=Ag;He.verifySessionKey=Ig;He.buildKxCanonical=Lg;He.buildKxAckCanonical=Ng;He.fingerprintIdentityKey=Mg;He.fingerprintShortHex=Fg;var sr=Og(_n()),Ot=bn();He.KX_SIGN_LABEL="termiq-kx-v1";He.KX_ACK_LABEL="termiq-kxack-v1";He.FP_LABEL="termiq-fp-v1";function Sn(...r){let e=0;for(let n of r)e+=n.length;let t=new Uint8Array(e),i=0;for(let n of r)t.set(n,i),i+=n.length;return t}function Pg(){let r=sr.default.sign.keyPair();return{identityPublicKey:(0,Ot.encodeBase64)(r.publicKey),identitySecretKey:(0,Ot.encodeBase64)(r.secretKey)}}function Rg(r){let e=(0,Ot.decodeBase64)(r);if(e.length!==sr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");let t=sr.default.sign.keyPair.fromSecretKey(e);return(0,Ot.encodeBase64)(t.publicKey)}function Ag(r,e){let t=(0,Ot.decodeBase64)(e);if(t.length!==sr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");return(0,Ot.encodeBase64)(sr.default.sign.detached(r,t))}function Ig(r,e,t){try{let i=(0,Ot.decodeBase64)(e),n=(0,Ot.decodeBase64)(t);return n.length!==sr.default.sign.publicKeyLength||i.length!==sr.default.sign.signatureLength?!1:sr.default.sign.detached.verify(r,i,n)}catch{return!1}}var li=new Uint8Array([0]);function Lg(r){let e=new TextEncoder,t=e.encode(He.KX_SIGN_LABEL),i=e.encode(r.agentId),n=e.encode(String(r.keyVersion)),s=(0,Ot.decodeBase64)(r.boxPublicKey);return Sn(t,li,i,li,n,li,s)}function Ng(r){let e=new TextEncoder;return Sn(e.encode(He.KX_ACK_LABEL),li,e.encode(r.agentId),li,e.encode(String(r.keyVersion)),li,(0,Ot.decodeBase64)(r.boxPublicKey),li,(0,Ot.decodeBase64)(r.boundClientKey))}function Mg(r){let e=(0,Ot.decodeBase64)(r),t=Sn(new TextEncoder().encode(He.FP_LABEL),e),i=sr.default.hash(t),n=[];for(let s=0;s<12;s++){let a=s*5,u=(((i[a]<<24>>>0)+(i[a+1]<<16)+(i[a+2]<<8)+i[a+3]^i[a+4])>>>0)%1e5;n.push(String(u).padStart(5,"0"))}return n.join(" ")}function Fg(r){let e=(0,Ot.decodeBase64)(r),t=Sn(new TextEncoder().encode(He.FP_LABEL),e),i=sr.default.hash(t).slice(0,8);return Array.from(i).map(n=>n.toString(16).padStart(2,"0")).join(":").toUpperCase()}});var mu=M(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.CryptoService=void 0;var et=xr(),qr=Qo(),Dg=3600*1e3,gu=10,ea=class{storage;logger;sessions=new Map;agentSessions=new Map;metaSessions=new Map;keyPair=null;identityKeyPair=null;publicKeyKey;secretKeyKey;keyVersionKey;identityPublicKeyKey;identitySecretKeyKey;constructor(e,t,i,n){this.storage=e,this.logger=t;let s=`termiq.${i}.${n}`;this.publicKeyKey=`${s}.crypto.publicKey`,this.secretKeyKey=`${s}.crypto.secretKey`,this.keyVersionKey=`${s}.crypto.keyVersion`,this.identityPublicKeyKey=`${s}.crypto.identityPublicKey`,this.identitySecretKeyKey=`${s}.crypto.identitySecretKey`,this.logger.info("CryptoService namespace",i,n)}async initialize(){let e=await this.storage.get(this.publicKeyKey),t=await this.storage.get(this.secretKeyKey);e&&t?(this.keyPair={publicKey:e,secretKey:t},this.logger.info("Loaded existing box key pair")):await this.generateBoxKeyPair(),await this.ensureIdentityKeyPair()}async generateBoxKeyPair(){this.logger.info("Generating new box key pair"),this.keyPair=(0,et.generateKeyPair)(),await this.storage.set(this.publicKeyKey,this.keyPair.publicKey),await this.storage.set(this.secretKeyKey,this.keyPair.secretKey);let e=await this.getKeyVersion();return await this.storage.set(this.keyVersionKey,String(e+1)),this.logger.info("Box key pair generated and stored"),this.keyPair}async generateIdentityKeyPair(){return this.generateBoxKeyPair()}async ensureIdentityKeyPair(){if(this.identityKeyPair)return this.identityKeyPair;let e=await this.storage.get(this.identitySecretKeyKey),t=await this.storage.get(this.identityPublicKeyKey);return e?(t||(t=(0,qr.identityPublicFromSecret)(e),await this.storage.set(this.identityPublicKeyKey,t)),this.identityKeyPair={identityPublicKey:t,identitySecretKey:e},this.logger.info("Loaded existing identity (Ed25519) key pair"),this.identityKeyPair):(this.logger.info("Generating new identity (Ed25519) key pair"),this.identityKeyPair=(0,qr.generateIdentityKeyPair)(),await this.storage.set(this.identityPublicKeyKey,this.identityKeyPair.identityPublicKey),await this.storage.set(this.identitySecretKeyKey,this.identityKeyPair.identitySecretKey),this.logger.info("Identity (Ed25519) key pair generated and stored"),this.identityKeyPair)}async getIdentityPublicKey(){return(await this.ensureIdentityKeyPair()).identityPublicKey}async getPublicKey(){return this.keyPair?this.keyPair.publicKey:await this.storage.get(this.publicKeyKey)||null}async getKeyVersion(){let e=await this.storage.get(this.keyVersionKey);return e?parseInt(e,10):1}async getSignedAgentKey(e){if(!this.keyPair&&(await this.initialize(),!this.keyPair))return this.logger.error("No box key pair available for signing"),null;let t=await this.ensureIdentityKeyPair(),i=await this.getKeyVersion(),n=this.keyPair.publicKey,s=(0,qr.buildKxCanonical)({agentId:e,keyVersion:i,boxPublicKey:n}),a=(0,qr.signSessionKey)(s,t.identitySecretKey);return{boxPublicKey:n,identityPublicKey:t.identityPublicKey,keyVersion:i,signature:a,sigVersion:1}}async signKeyExchangeAck(e,t){if(!this.keyPair&&(await this.initialize(),!this.keyPair))return this.logger.error("No box key pair available for ACK signing"),null;let i=await this.ensureIdentityKeyPair(),n=await this.getKeyVersion(),s=(0,qr.buildKxAckCanonical)({agentId:e,keyVersion:n,boxPublicKey:this.keyPair.publicKey,boundClientKey:t});return(0,qr.signSessionKey)(s,i.identitySecretKey)}async getSafetyNumber(){let e=await this.ensureIdentityKeyPair();return(0,qr.fingerprintIdentityKey)(e.identityPublicKey)}async getShortFingerprint(){let e=await this.ensureIdentityKeyPair();return(0,qr.fingerprintShortHex)(e.identityPublicKey)}async handleKeyExchange(e,t,i){if(!this.keyPair&&(this.logger.warn("Key pair missing, attempting re-initialization"),await this.initialize(),!this.keyPair))return this.logger.error("No identity key pair available after re-initialization"),!1;this.logger.info("Starting key exchange",e,i);try{let n=this.sessions.get(e);n||(n=new Map,this.sessions.set(e,n));let s=(0,et.deriveSharedSecret)(t,this.keyPair.secretKey),a={terminalId:e,clientPublicKey:t,sharedSecret:s,createdAt:Date.now(),sessionId:i};return n.set(i,a),this.logger.info("Key exchange completed",e,i,"total:",n.size),!0}catch(n){return this.logger.error("Key exchange failed",n),!1}}encryptOutput(e,t){let i=this.sessions.get(e);if(!i||i.size===0)return null;try{if(i.size===1){let s=i.values().next().value;return s?(0,et.encrypt)(t,s.sharedSecret,s.sessionId):null}let n=[];for(let s of i.values()){let a=(0,et.encrypt)(t,s.sharedSecret,s.sessionId);n.push({sid:a.sid,n:a.n,c:a.c})}return{v:2,recipients:n}}catch(n){return this.logger.error("Encryption failed",n),null}}decryptInput(e,t){let i=this.sessions.get(e);if(!i)return this.logger.error("No sessions for terminal",e),null;let n=i.get(t.sid);if(!n)return this.logger.error("No session for sessionId",t.sid),null;try{return(0,et.decrypt)(t,n.sharedSecret)}catch(s){return this.logger.error("Decryption failed",s),null}}encryptFileChunk(e,t){let i=this.sessions.get(e);if(!i||i.size===0)return null;let n=null;for(let s of i.values())(!n||s.createdAt>n.createdAt)&&(n=s);if(!n)return null;try{return(0,et.encryptBinary)(t,n.sharedSecret,n.sessionId)}catch(s){return this.logger.error("File chunk encryption failed",s),null}}decryptFileChunk(e,t){let i=this.sessions.get(e)?.get(t.sid);if(!i)return this.logger.error("No session for file chunk",e,t.sid),null;try{return(0,et.decryptBinary)(t,i.sharedSecret)}catch(n){return this.logger.error("File chunk decryption failed",n),null}}hasSession(e){let t=this.sessions.get(e);return t!==void 0&&t.size>0}removeSession(e,t){let i=this.sessions.get(e);if(i)if(t){let n=i.get(t);n&&((0,et.clearKey)(n.sharedSecret),i.delete(t),this.logger.info("Session removed",e,t)),i.size===0&&this.sessions.delete(e)}else{for(let n of i.values())(0,et.clearKey)(n.sharedSecret);this.sessions.delete(e),this.logger.debug("All sessions removed for terminal",e)}}clearAllSessions(){for(let e of this.sessions.values())for(let t of e.values())(0,et.clearKey)(t.sharedSecret);this.sessions.clear(),this.logger.debug("All sessions cleared")}cleanupStaleSessions(e){let t=this.sessions.get(e);if(!t||t.size===0)return;let i=Date.now(),n=[];for(let[s,a]of t)i-a.createdAt>Dg&&n.push(s);for(let s of n){let a=t.get(s);a&&((0,et.clearKey)(a.sharedSecret),t.delete(s),this.logger.info("Session expired (TTL)",e,s,`age:${Math.round((i-a.createdAt)/1e3)}s`))}if(t.size>gu){let a=Array.from(t.entries()).sort((c,u)=>c[1].createdAt-u[1].createdAt).slice(0,t.size-gu);for(let[,c]of a)(0,et.clearKey)(c.sharedSecret),t.delete(c.sessionId)}t.size===0&&this.sessions.delete(e)}cleanupAllStaleSessions(){for(let e of this.sessions.keys())this.cleanupStaleSessions(e)}getSessionInfo(){let e=[];for(let[t,i]of this.sessions.entries())for(let n of i.values())e.push({terminalId:t,createdAt:n.createdAt,sessionId:n.sessionId});return e}async handleAgentKeyExchange(e,t){if(!this.keyPair&&(this.logger.warn("Key pair missing for agent key exchange"),await this.initialize(),!this.keyPair))return this.logger.error("No identity key pair available for agent key exchange"),!1;try{let i=this.agentSessions.get(t);i&&(this.logger.info("Rekeying existing agent session",t),(0,et.clearKey)(i.sharedSecret));let n=(0,et.deriveSharedSecret)(e,this.keyPair.secretKey),s={sessionId:t,clientPublicKey:e,sharedSecret:n,createdAt:Date.now()};return this.agentSessions.set(t,s),this.logger.info("Agent key exchange completed",t,"total:",this.agentSessions.size),!0}catch(i){return this.logger.error("Agent key exchange failed",i),!1}}removeAgentSession(e){let t=this.agentSessions.get(e);t&&((0,et.clearKey)(t.sharedSecret),this.agentSessions.delete(e),this.logger.info("Agent session removed",e))}hasAgentSessions(){return this.agentSessions.size>0}async handleMetaKeyExchange(e){if(!this.keyPair&&(await this.initialize(),!this.keyPair))return{ok:!1,isNew:!1};try{let t=!this.metaSessions.has(e),i=(0,et.deriveSharedSecret)(e,this.keyPair.secretKey),n=(0,et.deriveMetaSid)(this.keyPair.publicKey,e);return this.metaSessions.set(e,{clientIdentityPub:e,sharedSecret:i,sidMeta:n}),this.logger.info("Meta key exchange completed",n,"isNew:",t,"total:",this.metaSessions.size),{ok:!0,isNew:t}}catch(t){return this.logger.error("Meta key exchange failed",t),{ok:!1,isNew:!1}}}hasMetaSession(){return this.metaSessions.size>0}encryptWorkspaceInfo(e){let t=this.encryptForMeta(JSON.stringify(e));return t?{encrypted:t}:null}encryptTerminalInfo(e){let t=this.encryptForMeta(JSON.stringify(e));return t?{encrypted:t}:null}encryptPromptInfo(e){let t=this.encryptForMeta(JSON.stringify(e));return t?{encrypted:t}:null}encryptForMeta(e){if(this.metaSessions.size===0)return null;try{if(this.metaSessions.size===1){let i=this.metaSessions.values().next().value;return i?(0,et.encrypt)(e,i.sharedSecret,i.sidMeta):null}let t=[];for(let i of this.metaSessions.values()){let n=(0,et.encrypt)(e,i.sharedSecret,i.sidMeta);t.push({sid:n.sid,n:n.n,c:n.c})}return{v:2,recipients:t}}catch(t){return this.logger.error("Meta encryption failed",t),null}}clearAllAgentSessions(){for(let e of this.agentSessions.values())(0,et.clearKey)(e.sharedSecret);this.agentSessions.clear(),this.logger.debug("All agent sessions cleared")}async deleteKeys(){await this.storage.delete(this.publicKeyKey),await this.storage.delete(this.secretKeyKey),await this.storage.delete(this.keyVersionKey),await this.storage.delete(this.identityPublicKeyKey),await this.storage.delete(this.identitySecretKeyKey),this.keyPair=null,this.identityKeyPair=null,this.clearAllSessions(),this.clearAllAgentSessions(),this.logger.info("All crypto keys deleted")}};Ss.CryptoService=ea});var yu=M(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});xs.AuthService=void 0;var xn=us(),ta=class{storage;cryptoService;machineId;config;logger;notification;browser;pollingAbortController=null;tokenKey;refreshTokenKey;agentIdKey;constructor(e,t,i,n,s,a,c,u,d){this.storage=e,this.cryptoService=t,this.machineId=i,this.config=n,this.logger=s,this.notification=a,this.browser=c;let p=`termiq.${u}.${d}`;this.tokenKey=`${p}.accessToken`,this.refreshTokenKey=`${p}.refreshToken`,this.agentIdKey=`${p}.agentId`,this.logger.info("AuthService namespace",u,d)}cancelPolling(){this.pollingAbortController&&(this.logger.info("Cancelling active polling"),this.pollingAbortController.abort(),this.pollingAbortController=null)}async startDeviceCodeFlow(){this.cancelPolling();let e=(0,xn.getApiUrl)(this.config),t=await this.machineId.getMachineId(),i=this.machineId.getMachineName(),n=await this.cryptoService.getPublicKey();n||(await this.cryptoService.generateIdentityKeyPair(),n=await this.cryptoService.getPublicKey()),this.logger.info("Starting device code flow",t,i);let s=await fetch(`${e}/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machineId:t,machineName:i,publicKey:n})});if(!s.ok){let a=await s.text();throw new Error(`Failed to get device code: ${a}`)}return s.json()}async pollForToken(e){this.cancelPolling();let t=(0,xn.getApiUrl)(this.config),i=5e3,n=60;this.pollingAbortController=new AbortController;let s=this.pollingAbortController.signal;this.logger.info("Starting token polling");for(let a=0;a<n;a++){if(s.aborted)return this.logger.info("Polling was cancelled"),null;if(await this.sleep(i),s.aborted)return this.logger.info("Polling was cancelled"),null;try{let c=await fetch(`${t}/auth/device/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:e}),signal:s});if(!c.ok){if(c.status===403)try{let d=await c.json();if(d.error==="AGENT_LIMIT_EXCEEDED")return this.logger.warn("Agent limit exceeded",String(d.current),"/",String(d.max)),this.notification.warn(`Agent limit reached (${d.current}/${d.max}). Upgrade your plan to add more devices.`),null}catch{}this.logger.warn("Poll request failed",String(c.status));continue}let u=await c.json();if(u.status==="success"&&u.accessToken)return this.logger.info("Token received successfully"),this.pollingAbortController=null,await this.saveTokens(u),u;if(u.status==="expired")return this.logger.warn("Device code expired"),null;if(u.status==="limit_exceeded")return this.logger.warn("Agent limit exceeded",String(u.current),"/",String(u.max)),this.notification.warn(`Agent limit reached (${u.current}/${u.max}). Remove an old agent or upgrade your plan.`),null;this.logger.debug("Token pending, continuing poll",String(a))}catch(c){if(s.aborted)return this.logger.info("Polling was cancelled"),null;let u=c instanceof Error?c.message:String(c);this.logger.warn(`Poll error: ${u}`)}}return this.logger.warn("Polling timed out"),this.pollingAbortController=null,null}async loginWithApiKey(e){let t=(0,xn.getApiUrl)(this.config),i=await this.machineId.getMachineId(),n=this.machineId.getMachineName(),s=await this.cryptoService.getPublicKey();s||(await this.cryptoService.generateIdentityKeyPair(),s=await this.cryptoService.getPublicKey()),this.logger.info("Logging in with API key");try{let a=await fetch(`${t}/auth/api-key/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e,machineId:i,machineName:n,publicKey:s})});if(!a.ok){let u=await a.text();return this.logger.error("API key login failed",u),!1}let c=await a.json();return c.accessToken?(await this.saveTokens(c),this.logger.info("API key login successful"),!0):!1}catch(a){return this.logger.error("API key login error",a),!1}}async hasValidToken(){let e=await this.storage.get(this.tokenKey);if(!e)return!1;try{let i=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()).exp*1e3;return Date.now()<i}catch{return!1}}async getAccessToken(){return await this.storage.get(this.tokenKey)||null}async getAgentId(){return await this.storage.get(this.agentIdKey)||null}async refreshAccessToken(){let e=await this.storage.get(this.refreshTokenKey);if(!e)return this.logger.debug("No refresh token available"),null;let t=(0,xn.getApiUrl)(this.config);try{this.logger.info("Refreshing access token");let i=await fetch(`${t}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!i.ok)return this.logger.warn("Token refresh failed",String(i.status)),i.status===401&&await this.storage.delete(this.refreshTokenKey),null;let n=await i.json();return await this.storage.set(this.tokenKey,n.accessToken),await this.storage.set(this.refreshTokenKey,n.refreshToken),this.logger.info("Access token refreshed successfully"),n.accessToken}catch(i){return this.logger.warn("Token refresh error",i),null}}async logout(){this.logger.info("Logging out"),this.cancelPolling(),await this.storage.delete(this.tokenKey),await this.storage.delete(this.refreshTokenKey),await this.storage.delete(this.agentIdKey),await this.cryptoService.deleteKeys()}async saveTokens(e){e.accessToken&&await this.storage.set(this.tokenKey,e.accessToken),e.refreshToken&&await this.storage.set(this.refreshTokenKey,e.refreshToken),e.agentId&&await this.storage.set(this.agentIdKey,e.agentId)}async getLimits(){let e=await this.getAccessToken();if(!e)return this.logger.warn("Cannot fetch limits: no access token"),null;let t=(0,xn.getApiUrl)(this.config);try{let i=await fetch(`${t}/users/me/limits`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});return i.ok?await i.json():(this.logger.error("Failed to fetch limits",String(i.status)),null)}catch(i){let n=i instanceof Error?i.message:String(i);return this.logger.error(`Error fetching limits: ${n}`),null}}async openUrl(e){await this.browser.openUrl(e)}async canCreateTerminal(){let e=await this.getLimits();return e?e.terminals.unlimited?{allowed:!0,limits:e}:e.terminals.current>=e.terminals.max?{allowed:!1,reason:`Terminal limit reached (${e.terminals.current}/${e.terminals.max}). Upgrade your plan to create more terminals.`,limits:e}:{allowed:!0,limits:e}:{allowed:!0}}sleep(e){return new Promise(t=>setTimeout(t,e))}};xs.AuthService=ta});var _u=M(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.StatusDetector=void 0;Tn.isAnswerKeystroke=Bg;var Ts={working:[/✶/,/⠋|⠙|⠹|⠸|⠼|⠴|⠦|⠧|⠇|⠏/],idle:[/[❯$#>]\s*$/,/^\s*\d+\s*[❯$#>]\s*$/,/\(base\)\s*[❯$#>]\s*$/,/\)\s*[❯$#>]\s*$/],waiting:[/\[y\/n\]\s*$/i,/\[y\/N\]\s*$/i,/\(y\/n\)\s*$/i,/\(yes\/no\)\s*$/i,/press enter to continue\s*$/i,/press any key\s*$/i,/\[enter\]\s*$/i],completed:[/✓\s*(Done|Complete|Success|Finished)/i,/\[done\]/i,/\[success\]/i,/completed successfully/i,/Build succeeded/i,/All tests passed/i],error:[/✕\s*(Error|Failed|Failure)/i,/\[error\]/i,/\[failed\]/i,/Error:/i,/Exception:/i,/FATAL:/i,/Build failed/i,/Tests failed/i,/command not found/i,/Permission denied/i,/No such file or directory/i]},hi={IDLE_TIMEOUT_MS:5e3,DEBOUNCE_MS:500,BUFFER_SIZE:16e3,WORKING_TIMEOUT_MS:3e4,RESOLVE_GRACE_MS:1500,PROMPT_REFRESH_MS:450},ra=class r{states=new Map;onStatusChange;constructor(e){this.onStatusChange=e}startTracking(e){if(this.states.has(e))return;let t={status:"idle",lastUpdate:Date.now(),lastOutput:Date.now(),outputBuffer:"",pendingUpdate:null,pendingStatus:null,pendingPrompt:null,emittedPromptKey:null,lastSeenPromptKey:null,promptRefreshTimer:null,resolveGraceUntil:0,workingTimeout:null};this.states.set(e,t),this.emitStatus(e,"idle")}stopTracking(e){let t=this.states.get(e);t&&(t.pendingUpdate&&clearTimeout(t.pendingUpdate),t.workingTimeout&&clearTimeout(t.workingTimeout),t.promptRefreshTimer&&clearTimeout(t.promptRefreshTimer)),this.states.delete(e)}processOutput(e,t){let i=this.states.get(e);if(!i)return;i.lastOutput=Date.now(),i.outputBuffer+=t,i.outputBuffer.length>hi.BUFFER_SIZE&&(i.outputBuffer=i.outputBuffer.slice(-hi.BUFFER_SIZE));let n=Date.now()<i.resolveGraceUntil,s=!1;if(!n){let a=this.detectPrompt(i.outputBuffer);if(a&&a.type!=="free-input"&&this.isPromptActive(i.outputBuffer)&&(s=!0,i.pendingPrompt=a,i.status==="waiting")){let c=this.promptKey(a);c!==i.lastSeenPromptKey&&(i.lastSeenPromptKey=c,this.schedulePromptRefresh(e))}}if(s)this.scheduleStatusUpdate(e,"waiting");else if(i.status==="waiting"&&!n){let a=this.analyzeOutput(i.outputBuffer);(a==="completed"||a==="error")&&this.scheduleStatusUpdate(e,a)}else{let a=this.analyzeOutput(i.outputBuffer);a&&this.scheduleStatusUpdate(e,a)}this.resetWorkingTimeout(e,i)}isPromptActive(e){let i=this.normalizeBuffer(this.stripAnsi(e)).split(`
|
|
6
6
|
`).map(a=>a.trim()).filter(Boolean);if(i.length===0)return!1;let n=i[i.length-1],s=i.slice(-18).join(`
|
|
7
7
|
`);return/[❯›●]/.test(s)||/\[y\/n\]|\(y\/n\)|\[y\/N\]|\(yes\/no\)/i.test(n)||/esc to cancel|enter to confirm|press enter|press any key|\[enter\]|\(esc\)/i.test(s)}onCommandStart(e){let t=this.states.get(e);t&&(t.outputBuffer="",this.scheduleStatusUpdate(e,"working"),this.resetWorkingTimeout(e,t))}onCommandEnd(e,t){let i=this.states.get(e);if(!i)return;i.workingTimeout&&(clearTimeout(i.workingTimeout),i.workingTimeout=null);let n;if(t!==void 0&&t!==0)n="error";else{let s=this.analyzeOutput(i.outputBuffer);s==="waiting"?n="waiting":s==="error"?n="error":s==="completed"?n="completed":n="idle"}this.scheduleStatusUpdate(e,n),(n==="completed"||n==="error")&&setTimeout(()=>{let s=this.states.get(e);s&&(s.status==="completed"||s.status==="error")&&this.scheduleStatusUpdate(e,"idle")},hi.IDLE_TIMEOUT_MS)}analyzeOutput(e){let i=this.normalizeBuffer(this.stripAnsi(e)).split(`
|
|
8
8
|
`).slice(-10),n=i.join(`
|
|
9
9
|
`),s=(i[i.length-1]||"").trim();for(let a of Ts.waiting)if(a.test(s))return"waiting";for(let a of Ts.working)if(a.test(s))return"working";for(let a of Ts.completed)if(a.test(n))return"completed";for(let a of Ts.idle)if(a.test(s))return"idle";return null}detectPrompt(e){let n=this.normalizeBuffer(this.stripAnsi(e)).split(`
|
|
10
10
|
`).slice(-20),s=n.join(`
|
|
11
|
-
`),a=n[n.length-1]||"",c=this.extractNumberedChoices(e);if(c.length>=2)return{type:"numbered-choice",question:this.extractQuestion(s)||"Select an option:",choices:c};let
|
|
12
|
-
`),s=/^[\s│┃┊┋┆┇╎╏]*(?:[❯▶▸›●>*]\s*)?(?:(\d+)[.)]\s*|\[(\d+)\]\s*)(.+?)[\s│┃]*$/u,a=[],
|
|
11
|
+
`),a=n[n.length-1]||"",{choices:c,digitSelect:u}=this.extractNumberedChoices(e);if(c.length>=2)return{type:"numbered-choice",question:this.extractQuestion(s)||"Select an option:",choices:c,digitSelect:u};let d=[/\[Y\/n\]/i,/\[y\/N\]/i,/\(y\/n\)/i,/\(yes\/no\)/i];for(let _ of d)if(_.test(s))return{type:"yes-no",question:this.extractQuestion(s)||"Confirm?"};let p=[/Press Enter to continue/i,/Press Enter/i,/Hit Enter/i,/\[Enter\]/i,/press return/i];for(let _ of p)if(_.test(s))return{type:"enter",question:this.extractQuestion(s)||"Press Enter to continue"};let m=[/Press any key/i,/press a key/i];for(let _ of m)if(_.test(s))return{type:"any-key",question:this.extractQuestion(s)||"Press any key"};return(a.endsWith("?")||a.endsWith(":"))&&!a.startsWith("/")&&!a.includes("error")&&a.length<100?{type:"free-input",question:a}:null}extractNumberedChoices(e){let t=[],n=this.normalizeBuffer(this.stripAnsi(e)).split(`
|
|
12
|
+
`),s=/^[\s│┃┊┋┆┇╎╏]*(?:[❯▶▸›●>*]\s*)?(?:(\d+)[.)]\s*|\[(\d+)\]\s*)(.+?)[\s│┃]*$/u,a=100,c=12,u=2,d=/^[\s│┃┊┋┆┇╎╏]*([❯▶▸›●])\s*(?:\d+[.)]|\[\d+\])/u,p=[],m=-1,_=-1,v=!1,T="",x=[],H=-1,oe=!1,J="",k=j=>j.length*1e3+j.reduce((U,ne)=>U+ne.label.length,0),B=()=>{x.length>=1&&k(x)>=m&&(p=x.slice(),m=k(x),_=H,v=oe,T=J)};for(let j=0;j<n.length;j++){let U=n[j],ne=U.match(s);if(!ne)continue;let _e=ne[1]||ne[2],se=ne[3].replace(/\s+/g," ").trim();if(!_e||!se)continue;let ze=se.length>a?se.slice(0,a-1)+"\u2026":se,ve=parseInt(_e,10),be=U.match(d),he=be!==null;ve===x.length+1?(x.push({key:_e,label:ze}),H=j,oe=oe||he,be&&(J=be[1])):ve===1?(B(),x=[{key:_e,label:ze}],H=j,oe=he,J=be?be[1]:""):(B(),x=[],H=-1,oe=!1,J="")}if(B(),_>=0){let j=n.slice(_+1).filter(ne=>ne.trim().length>0),U=v?c:u;if(j.length>U)return{choices:t,digitSelect:"enter"}}return t.push(...p),{choices:t,digitSelect:T==="\u25CF"?"immediate":"enter"}}static MAX_QUESTION_LEN=160;clampQuestion(e){let t=e.replace(/\s+/g," ").trim(),i=r.MAX_QUESTION_LEN;return t.length<=i?t:t.slice(0,i-1).trimEnd()+"\u2026"}extractQuestion(e){let t=e.split(`
|
|
13
13
|
`).filter(i=>i.trim());for(let i=t.length-1;i>=Math.max(0,t.length-8);i--){let n=t[i].trim();if(!n||/^[\s│┃]*(?:[❯▶▸›●>*]\s*)?\d+[.)]\s/.test(n)||/^[\s│┃]*\[/.test(n))continue;let s=this.stripAnsi(n).replace(/^[\s│┃┊┋┆┇╎╏]+/u,"").replace(/[\s│┃┊┋┆┇╎╏]+$/u,"").replace(/\s+/g," ");if(s.endsWith("?")||s.endsWith(":"))return this.clampQuestion(s.replace(/\s*\[Y\/n\]\s*$/i,"").replace(/\s*\(y\/n\)\s*$/i,"").replace(/\s*\(yes\/no\)\s*$/i,""))}return null}stripAnsi(e){return e.replace(/\x1b\[[0-9]*[GC]/g," ").replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\x1b\][^\x07]*\x07/g,"").replace(/\x1b[()][AB012]/g,"").replace(/\x1b[=>]/g,"").replace(/\x1b[78DMEHc]/g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g,"")}normalizeBuffer(e){return e.replace(/\r\n/g,`
|
|
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)}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)}};Tn.StatusDetector=ra;function Bg(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
|
|
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=vu.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)Fi.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=Fi.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 be=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=vu.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=be(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 be(Se,We).on("error",st);e.handleError(A)};n=be(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;Fi.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=jg(process.argv[0],["-e",it]),gt;Fi.existsSync(Te););if(e.responseText=Fi.readFileSync(Ze,"utf8"),ze.stdin.end(),Fi.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 Cs=M(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.ERROR_PACKET=Wr.PACKET_TYPES_REVERSE=Wr.PACKET_TYPES=void 0;var or=Object.create(null);Wr.PACKET_TYPES=or;or.open="0";or.close="1";or.ping="2";or.pong="3";or.message="4";or.upgrade="5";or.noop="6";var wu=Object.create(null);Wr.PACKET_TYPES_REVERSE=wu;Object.keys(or).forEach(r=>{wu[or[r]]=r});var Ug={type:"error",data:"parser error"};Wr.ERROR_PACKET=Ug});var Su=M(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.encodePacket=void 0;Di.encodePacketToBinary=Wg;var Kg=Cs(),qg=({type:r,data:e},t,i)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?i(t?e:"b"+xu(e,!0).toString("base64")):i(Kg.PACKET_TYPES[r]+(e||""));Di.encodePacket=qg;var xu=(r,e)=>Buffer.isBuffer(r)||r instanceof Uint8Array&&!e?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength),na;function Wg(r,e){if(r.data instanceof ArrayBuffer||ArrayBuffer.isView(r.data))return e(xu(r.data,!1));(0,Di.encodePacket)(r,!0,t=>{na||(na=new TextEncoder),e(na.encode(t))})}});var Cu=M(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});Os.decodePacket=void 0;var ks=Cs(),Hg=(r,e)=>{if(typeof r!="string")return{type:"message",data:Tu(r,e)};let t=r.charAt(0);if(t==="b"){let i=Buffer.from(r.substring(1),"base64");return{type:"message",data:Tu(i,e)}}return ks.PACKET_TYPES_REVERSE[t]?r.length>1?{type:ks.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:ks.PACKET_TYPES_REVERSE[t]}:ks.ERROR_PACKET};Os.decodePacket=Hg;var Tu=(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 Bi=M(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.decodePayload=bt.decodePacket=bt.encodePayload=bt.encodePacket=bt.protocol=void 0;bt.createPacketEncoderStream=$g;bt.createPacketDecoderStream=Gg;var oa=Su();Object.defineProperty(bt,"encodePacket",{enumerable:!0,get:function(){return oa.encodePacket}});var aa=Cu();Object.defineProperty(bt,"decodePacket",{enumerable:!0,get:function(){return aa.decodePacket}});var ku=Cs(),Ou="",Vg=(r,e)=>{let t=r.length,i=new Array(t),n=0;r.forEach((s,a)=>{(0,oa.encodePacket)(s,!1,c=>{i[a]=c,++n===t&&e(i.join(Ou))})})};bt.encodePayload=Vg;var zg=(r,e)=>{let t=r.split(Ou),i=[];for(let n=0;n<t.length;n++){let s=(0,aa.decodePacket)(t[n],e);if(i.push(s),s.type==="error")break}return i};bt.decodePayload=zg;function $g(){return new TransformStream({transform(r,e){(0,oa.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 sa;function Ps(r){return r.reduce((e,t)=>e+t.length,0)}function Rs(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 Gg(r,e){sa||(sa=new TextDecoder);let t=[],i=0,n=-1,s=!1;return new TransformStream({transform(a,c){for(t.push(a);;){if(i===0){if(Ps(t)<1)break;let u=Rs(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(Ps(t)<2)break;let u=Rs(t,2);n=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),i=3}else if(i===2){if(Ps(t)<8)break;let u=Rs(t,8),d=new DataView(u.buffer,u.byteOffset,u.length),p=d.getUint32(0);if(p>Math.pow(2,21)-1){c.enqueue(ku.ERROR_PACKET);break}n=p*Math.pow(2,32)+d.getUint32(4),i=3}else{if(Ps(t)<n)break;let u=Rs(t,n);c.enqueue((0,aa.decodePacket)(s?u:sa.decode(u),e)),i=0}if(n===0||n>r){c.enqueue(ku.ERROR_PACKET);break}}}})}bt.protocol=4});var di=M(Pu=>{Pu.Emitter=yt;function yt(r){if(r)return Yg(r)}function Yg(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=Xg;Nt.parse=Ru;Nt.nextTick=process.nextTick;Nt.globalThisShim=global;Nt.defaultBinaryType="nodebuffer";function Xg(){return new As}function Ru(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 As=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let i=Ru(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=As});var gi=M(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.pick=Jg;ji.installTimerFunctions=em;ji.byteLength=rm;ji.randomString=nm;var Hr=pi();function Jg(r,...e){return e.reduce((t,i)=>(r.hasOwnProperty(i)&&(t[i]=r[i]),t),{})}var Zg=Hr.globalThisShim.setTimeout,Qg=Hr.globalThisShim.clearTimeout;function em(r,e){e.useNativeTimers?(r.setTimeoutFn=Zg.bind(Hr.globalThisShim),r.clearTimeoutFn=Qg.bind(Hr.globalThisShim)):(r.setTimeoutFn=Hr.globalThisShim.setTimeout.bind(Hr.globalThisShim),r.clearTimeoutFn=Hr.globalThisShim.clearTimeout.bind(Hr.globalThisShim))}var tm=1.33;function rm(r){return typeof r=="string"?im(r):Math.ceil((r.byteLength||r.size)*tm)}function im(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 nm(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}});var ca=M(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});Is.encode=sm;Is.decode=om;function sm(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function om(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 Iu=M((NE,Au)=>{var Ui=1e3,Ki=Ui*60,qi=Ki*60,mi=qi*24,am=mi*7,cm=mi*365.25;Au.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return fm(r);if(t==="number"&&isFinite(r))return e.long?lm(r):um(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function fm(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*cm;case"weeks":case"week":case"w":return t*am;case"days":case"day":case"d":return t*mi;case"hours":case"hour":case"hrs":case"hr":case"h":return t*qi;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ki;case"seconds":case"second":case"secs":case"sec":case"s":return t*Ui;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function um(r){var e=Math.abs(r);return e>=mi?Math.round(r/mi)+"d":e>=qi?Math.round(r/qi)+"h":e>=Ki?Math.round(r/Ki)+"m":e>=Ui?Math.round(r/Ui)+"s":r+"ms"}function lm(r){var e=Math.abs(r);return e>=mi?Ls(r,e,mi,"day"):e>=qi?Ls(r,e,qi,"hour"):e>=Ki?Ls(r,e,Ki,"minute"):e>=Ui?Ls(r,e,Ui,"second"):r+" ms"}function Ls(r,e,t,i){var n=e>=t*1.5;return Math.round(r/t)+" "+i+(n?"s":"")}});var fa=M((ME,Lu)=>{function hm(r){t.debug=t,t.default=t,t.coerce=u,t.disable=a,t.enable=n,t.enabled=c,t.humanize=Iu(),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}Lu.exports=hm});var Nu=M((Et,Ns)=>{Et.formatArgs=pm;Et.save=gm;Et.load=mm;Et.useColors=dm;Et.storage=ym();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 dm(){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 pm(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ns.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 gm(r){try{r?Et.storage.setItem("debug",r):Et.storage.removeItem("debug")}catch{}}function mm(){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 ym(){try{return localStorage}catch{}}Ns.exports=fa()(Et);var{formatters:_m}=Ns.exports;_m.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Fu=M((FE,Mu)=>{"use strict";Mu.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 ju=M((DE,Bu)=>{"use strict";var vm=require("os"),Du=require("tty"),Mt=Fu(),{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 ua(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function la(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=vm.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 bm(r){let e=la(r,r&&r.isTTY);return ua(e)}Bu.exports={supportsColor:bm,stdout:ua(la(!0,Du.isatty(1))),stderr:ua(la(!0,Du.isatty(2)))}});var Ku=M((at,Fs)=>{var Em=require("tty"),Ms=require("util");at.init=Om;at.log=Tm;at.formatArgs=xm;at.save=Cm;at.load=km;at.useColors=wm;at.destroy=Ms.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=ju();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 wm(){return"colors"in at.inspectOpts?!!at.inspectOpts.colors:Em.isatty(process.stderr.fd)}function xm(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(`
|
|
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)}getEmittedPromptKey(e){return this.states.get(e)?.emittedPromptKey??null}reEmitPrompt(e){let t=this.states.get(e);if(!t)return;let i=this.detectPrompt(t.outputBuffer),n=i&&i.type!=="free-input"?i:t.pendingPrompt||void 0;n&&(t.emittedPromptKey=this.promptKey(n),t.lastSeenPromptKey=t.emittedPromptKey,this.onStatusChange(e,"waiting",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)}};Tn.StatusDetector=ra;function Bg(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((Tv,Eu)=>{var Fi=require("fs"),bu=require("url"),jg=require("child_process").spawn;Eu.exports=ia;ia.XMLHttpRequest=ia;function ia(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,v=!1,T=!1,x={};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 H=function(k){return c||k&&p.indexOf(k.toLowerCase())===-1},oe=function(k){return k&&m.indexOf(k)===-1};this.open=function(k,B,te,j,U){if(this.abort(),v=!1,T=!1,!oe(k))throw new Error("SecurityError: Request method not allowed");a={method:k,url:B.toString(),async:typeof te!="boolean"?!0:te,user:j||null,password:U||null},J(this.OPENED)},this.setDisableHeaderCheck=function(k){c=k},this.setRequestHeader=function(k,B){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!H(k))return console.warn('Refused to set unsafe header "'+k+'"'),!1;if(_)throw new Error("INVALID_STATE_ERR: send flag is true");return d[k]=B,!0},this.getResponseHeader=function(k){return typeof k=="string"&&this.readyState>this.OPENED&&s.headers[k.toLowerCase()]&&!v?s.headers[k.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||v)return"";var k="";for(var B in s.headers)B!=="set-cookie"&&B!=="set-cookie2"&&(k+=B+": "+s.headers[B]+`\r
|
|
18
|
+
`);return k.substr(0,k.length-2)},this.getRequestHeader=function(k){return typeof k=="string"&&d[k]?d[k]:""},this.send=function(k){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,te=!1,j=bu.parse(a.url),U;switch(j.protocol){case"https:":B=!0;case"http:":U=j.hostname;break;case"file:":te=!0;break;case void 0:case"":U="localhost";break;default:throw new Error("Protocol not supported.")}if(te){if(a.method!=="GET")throw new Error("XMLHttpRequest: Only GET method is supported");if(a.async)Fi.readFile(unescape(j.pathname),function(A,R){A?e.handleError(A,A.errno||-1):(e.status=200,e.responseText=R.toString("utf8"),e.response=R,J(e.DONE))});else try{this.response=Fi.readFileSync(unescape(j.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,J(e.DONE)}catch(A){this.handleError(A,A.errno||-1)}return}var ne=j.port||(B?443:80),_e=j.pathname+(j.search?j.search:"");if(d.Host=U,B&&ne===443||ne===80||(d.Host+=":"+j.port),a.user){typeof a.password>"u"&&(a.password="");var se=new Buffer(a.user+":"+a.password);d.Authorization="Basic "+se.toString("base64")}if(a.method==="GET"||a.method==="HEAD")k=null;else if(k){d["Content-Length"]=Buffer.isBuffer(k)?k.length:Buffer.byteLength(k);var ze=Object.keys(d);ze.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 ve=r.agent||!1,be={host:U,port:ne,path:_e,method:a.method,headers:d,agent:ve};if(B&&(be.pfx=r.pfx,be.key=r.key,be.passphrase=r.passphrase,be.cert=r.cert,be.ca=r.ca,be.ciphers=r.ciphers,be.rejectUnauthorized=r.rejectUnauthorized!==!1),v=!1,a.async){var he=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 R=bu.parse(a.url);U=R.hostname;var Q={hostname:R.hostname,port:R.port,path:R.path,method:s.statusCode===303?"GET":a.method,headers:d};B&&(Q.pfx=r.pfx,Q.key=r.key,Q.passphrase=r.passphrase,Q.cert=r.cert,Q.ca=r.ca,Q.ciphers=r.ciphers,Q.rejectUnauthorized=r.rejectUnauthorized!==!1),n=he(Q,We).on("error",ot),n.end();return}J(e.HEADERS_RECEIVED),e.status=s.statusCode,s.on("data",function(Ne){if(Ne){var Je=Buffer.from(Ne);e.response=Buffer.concat([e.response,Je])}_&&J(e.LOADING)}),s.on("end",function(){_&&(_=!1,J(e.DONE),e.responseText=e.response.toString("utf8"))}),s.on("error",function(Ne){e.handleError(Ne)})},ot=function(A){if(n.reusedSocket&&A.code==="ECONNRESET")return he(be,We).on("error",ot);e.handleError(A)};n=he(be,We).on("error",ot),r.autoUnref&&n.on("socket",A=>{A.unref()}),k&&n.write(k),n.end(),e.dispatchEvent("loadstart")}else{var Qe=".node-xmlhttprequest-content-"+process.pid,Te=".node-xmlhttprequest-sync-"+process.pid;Fi.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(be)+";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('"+Qe+"', 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('"+Qe+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Te+"');});}).on('error', function(error) {fs.writeFileSync('"+Qe+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Te+"');});"+(k?"req.write('"+JSON.stringify(k).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",$e=jg(process.argv[0],["-e",it]),mt;Fi.existsSync(Te););if(e.responseText=Fi.readFileSync(Qe,"utf8"),$e.stdin.end(),Fi.unlinkSync(Qe),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 K=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));s={statusCode:e.status,headers:K.data.headers},e.responseText=K.data.text,e.response=Buffer.from(K.data.data,"base64"),J(e.DONE,!0)}}},this.handleError=function(k,B){this.status=B||0,this.statusText=k,this.responseText=k.stack,v=!0,J(this.DONE)},this.abort=function(){n&&(n.abort(),n=null),d=Object.assign({},u),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),v=T=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||_)&&this.readyState!==this.DONE&&(_=!1,J(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(k,B){k in x||(x[k]=[]),x[k].push(B)},this.removeEventListener=function(k,B){k in x&&(x[k]=x[k].filter(function(te){return te!==B}))},this.dispatchEvent=function(k){if(typeof e["on"+k]=="function"&&(this.readyState===this.DONE&&a.async?setTimeout(function(){e["on"+k]()},0):e["on"+k]()),k in x)for(let B=0,te=x[k].length;B<te;B++)this.readyState===this.DONE?setTimeout(function(){x[k][B].call(e)},0):x[k][B].call(e)};var J=function(k){if(!(e.readyState===k||e.readyState===e.UNSENT&&T)&&(e.readyState=k,(a.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let B;T?B="abort":v?B="error":B="load",e.dispatchEvent(B),e.dispatchEvent("loadend")}}}});var Cs=M(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.ERROR_PACKET=Wr.PACKET_TYPES_REVERSE=Wr.PACKET_TYPES=void 0;var or=Object.create(null);Wr.PACKET_TYPES=or;or.open="0";or.close="1";or.ping="2";or.pong="3";or.message="4";or.upgrade="5";or.noop="6";var wu=Object.create(null);Wr.PACKET_TYPES_REVERSE=wu;Object.keys(or).forEach(r=>{wu[or[r]]=r});var Ug={type:"error",data:"parser error"};Wr.ERROR_PACKET=Ug});var xu=M(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.encodePacket=void 0;Di.encodePacketToBinary=Wg;var Kg=Cs(),qg=({type:r,data:e},t,i)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?i(t?e:"b"+Su(e,!0).toString("base64")):i(Kg.PACKET_TYPES[r]+(e||""));Di.encodePacket=qg;var Su=(r,e)=>Buffer.isBuffer(r)||r instanceof Uint8Array&&!e?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength),na;function Wg(r,e){if(r.data instanceof ArrayBuffer||ArrayBuffer.isView(r.data))return e(Su(r.data,!1));(0,Di.encodePacket)(r,!0,t=>{na||(na=new TextEncoder),e(na.encode(t))})}});var Cu=M(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});Os.decodePacket=void 0;var ks=Cs(),Hg=(r,e)=>{if(typeof r!="string")return{type:"message",data:Tu(r,e)};let t=r.charAt(0);if(t==="b"){let i=Buffer.from(r.substring(1),"base64");return{type:"message",data:Tu(i,e)}}return ks.PACKET_TYPES_REVERSE[t]?r.length>1?{type:ks.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:ks.PACKET_TYPES_REVERSE[t]}:ks.ERROR_PACKET};Os.decodePacket=Hg;var Tu=(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 Bi=M(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.decodePayload=vt.decodePacket=vt.encodePayload=vt.encodePacket=vt.protocol=void 0;vt.createPacketEncoderStream=$g;vt.createPacketDecoderStream=Gg;var oa=xu();Object.defineProperty(vt,"encodePacket",{enumerable:!0,get:function(){return oa.encodePacket}});var aa=Cu();Object.defineProperty(vt,"decodePacket",{enumerable:!0,get:function(){return aa.decodePacket}});var ku=Cs(),Ou="",Vg=(r,e)=>{let t=r.length,i=new Array(t),n=0;r.forEach((s,a)=>{(0,oa.encodePacket)(s,!1,c=>{i[a]=c,++n===t&&e(i.join(Ou))})})};vt.encodePayload=Vg;var zg=(r,e)=>{let t=r.split(Ou),i=[];for(let n=0;n<t.length;n++){let s=(0,aa.decodePacket)(t[n],e);if(i.push(s),s.type==="error")break}return i};vt.decodePayload=zg;function $g(){return new TransformStream({transform(r,e){(0,oa.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 sa;function Ps(r){return r.reduce((e,t)=>e+t.length,0)}function Rs(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 Gg(r,e){sa||(sa=new TextDecoder);let t=[],i=0,n=-1,s=!1;return new TransformStream({transform(a,c){for(t.push(a);;){if(i===0){if(Ps(t)<1)break;let u=Rs(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(Ps(t)<2)break;let u=Rs(t,2);n=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),i=3}else if(i===2){if(Ps(t)<8)break;let u=Rs(t,8),d=new DataView(u.buffer,u.byteOffset,u.length),p=d.getUint32(0);if(p>Math.pow(2,21)-1){c.enqueue(ku.ERROR_PACKET);break}n=p*Math.pow(2,32)+d.getUint32(4),i=3}else{if(Ps(t)<n)break;let u=Rs(t,n);c.enqueue((0,aa.decodePacket)(s?u:sa.decode(u),e)),i=0}if(n===0||n>r){c.enqueue(ku.ERROR_PACKET);break}}}})}vt.protocol=4});var di=M(Pu=>{Pu.Emitter=_t;function _t(r){if(r)return Yg(r)}function Yg(r){for(var e in _t.prototype)r[e]=_t.prototype[e];return r}_t.prototype.on=_t.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};_t.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};_t.prototype.off=_t.prototype.removeListener=_t.prototype.removeAllListeners=_t.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};_t.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};_t.prototype.emitReserved=_t.prototype.emit;_t.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};_t.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=Xg;Nt.parse=Ru;Nt.nextTick=process.nextTick;Nt.globalThisShim=global;Nt.defaultBinaryType="nodebuffer";function Xg(){return new As}function Ru(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 As=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let i=Ru(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=As});var gi=M(ji=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});ji.pick=Jg;ji.installTimerFunctions=em;ji.byteLength=rm;ji.randomString=nm;var Hr=pi();function Jg(r,...e){return e.reduce((t,i)=>(r.hasOwnProperty(i)&&(t[i]=r[i]),t),{})}var Zg=Hr.globalThisShim.setTimeout,Qg=Hr.globalThisShim.clearTimeout;function em(r,e){e.useNativeTimers?(r.setTimeoutFn=Zg.bind(Hr.globalThisShim),r.clearTimeoutFn=Qg.bind(Hr.globalThisShim)):(r.setTimeoutFn=Hr.globalThisShim.setTimeout.bind(Hr.globalThisShim),r.clearTimeoutFn=Hr.globalThisShim.clearTimeout.bind(Hr.globalThisShim))}var tm=1.33;function rm(r){return typeof r=="string"?im(r):Math.ceil((r.byteLength||r.size)*tm)}function im(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 nm(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}});var ca=M(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});Is.encode=sm;Is.decode=om;function sm(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function om(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 Iu=M((Nv,Au)=>{var Ui=1e3,Ki=Ui*60,qi=Ki*60,mi=qi*24,am=mi*7,cm=mi*365.25;Au.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return fm(r);if(t==="number"&&isFinite(r))return e.long?lm(r):um(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function fm(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*cm;case"weeks":case"week":case"w":return t*am;case"days":case"day":case"d":return t*mi;case"hours":case"hour":case"hrs":case"hr":case"h":return t*qi;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ki;case"seconds":case"second":case"secs":case"sec":case"s":return t*Ui;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function um(r){var e=Math.abs(r);return e>=mi?Math.round(r/mi)+"d":e>=qi?Math.round(r/qi)+"h":e>=Ki?Math.round(r/Ki)+"m":e>=Ui?Math.round(r/Ui)+"s":r+"ms"}function lm(r){var e=Math.abs(r);return e>=mi?Ls(r,e,mi,"day"):e>=qi?Ls(r,e,qi,"hour"):e>=Ki?Ls(r,e,Ki,"minute"):e>=Ui?Ls(r,e,Ui,"second"):r+" ms"}function Ls(r,e,t,i){var n=e>=t*1.5;return Math.round(r/t)+" "+i+(n?"s":"")}});var fa=M((Mv,Lu)=>{function hm(r){t.debug=t,t.default=t,t.coerce=u,t.disable=a,t.enable=n,t.enabled=c,t.humanize=Iu(),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,v,T;function x(...H){if(!x.enabled)return;let oe=x,J=Number(new Date),k=J-(m||J);oe.diff=k,oe.prev=m,oe.curr=J,m=J,H[0]=t.coerce(H[0]),typeof H[0]!="string"&&H.unshift("%O");let B=0;H[0]=H[0].replace(/%([a-zA-Z%])/g,(j,U)=>{if(j==="%%")return"%";B++;let ne=t.formatters[U];if(typeof ne=="function"){let _e=H[B];j=ne.call(oe,_e),H.splice(B,1),B--}return j}),t.formatArgs.call(oe,H),(oe.log||t.log).apply(oe,H)}return x.namespace=p,x.useColors=t.useColors(),x.color=t.selectColor(p),x.extend=i,x.destroy=t.destroy,Object.defineProperty(x,"enabled",{enumerable:!0,configurable:!1,get:()=>_!==null?_:(v!==t.namespaces&&(v=t.namespaces,T=t.enabled(p)),T),set:H=>{_=H}}),typeof t.init=="function"&&t.init(x),x}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,v=0,T=-1,x=0;for(;_<p.length;)if(v<m.length&&(m[v]===p[_]||m[v]==="*"))m[v]==="*"?(T=v,x=_,v++):(_++,v++);else if(T!==-1)v=T+1,x++,_=x;else return!1;for(;v<m.length&&m[v]==="*";)v++;return v===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}Lu.exports=hm});var Nu=M((wt,Ns)=>{wt.formatArgs=pm;wt.save=gm;wt.load=mm;wt.useColors=dm;wt.storage=ym();wt.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`."))}})();wt.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 dm(){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 pm(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ns.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)}wt.log=console.debug||console.log||(()=>{});function gm(r){try{r?wt.storage.setItem("debug",r):wt.storage.removeItem("debug")}catch{}}function mm(){let r;try{r=wt.storage.getItem("debug")||wt.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function ym(){try{return localStorage}catch{}}Ns.exports=fa()(wt);var{formatters:_m}=Ns.exports;_m.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Fu=M((Fv,Mu)=>{"use strict";Mu.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 ju=M((Dv,Bu)=>{"use strict";var bm=require("os"),Du=require("tty"),Mt=Fu(),{env:at}=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 at&&(at.FORCE_COLOR==="true"?Vr=1:at.FORCE_COLOR==="false"?Vr=0:Vr=at.FORCE_COLOR.length===0?1:Math.min(parseInt(at.FORCE_COLOR,10),3));function ua(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function la(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(at.TERM==="dumb")return t;if(process.platform==="win32"){let i=bm.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in at)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(i=>i in at)||at.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in at)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(at.TEAMCITY_VERSION)?1:0;if(at.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in at){let i=parseInt((at.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(at.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(at.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(at.TERM)||"COLORTERM"in at?1:t}function Em(r){let e=la(r,r&&r.isTTY);return ua(e)}Bu.exports={supportsColor:Em,stdout:ua(la(!0,Du.isatty(1))),stderr:ua(la(!0,Du.isatty(2)))}});var Ku=M((ct,Fs)=>{var vm=require("tty"),Ms=require("util");ct.init=Om;ct.log=Tm;ct.formatArgs=Sm;ct.save=Cm;ct.load=km;ct.useColors=wm;ct.destroy=Ms.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");ct.colors=[6,2,3,4,5,1];try{let r=ju();r&&(r.stderr||r).level>=2&&(ct.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{}ct.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 wm(){return"colors"in ct.inspectOpts?!!ct.inspectOpts.colors:vm.isatty(process.stderr.fd)}function Sm(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
|
-
`+s),r.push(n+"m+"+Fs.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=
|
|
21
|
-
`)}function Cm(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function km(){return process.env.DEBUG}function Om(r){r.inspectOpts={};let e=Object.keys(
|
|
22
|
-
`).map(e=>e.trim()).join(" ")};Uu.O=function(r){return this.inspectOpts.colors=this.useColors,Ms.inspect(r,this.inspectOpts)}});var Ft=M((BE,ha)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?ha.exports=Nu():ha.exports=Ku()});var Cn=M(zr=>{"use strict";var Pm=zr&&zr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(zr,"__esModule",{value:!0});zr.Transport=zr.TransportError=void 0;var Rm=Bi(),Am=di(),Im=gi(),Lm=ca(),Nm=Pm(Ft()),Mm=(0,Nm.default)("engine.io-client:transport"),Ds=class extends Error{constructor(e,t,i){super(e),this.description=t,this.context=i,this.type="TransportError"}};zr.TransportError=Ds;var da=class extends Am.Emitter{constructor(e){super(),this.writable=!1,(0,Im.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,i){return super.emitReserved("error",new Ds(e,t,i)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"?this.write(e):Mm("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=(0,Rm.decodePacket)(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=(0,Lm.encode)(e);return t.length?"?"+t:""}};zr.Transport=da});var ga=M(Wi=>{"use strict";var Fm=Wi&&Wi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Wi,"__esModule",{value:!0});Wi.Polling=void 0;var Dm=Cn(),Bm=gi(),qu=Bi(),jm=Fm(Ft()),Ht=(0,jm.default)("engine.io-client:polling"),pa=class extends Dm.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{Ht("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let i=0;this._polling&&(Ht("we are currently polling - waiting to pause"),i++,this.once("pollComplete",function(){Ht("pre-pause polling complete"),--i||t()})),this.writable||(Ht("we are currently writing - waiting to pause"),i++,this.once("drain",function(){Ht("pre-pause writing complete"),--i||t()}))}else t()}_poll(){Ht("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Ht("polling got data %s",e);let t=i=>{if(this.readyState==="opening"&&i.type==="open"&&this.onOpen(),i.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(i)};(0,qu.decodePayload)(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Ht('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{Ht("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Ht("transport open - closing"),e()):(Ht("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,qu.encodePayload)(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=(0,Bm.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};Wi.Polling=pa});var Hu=M(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});Bs.hasCORS=void 0;var Wu=!1;try{Wu=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}Bs.hasCORS=Wu});var _a=M(ar=>{"use strict";var Um=ar&&ar.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ar,"__esModule",{value:!0});ar.XHR=ar.Request=ar.BaseXHR=void 0;var Km=ga(),qm=di(),Vu=gi(),$u=pi(),Wm=Hu(),Hm=Um(Ft()),ma=(0,Hm.default)("engine.io-client:polling");function Vm(){}var js=class extends Km.Polling{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",i=location.port;i||(i=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||i!==e.port}}doWrite(e,t){let i=this.request({method:"POST",data:e});i.on("success",t),i.on("error",(n,s)=>{this.onError("xhr post error",n,s)})}doPoll(){ma("xhr poll");let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,i)=>{this.onError("xhr poll error",t,i)}),this.pollXhr=e}};ar.BaseXHR=js;var Tr=class r extends qm.Emitter{constructor(e,t,i){super(),this.createRequest=e,(0,Vu.installTimerFunctions)(this,i),this._opts=i,this._method=i.method||"GET",this._uri=t,this._data=i.data!==void 0?i.data:null,this._create()}_create(){var e;let t=(0,Vu.pick)(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let i=this._xhr=this.createRequest(t);try{ma("xhr open %s: %s",this._method,this._uri),i.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let n in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(n)&&i.setRequestHeader(n,this._opts.extraHeaders[n])}}catch{}if(this._method==="POST")try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{i.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(i),"withCredentials"in i&&(i.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(i.timeout=this._opts.requestTimeout),i.onreadystatechange=()=>{var n;i.readyState===3&&((n=this._opts.cookieJar)===null||n===void 0||n.parseCookies(i.getResponseHeader("set-cookie"))),i.readyState===4&&(i.status===200||i.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof i.status=="number"?i.status:0)},0))},ma("xhr data %s",this._data),i.send(this._data)}catch(n){this.setTimeoutFn(()=>{this._onError(n)},0);return}typeof document<"u"&&(this._index=r.requestsCount++,r.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Vm,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete r.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};ar.Request=Tr;Tr.requestsCount=0;Tr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",zu);else if(typeof addEventListener=="function"){let r="onpagehide"in $u.globalThisShim?"pagehide":"unload";addEventListener(r,zu,!1)}}function zu(){for(let r in Tr.requests)Tr.requests.hasOwnProperty(r)&&Tr.requests[r].abort()}var zm=(function(){let r=Gu({xdomain:!1});return r&&r.responseType!==null})(),ya=class extends js{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=zm&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Tr(Gu,this.uri(),e)}};ar.XHR=ya;function Gu(r){let e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Wm.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new $u.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}});var ba=M(cr=>{"use strict";var $m=cr&&cr.__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]})),Gm=cr&&cr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Ym=cr&&cr.__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)&&$m(e,r,t);return Gm(e,r),e};Object.defineProperty(cr,"__esModule",{value:!0});cr.XHR=void 0;var Yu=Ym(Eu()),Xu=_a(),Xm=Yu.default||Yu,va=class extends Xu.BaseXHR{request(e={}){var t;return Object.assign(e,{xd:this.xd,cookieJar:(t=this.socket)===null||t===void 0?void 0:t._cookieJar},this.opts),new Xu.Request(i=>new Xm(i),this.uri(),e)}};cr.XHR=va});var Cr=M((HE,Qu)=>{"use strict";var Ju=["nodebuffer","arraybuffer","fragments"],Zu=typeof Blob<"u";Zu&&Ju.push("blob");Qu.exports={BINARY_TYPES:Ju,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Zu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var kn=M((VE,Us)=>{"use strict";var{EMPTY_BUFFER:Jm}=Cr(),Ea=Buffer[Symbol.species];function Zm(r,e){if(r.length===0)return Jm;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),i=0;for(let n=0;n<r.length;n++){let s=r[n];t.set(s,i),i+=s.length}return i<e?new Ea(t.buffer,t.byteOffset,i):t}function el(r,e,t,i,n){for(let s=0;s<n;s++)t[i+s]=r[s]^e[s&3]}function tl(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Qm(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function wa(r){if(wa.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Ea(r):ArrayBuffer.isView(r)?e=new Ea(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),wa.readOnly=!1),e}Us.exports={concat:Zm,mask:el,toArrayBuffer:Qm,toBuffer:wa,unmask:tl};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");Us.exports.mask=function(e,t,i,n,s){s<48?el(e,t,i,n,s):r.mask(e,t,i,n,s)},Us.exports.unmask=function(e,t){e.length<32?tl(e,t):r.unmask(e,t)}}catch{}});var nl=M((zE,il)=>{"use strict";var rl=Symbol("kDone"),xa=Symbol("kRun"),Sa=class{constructor(e){this[rl]=()=>{this.pending--,this[xa]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[xa]()}[xa](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[rl])}}};il.exports=Sa});var Pn=M(($E,cl)=>{"use strict";var On=require("zlib"),sl=kn(),ey=nl(),{kStatusCode:ol}=Cr(),ty=Buffer[Symbol.species],ry=Buffer.from([0,0,255,255]),qs=Symbol("permessage-deflate"),kr=Symbol("total-length"),Hi=Symbol("callback"),$r=Symbol("buffers"),Vi=Symbol("error"),Ks,Ta=class{constructor(e,t,i){if(this._maxPayload=i|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!Ks){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ks=new ey(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Hi];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,i=e.find(n=>!(t.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>n.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!n.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(i.server_no_context_takeover=!0),t.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(i.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?i.client_max_window_bits=t.clientMaxWindowBits:(i.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(i=>{let n=t[i];if(n.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(n=n[0],i==="client_max_window_bits"){if(n!==!0){let s=+n;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${i}": ${n}`);n=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${n}`)}else if(i==="server_max_window_bits"){let s=+n;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${i}": ${n}`);n=s}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${n}`)}else throw new Error(`Unknown parameter "${i}"`);t[i]=n})}),e}decompress(e,t,i){Ks.add(n=>{this._decompress(e,t,(s,a)=>{n(),i(s,a)})})}compress(e,t,i){Ks.add(n=>{this._compress(e,t,(s,a)=>{n(),i(s,a)})})}_decompress(e,t,i){let n=this._isServer?"client":"server";if(!this._inflate){let s=`${n}_max_window_bits`,a=typeof this.params[s]!="number"?On.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=On.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[qs]=this,this._inflate[kr]=0,this._inflate[$r]=[],this._inflate.on("error",ny),this._inflate.on("data",al)}this._inflate[Hi]=i,this._inflate.write(e),t&&this._inflate.write(ry),this._inflate.flush(()=>{let s=this._inflate[Vi];if(s){this._inflate.close(),this._inflate=null,i(s);return}let a=sl.concat(this._inflate[$r],this._inflate[kr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[kr]=0,this._inflate[$r]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),i(null,a)})}_compress(e,t,i){let n=this._isServer?"server":"client";if(!this._deflate){let s=`${n}_max_window_bits`,a=typeof this.params[s]!="number"?On.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=On.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[kr]=0,this._deflate[$r]=[],this._deflate.on("data",iy)}this._deflate[Hi]=i,this._deflate.write(e),this._deflate.flush(On.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=sl.concat(this._deflate[$r],this._deflate[kr]);t&&(s=new ty(s.buffer,s.byteOffset,s.length-4)),this._deflate[Hi]=null,this._deflate[kr]=0,this._deflate[$r]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),i(null,s)})}};cl.exports=Ta;function iy(r){this[$r].push(r),this[kr]+=r.length}function al(r){if(this[kr]+=r.length,this[qs]._maxPayload<1||this[kr]<=this[qs]._maxPayload){this[$r].push(r);return}this[Vi]=new RangeError("Max payload size exceeded"),this[Vi].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Vi][ol]=1009,this.removeListener("data",al),this.reset()}function ny(r){if(this[qs]._inflate=null,this[Vi]){this[Hi](this[Vi]);return}r[ol]=1007,this[Hi](r)}});var zi=M((GE,Ws)=>{"use strict";var{isUtf8:fl}=require("buffer"),{hasBlob:sy}=Cr(),oy=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function ay(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Ca(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function cy(r){return sy&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Ws.exports={isBlob:cy,isValidStatusCode:ay,isValidUTF8:Ca,tokenChars:oy};if(fl)Ws.exports.isValidUTF8=function(r){return r.length<24?Ca(r):fl(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Ws.exports.isValidUTF8=function(e){return e.length<32?Ca(e):r(e)}}catch{}});var Aa=M((YE,ml)=>{"use strict";var{Writable:fy}=require("stream"),ul=Pn(),{BINARY_TYPES:uy,EMPTY_BUFFER:ll,kStatusCode:ly,kWebSocket:hy}=Cr(),{concat:ka,toArrayBuffer:dy,unmask:py}=kn(),{isValidStatusCode:gy,isValidUTF8:hl}=zi(),Hs=Buffer[Symbol.species],Dt=0,dl=1,pl=2,gl=3,Oa=4,Pa=5,Vs=6,Ra=class extends fy{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||uy[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[hy]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Dt}_write(e,t,i){if(this._opcode===8&&this._state==Dt)return i();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Hs(i.buffer,i.byteOffset+e,i.length-e),new Hs(i.buffer,i.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let i=this._buffers[0],n=t.length-e;e>=i.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(i.buffer,i.byteOffset,e),n),this._buffers[0]=new Hs(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Dt:this.getInfo(e);break;case dl:this.getPayloadLength16(e);break;case pl:this.getPayloadLength64(e);break;case gl:this.getMask();break;case Oa:this.getData(e);break;case Pa:case Vs:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let i=(t[0]&64)===64;if(i&&!this._extensions[ul.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(i){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(i){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}this._payloadLength===126?this._state=dl:this._payloadLength===127?this._state=pl:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),i=t.readUInt32BE(0);if(i>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);return}this._payloadLength=i*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=gl:this._state=Oa}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Oa}getData(e){let t=ll;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&py(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Pa,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[ul.extensionName].decompress(e,this._fin,(n,s)=>{if(n)return t(n);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(a);return}this._fragments.push(s)}this.dataMessage(t),this._state===Dt&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Dt;return}let t=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let n;this._binaryType==="nodebuffer"?n=ka(i,t):this._binaryType==="arraybuffer"?n=dy(ka(i,t)):this._binaryType==="blob"?n=new Blob(i):n=i,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=Dt):(this._state=Vs,setImmediate(()=>{this.emit("message",n,!0),this._state=Dt,this.startLoop(e)}))}else{let n=ka(i,t);if(!this._skipUTF8Validation&&!hl(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Pa||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=Dt):(this._state=Vs,setImmediate(()=>{this.emit("message",n,!1),this._state=Dt,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,ll),this.end();else{let i=e.readUInt16BE(0);if(!gy(i)){let s=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(s);return}let n=new Hs(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!hl(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(s);return}this._loop=!1,this.emit("conclude",i,n),this.end()}this._state=Dt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Dt):(this._state=Vs,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Dt,this.startLoop(t)}))}createError(e,t,i,n,s){this._loop=!1,this._errored=!0;let a=new e(i?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=s,a[ly]=n,a}};ml.exports=Ra});var Na=M((JE,vl)=>{"use strict";var{Duplex:XE}=require("stream"),{randomFillSync:my}=require("crypto"),yl=Pn(),{EMPTY_BUFFER:yy,kWebSocket:_y,NOOP:vy}=Cr(),{isBlob:$i,isValidStatusCode:by}=zi(),{mask:_l,toBuffer:yi}=kn(),Bt=Symbol("kByteLength"),Ey=Buffer.alloc(4),zs=8*1024,_i,Gi=zs,Vt=0,wy=1,xy=2,Ia=class r{constructor(e,t,i){this._extensions=t||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Vt,this.onerror=vy,this[_y]=void 0}static frame(e,t){let i,n=!1,s=2,a=!1;t.mask&&(i=t.maskBuffer||Ey,t.generateMask?t.generateMask(i):(Gi===zs&&(_i===void 0&&(_i=Buffer.alloc(zs)),my(_i,0,zs),Gi=0),i[0]=_i[Gi++],i[1]=_i[Gi++],i[2]=_i[Gi++],i[3]=_i[Gi++]),a=(i[0]|i[1]|i[2]|i[3])===0,s=6);let c;typeof e=="string"?(!t.mask||a)&&t[Bt]!==void 0?c=t[Bt]:(e=Buffer.from(e),c=e.length):(c=e.length,n=t.mask&&t.readOnly&&!a);let u=c;c>=65536?(s+=8,u=127):c>125&&(s+=2,u=126);let d=Buffer.allocUnsafe(n?c+s:s);return d[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(d[0]|=64),d[1]=u,u===126?d.writeUInt16BE(c,2):u===127&&(d[2]=d[3]=0,d.writeUIntBE(c,4,6)),t.mask?(d[1]|=128,d[s-4]=i[0],d[s-3]=i[1],d[s-2]=i[2],d[s-1]=i[3],a?[d,e]:n?(_l(e,i,d,s,c),[d]):(_l(e,i,e,0,c),[d,e])):[d,e]}close(e,t,i,n){let s;if(e===void 0)s=yy;else{if(typeof e!="number"||!by(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+c),s.writeUInt16BE(e,0),typeof t=="string"?s.write(t,2):s.set(t,2)}}let a={[Bt]:s.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Vt?this.enqueue([this.dispatch,s,!1,a,n]):this.sendFrame(r.frame(s,a),n)}ping(e,t,i){let n,s;if(typeof e=="string"?(n=Buffer.byteLength(e),s=!1):$i(e)?(n=e.size,s=!1):(e=yi(e),n=e.length,s=yi.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Bt]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};$i(e)?this._state!==Vt?this.enqueue([this.getBlobData,e,!1,a,i]):this.getBlobData(e,!1,a,i):this._state!==Vt?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(r.frame(e,a),i)}pong(e,t,i){let n,s;if(typeof e=="string"?(n=Buffer.byteLength(e),s=!1):$i(e)?(n=e.size,s=!1):(e=yi(e),n=e.length,s=yi.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Bt]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};$i(e)?this._state!==Vt?this.enqueue([this.getBlobData,e,!1,a,i]):this.getBlobData(e,!1,a,i):this._state!==Vt?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(r.frame(e,a),i)}send(e,t,i){let n=this._extensions[yl.extensionName],s=t.binary?2:1,a=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):$i(e)?(c=e.size,u=!1):(e=yi(e),c=e.length,u=yi.readOnly),this._firstFragment?(this._firstFragment=!1,a&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=c>=n._threshold),this._compress=a):(a=!1,s=0),t.fin&&(this._firstFragment=!0);let d={[Bt]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:u,rsv1:a};$i(e)?this._state!==Vt?this.enqueue([this.getBlobData,e,this._compress,d,i]):this.getBlobData(e,this._compress,d,i):this._state!==Vt?this.enqueue([this.dispatch,e,this._compress,d,i]):this.dispatch(e,this._compress,d,i)}getBlobData(e,t,i,n){this._bufferedBytes+=i[Bt],this._state=xy,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(La,this,c,n);return}this._bufferedBytes-=i[Bt];let a=yi(s);t?this.dispatch(a,t,i,n):(this._state=Vt,this.sendFrame(r.frame(a,i),n),this.dequeue())}).catch(s=>{process.nextTick(Sy,this,s,n)})}dispatch(e,t,i,n){if(!t){this.sendFrame(r.frame(e,i),n);return}let s=this._extensions[yl.extensionName];this._bufferedBytes+=i[Bt],this._state=wy,s.compress(e,i.fin,(a,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");La(this,u,n);return}this._bufferedBytes-=i[Bt],this._state=Vt,i.readOnly=!1,this.sendFrame(r.frame(c,i),n),this.dequeue()})}dequeue(){for(;this._state===Vt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Bt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Bt],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};vl.exports=Ia;function La(r,e,t){typeof t=="function"&&t(e);for(let i=0;i<r._queue.length;i++){let n=r._queue[i],s=n[n.length-1];typeof s=="function"&&s(e)}}function Sy(r,e,t){La(r,e,t),r.onerror(e)}});var Ol=M((ZE,kl)=>{"use strict";var{kForOnEventAttribute:Rn,kListener:Ma}=Cr(),bl=Symbol("kCode"),El=Symbol("kData"),wl=Symbol("kError"),xl=Symbol("kMessage"),Sl=Symbol("kReason"),Yi=Symbol("kTarget"),Tl=Symbol("kType"),Cl=Symbol("kWasClean"),Or=class{constructor(e){this[Yi]=null,this[Tl]=e}get target(){return this[Yi]}get type(){return this[Tl]}};Object.defineProperty(Or.prototype,"target",{enumerable:!0});Object.defineProperty(Or.prototype,"type",{enumerable:!0});var vi=class extends Or{constructor(e,t={}){super(e),this[bl]=t.code===void 0?0:t.code,this[Sl]=t.reason===void 0?"":t.reason,this[Cl]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[bl]}get reason(){return this[Sl]}get wasClean(){return this[Cl]}};Object.defineProperty(vi.prototype,"code",{enumerable:!0});Object.defineProperty(vi.prototype,"reason",{enumerable:!0});Object.defineProperty(vi.prototype,"wasClean",{enumerable:!0});var Xi=class extends Or{constructor(e,t={}){super(e),this[wl]=t.error===void 0?null:t.error,this[xl]=t.message===void 0?"":t.message}get error(){return this[wl]}get message(){return this[xl]}};Object.defineProperty(Xi.prototype,"error",{enumerable:!0});Object.defineProperty(Xi.prototype,"message",{enumerable:!0});var An=class extends Or{constructor(e,t={}){super(e),this[El]=t.data===void 0?null:t.data}get data(){return this[El]}};Object.defineProperty(An.prototype,"data",{enumerable:!0});var Ty={addEventListener(r,e,t={}){for(let n of this.listeners(r))if(!t[Rn]&&n[Ma]===e&&!n[Rn])return;let i;if(r==="message")i=function(s,a){let c=new An("message",{data:a?s:s.toString()});c[Yi]=this,$s(e,this,c)};else if(r==="close")i=function(s,a){let c=new vi("close",{code:s,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Yi]=this,$s(e,this,c)};else if(r==="error")i=function(s){let a=new Xi("error",{error:s,message:s.message});a[Yi]=this,$s(e,this,a)};else if(r==="open")i=function(){let s=new Or("open");s[Yi]=this,$s(e,this,s)};else return;i[Rn]=!!t[Rn],i[Ma]=e,t.once?this.once(r,i):this.on(r,i)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[Ma]===e&&!t[Rn]){this.removeListener(r,t);break}}};kl.exports={CloseEvent:vi,ErrorEvent:Xi,Event:Or,EventTarget:Ty,MessageEvent:An};function $s(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var Fa=M((QE,Pl)=>{"use strict";var{tokenChars:In}=zi();function fr(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function Cy(r){let e=Object.create(null),t=Object.create(null),i=!1,n=!1,s=!1,a,c,u=-1,d=-1,p=-1,m=0;for(;m<r.length;m++)if(d=r.charCodeAt(m),a===void 0)if(p===-1&&In[d]===1)u===-1&&(u=m);else if(m!==0&&(d===32||d===9))p===-1&&u!==-1&&(p=m);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let E=r.slice(u,p);d===44?(fr(e,E,t),t=Object.create(null)):a=E,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(c===void 0)if(p===-1&&In[d]===1)u===-1&&(u=m);else if(d===32||d===9)p===-1&&u!==-1&&(p=m);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m),fr(t,r.slice(u,p),!0),d===44&&(fr(e,a,t),t=Object.create(null),a=void 0),u=p=-1}else if(d===61&&u!==-1&&p===-1)c=r.slice(u,m),u=p=-1;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(n){if(In[d]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);u===-1?u=m:i||(i=!0),n=!1}else if(s)if(In[d]===1)u===-1&&(u=m);else if(d===34&&u!==-1)s=!1,p=m;else if(d===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(d===34&&r.charCodeAt(m-1)===61)s=!0;else if(p===-1&&In[d]===1)u===-1&&(u=m);else if(u!==-1&&(d===32||d===9))p===-1&&(p=m);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let E=r.slice(u,p);i&&(E=E.replace(/\\/g,""),i=!1),fr(t,c,E),d===44&&(fr(e,a,t),t=Object.create(null),a=void 0),c=void 0,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);if(u===-1||s||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=m);let _=r.slice(u,p);return a===void 0?fr(e,_,t):(c===void 0?fr(t,_,!0):i?fr(t,c,_.replace(/\\/g,"")):fr(t,c,_),fr(e,a,t)),e}function ky(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(i=>[e].concat(Object.keys(i).map(n=>{let s=i[n];return Array.isArray(s)||(s=[s]),s.map(a=>a===!0?n:`${n}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Pl.exports={format:ky,parse:Cy}});var Js=M((rw,Kl)=>{"use strict";var Oy=require("events"),Py=require("https"),Ry=require("http"),Il=require("net"),Ay=require("tls"),{randomBytes:Iy,createHash:Ly}=require("crypto"),{Duplex:ew,Readable:tw}=require("stream"),{URL:Da}=require("url"),Gr=Pn(),Ny=Aa(),My=Na(),{isBlob:Fy}=zi(),{BINARY_TYPES:Rl,EMPTY_BUFFER:Gs,GUID:Dy,kForOnEventAttribute:Ba,kListener:By,kStatusCode:jy,kWebSocket:ct,NOOP:Ll}=Cr(),{EventTarget:{addEventListener:Uy,removeEventListener:Ky}}=Ol(),{format:qy,parse:Wy}=Fa(),{toBuffer:Hy}=kn(),Vy=30*1e3,Nl=Symbol("kAborted"),ja=[8,13],Pr=["CONNECTING","OPEN","CLOSING","CLOSED"],zy=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ke=class r extends Oy{constructor(e,t,i){super(),this._binaryType=Rl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Gs,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(i=t,t=[]):t=[t]),Ml(this,e,t,i)):(this._autoPong=i.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Rl.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,i){let n=new Ny({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),s=new My(e,this._extensions,i.generateMask);this._receiver=n,this._sender=s,this._socket=e,n[ct]=this,s[ct]=this,e[ct]=this,n.on("conclude",Yy),n.on("drain",Xy),n.on("error",Jy),n.on("message",Zy),n.on("ping",Qy),n.on("pong",e_),s.onerror=t_,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Bl),e.on("data",Xs),e.on("end",jl),e.on("error",Ul),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Gr.extensionName]&&this._extensions[Gr.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Pt(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Dl(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,i){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=t=void 0):typeof t=="function"&&(i=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ua(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Gs,t,i)}pong(e,t,i){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=t=void 0):typeof t=="function"&&(i=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ua(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Gs,t,i)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,i){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(i=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ua(this,e,i);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Gr.extensionName]||(n.compress=!1),this._sender.send(e||Gs,n,i)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Pt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ke,"CONNECTING",{enumerable:!0,value:Pr.indexOf("CONNECTING")});Object.defineProperty(Ke.prototype,"CONNECTING",{enumerable:!0,value:Pr.indexOf("CONNECTING")});Object.defineProperty(Ke,"OPEN",{enumerable:!0,value:Pr.indexOf("OPEN")});Object.defineProperty(Ke.prototype,"OPEN",{enumerable:!0,value:Pr.indexOf("OPEN")});Object.defineProperty(Ke,"CLOSING",{enumerable:!0,value:Pr.indexOf("CLOSING")});Object.defineProperty(Ke.prototype,"CLOSING",{enumerable:!0,value:Pr.indexOf("CLOSING")});Object.defineProperty(Ke,"CLOSED",{enumerable:!0,value:Pr.indexOf("CLOSED")});Object.defineProperty(Ke.prototype,"CLOSED",{enumerable:!0,value:Pr.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(Ke.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(Ke.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Ba])return e[By];return null},set(e){for(let t of this.listeners(r))if(t[Ba]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[Ba]:!0})}})});Ke.prototype.addEventListener=Uy;Ke.prototype.removeEventListener=Ky;Kl.exports=Ke;function Ml(r,e,t,i){let n={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:ja[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=n.autoPong,!ja.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${ja.join(", ")})`);let s;if(e instanceof Da)s=e;else try{s=new Da(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),r._url=s.href;let a=s.protocol==="wss:",c=s.protocol==="ws+unix:",u;if(s.protocol!=="ws:"&&!a&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!s.pathname?u="The URL's pathname is empty":s.hash&&(u="The URL contains a fragment identifier"),u){let T=new SyntaxError(u);if(r._redirects===0)throw T;Ys(r,T);return}let d=a?443:80,p=Iy(16).toString("base64"),m=a?Py.request:Ry.request,_=new Set,E;if(n.createConnection=n.createConnection||(a?Gy:$y),n.defaultPort=n.defaultPort||d,n.port=s.port||d,n.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},n.path=s.pathname+s.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(E=new Gr(n.perMessageDeflate!==!0?n.perMessageDeflate:{},!1,n.maxPayload),n.headers["Sec-WebSocket-Extensions"]=qy({[Gr.extensionName]:E.offer()})),t.length){for(let T of t){if(typeof T!="string"||!zy.test(T)||_.has(T))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(T)}n.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(s.username||s.password)&&(n.auth=`${s.username}:${s.password}`),c){let T=n.path.split(":");n.socketPath=T[0],n.path=T[1]}let S;if(n.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=a,r._originalHostOrSocketPath=c?n.socketPath:s.host;let T=i&&i.headers;if(i={...i,headers:{}},T)for(let[z,ge]of Object.entries(T))i.headers[z.toLowerCase()]=ge}else if(r.listenerCount("redirect")===0){let T=c?r._originalIpc?n.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:s.host===r._originalHostOrSocketPath;(!T||r._originalSecure&&!a)&&(delete n.headers.authorization,delete n.headers.cookie,T||delete n.headers.host,n.auth=void 0)}n.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),S=r._req=m(n),r._redirects&&r.emit("redirect",r.url,S)}else S=r._req=m(n);n.timeout&&S.on("timeout",()=>{Pt(r,S,"Opening handshake has timed out")}),S.on("error",T=>{S===null||S[Nl]||(S=r._req=null,Ys(r,T))}),S.on("response",T=>{let z=T.headers.location,ge=T.statusCode;if(z&&n.followRedirects&&ge>=300&&ge<400){if(++r._redirects>n.maxRedirects){Pt(r,S,"Maximum redirects exceeded");return}S.abort();let ee;try{ee=new Da(z,e)}catch{let B=new SyntaxError(`Invalid URL: ${z}`);Ys(r,B);return}Ml(r,ee,t,i)}else r.emit("unexpected-response",S,T)||Pt(r,S,`Unexpected server response: ${T.statusCode}`)}),S.on("upgrade",(T,z,ge)=>{if(r.emit("upgrade",T),r.readyState!==Ke.CONNECTING)return;S=r._req=null;let ee=T.headers.upgrade;if(ee===void 0||ee.toLowerCase()!=="websocket"){Pt(r,z,"Invalid Upgrade header");return}let R=Ly("sha1").update(p+Dy).digest("base64");if(T.headers["sec-websocket-accept"]!==R){Pt(r,z,"Invalid Sec-WebSocket-Accept header");return}let B=T.headers["sec-websocket-protocol"],re;if(B!==void 0?_.size?_.has(B)||(re="Server sent an invalid subprotocol"):re="Server sent a subprotocol but none was requested":_.size&&(re="Server sent no subprotocol"),re){Pt(r,z,re);return}B&&(r._protocol=B);let K=T.headers["sec-websocket-extensions"];if(K!==void 0){if(!E){Pt(r,z,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let U;try{U=Wy(K)}catch{Pt(r,z,"Invalid Sec-WebSocket-Extensions header");return}let ye=Object.keys(U);if(ye.length!==1||ye[0]!==Gr.extensionName){Pt(r,z,"Server indicated an extension that was not requested");return}try{E.accept(U[Gr.extensionName])}catch{Pt(r,z,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Gr.extensionName]=E}r.setSocket(z,ge,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(S,r):S.end()}function Ys(r,e){r._readyState=Ke.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function $y(r){return r.path=r.socketPath,Il.connect(r)}function Gy(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Il.isIP(r.host)?"":r.host),Ay.connect(r)}function Pt(r,e,t){r._readyState=Ke.CLOSING;let i=new Error(t);Error.captureStackTrace(i,Pt),e.setHeader?(e[Nl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ys,r,i)):(e.destroy(i),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function Ua(r,e,t){if(e){let i=Fy(e)?e.size:Hy(e).length;r._socket?r._sender._bufferedBytes+=i:r._bufferedAmount+=i}if(t){let i=new Error(`WebSocket is not open: readyState ${r.readyState} (${Pr[r.readyState]})`);process.nextTick(t,i)}}function Yy(r,e){let t=this[ct];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[ct]!==void 0&&(t._socket.removeListener("data",Xs),process.nextTick(Fl,t._socket),r===1005?t.close():t.close(r,e))}function Xy(){let r=this[ct];r.isPaused||r._socket.resume()}function Jy(r){let e=this[ct];e._socket[ct]!==void 0&&(e._socket.removeListener("data",Xs),process.nextTick(Fl,e._socket),e.close(r[jy])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Al(){this[ct].emitClose()}function Zy(r,e){this[ct].emit("message",r,e)}function Qy(r){let e=this[ct];e._autoPong&&e.pong(r,!this._isServer,Ll),e.emit("ping",r)}function e_(r){this[ct].emit("pong",r)}function Fl(r){r.resume()}function t_(r){let e=this[ct];e.readyState!==Ke.CLOSED&&(e.readyState===Ke.OPEN&&(e._readyState=Ke.CLOSING,Dl(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Dl(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),Vy)}function Bl(){let r=this[ct];this.removeListener("close",Bl),this.removeListener("data",Xs),this.removeListener("end",jl),r._readyState=Ke.CLOSING;let e;!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&(e=r._socket.read())!==null&&r._receiver.write(e),r._receiver.end(),this[ct]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Al),r._receiver.on("finish",Al))}function Xs(r){this[ct]._receiver.write(r)||this.pause()}function jl(){let r=this[ct];r._readyState=Ke.CLOSING,r._receiver.end(),this.end()}function Ul(){let r=this[ct];this.removeListener("error",Ul),this.on("error",Ll),r&&(r._readyState=Ke.CLOSING,this.destroy())}});var Vl=M((nw,Hl)=>{"use strict";var iw=Js(),{Duplex:r_}=require("stream");function ql(r){r.emit("close")}function i_(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Wl(r){this.removeListener("error",Wl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function n_(r,e){let t=!0,i=new r_({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(s,a){let c=!a&&i._readableState.objectMode?s.toString():s;i.push(c)||r.pause()}),r.once("error",function(s){i.destroyed||(t=!1,i.destroy(s))}),r.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(n,s){if(r.readyState===r.CLOSED){s(n),process.nextTick(ql,i);return}let a=!1;r.once("error",function(u){a=!0,s(u)}),r.once("close",function(){a||s(n),process.nextTick(ql,i)}),t&&r.terminate()},i._final=function(n){if(r.readyState===r.CONNECTING){r.once("open",function(){i._final(n)});return}r._socket!==null&&(r._socket._writableState.finished?(n(),i._readableState.endEmitted&&i.destroy()):(r._socket.once("finish",function(){n()}),r.close()))},i._read=function(){r.isPaused&&r.resume()},i._write=function(n,s,a){if(r.readyState===r.CONNECTING){r.once("open",function(){i._write(n,s,a)});return}r.send(n,a)},i.on("end",i_),i.on("error",Wl),i}Hl.exports=n_});var $l=M((sw,zl)=>{"use strict";var{tokenChars:s_}=zi();function o_(r){let e=new Set,t=-1,i=-1,n=0;for(n;n<r.length;n++){let a=r.charCodeAt(n);if(i===-1&&s_[a]===1)t===-1&&(t=n);else if(n!==0&&(a===32||a===9))i===-1&&t!==-1&&(i=n);else if(a===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${n}`);i===-1&&(i=n);let c=r.slice(t,i);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),t=i=-1}else throw new SyntaxError(`Unexpected character at index ${n}`)}if(t===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let s=r.slice(t,n);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}zl.exports={parse:o_}});var eh=M((aw,Ql)=>{"use strict";var a_=require("events"),Zs=require("http"),{Duplex:ow}=require("stream"),{createHash:c_}=require("crypto"),Gl=Fa(),bi=Pn(),f_=$l(),u_=Js(),{GUID:l_,kWebSocket:h_}=Cr(),d_=/^[+/0-9A-Za-z]{22}==$/,Yl=0,Xl=1,Zl=2,Ka=class extends a_{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:u_,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Zs.createServer((i,n)=>{let s=Zs.STATUS_CODES[426];n.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),n.end(s)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=p_(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(n,s,a)=>{this.handleUpgrade(n,s,a,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Yl}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Zl){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Ln,this);return}if(e&&this.once("close",e),this._state!==Xl)if(this._state=Xl,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Ln,this):process.nextTick(Ln,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Ln(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,i,n){t.on("error",Jl);let s=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ei(this,e,t,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){Ei(this,e,t,400,"Invalid Upgrade header");return}if(s===void 0||!d_.test(s)){Ei(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){Ei(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Nn(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=f_.parse(u)}catch{Ei(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],m={};if(this.options.perMessageDeflate&&p!==void 0){let _=new bi(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let E=Gl.parse(p);E[bi.extensionName]&&(_.accept(E[bi.extensionName]),m[bi.extensionName]=_)}catch{Ei(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let _={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(_,(E,S,T,z)=>{if(!E)return Nn(t,S||401,T,z);this.completeUpgrade(m,s,d,e,t,i,n)});return}if(!this.options.verifyClient(_))return Nn(t,401)}this.completeUpgrade(m,s,d,e,t,i,n)}completeUpgrade(e,t,i,n,s,a,c){if(!s.readable||!s.writable)return s.destroy();if(s[h_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Yl)return Nn(s,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${c_("sha1").update(t+l_).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(i.size){let m=this.options.handleProtocols?this.options.handleProtocols(i,n):i.values().next().value;m&&(d.push(`Sec-WebSocket-Protocol: ${m}`),p._protocol=m)}if(e[bi.extensionName]){let m=e[bi.extensionName].params,_=Gl.format({[bi.extensionName]:[m]});d.push(`Sec-WebSocket-Extensions: ${_}`),p._extensions=e}this.emit("headers",d,n),s.write(d.concat(`\r
|
|
20
|
+
`+s),r.push(n+"m+"+Fs.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=xm()+e+" "+r[0]}function xm(){return ct.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Tm(...r){return process.stderr.write(Ms.formatWithOptions(ct.inspectOpts,...r)+`
|
|
21
|
+
`)}function Cm(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function km(){return process.env.DEBUG}function Om(r){r.inspectOpts={};let e=Object.keys(ct.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=ct.inspectOpts[e[t]]}Fs.exports=fa()(ct);var{formatters:Uu}=Fs.exports;Uu.o=function(r){return this.inspectOpts.colors=this.useColors,Ms.inspect(r,this.inspectOpts).split(`
|
|
22
|
+
`).map(e=>e.trim()).join(" ")};Uu.O=function(r){return this.inspectOpts.colors=this.useColors,Ms.inspect(r,this.inspectOpts)}});var Ft=M((Bv,ha)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?ha.exports=Nu():ha.exports=Ku()});var Cn=M(zr=>{"use strict";var Pm=zr&&zr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(zr,"__esModule",{value:!0});zr.Transport=zr.TransportError=void 0;var Rm=Bi(),Am=di(),Im=gi(),Lm=ca(),Nm=Pm(Ft()),Mm=(0,Nm.default)("engine.io-client:transport"),Ds=class extends Error{constructor(e,t,i){super(e),this.description=t,this.context=i,this.type="TransportError"}};zr.TransportError=Ds;var da=class extends Am.Emitter{constructor(e){super(),this.writable=!1,(0,Im.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,i){return super.emitReserved("error",new Ds(e,t,i)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"?this.write(e):Mm("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=(0,Rm.decodePacket)(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=(0,Lm.encode)(e);return t.length?"?"+t:""}};zr.Transport=da});var ga=M(Wi=>{"use strict";var Fm=Wi&&Wi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Wi,"__esModule",{value:!0});Wi.Polling=void 0;var Dm=Cn(),Bm=gi(),qu=Bi(),jm=Fm(Ft()),Ht=(0,jm.default)("engine.io-client:polling"),pa=class extends Dm.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{Ht("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let i=0;this._polling&&(Ht("we are currently polling - waiting to pause"),i++,this.once("pollComplete",function(){Ht("pre-pause polling complete"),--i||t()})),this.writable||(Ht("we are currently writing - waiting to pause"),i++,this.once("drain",function(){Ht("pre-pause writing complete"),--i||t()}))}else t()}_poll(){Ht("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Ht("polling got data %s",e);let t=i=>{if(this.readyState==="opening"&&i.type==="open"&&this.onOpen(),i.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(i)};(0,qu.decodePayload)(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Ht('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{Ht("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Ht("transport open - closing"),e()):(Ht("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,qu.encodePayload)(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=(0,Bm.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};Wi.Polling=pa});var Hu=M(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});Bs.hasCORS=void 0;var Wu=!1;try{Wu=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}Bs.hasCORS=Wu});var _a=M(ar=>{"use strict";var Um=ar&&ar.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ar,"__esModule",{value:!0});ar.XHR=ar.Request=ar.BaseXHR=void 0;var Km=ga(),qm=di(),Vu=gi(),$u=pi(),Wm=Hu(),Hm=Um(Ft()),ma=(0,Hm.default)("engine.io-client:polling");function Vm(){}var js=class extends Km.Polling{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",i=location.port;i||(i=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||i!==e.port}}doWrite(e,t){let i=this.request({method:"POST",data:e});i.on("success",t),i.on("error",(n,s)=>{this.onError("xhr post error",n,s)})}doPoll(){ma("xhr poll");let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,i)=>{this.onError("xhr poll error",t,i)}),this.pollXhr=e}};ar.BaseXHR=js;var Tr=class r extends qm.Emitter{constructor(e,t,i){super(),this.createRequest=e,(0,Vu.installTimerFunctions)(this,i),this._opts=i,this._method=i.method||"GET",this._uri=t,this._data=i.data!==void 0?i.data:null,this._create()}_create(){var e;let t=(0,Vu.pick)(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let i=this._xhr=this.createRequest(t);try{ma("xhr open %s: %s",this._method,this._uri),i.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let n in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(n)&&i.setRequestHeader(n,this._opts.extraHeaders[n])}}catch{}if(this._method==="POST")try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{i.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(i),"withCredentials"in i&&(i.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(i.timeout=this._opts.requestTimeout),i.onreadystatechange=()=>{var n;i.readyState===3&&((n=this._opts.cookieJar)===null||n===void 0||n.parseCookies(i.getResponseHeader("set-cookie"))),i.readyState===4&&(i.status===200||i.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof i.status=="number"?i.status:0)},0))},ma("xhr data %s",this._data),i.send(this._data)}catch(n){this.setTimeoutFn(()=>{this._onError(n)},0);return}typeof document<"u"&&(this._index=r.requestsCount++,r.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Vm,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete r.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};ar.Request=Tr;Tr.requestsCount=0;Tr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",zu);else if(typeof addEventListener=="function"){let r="onpagehide"in $u.globalThisShim?"pagehide":"unload";addEventListener(r,zu,!1)}}function zu(){for(let r in Tr.requests)Tr.requests.hasOwnProperty(r)&&Tr.requests[r].abort()}var zm=(function(){let r=Gu({xdomain:!1});return r&&r.responseType!==null})(),ya=class extends js{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=zm&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Tr(Gu,this.uri(),e)}};ar.XHR=ya;function Gu(r){let e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Wm.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new $u.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}});var Ea=M(cr=>{"use strict";var $m=cr&&cr.__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]})),Gm=cr&&cr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Ym=cr&&cr.__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)&&$m(e,r,t);return Gm(e,r),e};Object.defineProperty(cr,"__esModule",{value:!0});cr.XHR=void 0;var Yu=Ym(vu()),Xu=_a(),Xm=Yu.default||Yu,ba=class extends Xu.BaseXHR{request(e={}){var t;return Object.assign(e,{xd:this.xd,cookieJar:(t=this.socket)===null||t===void 0?void 0:t._cookieJar},this.opts),new Xu.Request(i=>new Xm(i),this.uri(),e)}};cr.XHR=ba});var Cr=M((Hv,Qu)=>{"use strict";var Ju=["nodebuffer","arraybuffer","fragments"],Zu=typeof Blob<"u";Zu&&Ju.push("blob");Qu.exports={BINARY_TYPES:Ju,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Zu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var kn=M((Vv,Us)=>{"use strict";var{EMPTY_BUFFER:Jm}=Cr(),va=Buffer[Symbol.species];function Zm(r,e){if(r.length===0)return Jm;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),i=0;for(let n=0;n<r.length;n++){let s=r[n];t.set(s,i),i+=s.length}return i<e?new va(t.buffer,t.byteOffset,i):t}function el(r,e,t,i,n){for(let s=0;s<n;s++)t[i+s]=r[s]^e[s&3]}function tl(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Qm(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function wa(r){if(wa.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new va(r):ArrayBuffer.isView(r)?e=new va(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),wa.readOnly=!1),e}Us.exports={concat:Zm,mask:el,toArrayBuffer:Qm,toBuffer:wa,unmask:tl};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");Us.exports.mask=function(e,t,i,n,s){s<48?el(e,t,i,n,s):r.mask(e,t,i,n,s)},Us.exports.unmask=function(e,t){e.length<32?tl(e,t):r.unmask(e,t)}}catch{}});var nl=M((zv,il)=>{"use strict";var rl=Symbol("kDone"),Sa=Symbol("kRun"),xa=class{constructor(e){this[rl]=()=>{this.pending--,this[Sa]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Sa]()}[Sa](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[rl])}}};il.exports=xa});var Pn=M(($v,cl)=>{"use strict";var On=require("zlib"),sl=kn(),ey=nl(),{kStatusCode:ol}=Cr(),ty=Buffer[Symbol.species],ry=Buffer.from([0,0,255,255]),qs=Symbol("permessage-deflate"),kr=Symbol("total-length"),Hi=Symbol("callback"),$r=Symbol("buffers"),Vi=Symbol("error"),Ks,Ta=class{constructor(e,t,i){if(this._maxPayload=i|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!Ks){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ks=new ey(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Hi];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,i=e.find(n=>!(t.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>n.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!n.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(i.server_no_context_takeover=!0),t.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(i.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?i.client_max_window_bits=t.clientMaxWindowBits:(i.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(i=>{let n=t[i];if(n.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(n=n[0],i==="client_max_window_bits"){if(n!==!0){let s=+n;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${i}": ${n}`);n=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${n}`)}else if(i==="server_max_window_bits"){let s=+n;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${i}": ${n}`);n=s}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${n}`)}else throw new Error(`Unknown parameter "${i}"`);t[i]=n})}),e}decompress(e,t,i){Ks.add(n=>{this._decompress(e,t,(s,a)=>{n(),i(s,a)})})}compress(e,t,i){Ks.add(n=>{this._compress(e,t,(s,a)=>{n(),i(s,a)})})}_decompress(e,t,i){let n=this._isServer?"client":"server";if(!this._inflate){let s=`${n}_max_window_bits`,a=typeof this.params[s]!="number"?On.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=On.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[qs]=this,this._inflate[kr]=0,this._inflate[$r]=[],this._inflate.on("error",ny),this._inflate.on("data",al)}this._inflate[Hi]=i,this._inflate.write(e),t&&this._inflate.write(ry),this._inflate.flush(()=>{let s=this._inflate[Vi];if(s){this._inflate.close(),this._inflate=null,i(s);return}let a=sl.concat(this._inflate[$r],this._inflate[kr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[kr]=0,this._inflate[$r]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),i(null,a)})}_compress(e,t,i){let n=this._isServer?"server":"client";if(!this._deflate){let s=`${n}_max_window_bits`,a=typeof this.params[s]!="number"?On.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=On.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[kr]=0,this._deflate[$r]=[],this._deflate.on("data",iy)}this._deflate[Hi]=i,this._deflate.write(e),this._deflate.flush(On.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=sl.concat(this._deflate[$r],this._deflate[kr]);t&&(s=new ty(s.buffer,s.byteOffset,s.length-4)),this._deflate[Hi]=null,this._deflate[kr]=0,this._deflate[$r]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),i(null,s)})}};cl.exports=Ta;function iy(r){this[$r].push(r),this[kr]+=r.length}function al(r){if(this[kr]+=r.length,this[qs]._maxPayload<1||this[kr]<=this[qs]._maxPayload){this[$r].push(r);return}this[Vi]=new RangeError("Max payload size exceeded"),this[Vi].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Vi][ol]=1009,this.removeListener("data",al),this.reset()}function ny(r){if(this[qs]._inflate=null,this[Vi]){this[Hi](this[Vi]);return}r[ol]=1007,this[Hi](r)}});var zi=M((Gv,Ws)=>{"use strict";var{isUtf8:fl}=require("buffer"),{hasBlob:sy}=Cr(),oy=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function ay(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Ca(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function cy(r){return sy&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Ws.exports={isBlob:cy,isValidStatusCode:ay,isValidUTF8:Ca,tokenChars:oy};if(fl)Ws.exports.isValidUTF8=function(r){return r.length<24?Ca(r):fl(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Ws.exports.isValidUTF8=function(e){return e.length<32?Ca(e):r(e)}}catch{}});var Aa=M((Yv,ml)=>{"use strict";var{Writable:fy}=require("stream"),ul=Pn(),{BINARY_TYPES:uy,EMPTY_BUFFER:ll,kStatusCode:ly,kWebSocket:hy}=Cr(),{concat:ka,toArrayBuffer:dy,unmask:py}=kn(),{isValidStatusCode:gy,isValidUTF8:hl}=zi(),Hs=Buffer[Symbol.species],Dt=0,dl=1,pl=2,gl=3,Oa=4,Pa=5,Vs=6,Ra=class extends fy{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||uy[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[hy]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Dt}_write(e,t,i){if(this._opcode===8&&this._state==Dt)return i();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Hs(i.buffer,i.byteOffset+e,i.length-e),new Hs(i.buffer,i.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let i=this._buffers[0],n=t.length-e;e>=i.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(i.buffer,i.byteOffset,e),n),this._buffers[0]=new Hs(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Dt:this.getInfo(e);break;case dl:this.getPayloadLength16(e);break;case pl:this.getPayloadLength64(e);break;case gl:this.getMask();break;case Oa:this.getData(e);break;case Pa:case Vs:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let i=(t[0]&64)===64;if(i&&!this._extensions[ul.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(i){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(i){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}this._payloadLength===126?this._state=dl:this._payloadLength===127?this._state=pl:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),i=t.readUInt32BE(0);if(i>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);return}this._payloadLength=i*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=gl:this._state=Oa}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Oa}getData(e){let t=ll;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&py(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Pa,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[ul.extensionName].decompress(e,this._fin,(n,s)=>{if(n)return t(n);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(a);return}this._fragments.push(s)}this.dataMessage(t),this._state===Dt&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Dt;return}let t=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let n;this._binaryType==="nodebuffer"?n=ka(i,t):this._binaryType==="arraybuffer"?n=dy(ka(i,t)):this._binaryType==="blob"?n=new Blob(i):n=i,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=Dt):(this._state=Vs,setImmediate(()=>{this.emit("message",n,!0),this._state=Dt,this.startLoop(e)}))}else{let n=ka(i,t);if(!this._skipUTF8Validation&&!hl(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Pa||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=Dt):(this._state=Vs,setImmediate(()=>{this.emit("message",n,!1),this._state=Dt,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,ll),this.end();else{let i=e.readUInt16BE(0);if(!gy(i)){let s=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(s);return}let n=new Hs(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!hl(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(s);return}this._loop=!1,this.emit("conclude",i,n),this.end()}this._state=Dt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Dt):(this._state=Vs,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Dt,this.startLoop(t)}))}createError(e,t,i,n,s){this._loop=!1,this._errored=!0;let a=new e(i?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=s,a[ly]=n,a}};ml.exports=Ra});var Na=M((Jv,bl)=>{"use strict";var{Duplex:Xv}=require("stream"),{randomFillSync:my}=require("crypto"),yl=Pn(),{EMPTY_BUFFER:yy,kWebSocket:_y,NOOP:by}=Cr(),{isBlob:$i,isValidStatusCode:Ey}=zi(),{mask:_l,toBuffer:yi}=kn(),Bt=Symbol("kByteLength"),vy=Buffer.alloc(4),zs=8*1024,_i,Gi=zs,Vt=0,wy=1,Sy=2,Ia=class r{constructor(e,t,i){this._extensions=t||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Vt,this.onerror=by,this[_y]=void 0}static frame(e,t){let i,n=!1,s=2,a=!1;t.mask&&(i=t.maskBuffer||vy,t.generateMask?t.generateMask(i):(Gi===zs&&(_i===void 0&&(_i=Buffer.alloc(zs)),my(_i,0,zs),Gi=0),i[0]=_i[Gi++],i[1]=_i[Gi++],i[2]=_i[Gi++],i[3]=_i[Gi++]),a=(i[0]|i[1]|i[2]|i[3])===0,s=6);let c;typeof e=="string"?(!t.mask||a)&&t[Bt]!==void 0?c=t[Bt]:(e=Buffer.from(e),c=e.length):(c=e.length,n=t.mask&&t.readOnly&&!a);let u=c;c>=65536?(s+=8,u=127):c>125&&(s+=2,u=126);let d=Buffer.allocUnsafe(n?c+s:s);return d[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(d[0]|=64),d[1]=u,u===126?d.writeUInt16BE(c,2):u===127&&(d[2]=d[3]=0,d.writeUIntBE(c,4,6)),t.mask?(d[1]|=128,d[s-4]=i[0],d[s-3]=i[1],d[s-2]=i[2],d[s-1]=i[3],a?[d,e]:n?(_l(e,i,d,s,c),[d]):(_l(e,i,e,0,c),[d,e])):[d,e]}close(e,t,i,n){let s;if(e===void 0)s=yy;else{if(typeof e!="number"||!Ey(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+c),s.writeUInt16BE(e,0),typeof t=="string"?s.write(t,2):s.set(t,2)}}let a={[Bt]:s.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Vt?this.enqueue([this.dispatch,s,!1,a,n]):this.sendFrame(r.frame(s,a),n)}ping(e,t,i){let n,s;if(typeof e=="string"?(n=Buffer.byteLength(e),s=!1):$i(e)?(n=e.size,s=!1):(e=yi(e),n=e.length,s=yi.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Bt]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};$i(e)?this._state!==Vt?this.enqueue([this.getBlobData,e,!1,a,i]):this.getBlobData(e,!1,a,i):this._state!==Vt?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(r.frame(e,a),i)}pong(e,t,i){let n,s;if(typeof e=="string"?(n=Buffer.byteLength(e),s=!1):$i(e)?(n=e.size,s=!1):(e=yi(e),n=e.length,s=yi.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Bt]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};$i(e)?this._state!==Vt?this.enqueue([this.getBlobData,e,!1,a,i]):this.getBlobData(e,!1,a,i):this._state!==Vt?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(r.frame(e,a),i)}send(e,t,i){let n=this._extensions[yl.extensionName],s=t.binary?2:1,a=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):$i(e)?(c=e.size,u=!1):(e=yi(e),c=e.length,u=yi.readOnly),this._firstFragment?(this._firstFragment=!1,a&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=c>=n._threshold),this._compress=a):(a=!1,s=0),t.fin&&(this._firstFragment=!0);let d={[Bt]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:u,rsv1:a};$i(e)?this._state!==Vt?this.enqueue([this.getBlobData,e,this._compress,d,i]):this.getBlobData(e,this._compress,d,i):this._state!==Vt?this.enqueue([this.dispatch,e,this._compress,d,i]):this.dispatch(e,this._compress,d,i)}getBlobData(e,t,i,n){this._bufferedBytes+=i[Bt],this._state=Sy,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(La,this,c,n);return}this._bufferedBytes-=i[Bt];let a=yi(s);t?this.dispatch(a,t,i,n):(this._state=Vt,this.sendFrame(r.frame(a,i),n),this.dequeue())}).catch(s=>{process.nextTick(xy,this,s,n)})}dispatch(e,t,i,n){if(!t){this.sendFrame(r.frame(e,i),n);return}let s=this._extensions[yl.extensionName];this._bufferedBytes+=i[Bt],this._state=wy,s.compress(e,i.fin,(a,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");La(this,u,n);return}this._bufferedBytes-=i[Bt],this._state=Vt,i.readOnly=!1,this.sendFrame(r.frame(c,i),n),this.dequeue()})}dequeue(){for(;this._state===Vt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Bt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Bt],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};bl.exports=Ia;function La(r,e,t){typeof t=="function"&&t(e);for(let i=0;i<r._queue.length;i++){let n=r._queue[i],s=n[n.length-1];typeof s=="function"&&s(e)}}function xy(r,e,t){La(r,e,t),r.onerror(e)}});var Ol=M((Zv,kl)=>{"use strict";var{kForOnEventAttribute:Rn,kListener:Ma}=Cr(),El=Symbol("kCode"),vl=Symbol("kData"),wl=Symbol("kError"),Sl=Symbol("kMessage"),xl=Symbol("kReason"),Yi=Symbol("kTarget"),Tl=Symbol("kType"),Cl=Symbol("kWasClean"),Or=class{constructor(e){this[Yi]=null,this[Tl]=e}get target(){return this[Yi]}get type(){return this[Tl]}};Object.defineProperty(Or.prototype,"target",{enumerable:!0});Object.defineProperty(Or.prototype,"type",{enumerable:!0});var bi=class extends Or{constructor(e,t={}){super(e),this[El]=t.code===void 0?0:t.code,this[xl]=t.reason===void 0?"":t.reason,this[Cl]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[El]}get reason(){return this[xl]}get wasClean(){return this[Cl]}};Object.defineProperty(bi.prototype,"code",{enumerable:!0});Object.defineProperty(bi.prototype,"reason",{enumerable:!0});Object.defineProperty(bi.prototype,"wasClean",{enumerable:!0});var Xi=class extends Or{constructor(e,t={}){super(e),this[wl]=t.error===void 0?null:t.error,this[Sl]=t.message===void 0?"":t.message}get error(){return this[wl]}get message(){return this[Sl]}};Object.defineProperty(Xi.prototype,"error",{enumerable:!0});Object.defineProperty(Xi.prototype,"message",{enumerable:!0});var An=class extends Or{constructor(e,t={}){super(e),this[vl]=t.data===void 0?null:t.data}get data(){return this[vl]}};Object.defineProperty(An.prototype,"data",{enumerable:!0});var Ty={addEventListener(r,e,t={}){for(let n of this.listeners(r))if(!t[Rn]&&n[Ma]===e&&!n[Rn])return;let i;if(r==="message")i=function(s,a){let c=new An("message",{data:a?s:s.toString()});c[Yi]=this,$s(e,this,c)};else if(r==="close")i=function(s,a){let c=new bi("close",{code:s,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Yi]=this,$s(e,this,c)};else if(r==="error")i=function(s){let a=new Xi("error",{error:s,message:s.message});a[Yi]=this,$s(e,this,a)};else if(r==="open")i=function(){let s=new Or("open");s[Yi]=this,$s(e,this,s)};else return;i[Rn]=!!t[Rn],i[Ma]=e,t.once?this.once(r,i):this.on(r,i)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[Ma]===e&&!t[Rn]){this.removeListener(r,t);break}}};kl.exports={CloseEvent:bi,ErrorEvent:Xi,Event:Or,EventTarget:Ty,MessageEvent:An};function $s(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var Fa=M((Qv,Pl)=>{"use strict";var{tokenChars:In}=zi();function fr(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function Cy(r){let e=Object.create(null),t=Object.create(null),i=!1,n=!1,s=!1,a,c,u=-1,d=-1,p=-1,m=0;for(;m<r.length;m++)if(d=r.charCodeAt(m),a===void 0)if(p===-1&&In[d]===1)u===-1&&(u=m);else if(m!==0&&(d===32||d===9))p===-1&&u!==-1&&(p=m);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let v=r.slice(u,p);d===44?(fr(e,v,t),t=Object.create(null)):a=v,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(c===void 0)if(p===-1&&In[d]===1)u===-1&&(u=m);else if(d===32||d===9)p===-1&&u!==-1&&(p=m);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m),fr(t,r.slice(u,p),!0),d===44&&(fr(e,a,t),t=Object.create(null),a=void 0),u=p=-1}else if(d===61&&u!==-1&&p===-1)c=r.slice(u,m),u=p=-1;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(n){if(In[d]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);u===-1?u=m:i||(i=!0),n=!1}else if(s)if(In[d]===1)u===-1&&(u=m);else if(d===34&&u!==-1)s=!1,p=m;else if(d===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(d===34&&r.charCodeAt(m-1)===61)s=!0;else if(p===-1&&In[d]===1)u===-1&&(u=m);else if(u!==-1&&(d===32||d===9))p===-1&&(p=m);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let v=r.slice(u,p);i&&(v=v.replace(/\\/g,""),i=!1),fr(t,c,v),d===44&&(fr(e,a,t),t=Object.create(null),a=void 0),c=void 0,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);if(u===-1||s||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=m);let _=r.slice(u,p);return a===void 0?fr(e,_,t):(c===void 0?fr(t,_,!0):i?fr(t,c,_.replace(/\\/g,"")):fr(t,c,_),fr(e,a,t)),e}function ky(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(i=>[e].concat(Object.keys(i).map(n=>{let s=i[n];return Array.isArray(s)||(s=[s]),s.map(a=>a===!0?n:`${n}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Pl.exports={format:ky,parse:Cy}});var Js=M((rw,Kl)=>{"use strict";var Oy=require("events"),Py=require("https"),Ry=require("http"),Il=require("net"),Ay=require("tls"),{randomBytes:Iy,createHash:Ly}=require("crypto"),{Duplex:ew,Readable:tw}=require("stream"),{URL:Da}=require("url"),Gr=Pn(),Ny=Aa(),My=Na(),{isBlob:Fy}=zi(),{BINARY_TYPES:Rl,EMPTY_BUFFER:Gs,GUID:Dy,kForOnEventAttribute:Ba,kListener:By,kStatusCode:jy,kWebSocket:ft,NOOP:Ll}=Cr(),{EventTarget:{addEventListener:Uy,removeEventListener:Ky}}=Ol(),{format:qy,parse:Wy}=Fa(),{toBuffer:Hy}=kn(),Vy=30*1e3,Nl=Symbol("kAborted"),ja=[8,13],Pr=["CONNECTING","OPEN","CLOSING","CLOSED"],zy=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ke=class r extends Oy{constructor(e,t,i){super(),this._binaryType=Rl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Gs,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(i=t,t=[]):t=[t]),Ml(this,e,t,i)):(this._autoPong=i.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Rl.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,i){let n=new Ny({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),s=new My(e,this._extensions,i.generateMask);this._receiver=n,this._sender=s,this._socket=e,n[ft]=this,s[ft]=this,e[ft]=this,n.on("conclude",Yy),n.on("drain",Xy),n.on("error",Jy),n.on("message",Zy),n.on("ping",Qy),n.on("pong",e_),s.onerror=t_,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Bl),e.on("data",Xs),e.on("end",jl),e.on("error",Ul),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Gr.extensionName]&&this._extensions[Gr.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Pt(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Dl(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,i){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=t=void 0):typeof t=="function"&&(i=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ua(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Gs,t,i)}pong(e,t,i){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=t=void 0):typeof t=="function"&&(i=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ua(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Gs,t,i)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,i){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(i=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ua(this,e,i);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Gr.extensionName]||(n.compress=!1),this._sender.send(e||Gs,n,i)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Pt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ke,"CONNECTING",{enumerable:!0,value:Pr.indexOf("CONNECTING")});Object.defineProperty(Ke.prototype,"CONNECTING",{enumerable:!0,value:Pr.indexOf("CONNECTING")});Object.defineProperty(Ke,"OPEN",{enumerable:!0,value:Pr.indexOf("OPEN")});Object.defineProperty(Ke.prototype,"OPEN",{enumerable:!0,value:Pr.indexOf("OPEN")});Object.defineProperty(Ke,"CLOSING",{enumerable:!0,value:Pr.indexOf("CLOSING")});Object.defineProperty(Ke.prototype,"CLOSING",{enumerable:!0,value:Pr.indexOf("CLOSING")});Object.defineProperty(Ke,"CLOSED",{enumerable:!0,value:Pr.indexOf("CLOSED")});Object.defineProperty(Ke.prototype,"CLOSED",{enumerable:!0,value:Pr.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(Ke.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(Ke.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Ba])return e[By];return null},set(e){for(let t of this.listeners(r))if(t[Ba]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[Ba]:!0})}})});Ke.prototype.addEventListener=Uy;Ke.prototype.removeEventListener=Ky;Kl.exports=Ke;function Ml(r,e,t,i){let n={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:ja[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=n.autoPong,!ja.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${ja.join(", ")})`);let s;if(e instanceof Da)s=e;else try{s=new Da(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),r._url=s.href;let a=s.protocol==="wss:",c=s.protocol==="ws+unix:",u;if(s.protocol!=="ws:"&&!a&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!s.pathname?u="The URL's pathname is empty":s.hash&&(u="The URL contains a fragment identifier"),u){let x=new SyntaxError(u);if(r._redirects===0)throw x;Ys(r,x);return}let d=a?443:80,p=Iy(16).toString("base64"),m=a?Py.request:Ry.request,_=new Set,v;if(n.createConnection=n.createConnection||(a?Gy:$y),n.defaultPort=n.defaultPort||d,n.port=s.port||d,n.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},n.path=s.pathname+s.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(v=new Gr(n.perMessageDeflate!==!0?n.perMessageDeflate:{},!1,n.maxPayload),n.headers["Sec-WebSocket-Extensions"]=qy({[Gr.extensionName]:v.offer()})),t.length){for(let x of t){if(typeof x!="string"||!zy.test(x)||_.has(x))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(x)}n.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(s.username||s.password)&&(n.auth=`${s.username}:${s.password}`),c){let x=n.path.split(":");n.socketPath=x[0],n.path=x[1]}let T;if(n.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=a,r._originalHostOrSocketPath=c?n.socketPath:s.host;let x=i&&i.headers;if(i={...i,headers:{}},x)for(let[H,oe]of Object.entries(x))i.headers[H.toLowerCase()]=oe}else if(r.listenerCount("redirect")===0){let x=c?r._originalIpc?n.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:s.host===r._originalHostOrSocketPath;(!x||r._originalSecure&&!a)&&(delete n.headers.authorization,delete n.headers.cookie,x||delete n.headers.host,n.auth=void 0)}n.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),T=r._req=m(n),r._redirects&&r.emit("redirect",r.url,T)}else T=r._req=m(n);n.timeout&&T.on("timeout",()=>{Pt(r,T,"Opening handshake has timed out")}),T.on("error",x=>{T===null||T[Nl]||(T=r._req=null,Ys(r,x))}),T.on("response",x=>{let H=x.headers.location,oe=x.statusCode;if(H&&n.followRedirects&&oe>=300&&oe<400){if(++r._redirects>n.maxRedirects){Pt(r,T,"Maximum redirects exceeded");return}T.abort();let J;try{J=new Da(H,e)}catch{let B=new SyntaxError(`Invalid URL: ${H}`);Ys(r,B);return}Ml(r,J,t,i)}else r.emit("unexpected-response",T,x)||Pt(r,T,`Unexpected server response: ${x.statusCode}`)}),T.on("upgrade",(x,H,oe)=>{if(r.emit("upgrade",x),r.readyState!==Ke.CONNECTING)return;T=r._req=null;let J=x.headers.upgrade;if(J===void 0||J.toLowerCase()!=="websocket"){Pt(r,H,"Invalid Upgrade header");return}let k=Ly("sha1").update(p+Dy).digest("base64");if(x.headers["sec-websocket-accept"]!==k){Pt(r,H,"Invalid Sec-WebSocket-Accept header");return}let B=x.headers["sec-websocket-protocol"],te;if(B!==void 0?_.size?_.has(B)||(te="Server sent an invalid subprotocol"):te="Server sent a subprotocol but none was requested":_.size&&(te="Server sent no subprotocol"),te){Pt(r,H,te);return}B&&(r._protocol=B);let j=x.headers["sec-websocket-extensions"];if(j!==void 0){if(!v){Pt(r,H,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let U;try{U=Wy(j)}catch{Pt(r,H,"Invalid Sec-WebSocket-Extensions header");return}let ne=Object.keys(U);if(ne.length!==1||ne[0]!==Gr.extensionName){Pt(r,H,"Server indicated an extension that was not requested");return}try{v.accept(U[Gr.extensionName])}catch{Pt(r,H,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Gr.extensionName]=v}r.setSocket(H,oe,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(T,r):T.end()}function Ys(r,e){r._readyState=Ke.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function $y(r){return r.path=r.socketPath,Il.connect(r)}function Gy(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Il.isIP(r.host)?"":r.host),Ay.connect(r)}function Pt(r,e,t){r._readyState=Ke.CLOSING;let i=new Error(t);Error.captureStackTrace(i,Pt),e.setHeader?(e[Nl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ys,r,i)):(e.destroy(i),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function Ua(r,e,t){if(e){let i=Fy(e)?e.size:Hy(e).length;r._socket?r._sender._bufferedBytes+=i:r._bufferedAmount+=i}if(t){let i=new Error(`WebSocket is not open: readyState ${r.readyState} (${Pr[r.readyState]})`);process.nextTick(t,i)}}function Yy(r,e){let t=this[ft];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[ft]!==void 0&&(t._socket.removeListener("data",Xs),process.nextTick(Fl,t._socket),r===1005?t.close():t.close(r,e))}function Xy(){let r=this[ft];r.isPaused||r._socket.resume()}function Jy(r){let e=this[ft];e._socket[ft]!==void 0&&(e._socket.removeListener("data",Xs),process.nextTick(Fl,e._socket),e.close(r[jy])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Al(){this[ft].emitClose()}function Zy(r,e){this[ft].emit("message",r,e)}function Qy(r){let e=this[ft];e._autoPong&&e.pong(r,!this._isServer,Ll),e.emit("ping",r)}function e_(r){this[ft].emit("pong",r)}function Fl(r){r.resume()}function t_(r){let e=this[ft];e.readyState!==Ke.CLOSED&&(e.readyState===Ke.OPEN&&(e._readyState=Ke.CLOSING,Dl(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Dl(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),Vy)}function Bl(){let r=this[ft];this.removeListener("close",Bl),this.removeListener("data",Xs),this.removeListener("end",jl),r._readyState=Ke.CLOSING;let e;!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&(e=r._socket.read())!==null&&r._receiver.write(e),r._receiver.end(),this[ft]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Al),r._receiver.on("finish",Al))}function Xs(r){this[ft]._receiver.write(r)||this.pause()}function jl(){let r=this[ft];r._readyState=Ke.CLOSING,r._receiver.end(),this.end()}function Ul(){let r=this[ft];this.removeListener("error",Ul),this.on("error",Ll),r&&(r._readyState=Ke.CLOSING,this.destroy())}});var Vl=M((nw,Hl)=>{"use strict";var iw=Js(),{Duplex:r_}=require("stream");function ql(r){r.emit("close")}function i_(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Wl(r){this.removeListener("error",Wl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function n_(r,e){let t=!0,i=new r_({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(s,a){let c=!a&&i._readableState.objectMode?s.toString():s;i.push(c)||r.pause()}),r.once("error",function(s){i.destroyed||(t=!1,i.destroy(s))}),r.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(n,s){if(r.readyState===r.CLOSED){s(n),process.nextTick(ql,i);return}let a=!1;r.once("error",function(u){a=!0,s(u)}),r.once("close",function(){a||s(n),process.nextTick(ql,i)}),t&&r.terminate()},i._final=function(n){if(r.readyState===r.CONNECTING){r.once("open",function(){i._final(n)});return}r._socket!==null&&(r._socket._writableState.finished?(n(),i._readableState.endEmitted&&i.destroy()):(r._socket.once("finish",function(){n()}),r.close()))},i._read=function(){r.isPaused&&r.resume()},i._write=function(n,s,a){if(r.readyState===r.CONNECTING){r.once("open",function(){i._write(n,s,a)});return}r.send(n,a)},i.on("end",i_),i.on("error",Wl),i}Hl.exports=n_});var $l=M((sw,zl)=>{"use strict";var{tokenChars:s_}=zi();function o_(r){let e=new Set,t=-1,i=-1,n=0;for(n;n<r.length;n++){let a=r.charCodeAt(n);if(i===-1&&s_[a]===1)t===-1&&(t=n);else if(n!==0&&(a===32||a===9))i===-1&&t!==-1&&(i=n);else if(a===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${n}`);i===-1&&(i=n);let c=r.slice(t,i);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),t=i=-1}else throw new SyntaxError(`Unexpected character at index ${n}`)}if(t===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let s=r.slice(t,n);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}zl.exports={parse:o_}});var eh=M((aw,Ql)=>{"use strict";var a_=require("events"),Zs=require("http"),{Duplex:ow}=require("stream"),{createHash:c_}=require("crypto"),Gl=Fa(),Ei=Pn(),f_=$l(),u_=Js(),{GUID:l_,kWebSocket:h_}=Cr(),d_=/^[+/0-9A-Za-z]{22}==$/,Yl=0,Xl=1,Zl=2,Ka=class extends a_{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:u_,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Zs.createServer((i,n)=>{let s=Zs.STATUS_CODES[426];n.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),n.end(s)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=p_(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(n,s,a)=>{this.handleUpgrade(n,s,a,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Yl}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Zl){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Ln,this);return}if(e&&this.once("close",e),this._state!==Xl)if(this._state=Xl,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Ln,this):process.nextTick(Ln,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Ln(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,i,n){t.on("error",Jl);let s=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){vi(this,e,t,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){vi(this,e,t,400,"Invalid Upgrade header");return}if(s===void 0||!d_.test(s)){vi(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){vi(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Nn(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=f_.parse(u)}catch{vi(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],m={};if(this.options.perMessageDeflate&&p!==void 0){let _=new Ei(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let v=Gl.parse(p);v[Ei.extensionName]&&(_.accept(v[Ei.extensionName]),m[Ei.extensionName]=_)}catch{vi(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let _={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(_,(v,T,x,H)=>{if(!v)return Nn(t,T||401,x,H);this.completeUpgrade(m,s,d,e,t,i,n)});return}if(!this.options.verifyClient(_))return Nn(t,401)}this.completeUpgrade(m,s,d,e,t,i,n)}completeUpgrade(e,t,i,n,s,a,c){if(!s.readable||!s.writable)return s.destroy();if(s[h_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Yl)return Nn(s,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${c_("sha1").update(t+l_).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(i.size){let m=this.options.handleProtocols?this.options.handleProtocols(i,n):i.values().next().value;m&&(d.push(`Sec-WebSocket-Protocol: ${m}`),p._protocol=m)}if(e[Ei.extensionName]){let m=e[Ei.extensionName].params,_=Gl.format({[Ei.extensionName]:[m]});d.push(`Sec-WebSocket-Extensions: ${_}`),p._extensions=e}this.emit("headers",d,n),s.write(d.concat(`\r
|
|
23
23
|
`).join(`\r
|
|
24
24
|
`)),s.removeListener("error",Jl),p.setSocket(s,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on("close",()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Ln,this)})),c(p,n)}};Ql.exports=Ka;function p_(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let i of Object.keys(e))r.removeListener(i,e[i])}}function Ln(r){r._state=Zl,r.emit("close")}function Jl(){this.destroy()}function Nn(r,e,t,i){t=t||Zs.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...i},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${Zs.STATUS_CODES[e]}\r
|
|
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 Nn(t,i,n,s)}});var rh=M((cw,th)=>{"use strict";var Rr=Js();Rr.createWebSocketStream=Vl();Rr.Server=eh();Rr.Receiver=Aa();Rr.Sender=Na();Rr.WebSocket=Rr;Rr.WebSocketServer=Rr.Server;th.exports=Rr});var Va=M(Yr=>{"use strict";var g_=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 m_=Cn(),ih=gi(),y_=Bi(),Wa=pi(),__=g_(Ft()),v_=(0,__.default)("engine.io-client:websocket"),nh=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Qs=class extends m_.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,i=nh?{}:(0,ih.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,y_.encodePacket)(i,this.supportsBinary,s=>{try{this.doWrite(i,s)}catch{v_("websocket closed before onclose event")}n&&(0,Wa.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,ih.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}};Yr.BaseWS=Qs;var qa=Wa.globalThisShim.WebSocket||Wa.globalThisShim.MozWebSocket,Ha=class extends Qs{createSocket(e,t,i){return nh?new qa(e,t,i):t?new qa(e,t):new qa(e)}doWrite(e,t){this.ws.send(t)}};Yr.WS=Ha});var $a=M(ur=>{"use strict";var b_=ur&&ur.__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]})),E_=ur&&ur.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),w_=ur&&ur.__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)&&b_(e,r,t);return E_(e,r),e};Object.defineProperty(ur,"__esModule",{value:!0});ur.WS=void 0;var x_=w_(rh()),S_=Va(),za=class extends S_.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 x_.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)}};ur.WS=za});var Ya=M(Ji=>{"use strict";var T_=Ji&&Ji.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ji,"__esModule",{value:!0});Ji.WT=void 0;var C_=Cn(),k_=pi(),sh=Bi(),O_=T_(Ft()),Mn=(0,O_.default)("engine.io-client:webtransport"),Ga=class extends C_.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(()=>{Mn("transport closed gracefully"),this.onClose()}).catch(e=>{Mn("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=(0,sh.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),n=(0,sh.createPacketEncoderStream)();n.readable.pipeTo(e.writable),this._writer=n.writable.getWriter();let s=()=>{i.read().then(({done:c,value:u})=>{if(c){Mn("session is closed");return}Mn("received chunk: %o",u),this.onPacket(u),s()}).catch(c=>{Mn("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,k_.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};Ji.WT=Ga});var Xa=M(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});eo.transports=void 0;var P_=ba(),R_=$a(),A_=Ya();eo.transports={websocket:R_.WS,webtransport:A_.WT,polling:P_.XHR}});var Za=M(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.parse=N_;var I_=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,L_=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function N_(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=I_.exec(r||""),s={},a=14;for(;a--;)s[L_[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=M_(s,s.path),s.queryKey=F_(s,s.query),s}function M_(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 F_(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(i,n,s){n&&(t[n]=s)}),t}});var rc=M(lr=>{"use strict";var D_=lr&&lr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(lr,"__esModule",{value:!0});lr.Socket=lr.SocketWithUpgrade=lr.SocketWithoutUpgrade=void 0;var B_=Xa(),oh=gi(),j_=ca(),ah=Za(),U_=di(),ch=Bi(),Qa=pi(),K_=D_(Ft()),De=(0,K_.default)("engine.io-client:socket"),ec=typeof addEventListener=="function"&&typeof removeEventListener=="function",Fn=[];ec&&addEventListener("offline",()=>{De("closing %d connection(s) because the network was lost",Fn.length),Fn.forEach(r=>r())},!1);var wi=class r extends U_.Emitter{constructor(e,t){if(super(),this.binaryType=Qa.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,ah.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,ah.parse)(t.host).host);(0,oh.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,j_.decode)(this.opts.query)),ec&&(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"})},Fn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Qa.createCookieJar)()),this._open()}createTransport(e){De('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=ch.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,oh.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,Qa.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(),ec&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let i=Fn.indexOf(this._offlineEventListener);i!==-1&&(De("removing listener for the 'offline' event"),Fn.splice(i,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};lr.SocketWithoutUpgrade=wi;wi.protocol=ch.protocol;var to=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}};lr.SocketWithUpgrade=to;var tc=class extends to{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=>B_.transports[n]).filter(n=>!!n)),super(e,i)}};lr.Socket=tc});var fh=M(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.Fetch=void 0;var q_=ga(),ic=class extends q_.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})}};ro.Fetch=ic});var io=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 uh=rc();Object.defineProperty(Oe,"Socket",{enumerable:!0,get:function(){return uh.Socket}});var lh=rc();Object.defineProperty(Oe,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return lh.SocketWithoutUpgrade}});Object.defineProperty(Oe,"SocketWithUpgrade",{enumerable:!0,get:function(){return lh.SocketWithUpgrade}});Oe.protocol=uh.Socket.protocol;var hh=Cn();Object.defineProperty(Oe,"Transport",{enumerable:!0,get:function(){return hh.Transport}});Object.defineProperty(Oe,"TransportError",{enumerable:!0,get:function(){return hh.TransportError}});var W_=Xa();Object.defineProperty(Oe,"transports",{enumerable:!0,get:function(){return W_.transports}});var H_=gi();Object.defineProperty(Oe,"installTimerFunctions",{enumerable:!0,get:function(){return H_.installTimerFunctions}});var V_=Za();Object.defineProperty(Oe,"parse",{enumerable:!0,get:function(){return V_.parse}});var z_=pi();Object.defineProperty(Oe,"nextTick",{enumerable:!0,get:function(){return z_.nextTick}});var $_=fh();Object.defineProperty(Oe,"Fetch",{enumerable:!0,get:function(){return $_.Fetch}});var G_=ba();Object.defineProperty(Oe,"NodeXHR",{enumerable:!0,get:function(){return G_.XHR}});var Y_=_a();Object.defineProperty(Oe,"XHR",{enumerable:!0,get:function(){return Y_.XHR}});var X_=$a();Object.defineProperty(Oe,"NodeWebSocket",{enumerable:!0,get:function(){return X_.WS}});var J_=Va();Object.defineProperty(Oe,"WebSocket",{enumerable:!0,get:function(){return J_.WS}});var Z_=Ya();Object.defineProperty(Oe,"WebTransport",{enumerable:!0,get:function(){return Z_.WT}})});var ph=M(Dn=>{"use strict";var Q_=Dn&&Dn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Dn,"__esModule",{value:!0});Dn.url=r0;var e0=io(),t0=Q_(Ft()),dh=(0,t0.default)("socket.io-client:url");function r0(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)||(dh("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),dh("parse %s",r),i=(0,e0.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 nc=M(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.isBinary=mh;so.hasBinary=no;var i0=typeof ArrayBuffer=="function",n0=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,gh=Object.prototype.toString,s0=typeof Blob=="function"||typeof Blob<"u"&&gh.call(Blob)==="[object BlobConstructor]",o0=typeof File=="function"||typeof File<"u"&&gh.call(File)==="[object FileConstructor]";function mh(r){return i0&&(r instanceof ArrayBuffer||n0(r))||s0&&r instanceof Blob||o0&&r instanceof File}function no(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,i=r.length;t<i;t++)if(no(r[t]))return!0;return!1}if(mh(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return no(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&no(r[t]))return!0;return!1}});var yh=M(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.deconstructPacket=c0;oo.reconstructPacket=f0;var a0=nc();function c0(r){let e=[],t=r.data,i=r;return i.data=sc(t,e),i.attachments=e.length,{packet:i,buffers:e}}function sc(r,e){if(!r)return r;if((0,a0.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]=sc(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]=sc(r[i],e));return t}return r}function f0(r,e){return r.data=oc(r.data,e),delete r.attachments,r}function oc(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]=oc(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=oc(r[t],e));return r}});var co=M(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.Decoder=zt.Encoder=zt.PacketType=zt.protocol=void 0;zt.isPacketValid=m0;var u0=di(),_h=yh(),vh=nc(),l0=Ft(),ac=(0,l0.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 cc=class{constructor(e){this.replacer=e}encode(e){return ac("encoding packet %j",e),(e.type===Fe.EVENT||e.type===Fe.ACK)&&(0,vh.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)),ac("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,_h.deconstructPacket)(e),i=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(i),n}};zt.Encoder=cc;var fc=class r extends u0.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 uc(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,vh.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 ac("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 ao(t);case Fe.DISCONNECT:return t===void 0;case Fe.CONNECT_ERROR:return typeof t=="string"||ao(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=fc;var uc=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,_h.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function h0(r){return typeof r=="string"}var d0=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function p0(r){return r===void 0||d0(r)}function ao(r){return Object.prototype.toString.call(r)==="[object Object]"}function g0(r,e){switch(r){case Fe.CONNECT:return e===void 0||ao(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"||ao(e);default:return!1}}function m0(r){return h0(r.nsp)&&p0(r.id)&&g0(r.type,r.data)}});var hc=M(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});lc.on=y0;function y0(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var pc=M(Zi=>{"use strict";var _0=Zi&&Zi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Zi,"__esModule",{value:!0});Zi.Socket=void 0;var $t=co(),fo=hc(),v0=di(),b0=_0(Ft()),et=(0,b0.default)("socket.io-client:socket"),E0=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),dc=class extends v0.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,fo.on)(e,"open",this.onopen.bind(this)),(0,fo.on)(e,"packet",this.onpacket.bind(this)),(0,fo.on)(e,"error",this.onerror.bind(this)),(0,fo.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(E0.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)}}};Zi.Socket=dc});var Eh=M(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});gc.Backoff=Qi;function Qi(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}Qi.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};Qi.prototype.reset=function(){this.attempts=0};Qi.prototype.setMin=function(r){this.ms=r};Qi.prototype.setMax=function(r){this.max=r};Qi.prototype.setJitter=function(r){this.jitter=r}});var wh=M(jt=>{"use strict";var w0=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]})),x0=jt&&jt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),S0=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)&&w0(e,r,t);return x0(e,r),e},T0=jt&&jt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(jt,"__esModule",{value:!0});jt.Manager=void 0;var mc=io(),C0=pc(),k0=S0(co()),xi=hc(),O0=Eh(),P0=di(),R0=T0(Ft()),ft=(0,R0.default)("socket.io-client:manager"),yc=class extends P0.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,mc.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 O0.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||k0;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 mc.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,mc.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 C0.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=yc});var Ch=M((Be,Th)=>{"use strict";var A0=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 I0=ph(),uo=wh();Object.defineProperty(Be,"Manager",{enumerable:!0,get:function(){return uo.Manager}});var Sh=pc();Object.defineProperty(Be,"Socket",{enumerable:!0,get:function(){return Sh.Socket}});var L0=A0(Ft()),xh=(0,L0.default)("socket.io-client"),Bn={};function Si(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,I0.url)(r,e.path||"/socket.io"),i=t.source,n=t.id,s=t.path,a=Bn[n]&&s in Bn[n].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||a,u;return c?(xh("ignoring socket cache for %s",i),u=new uo.Manager(i,e)):(Bn[n]||(xh("new io instance for %s",i),Bn[n]=new uo.Manager(i,e)),u=Bn[n]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(Si,{Manager:uo.Manager,Socket:Sh.Socket,io:Si,connect:Si});var N0=co();Object.defineProperty(Be,"protocol",{enumerable:!0,get:function(){return N0.protocol}});var en=io();Object.defineProperty(Be,"Fetch",{enumerable:!0,get:function(){return en.Fetch}});Object.defineProperty(Be,"NodeXHR",{enumerable:!0,get:function(){return en.NodeXHR}});Object.defineProperty(Be,"XHR",{enumerable:!0,get:function(){return en.XHR}});Object.defineProperty(Be,"NodeWebSocket",{enumerable:!0,get:function(){return en.NodeWebSocket}});Object.defineProperty(Be,"WebSocket",{enumerable:!0,get:function(){return en.WebSocket}});Object.defineProperty(Be,"WebTransport",{enumerable:!0,get:function(){return en.WebTransport}});Th.exports=Si});var vc=M(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.InputStreamReceiver=void 0;var M0=64,F0=30,D0=4,B0=256,j0=16,_c=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??M0),this.ackThrottleMs=Math.max(0,i.ackThrottleMs??F0)}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*D0,B0);e-this.lastAppliedSeq>n||this.maybeResend(this.lastAppliedSeq+1)}maybeResend(e){if(e===this.lastResendFrom){if(++this.resendSuppressed<j0)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)}};lo.InputStreamReceiver=_c});var Rh=M(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.WebSocketService=void 0;var U0=Ch(),kh=Sr(),Oh=us(),Ph=as(),K0=vc(),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,Oh.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([...kh.DEFAULT_CLIENT_CAPABILITIES,...this.extraCapabilities]));this.socket=(0,U0.io)(`${t}/agent`,{auth:{token:e,protocolVersion:kh.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,Ph.generateCorrelationId)(),n=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:i}:t;return(0,Ph.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 K0.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,Oh.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)}};ho.WebSocketService=bc});var Lh=M(Gt=>{"use strict";var q0=Gt&&Gt.__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]})),W0=Gt&&Gt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),wc=Gt&&Gt.__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"&&q0(t,e,i[n]);return W0(t,e),t}})();Object.defineProperty(Gt,"__esModule",{value:!0});Gt.FileTransferService=void 0;Gt.resolveUploadPath=Ih;var po=wc(require("fs")),Ti=wc(require("path")),Ah=wc(require("crypto")),je=Sr();function Ih(r,e,t){let i=Ti.basename(t),n=(e??"").trim()||".";if(Ti.isAbsolute(n))return Ti.resolve(n,i);let s=Ti.resolve(r,n),a=s===r||s.startsWith(r+Ti.sep)?s:r;return Ti.resolve(a,i)}var Ec=class{socket=null;activeTransfers=new Map;instanceId="";logger;fallbackDir;workspaceRoot=null;cryptoService=null;constructor(e,t="/tmp",i=null){this.logger=e,this.fallbackDir=t,this.workspaceRoot=i}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=po.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=Ah.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=Ti.dirname(e.filePath);po.existsSync(n)||po.mkdirSync(n,{recursive:!0}),po.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 i=Ih(this.workspaceRoot??this.fallbackDir,e.targetPath,e.filename);this.receiveFile(e.transferId,e.terminalId,e.filename,e.size,e.totalChunks,e.checksum,i,e.checksumAlgorithm||"sha256").then(()=>t({accepted:!0})).catch(n=>t({accepted:!1,error:n.message}))}calculateChecksum(e,t="sha256"){return t==="fnv1a"?this.fnv1aHash(e):Ah.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"}};Gt.FileTransferService=Ec});var Pc=M((Ow,yo)=>{function Fh(r){return Array.isArray(r)?r:[r]}var H0=void 0,Sc="",Nh=" ",xc="\\",V0=/^\s+$/,z0=/(?:[^\\]|^)\\$/,$0=/^\\!/,G0=/^\\#/,Y0=/\r?\n/g,X0=/^\.{0,2}\/|^\.{1,2}$/,J0=/\/$/,tn="/",Dh="node-ignore";typeof Symbol<"u"&&(Dh=Symbol.for("node-ignore"));var Bh=Dh,rn=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),Z0=/([0-z])-([0-z])/g,jh=()=>!1,Q0=r=>r.replace(Z0,(e,t,i)=>t.charCodeAt(0)<=i.charCodeAt(0)?e:Sc),ev=r=>{let{length:e}=r;return r.slice(0,e-e%2)},tv=[[/^\uFEFF/,()=>Sc],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?Nh:Sc)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+Nh}],[/[\\$.|*+(){^]/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,()=>xc],[/\\\\/g,()=>xc],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,i,n)=>e===xc?`\\[${t}${ev(i)}${n}`:n==="]"&&i.length%2===0?`[${Q0(t)}${i}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],rv=/(^|\\\/)?\\\*$/,jn="regex",go="checkRegex",Mh="_",iv={[jn](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[go](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},nv=r=>tv.reduce((e,[t,i])=>e.replace(t,i.bind(r)),r),mo=r=>typeof r=="string",sv=r=>r&&mo(r)&&!V0.test(r)&&!z0.test(r)&&r.indexOf("#")!==0,ov=r=>r.split(Y0).filter(Boolean),Tc=class{constructor(e,t,i,n,s,a){this.pattern=e,this.mark=t,this.negative=s,rn(this,"body",i),rn(this,"ignoreCase",n),rn(this,"regexPrefix",a)}get regex(){let e=Mh+jn;return this[e]?this[e]:this._make(jn,e)}get checkRegex(){let e=Mh+go;return this[e]?this[e]:this._make(go,e)}_make(e,t){let i=this.regexPrefix.replace(rv,iv[e]),n=this.ignoreCase?new RegExp(i,"i"):new RegExp(i);return rn(this,t,n)}},av=({pattern:r,mark:e},t)=>{let i=!1,n=r;n.indexOf("!")===0&&(i=!0,n=n.substr(1)),n=n.replace($0,"!").replace(G0,"#");let s=nv(n);return new Tc(r,e,n,t,i,s)},Cc=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[Bh]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(mo(e)&&(e={pattern:e}),sv(e.pattern)){let t=av(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,Fh(mo(e)?ov(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?H0:u)});let c={ignored:n,unignored:s};return a&&(c.rule=a),c}},cv=(r,e)=>{throw new e(r)},Ar=(r,e,t)=>mo(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),Uh=r=>X0.test(r);Ar.isNotRelative=Uh;Ar.convert=r=>r;var kc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:i=!1}={}){rn(this,Bh,!0),this._rules=new Cc(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?cv:jh),this._t(s,t,i,n)}checkIgnore(e){if(!J0.test(e))return this.test(e);let t=e.split(tn).filter(Boolean);if(t.pop(),t.length){let i=this._t(t.join(tn)+tn,this._testCache,!0,t);if(i.ignored)return i}return this._rules.test(e,!1,go)}_t(e,t,i,n){if(e in t)return t[e];if(n||(n=e.split(tn).filter(Boolean)),n.pop(),!n.length)return t[e]=this._rules.test(e,i,jn);let s=this._t(n.join(tn)+tn,t,i,n);return t[e]=s.ignored?s:this._rules.test(e,i,jn)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return Fh(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},Oc=r=>new kc(r),fv=r=>Ar(r&&Ar.convert(r),r,jh),Kh=()=>{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)||Uh(t)};typeof process<"u"&&process.platform==="win32"&&Kh();yo.exports=Oc;Oc.default=Oc;yo.exports.isPathValid=fv;rn(yo.exports,Symbol.for("setupWindows"),Kh)});var Wh=M(Ut=>{"use strict";var uv=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]})),lv=Ut&&Ut.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),qh=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"&&uv(t,e,i[n]);return lv(t,e),t}})(),hv=Ut&&Ut.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ut,"__esModule",{value:!0});Ut.FileListService=void 0;var nn=qh(require("path")),Rc=qh(require("fs/promises")),dv=hv(Pc()),Ac=Sr(),pv=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],Ic=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,dv.default)(),this.ignoreFilter.add(pv),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=nn.join(this.workspaceRoot,".gitignore");try{let t=await Rc.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 Rc.readdir(e,{withFileTypes:!0}),n=[];for(let s of i){let a=t==="."||t===""?s.name:nn.join(t,s.name);if(this.shouldHide(a,s.isDirectory()))continue;let c=nn.join(e,s.name),u={name:s.name,path:a,type:s.isDirectory()?Ac.FileEntryType.DIRECTORY:Ac.FileEntryType.FILE};if(!s.isDirectory())try{let d=await Rc.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===Ac.FileEntryType.DIRECTORY?-1:1:s.name.localeCompare(a.name))}shouldHide(e,t){let i=e.split(nn.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=nn.resolve(this.workspaceRoot,e);if(t!==this.workspaceRoot&&!t.startsWith(this.workspaceRoot+nn.sep))throw new Error("Path outside workspace");return t}sendResponse(e){this.onResponseCallback?.(e)}dispose(){this.onResponseCallback=null}};Ut.FileListService=Ic});var Vh=M(hr=>{"use strict";var gv=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]})),mv=hr&&hr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Hh=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"&&gv(t,e,i[n]);return mv(t,e),t}})();Object.defineProperty(hr,"__esModule",{value:!0});hr.FileTrackerService=void 0;var Lc=Hh(require("path")),Ci=Hh(require("fs/promises")),yv=require("child_process"),_v=require("util"),Yt=Sr(),Nc=(0,_v.promisify)(yv.execFile),Mc={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},Fc=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(Mc.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(Mc.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(Mc.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 Ci.readFile(a,"utf-8")}catch{u=void 0}let d={path:s,changeType:u===void 0?Yt.FileChangeType.CREATE:Yt.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 Ci.stat(u);c.size=p.size}catch{c.changeType=Yt.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 Ci.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===Yt.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===Yt.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 Ci.stat(t),s=await Ci.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:Yt.FileViewType.CONTENT,content:c,language:(0,Yt.getLanguageFromPath)(e.path),size:n.size,truncated:a}}async getFileDiff(e,t,i){let n=t.diffBase||Yt.DiffBase.GIT,s;return n===Yt.DiffBase.GIT?s=await this.getGitDiff(i):s=await this.getPreviousDiff(e,t.path,i),{requestId:t.requestId,path:t.path,type:Yt.FileViewType.DIFF,content:s,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await Nc("git",["diff","--cached","--",e],{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:i}=await Nc("git",["diff","--",e],{cwd:this.workspaceRoot});if(i.trim())return i;let{stdout:n}=await Nc("git",["status","--porcelain","--",e],{cwd:this.workspaceRoot});if(n.startsWith("??")||n.startsWith("A ")){let a=(await Ci.readFile(e,"utf-8")).split(`
|
|
28
|
+
`+t)}function vi(r,e,t,i,n,s){if(r.listenerCount("wsClientError")){let a=new Error(n);Error.captureStackTrace(a,vi),r.emit("wsClientError",a,t,e)}else Nn(t,i,n,s)}});var rh=M((cw,th)=>{"use strict";var Rr=Js();Rr.createWebSocketStream=Vl();Rr.Server=eh();Rr.Receiver=Aa();Rr.Sender=Na();Rr.WebSocket=Rr;Rr.WebSocketServer=Rr.Server;th.exports=Rr});var Va=M(Yr=>{"use strict";var g_=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 m_=Cn(),ih=gi(),y_=Bi(),Wa=pi(),__=g_(Ft()),b_=(0,__.default)("engine.io-client:websocket"),nh=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Qs=class extends m_.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,i=nh?{}:(0,ih.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,y_.encodePacket)(i,this.supportsBinary,s=>{try{this.doWrite(i,s)}catch{b_("websocket closed before onclose event")}n&&(0,Wa.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,ih.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}};Yr.BaseWS=Qs;var qa=Wa.globalThisShim.WebSocket||Wa.globalThisShim.MozWebSocket,Ha=class extends Qs{createSocket(e,t,i){return nh?new qa(e,t,i):t?new qa(e,t):new qa(e)}doWrite(e,t){this.ws.send(t)}};Yr.WS=Ha});var $a=M(ur=>{"use strict";var E_=ur&&ur.__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]})),v_=ur&&ur.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),w_=ur&&ur.__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_(e,r,t);return v_(e,r),e};Object.defineProperty(ur,"__esModule",{value:!0});ur.WS=void 0;var S_=w_(rh()),x_=Va(),za=class extends x_.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 S_.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)}};ur.WS=za});var Ya=M(Ji=>{"use strict";var T_=Ji&&Ji.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ji,"__esModule",{value:!0});Ji.WT=void 0;var C_=Cn(),k_=pi(),sh=Bi(),O_=T_(Ft()),Mn=(0,O_.default)("engine.io-client:webtransport"),Ga=class extends C_.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(()=>{Mn("transport closed gracefully"),this.onClose()}).catch(e=>{Mn("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=(0,sh.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),n=(0,sh.createPacketEncoderStream)();n.readable.pipeTo(e.writable),this._writer=n.writable.getWriter();let s=()=>{i.read().then(({done:c,value:u})=>{if(c){Mn("session is closed");return}Mn("received chunk: %o",u),this.onPacket(u),s()}).catch(c=>{Mn("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,k_.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};Ji.WT=Ga});var Xa=M(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});eo.transports=void 0;var P_=Ea(),R_=$a(),A_=Ya();eo.transports={websocket:R_.WS,webtransport:A_.WT,polling:P_.XHR}});var Za=M(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.parse=N_;var I_=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,L_=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function N_(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=I_.exec(r||""),s={},a=14;for(;a--;)s[L_[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=M_(s,s.path),s.queryKey=F_(s,s.query),s}function M_(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 F_(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(i,n,s){n&&(t[n]=s)}),t}});var rc=M(lr=>{"use strict";var D_=lr&&lr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(lr,"__esModule",{value:!0});lr.Socket=lr.SocketWithUpgrade=lr.SocketWithoutUpgrade=void 0;var B_=Xa(),oh=gi(),j_=ca(),ah=Za(),U_=di(),ch=Bi(),Qa=pi(),K_=D_(Ft()),De=(0,K_.default)("engine.io-client:socket"),ec=typeof addEventListener=="function"&&typeof removeEventListener=="function",Fn=[];ec&&addEventListener("offline",()=>{De("closing %d connection(s) because the network was lost",Fn.length),Fn.forEach(r=>r())},!1);var wi=class r extends U_.Emitter{constructor(e,t){if(super(),this.binaryType=Qa.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,ah.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,ah.parse)(t.host).host);(0,oh.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,j_.decode)(this.opts.query)),ec&&(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"})},Fn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Qa.createCookieJar)()),this._open()}createTransport(e){De('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=ch.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,oh.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,Qa.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(),ec&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let i=Fn.indexOf(this._offlineEventListener);i!==-1&&(De("removing listener for the 'offline' event"),Fn.splice(i,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};lr.SocketWithoutUpgrade=wi;wi.protocol=ch.protocol;var to=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}};lr.SocketWithUpgrade=to;var tc=class extends to{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=>B_.transports[n]).filter(n=>!!n)),super(e,i)}};lr.Socket=tc});var fh=M(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.Fetch=void 0;var q_=ga(),ic=class extends q_.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})}};ro.Fetch=ic});var io=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 uh=rc();Object.defineProperty(Oe,"Socket",{enumerable:!0,get:function(){return uh.Socket}});var lh=rc();Object.defineProperty(Oe,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return lh.SocketWithoutUpgrade}});Object.defineProperty(Oe,"SocketWithUpgrade",{enumerable:!0,get:function(){return lh.SocketWithUpgrade}});Oe.protocol=uh.Socket.protocol;var hh=Cn();Object.defineProperty(Oe,"Transport",{enumerable:!0,get:function(){return hh.Transport}});Object.defineProperty(Oe,"TransportError",{enumerable:!0,get:function(){return hh.TransportError}});var W_=Xa();Object.defineProperty(Oe,"transports",{enumerable:!0,get:function(){return W_.transports}});var H_=gi();Object.defineProperty(Oe,"installTimerFunctions",{enumerable:!0,get:function(){return H_.installTimerFunctions}});var V_=Za();Object.defineProperty(Oe,"parse",{enumerable:!0,get:function(){return V_.parse}});var z_=pi();Object.defineProperty(Oe,"nextTick",{enumerable:!0,get:function(){return z_.nextTick}});var $_=fh();Object.defineProperty(Oe,"Fetch",{enumerable:!0,get:function(){return $_.Fetch}});var G_=Ea();Object.defineProperty(Oe,"NodeXHR",{enumerable:!0,get:function(){return G_.XHR}});var Y_=_a();Object.defineProperty(Oe,"XHR",{enumerable:!0,get:function(){return Y_.XHR}});var X_=$a();Object.defineProperty(Oe,"NodeWebSocket",{enumerable:!0,get:function(){return X_.WS}});var J_=Va();Object.defineProperty(Oe,"WebSocket",{enumerable:!0,get:function(){return J_.WS}});var Z_=Ya();Object.defineProperty(Oe,"WebTransport",{enumerable:!0,get:function(){return Z_.WT}})});var ph=M(Dn=>{"use strict";var Q_=Dn&&Dn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Dn,"__esModule",{value:!0});Dn.url=r0;var e0=io(),t0=Q_(Ft()),dh=(0,t0.default)("socket.io-client:url");function r0(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)||(dh("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),dh("parse %s",r),i=(0,e0.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 nc=M(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.isBinary=mh;so.hasBinary=no;var i0=typeof ArrayBuffer=="function",n0=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,gh=Object.prototype.toString,s0=typeof Blob=="function"||typeof Blob<"u"&&gh.call(Blob)==="[object BlobConstructor]",o0=typeof File=="function"||typeof File<"u"&&gh.call(File)==="[object FileConstructor]";function mh(r){return i0&&(r instanceof ArrayBuffer||n0(r))||s0&&r instanceof Blob||o0&&r instanceof File}function no(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,i=r.length;t<i;t++)if(no(r[t]))return!0;return!1}if(mh(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return no(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&no(r[t]))return!0;return!1}});var yh=M(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.deconstructPacket=c0;oo.reconstructPacket=f0;var a0=nc();function c0(r){let e=[],t=r.data,i=r;return i.data=sc(t,e),i.attachments=e.length,{packet:i,buffers:e}}function sc(r,e){if(!r)return r;if((0,a0.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]=sc(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]=sc(r[i],e));return t}return r}function f0(r,e){return r.data=oc(r.data,e),delete r.attachments,r}function oc(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]=oc(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=oc(r[t],e));return r}});var co=M(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.Decoder=zt.Encoder=zt.PacketType=zt.protocol=void 0;zt.isPacketValid=m0;var u0=di(),_h=yh(),bh=nc(),l0=Ft(),ac=(0,l0.default)("socket.io-parser"),Eh=["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 cc=class{constructor(e){this.replacer=e}encode(e){return ac("encoding packet %j",e),(e.type===Fe.EVENT||e.type===Fe.ACK)&&(0,bh.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)),ac("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,_h.deconstructPacket)(e),i=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(i),n}};zt.Encoder=cc;var fc=class r extends u0.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 uc(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,bh.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 ac("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 ao(t);case Fe.DISCONNECT:return t===void 0;case Fe.CONNECT_ERROR:return typeof t=="string"||ao(t);case Fe.EVENT:case Fe.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Eh.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=fc;var uc=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,_h.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function h0(r){return typeof r=="string"}var d0=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function p0(r){return r===void 0||d0(r)}function ao(r){return Object.prototype.toString.call(r)==="[object Object]"}function g0(r,e){switch(r){case Fe.CONNECT:return e===void 0||ao(e);case Fe.DISCONNECT:return e===void 0;case Fe.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Eh.indexOf(e[0])===-1);case Fe.ACK:return Array.isArray(e);case Fe.CONNECT_ERROR:return typeof e=="string"||ao(e);default:return!1}}function m0(r){return h0(r.nsp)&&p0(r.id)&&g0(r.type,r.data)}});var hc=M(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});lc.on=y0;function y0(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var pc=M(Zi=>{"use strict";var _0=Zi&&Zi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Zi,"__esModule",{value:!0});Zi.Socket=void 0;var $t=co(),fo=hc(),b0=di(),E0=_0(Ft()),tt=(0,E0.default)("socket.io-client:socket"),v0=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),dc=class extends b0.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,fo.on)(e,"open",this.onopen.bind(this)),(0,fo.on)(e,"packet",this.onpacket.bind(this)),(0,fo.on)(e,"error",this.onerror.bind(this)),(0,fo.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(v0.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++;tt("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?tt("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&&(tt("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));tt("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]?tt("packet [%d] already acknowledged",i.id):(n!==null?i.tryCount>this._opts.retries&&(tt("packet [%d] is discarded after %d tries",i.id,i.tryCount),this._queue.shift(),t&&t(n)):(tt("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(tt("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){tt("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,tt("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(){tt("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){tt("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||[];tt("emitting event %j",t),e.id!=null&&(tt("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,tt("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"){tt("bad ack %s",e.id);return}delete this.acks[e.id],tt("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){tt("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(){tt("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&&(tt("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)}}};Zi.Socket=dc});var vh=M(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});gc.Backoff=Qi;function Qi(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}Qi.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};Qi.prototype.reset=function(){this.attempts=0};Qi.prototype.setMin=function(r){this.ms=r};Qi.prototype.setMax=function(r){this.max=r};Qi.prototype.setJitter=function(r){this.jitter=r}});var wh=M(jt=>{"use strict";var w0=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]})),S0=jt&&jt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),x0=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)&&w0(e,r,t);return S0(e,r),e},T0=jt&&jt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(jt,"__esModule",{value:!0});jt.Manager=void 0;var mc=io(),C0=pc(),k0=x0(co()),Si=hc(),O0=vh(),P0=di(),R0=T0(Ft()),ut=(0,R0.default)("socket.io-client:manager"),yc=class extends P0.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,mc.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 O0.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||k0;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(ut("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;ut("opening %s",this.uri),this.engine=new mc.Socket(this.uri,this.opts);let t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;let n=(0,Si.on)(t,"open",function(){i.onopen(),e&&e()}),s=c=>{ut("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,Si.on)(t,"error",s);if(this._timeout!==!1){let c=this._timeout;ut("connect attempt will timeout after %d",c);let u=this.setTimeoutFn(()=>{ut("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(){ut("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,Si.on)(e,"ping",this.onping.bind(this)),(0,Si.on)(e,"data",this.ondata.bind(this)),(0,Si.on)(e,"error",this.onerror.bind(this)),(0,Si.on)(e,"close",this.onclose.bind(this)),(0,Si.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,mc.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){ut("error",e),this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new C0.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){ut("socket %s is still active, skipping close",i);return}this._close()}_packet(e){ut("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(){ut("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){ut("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var i;ut("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)ut("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();ut("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let i=this.setTimeoutFn(()=>{e.skipReconnect||(ut("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(n=>{n?(ut("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",n)):(ut("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=yc});var Ch=M((Be,Th)=>{"use strict";var A0=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=xi;Be.connect=xi;Be.default=xi;var I0=ph(),uo=wh();Object.defineProperty(Be,"Manager",{enumerable:!0,get:function(){return uo.Manager}});var xh=pc();Object.defineProperty(Be,"Socket",{enumerable:!0,get:function(){return xh.Socket}});var L0=A0(Ft()),Sh=(0,L0.default)("socket.io-client"),Bn={};function xi(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,I0.url)(r,e.path||"/socket.io"),i=t.source,n=t.id,s=t.path,a=Bn[n]&&s in Bn[n].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||a,u;return c?(Sh("ignoring socket cache for %s",i),u=new uo.Manager(i,e)):(Bn[n]||(Sh("new io instance for %s",i),Bn[n]=new uo.Manager(i,e)),u=Bn[n]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(xi,{Manager:uo.Manager,Socket:xh.Socket,io:xi,connect:xi});var N0=co();Object.defineProperty(Be,"protocol",{enumerable:!0,get:function(){return N0.protocol}});var en=io();Object.defineProperty(Be,"Fetch",{enumerable:!0,get:function(){return en.Fetch}});Object.defineProperty(Be,"NodeXHR",{enumerable:!0,get:function(){return en.NodeXHR}});Object.defineProperty(Be,"XHR",{enumerable:!0,get:function(){return en.XHR}});Object.defineProperty(Be,"NodeWebSocket",{enumerable:!0,get:function(){return en.NodeWebSocket}});Object.defineProperty(Be,"WebSocket",{enumerable:!0,get:function(){return en.WebSocket}});Object.defineProperty(Be,"WebTransport",{enumerable:!0,get:function(){return en.WebTransport}});Th.exports=xi});var bc=M(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.InputStreamReceiver=void 0;var M0=64,F0=30,D0=4,B0=256,j0=16,_c=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??M0),this.ackThrottleMs=Math.max(0,i.ackThrottleMs??F0)}get appliedSeq(){return this.lastAppliedSeq}receive(e,t,i,n){if(e<=this.lastAppliedSeq){this.flushAck();return}if(e===this.lastAppliedSeq+1){try{this.cb.onApply(t,i,n)}catch{}this.lastAppliedSeq=e,this.scheduleAck();return}this.flushAck();let s=Math.max(this.windowSize*D0,B0);e-this.lastAppliedSeq>s||this.maybeResend(this.lastAppliedSeq+1)}maybeResend(e){if(e===this.lastResendFrom){if(++this.resendSuppressed<j0)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)}};lo.InputStreamReceiver=_c});var Rh=M(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.WebSocketService=void 0;var U0=Ch(),kh=xr(),Oh=us(),Ph=as(),K0=bc(),Ec=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,Oh.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([...kh.DEFAULT_CLIENT_CAPABILITIES,...this.extraCapabilities]));this.socket=(0,U0.io)(`${t}/agent`,{auth:{token:e,protocolVersion:kh.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,Ph.generateCorrelationId)(),n=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:i}:t;return(0,Ph.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,e.answerFor);return}this.inputHandler?.(e.terminalId,t,e.dbTerminalId,void 0,e.answerFor)}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 K0.InputStreamReceiver(t,{onApply:(c,u,d)=>this.inputHandler?.(e,c,this.routeIdFor(e),u,d),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,Oh.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)}};ho.WebSocketService=Ec});var Lh=M(Gt=>{"use strict";var q0=Gt&&Gt.__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]})),W0=Gt&&Gt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),wc=Gt&&Gt.__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"&&q0(t,e,i[n]);return W0(t,e),t}})();Object.defineProperty(Gt,"__esModule",{value:!0});Gt.FileTransferService=void 0;Gt.resolveUploadPath=Ih;var po=wc(require("fs")),Ti=wc(require("path")),Ah=wc(require("crypto")),je=xr();function Ih(r,e,t){let i=Ti.basename(t),n=(e??"").trim()||".";if(Ti.isAbsolute(n))return Ti.resolve(n,i);let s=Ti.resolve(r,n),a=s===r||s.startsWith(r+Ti.sep)?s:r;return Ti.resolve(a,i)}var vc=class{socket=null;activeTransfers=new Map;instanceId="";logger;fallbackDir;workspaceRoot=null;cryptoService=null;constructor(e,t="/tmp",i=null){this.logger=e,this.fallbackDir=t,this.workspaceRoot=i}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=po.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=Ah.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,v=Math.min(_+je.CHUNK_SIZE,s);d.chunks.push(t.subarray(_,v))}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,v=>{v.accepted?(d.status=je.TransferStatus.ACTIVE,this.startSendingChunks(u),m(u)):(this.activeTransfers.delete(u),_(new Error(v.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?(_,v)=>d(e,_,v):void 0,onComplete:p?(_,v)=>p(e,_,v):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=Ti.dirname(e.filePath);po.existsSync(n)||po.mkdirSync(n,{recursive:!0}),po.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 i=Ih(this.workspaceRoot??this.fallbackDir,e.targetPath,e.filename);this.receiveFile(e.transferId,e.terminalId,e.filename,e.size,e.totalChunks,e.checksum,i,e.checksumAlgorithm||"sha256").then(()=>t({accepted:!0})).catch(n=>t({accepted:!1,error:n.message}))}calculateChecksum(e,t="sha256"){return t==="fnv1a"?this.fnv1aHash(e):Ah.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"}};Gt.FileTransferService=vc});var Pc=M((Ow,yo)=>{function Fh(r){return Array.isArray(r)?r:[r]}var H0=void 0,xc="",Nh=" ",Sc="\\",V0=/^\s+$/,z0=/(?:[^\\]|^)\\$/,$0=/^\\!/,G0=/^\\#/,Y0=/\r?\n/g,X0=/^\.{0,2}\/|^\.{1,2}$/,J0=/\/$/,tn="/",Dh="node-ignore";typeof Symbol<"u"&&(Dh=Symbol.for("node-ignore"));var Bh=Dh,rn=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),Z0=/([0-z])-([0-z])/g,jh=()=>!1,Q0=r=>r.replace(Z0,(e,t,i)=>t.charCodeAt(0)<=i.charCodeAt(0)?e:xc),eb=r=>{let{length:e}=r;return r.slice(0,e-e%2)},tb=[[/^\uFEFF/,()=>xc],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?Nh:xc)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+Nh}],[/[\\$.|*+(){^]/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,()=>Sc],[/\\\\/g,()=>Sc],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,i,n)=>e===Sc?`\\[${t}${eb(i)}${n}`:n==="]"&&i.length%2===0?`[${Q0(t)}${i}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],rb=/(^|\\\/)?\\\*$/,jn="regex",go="checkRegex",Mh="_",ib={[jn](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[go](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},nb=r=>tb.reduce((e,[t,i])=>e.replace(t,i.bind(r)),r),mo=r=>typeof r=="string",sb=r=>r&&mo(r)&&!V0.test(r)&&!z0.test(r)&&r.indexOf("#")!==0,ob=r=>r.split(Y0).filter(Boolean),Tc=class{constructor(e,t,i,n,s,a){this.pattern=e,this.mark=t,this.negative=s,rn(this,"body",i),rn(this,"ignoreCase",n),rn(this,"regexPrefix",a)}get regex(){let e=Mh+jn;return this[e]?this[e]:this._make(jn,e)}get checkRegex(){let e=Mh+go;return this[e]?this[e]:this._make(go,e)}_make(e,t){let i=this.regexPrefix.replace(rb,ib[e]),n=this.ignoreCase?new RegExp(i,"i"):new RegExp(i);return rn(this,t,n)}},ab=({pattern:r,mark:e},t)=>{let i=!1,n=r;n.indexOf("!")===0&&(i=!0,n=n.substr(1)),n=n.replace($0,"!").replace(G0,"#");let s=nb(n);return new Tc(r,e,n,t,i,s)},Cc=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[Bh]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(mo(e)&&(e={pattern:e}),sb(e.pattern)){let t=ab(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,Fh(mo(e)?ob(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?H0:u)});let c={ignored:n,unignored:s};return a&&(c.rule=a),c}},cb=(r,e)=>{throw new e(r)},Ar=(r,e,t)=>mo(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),Uh=r=>X0.test(r);Ar.isNotRelative=Uh;Ar.convert=r=>r;var kc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:i=!1}={}){rn(this,Bh,!0),this._rules=new Cc(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?cb:jh),this._t(s,t,i,n)}checkIgnore(e){if(!J0.test(e))return this.test(e);let t=e.split(tn).filter(Boolean);if(t.pop(),t.length){let i=this._t(t.join(tn)+tn,this._testCache,!0,t);if(i.ignored)return i}return this._rules.test(e,!1,go)}_t(e,t,i,n){if(e in t)return t[e];if(n||(n=e.split(tn).filter(Boolean)),n.pop(),!n.length)return t[e]=this._rules.test(e,i,jn);let s=this._t(n.join(tn)+tn,t,i,n);return t[e]=s.ignored?s:this._rules.test(e,i,jn)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return Fh(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},Oc=r=>new kc(r),fb=r=>Ar(r&&Ar.convert(r),r,jh),Kh=()=>{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)||Uh(t)};typeof process<"u"&&process.platform==="win32"&&Kh();yo.exports=Oc;Oc.default=Oc;yo.exports.isPathValid=fb;rn(yo.exports,Symbol.for("setupWindows"),Kh)});var Wh=M(Ut=>{"use strict";var ub=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]})),lb=Ut&&Ut.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),qh=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"&&ub(t,e,i[n]);return lb(t,e),t}})(),hb=Ut&&Ut.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ut,"__esModule",{value:!0});Ut.FileListService=void 0;var nn=qh(require("path")),Rc=qh(require("fs/promises")),db=hb(Pc()),Ac=xr(),pb=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],Ic=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,db.default)(),this.ignoreFilter.add(pb),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=nn.join(this.workspaceRoot,".gitignore");try{let t=await Rc.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 Rc.readdir(e,{withFileTypes:!0}),n=[];for(let s of i){let a=t==="."||t===""?s.name:nn.join(t,s.name);if(this.shouldHide(a,s.isDirectory()))continue;let c=nn.join(e,s.name),u={name:s.name,path:a,type:s.isDirectory()?Ac.FileEntryType.DIRECTORY:Ac.FileEntryType.FILE};if(!s.isDirectory())try{let d=await Rc.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===Ac.FileEntryType.DIRECTORY?-1:1:s.name.localeCompare(a.name))}shouldHide(e,t){let i=e.split(nn.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=nn.resolve(this.workspaceRoot,e);if(t!==this.workspaceRoot&&!t.startsWith(this.workspaceRoot+nn.sep))throw new Error("Path outside workspace");return t}sendResponse(e){this.onResponseCallback?.(e)}dispose(){this.onResponseCallback=null}};Ut.FileListService=Ic});var Vh=M(hr=>{"use strict";var gb=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]})),mb=hr&&hr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Hh=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"&&gb(t,e,i[n]);return mb(t,e),t}})();Object.defineProperty(hr,"__esModule",{value:!0});hr.FileTrackerService=void 0;var Lc=Hh(require("path")),Ci=Hh(require("fs/promises")),yb=require("child_process"),_b=require("util"),Yt=xr(),Nc=(0,_b.promisify)(yb.execFile),Mc={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},Fc=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(Mc.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(Mc.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(Mc.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 Ci.readFile(a,"utf-8")}catch{u=void 0}let d={path:s,changeType:u===void 0?Yt.FileChangeType.CREATE:Yt.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 Ci.stat(u);c.size=p.size}catch{c.changeType=Yt.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 Ci.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===Yt.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===Yt.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 Ci.stat(t),s=await Ci.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:Yt.FileViewType.CONTENT,content:c,language:(0,Yt.getLanguageFromPath)(e.path),size:n.size,truncated:a}}async getFileDiff(e,t,i){let n=t.diffBase||Yt.DiffBase.GIT,s;return n===Yt.DiffBase.GIT?s=await this.getGitDiff(i):s=await this.getPreviousDiff(e,t.path,i),{requestId:t.requestId,path:t.path,type:Yt.FileViewType.DIFF,content:s,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await Nc("git",["diff","--cached","--",e],{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:i}=await Nc("git",["diff","--",e],{cwd:this.workspaceRoot});if(i.trim())return i;let{stdout:n}=await Nc("git",["status","--porcelain","--",e],{cwd:this.workspaceRoot});if(n.startsWith("??")||n.startsWith("A ")){let a=(await Ci.readFile(e,"utf-8")).split(`
|
|
29
29
|
`),c=Lc.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 Ci.readFile(i,"utf-8")}catch{c=""}let u=(0,Yt.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
|
-
`)}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=Lc.resolve(t,e);if(i!==t&&!i.startsWith(t+Lc.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=Fc});var $h=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 vv=mu();Object.defineProperty(tt,"CryptoService",{enumerable:!0,get:function(){return vv.CryptoService}});var bv=yu();Object.defineProperty(tt,"AuthService",{enumerable:!0,get:function(){return bv.AuthService}});var zh=_u();Object.defineProperty(tt,"StatusDetector",{enumerable:!0,get:function(){return zh.StatusDetector}});Object.defineProperty(tt,"isAnswerKeystroke",{enumerable:!0,get:function(){return zh.isAnswerKeystroke}});var Ev=Rh();Object.defineProperty(tt,"WebSocketService",{enumerable:!0,get:function(){return Ev.WebSocketService}});var wv=Lh();Object.defineProperty(tt,"FileTransferService",{enumerable:!0,get:function(){return wv.FileTransferService}});var xv=Wh();Object.defineProperty(tt,"FileListService",{enumerable:!0,get:function(){return xv.FileListService}});var Sv=Vh();Object.defineProperty(tt,"FileTrackerService",{enumerable:!0,get:function(){return Sv.FileTrackerService}});var Tv=vc();Object.defineProperty(tt,"InputStreamReceiver",{enumerable:!0,get:function(){return Tv.InputStreamReceiver}})});var Un=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 Dc=Nf();Object.defineProperty(X,"LOG_LEVELS",{enumerable:!0,get:function(){return Dc.LOG_LEVELS}});Object.defineProperty(X,"shouldLog",{enumerable:!0,get:function(){return Dc.shouldLog}});Object.defineProperty(X,"formatLogLine",{enumerable:!0,get:function(){return Dc.formatLogLine}});var sn=Df();Object.defineProperty(X,"CircularBuffer",{enumerable:!0,get:function(){return sn.CircularBuffer}});Object.defineProperty(X,"getApiUrl",{enumerable:!0,get:function(){return sn.getApiUrl}});Object.defineProperty(X,"getWsUrl",{enumerable:!0,get:function(){return sn.getWsUrl}});Object.defineProperty(X,"generateCorrelationId",{enumerable:!0,get:function(){return sn.generateCorrelationId}});Object.defineProperty(X,"runWithCorrelation",{enumerable:!0,get:function(){return sn.runWithCorrelation}});Object.defineProperty(X,"getCurrentCorrelationId",{enumerable:!0,get:function(){return sn.getCurrentCorrelationId}});var Ir=$h();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=Qo();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 Kc=M((qn,Uc)=>{(function(r,e){typeof qn=="object"&&typeof Uc=="object"?Uc.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof qn=="object"?qn["electron-machine-id"]=e(require("child_process"),require("crypto")):r["electron-machine-id"]=e(r.child_process,r.crypto)})(qn,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,be){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,be)}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,be=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||be(ye),gt=ye?st?be("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:be(ee),keys:xe?ze:be(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(`
|
|
32
|
-
`)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return R.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return R.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return R.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function d(R){var B=u((0,E.execSync)(ee[z]).toString());return R?B:c(B)}function p(R){return new _.default(function(B,re){return(0,E.exec)(ee[z],{},function(K,U,ye){if(K)return re(new Error("Error while obtaining machine id: "+K.stack));var xe=u(U.toString());return B(R?xe:c(xe))})})}Object.defineProperty(i,"__esModule",{value:!0});var m=n(35),_=s(m);i.machineIdSync=d,i.machineId=p;var E=n(70),S=n(71),T=process,z=T.platform,ge={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},ee={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:ge[a()]+"\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",linux:"( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :",freebsd:"kenv -q smbios.system.uuid || sysctl -n kern.hostuuid"}},function(t,i,n){t.exports={default:n(36),__esModule:!0}},function(t,i,n){n(66),n(68),n(69),n(67),t.exports=n(6).Promise},function(t,i){t.exports=function(){}},function(t,i){t.exports=function(n,s,a,c){if(!(n instanceof s)||c!==void 0&&c in n)throw TypeError(a+": incorrect invocation!");return n}},function(t,i,n){var s=n(13),a=n(31),c=n(62);t.exports=function(u){return function(d,p,m){var _,E=s(d),S=a(E.length),T=c(m,S);if(u&&p!=p){for(;S>T;)if(_=E[T++],_!=_)return!0}else for(;S>T;T++)if((u||T in E)&&E[T]===p)return u||T||0;return!u&&-1}}},function(t,E,n){var s=n(7),a=n(44),c=n(43),u=n(3),d=n(31),p=n(64),m={},_={},E=t.exports=function(S,T,z,ge,ee){var R,B,re,K,U=ee?function(){return S}:p(S),ye=s(z,ge,T?2:1),xe=0;if(typeof U!="function")throw TypeError(S+" is not iterable!");if(c(U)){for(R=d(S.length);R>xe;xe++)if(K=T?ye(u(B=S[xe])[0],B[1]):ye(S[xe]),K===m||K===_)return K}else for(re=U.call(S);!(B=re.next()).done;)if(K=a(re,ye,B.value,T),K===m||K===_)return K};E.BREAK=m,E.RETURN=_},function(t,i){t.exports=function(n,s,a){var c=a===void 0;switch(s.length){case 0:return c?n():n.call(a);case 1:return c?n(s[0]):n.call(a,s[0]);case 2:return c?n(s[0],s[1]):n.call(a,s[0],s[1]);case 3:return c?n(s[0],s[1],s[2]):n.call(a,s[0],s[1],s[2]);case 4:return c?n(s[0],s[1],s[2],s[3]):n.call(a,s[0],s[1],s[2],s[3])}return n.apply(a,s)}},function(t,i,n){var s=n(11);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(a){return s(a)=="String"?a.split(""):Object(a)}},function(t,i,n){var s=n(10),a=n(1)("iterator"),c=Array.prototype;t.exports=function(u){return u!==void 0&&(s.Array===u||c[a]===u)}},function(t,i,n){var s=n(3);t.exports=function(a,c,u,d){try{return d?c(s(u)[0],u[1]):c(u)}catch(m){var p=a.return;throw p!==void 0&&s(p.call(a)),m}}},function(t,i,n){"use strict";var s=n(49),a=n(17),c=n(18),u={};n(5)(u,n(1)("iterator"),function(){return this}),t.exports=function(d,p,m){d.prototype=s(u,{next:a(1,m)}),c(d,p+" Iterator")}},function(t,i,n){var s=n(1)("iterator"),a=!1;try{var c=[7][s]();c.return=function(){a=!0},Array.from(c,function(){throw 2})}catch{}t.exports=function(u,d){if(!d&&!a)return!1;var p=!1;try{var m=[7],_=m[s]();_.next=function(){return{done:p=!0}},m[s]=function(){return _},u(m)}catch{}return p}},function(t,i){t.exports=function(n,s){return{value:s,done:!!n}}},function(t,i,n){var s=n(2),a=n(30).set,c=s.MutationObserver||s.WebKitMutationObserver,u=s.process,d=s.Promise,p=n(11)(u)=="process";t.exports=function(){var m,_,E,S=function(){var ee,R;for(p&&(ee=u.domain)&&ee.exit();m;){R=m.fn,m=m.next;try{R()}catch(B){throw m?E():_=void 0,B}}_=void 0,ee&&ee.enter()};if(p)E=function(){u.nextTick(S)};else if(c){var T=!0,z=document.createTextNode("");new c(S).observe(z,{characterData:!0}),E=function(){z.data=T=!T}}else if(d&&d.resolve){var ge=d.resolve();E=function(){ge.then(S)}}else E=function(){a.call(s,S)};return function(ee){var R={fn:ee,next:void 0};_&&(_.next=R),m||(m=R,E()),_=R}}},function(t,i,n){var s=n(3),a=n(50),c=n(22),u=n(19)("IE_PROTO"),d=function(){},p="prototype",m=function(){var _,E=n(16)("iframe"),S=c.length,T=">";for(E.style.display="none",n(25).appendChild(E),E.src="javascript:",_=E.contentWindow.document,_.open(),_.write("<script>document.F=Object</script"+T),_.close(),m=_.F;S--;)delete m[p][c[S]];return m()};t.exports=Object.create||function(_,E){var S;return _!==null?(d[p]=s(_),S=new d,d[p]=null,S[u]=_):S=m(),E===void 0?S:a(S,E)}},function(t,i,n){var s=n(12),a=n(3),c=n(54);t.exports=n(4)?Object.defineProperties:function(u,d){a(u);for(var p,m=c(d),_=m.length,E=0;_>E;)s.f(u,p=m[E++],d[p]);return u}},function(t,i,n){var s=n(55),a=n(17),c=n(13),u=n(32),d=n(8),p=n(26),m=Object.getOwnPropertyDescriptor;i.f=n(4)?m:function(_,E){if(_=c(_),E=u(E,!0),p)try{return m(_,E)}catch{}if(d(_,E))return a(!s.f.call(_,E),_[E])}},function(t,i,n){var s=n(8),a=n(63),c=n(19)("IE_PROTO"),u=Object.prototype;t.exports=Object.getPrototypeOf||function(d){return d=a(d),s(d,c)?d[c]:typeof d.constructor=="function"&&d instanceof d.constructor?d.constructor.prototype:d instanceof Object?u:null}},function(t,i,n){var s=n(8),a=n(13),c=n(39)(!1),u=n(19)("IE_PROTO");t.exports=function(d,p){var m,_=a(d),E=0,S=[];for(m in _)m!=u&&s(_,m)&&S.push(m);for(;p.length>E;)s(_,m=p[E++])&&(~c(S,m)||S.push(m));return S}},function(t,i,n){var s=n(53),a=n(22);t.exports=Object.keys||function(c){return s(c,a)}},function(t,i){i.f={}.propertyIsEnumerable},function(t,i,n){var s=n(5);t.exports=function(a,c,u){for(var d in c)u&&a[d]?a[d]=c[d]:s(a,d,c[d]);return a}},function(t,i,n){t.exports=n(5)},function(t,i,n){var s=n(9),a=n(3),c=function(u,d){if(a(u),!s(d)&&d!==null)throw TypeError(d+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?(function(u,d,p){try{p=n(7)(Function.call,n(51).f(Object.prototype,"__proto__").set,2),p(u,[]),d=!(u instanceof Array)}catch{d=!0}return function(m,_){return c(m,_),d?m.__proto__=_:p(m,_),m}})({},!1):void 0),check:c}},function(t,i,n){"use strict";var s=n(2),a=n(6),c=n(12),u=n(4),d=n(1)("species");t.exports=function(p){var m=typeof a[p]=="function"?a[p]:s[p];u&&m&&!m[d]&&c.f(m,d,{configurable:!0,get:function(){return this}})}},function(t,i,n){var s=n(3),a=n(14),c=n(1)("species");t.exports=function(u,d){var p,m=s(u).constructor;return m===void 0||(p=s(m)[c])==null?d:a(p)}},function(t,i,n){var s=n(20),a=n(15);t.exports=function(c){return function(u,d){var p,m,_=String(a(u)),E=s(d),S=_.length;return E<0||E>=S?c?"":void 0:(p=_.charCodeAt(E),p<55296||p>56319||E+1===S||(m=_.charCodeAt(E+1))<56320||m>57343?c?_.charAt(E):p:c?_.slice(E,E+2):(p-55296<<10)+(m-56320)+65536)}}},function(t,i,n){var s=n(20),a=Math.max,c=Math.min;t.exports=function(u,d){return u=s(u),u<0?a(u+d,0):c(u,d)}},function(t,i,n){var s=n(15);t.exports=function(a){return Object(s(a))}},function(t,i,n){var s=n(21),a=n(1)("iterator"),c=n(10);t.exports=n(6).getIteratorMethod=function(u){if(u!=null)return u[a]||u["@@iterator"]||c[s(u)]}},function(t,i,n){"use strict";var s=n(37),a=n(47),c=n(10),u=n(13);t.exports=n(27)(Array,"Array",function(d,p){this._t=u(d),this._i=0,this._k=p},function(){var d=this._t,p=this._k,m=this._i++;return!d||m>=d.length?(this._t=void 0,a(1)):p=="keys"?a(0,m):p=="values"?a(0,d[m]):a(0,[m,d[m]])},"values"),c.Arguments=c.Array,s("keys"),s("values"),s("entries")},function(t,i){},function(t,i,n){"use strict";var s,a,c,u=n(28),d=n(2),p=n(7),m=n(21),_=n(23),E=n(9),S=(n(3),n(14)),T=n(38),z=n(40),ge=(n(58).set,n(60)),ee=n(30).set,R=n(48)(),B="Promise",re=d.TypeError,U=d.process,K=d[B],U=d.process,ye=m(U)=="process",xe=function(){},ue=!!(function(){try{var L=K.resolve(1),j=(L.constructor={})[n(1)("species")]=function(A){A(xe,xe)};return(ye||typeof PromiseRejectionEvent=="function")&&L.then(xe)instanceof j}catch{}})(),rt=function(L,j){return L===j||L===K&&j===c},Ee=function(L){var j;return!(!E(L)||typeof(j=L.then)!="function")&&j},Se=function(L){return rt(K,L)?new be(L):new a(L)},be=a=function(L){var j,A;this.promise=new L(function(P,Z){if(j!==void 0||A!==void 0)throw re("Bad Promise constructor");j=P,A=Z}),this.resolve=S(j),this.reject=S(A)},We=function(L){try{L()}catch(j){return{error:j}}},st=function(L,j){if(!L._n){L._n=!0;var A=L._c;R(function(){for(var P=L._v,Z=L._s==1,Ne=0,Xe=function(lt){var wt,mr,Mr=Z?lt.ok:lt.fail,ii=lt.resolve,Fr=lt.reject,Pi=lt.domain;try{Mr?(Z||(L._h==2&&it(L),L._h=1),Mr===!0?wt=P:(Pi&&Pi.enter(),wt=Mr(P),Pi&&Pi.exit()),wt===lt.promise?Fr(re("Promise-chain cycle")):(mr=Ee(wt))?mr.call(wt,ii,Fr):ii(wt)):Fr(P)}catch(Jn){Fr(Jn)}};A.length>Ne;)Xe(A[Ne++]);L._c=[],L._n=!1,j&&!L._h&&Ze(L)})}},Ze=function(L){ee.call(d,function(){var j,A,P,Z=L._v;if(Te(L)&&(j=We(function(){ye?U.emit("unhandledRejection",Z,L):(A=d.onunhandledrejection)?A({promise:L,reason:Z}):(P=d.console)&&P.error&&P.error("Unhandled promise rejection",Z)}),L._h=ye||Te(L)?2:1),L._a=void 0,j)throw j.error})},Te=function(L){if(L._h==1)return!1;for(var j,A=L._a||L._c,P=0;A.length>P;)if(j=A[P++],j.fail||!Te(j.promise))return!1;return!0},it=function(L){ee.call(d,function(){var j;ye?U.emit("rejectionHandled",L):(j=d.onrejectionhandled)&&j({promise:L,reason:L._v})})},ze=function(L){var j=this;j._d||(j._d=!0,j=j._w||j,j._v=L,j._s=2,j._a||(j._a=j._c.slice()),st(j,!0))},gt=function(L){var j,A=this;if(!A._d){A._d=!0,A=A._w||A;try{if(A===L)throw re("Promise can't be resolved itself");(j=Ee(L))?R(function(){var P={_w:A,_d:!1};try{j.call(L,p(gt,P,1),p(ze,P,1))}catch(Z){ze.call(P,Z)}}):(A._v=L,A._s=1,st(A,!1))}catch(P){ze.call({_w:A,_d:!1},P)}}};ue||(K=function(L){T(this,K,B,"_h"),S(L),s.call(this);try{L(p(gt,this,1),p(ze,this,1))}catch(j){ze.call(this,j)}},s=function(L){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},s.prototype=n(56)(K.prototype,{then:function(L,j){var A=Se(ge(this,K));return A.ok=typeof L!="function"||L,A.fail=typeof j=="function"&&j,A.domain=ye?U.domain:void 0,this._c.push(A),this._a&&this._a.push(A),this._s&&st(this,!1),A.promise},catch:function(L){return this.then(void 0,L)}}),be=function(){var L=new s;this.promise=L,this.resolve=p(gt,L,1),this.reject=p(ze,L,1)}),_(_.G+_.W+_.F*!ue,{Promise:K}),n(18)(K,B),n(59)(B),c=n(6)[B],_(_.S+_.F*!ue,B,{reject:function(L){var j=Se(this),A=j.reject;return A(L),j.promise}}),_(_.S+_.F*(u||!ue),B,{resolve:function(L){if(L instanceof K&&rt(L.constructor,this))return L;var j=Se(this),A=j.resolve;return A(L),j.promise}}),_(_.S+_.F*!(ue&&n(46)(function(L){K.all(L).catch(xe)})),B,{all:function(L){var j=this,A=Se(j),P=A.resolve,Z=A.reject,Ne=We(function(){var Xe=[],lt=0,wt=1;z(L,!1,function(mr){var Mr=lt++,ii=!1;Xe.push(void 0),wt++,j.resolve(mr).then(function(Fr){ii||(ii=!0,Xe[Mr]=Fr,--wt||P(Xe))},Z)}),--wt||P(Xe)});return Ne&&Z(Ne.error),A.promise},race:function(L){var j=this,A=Se(j),P=A.reject,Z=We(function(){z(L,!1,function(Ne){j.resolve(Ne).then(A.resolve,P)})});return Z&&P(Z.error),A.promise}})},function(t,i,n){"use strict";var s=n(61)(!0);n(27)(String,"String",function(a){this._t=String(a),this._i=0},function(){var a,c=this._t,u=this._i;return u>=c.length?{value:void 0,done:!0}:(a=s(c,u),this._i+=a.length,{value:a,done:!1})})},function(t,i,n){n(65);for(var s=n(2),a=n(5),c=n(10),u=n(1)("toStringTag"),d=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],p=0;p<5;p++){var m=d[p],_=s[m],E=_&&_.prototype;E&&!E[u]&&a(E,u,m),c[m]=c.Array}},function(t,i){t.exports=require("child_process")},function(t,i){t.exports=require("crypto")}])})});function Rv(){try{return Wc.default.statSync("/.dockerenv"),!0}catch{return!1}}function Av(){try{return Wc.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Hc(){return qc===void 0&&(qc=Rv()||Av()),qc}var Wc,qc,Zh=qt(()=>{Wc=fe(require("node:fs"),1)});function on(){return Vc===void 0&&(Vc=Iv()||Hc()),Vc}var Qh,Vc,Iv,zc=qt(()=>{Qh=fe(require("node:fs"),1);Zh();Iv=()=>{try{return Qh.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var $c,td,rd,ed,Jr,Gc=qt(()=>{$c=fe(require("node:process"),1),td=fe(require("node:os"),1),rd=fe(require("node:fs"),1);zc();ed=()=>{if($c.default.platform!=="linux")return!1;if(td.default.release().toLowerCase().includes("microsoft"))return!on();try{return rd.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!on():!1}catch{return!1}},Jr=$c.default.env.__IS_WSL_TEST__?ed:ed()});var Yc,Vn,Lv,Nv,Xc,id=qt(()=>{Yc=fe(require("node:process"),1),Vn=fe(require("node:fs/promises"),1);Gc();Gc();Lv=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",i=!1;try{await Vn.default.access(t,Vn.constants.F_OK),i=!0}catch{}if(!i)return r;let n=await Vn.default.readFile(t,{encoding:"utf8"}),s=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(n);return s?(e=s.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),Nv=async()=>`${await Lv()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Xc=async()=>Jr?Nv():`${Yc.default.env.SYSTEMROOT||Yc.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Zr(r,e,t){let i=n=>Object.defineProperty(r,e,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let n=t();return i(n),n},set(n){i(n)}}),r}var nd=qt(()=>{});async function Jc(){if(od.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await Mv("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(r)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}var sd,od,ad,Mv,cd=qt(()=>{sd=require("node:util"),od=fe(require("node:process"),1),ad=require("node:child_process"),Mv=(0,sd.promisify)(ad.execFile)});async function ld(r,{humanReadableOutput:e=!0,signal:t}={}){if(fd.default.platform!=="darwin")throw new Error("macOS only");let i=e?[]:["-ss"],n={};t&&(n.signal=t);let{stdout:s}=await Fv("osascript",["-e",r,i],n);return s.trim()}var fd,ud,Zc,Fv,hd=qt(()=>{fd=fe(require("node:process"),1),ud=require("node:util"),Zc=require("node:child_process"),Fv=(0,ud.promisify)(Zc.execFile)});async function Qc(r){return ld(`tell application "Finder" to set app_path to application file id "${r}" as string
|
|
33
|
-
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var dd=qt(()=>{hd()});async function tf(r=
|
|
34
|
-
`,{encoding:"utf8"})}catch{}}var Kn=class{level;toFile;constructor(e="silent",t=!1){typeof e=="boolean"?this.level=e?"info":"silent":this.level=e,this.toFile=t}static getLogFilePath(){return Xr}write(e,t,i){if(!(0,_o.shouldLog)(e,this.level))return;let n=(0,_o.formatLogLine)(e,
|
|
35
|
-
`)}info(e,...t){this.write("info",e,t)}warn(e,...t){this.write("warn",e,t)}error(e,...t){this.write("error",e,t)}debug(e,...t){this.write("debug",e,t)}};var Xh=fe(require("os")),Jh=fe(Kc()),Wn=class{cachedId=null;name;constructor(e){this.name=e||Xh.hostname()||"CLI"}async getMachineId(){if(this.cachedId)return this.cachedId;try{this.cachedId=(0,Jh.machineIdSync)()}catch{this.cachedId=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}return this.cachedId}getMachineName(){return this.name}};var Hn=class{constructor(e){this.logger=e}info(e){this.logger.info("Notification",{message:e})}warn(e){this.logger.warn("Notification",{message:e})}error(e){this.logger.error("Notification",{message:e})}};var $n=class{async openUrl(e){let{default:t}=await Promise.resolve().then(()=>(kd(),Cd));await t(e)}};var Od=fe(require("fs")),ff=fe(require("path"));function xo(r){let e=r?[r]:[ff.join(__dirname,"..","package.json"),ff.join(__dirname,"..","..","package.json")];for(let t of e)try{let i=JSON.parse(Od.readFileSync(t,"utf8"));if(typeof i.version=="string"&&i.version.length>0)return i.version}catch{}return"unknown"}function Pd(r,e){for(let t=0;t<r.length;t++){let i=r[t];if(i.startsWith("-")){e.has(i)&&t++;continue}return i}}var uf=new Set(["--cid","--token","--server","--log-level"]),Rd=new Set(["--help","-h","--version","-V","--verbose","-v","--watch","-w","--log-to-file","--statusline","--multi-viewer","--force"]);function Ad(r,e,t){for(let i=0;i<r.length;i++){let n=r[i];if(!n.startsWith("-"))continue;let s=n.includes("=")?n.slice(0,n.indexOf("=")):n;if(e.has(s)||t.has(s)){e.has(s)&&!n.includes("=")&&i++;continue}return n}}var sp=fe(require("path")),ut=fe(Un()),op=fe(Sr());var Id=fe(require("os")),Ld=require("crypto"),Nd=fe(require("node-pty")),Md=fe(Un()),So=class r{ptyProcess=null;outputBuffer=new Md.CircularBuffer(100);streamId=null;logger;onOutput=null;onExit=null;preWriteHook=null;onResize=null;onLocalClaim=null;onLocalInput=null;sigwinchEnabled=!0;sigwinchListener=null;desiredCols=null;desiredRows=null;rebroadcastTimers=[];static REBROADCAST_DELAYS_MS=[50,200,500];static PASTE_CHAR_DELAY_MS=10;writeQueue=[];draining=!1;drainTimer=null;reservedBottomRows=0;multiViewerMode=!1;constructor(e){this.logger=e}setMultiViewerMode(e){this.multiViewerMode!==e&&(this.multiViewerMode=e,this.logger.info("Multi-viewer mode",{enabled:e}))}spawn(e,t=0){let i=process.env.SHELL||(Id.platform()==="win32"?"powershell.exe":"/bin/bash"),n=process.stdout.columns||80,s=process.stdout.rows||24,a=Math.max(1,s-t);this.reservedBottomRows=t,this.ptyProcess=Nd.spawn(i,[],{name:"xterm-256color",cols:n,rows:a,cwd:e,env:{...process.env,TERMIQ_SESSION_ACTIVE:"1"}}),this.onResize?.(n,a),this.streamId=(0,Ld.randomUUID)();let c=`cli_${this.ptyProcess.pid}`;return this.ptyProcess.onData(u=>{this.preWriteHook?.(u),process.stdout.write(u),this.outputBuffer.append(u),this.onOutput?.(u)}),this.ptyProcess.onExit(({exitCode:u})=>{this.logger.info("Shell exited",String(u)),this.onExit?.(u)}),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u=>{this.multiViewerMode&&this.maybeClaimLocalControl(),this.onLocalInput?.(u.toString()),this.ptyProcess?.write(u.toString())}),this.sigwinchListener=()=>{let u=process.stdout.columns||80,d=Math.max(1,(process.stdout.rows||24)-this.reservedBottomRows);if(this.multiViewerMode){this.logger.info("Local resize claims control",{cols:u,rows:d}),this.resize(u,d),this.onLocalClaim?.(u,d);return}if(this.desiredCols!==null&&this.desiredRows!==null){this.logger.info("Local resize ignored (PWA desired-size set)",{host:{cols:u,rows:d},desired:{cols:this.desiredCols,rows:this.desiredRows}});return}if(!this.sigwinchEnabled){this.logger.info("Local resize ignored (PWA viewers attached)",{cols:u,rows:d});return}this.logger.info("Local resize applied",{cols:u,rows:d}),this.ptyProcess?.resize(u,d),this.onResize?.(u,d)},process.platform==="win32"?process.stdout.on("resize",this.sigwinchListener):process.on("SIGWINCH",this.sigwinchListener),this.logger.info("Shell spawned",i,c),c}write(e,t=!1){if(this.ptyProcess){if(!t&&!this.draining){this.ptyProcess.write(e);return}for(let i of e)this.writeQueue.push(i);this.drainWriteQueue()}}drainWriteQueue(){if(this.draining)return;this.draining=!0;let e=()=>{let t=this.writeQueue.shift();if(t===void 0||!this.ptyProcess){this.draining=!1;return}this.ptyProcess.write(t),this.drainTimer=setTimeout(e,r.PASTE_CHAR_DELAY_MS)};e()}getStreamId(){return this.streamId}getPtyCols(){return this.ptyProcess?.cols??0}getPtyRows(){return this.ptyProcess?.rows??0}resize(e,t){this.desiredCols=e,this.desiredRows=t,this.ptyProcess?.resize(e,t),this.onResize?.(e,t),this.cancelRebroadcast();for(let i of r.REBROADCAST_DELAYS_MS)this.rebroadcastTimers.push(setTimeout(()=>{this.ptyProcess&&(this.desiredCols!==e||this.desiredRows!==t||this.ptyProcess.resize(e,t))},i))}cancelRebroadcast(){for(let e of this.rebroadcastTimers)clearTimeout(e);this.rebroadcastTimers=[]}redrawNoResize(){if(this.ptyProcess){if(this.desiredCols===null||this.desiredRows===null){this.logger.info("Redraw skipped (no desired-size set yet)");return}this.ptyProcess.resize(this.desiredCols,this.desiredRows)}}maybeClaimLocalControl(){if(!this.ptyProcess)return;let e=process.stdout.columns||80,t=Math.max(1,(process.stdout.rows||24)-this.reservedBottomRows);this.ptyProcess.cols===e&&this.ptyProcess.rows===t||(this.logger.info("Local input claims control",{cols:e,rows:t}),this.resize(e,t),this.onLocalClaim?.(e,t))}setOnLocalClaim(e){this.onLocalClaim=e}setOnLocalInput(e){this.onLocalInput=e}setSigwinchEnabled(e){this.sigwinchEnabled!==e&&(this.sigwinchEnabled=e,this.logger.info("SIGWINCH listener",{enabled:e}))}getBuffer(){return this.outputBuffer.getContent()}getLastBytes(e){return this.outputBuffer.getLastBytes(e)}setOnOutput(e){this.onOutput=e}setPreWriteHook(e){this.preWriteHook=e}setOnResize(e){this.onResize=e}setOnExit(e){this.onExit=e}isAlive(){return this.ptyProcess!==null}kill(){this.ptyProcess?.kill(),this.ptyProcess=null}dispose(){this.kill(),this.cancelRebroadcast(),this.drainTimer&&(clearTimeout(this.drainTimer),this.drainTimer=null),this.writeQueue=[],this.draining=!1,this.sigwinchListener&&(process.platform==="win32"?process.stdout.removeListener("resize",this.sigwinchListener):process.removeListener("SIGWINCH",this.sigwinchListener),this.sigwinchListener=null),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()}};var ei=fe(require("path")),fn=fe(require("fs"));var Jd=require("node:events"),Zd=require("node:fs"),Io=require("node:fs/promises"),we=fe(require("node:path"),1);var Lr=require("node:fs/promises"),Nr=require("node:path"),jd=require("node:stream"),Rt={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},lf={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:Rt.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(lf);var Ud="READDIRP_RECURSIVE_ERROR",zv=new Set(["ENOENT","EPERM","EACCES","ELOOP",Ud]),Fd=[Rt.DIR_TYPE,Rt.EVERYTHING_TYPE,Rt.FILE_DIR_TYPE,Rt.FILE_TYPE],$v=new Set([Rt.DIR_TYPE,Rt.EVERYTHING_TYPE,Rt.FILE_DIR_TYPE]),Gv=new Set([Rt.EVERYTHING_TYPE,Rt.FILE_DIR_TYPE,Rt.FILE_TYPE]),Yv=r=>zv.has(r.code),Xv=process.platform==="win32",Dd=r=>!0,Bd=r=>{if(r===void 0)return Dd;if(typeof r=="function")return r;if(typeof r=="string"){let e=r.trim();return t=>t.basename===e}if(Array.isArray(r)){let e=r.map(t=>t.trim());return t=>e.some(i=>t.basename===i)}return Dd},hf=class extends jd.Readable{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...lf,...e},{root:i,type:n}=t;this._fileFilter=Bd(t.fileFilter),this._directoryFilter=Bd(t.directoryFilter);let s=t.lstat?Lr.lstat:Lr.stat;Xv?this._stat=a=>s(a,{bigint:!0}):this._stat=s,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:lf.depth,this._wantsDir=n?$v.has(n):!1,this._wantsFile=n?Gv.has(n):!1,this._wantsEverything=n===Rt.EVERYTHING_TYPE,this._root=(0,Nr.resolve)(i),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(i,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,i=t&&t.files;if(i&&i.length>0){let{path:n,depth:s}=t,a=i.splice(0,e).map(u=>this._formatEntry(u,n)),c=await Promise.all(a);for(let u of c){if(!u)continue;if(this.destroyed)return;let d=await this._getEntryType(u);d==="directory"&&this._directoryFilter(u)?(s<=this._maxDepth&&this.parents.push(this._exploreDir(u.fullPath,s+1)),this._wantsDir&&(this.push(u),e--)):(d==="file"||this._includeAsFile(u))&&this._fileFilter(u)&&this._wantsFile&&(this.push(u),e--)}}else{let n=this.parents.pop();if(!n){this.push(null);break}if(this.parent=await n,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let i;try{i=await(0,Lr.readdir)(e,this._rdOptions)}catch(n){this._onError(n)}return{files:i,depth:t,path:e}}async _formatEntry(e,t){let i,n=this._isDirent?e.name:e;try{let s=(0,Nr.resolve)((0,Nr.join)(t,n));i={path:(0,Nr.relative)(this._root,s),fullPath:s,basename:n},i[this._statsProp]=this._isDirent?e:await this._stat(s)}catch(s){this._onError(s);return}return i}_onError(e){Yv(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return"";let t=e[this._statsProp];if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let i=e.fullPath;try{let n=await(0,Lr.realpath)(i),s=await(0,Lr.lstat)(n);if(s.isFile())return"file";if(s.isDirectory()){let a=n.length;if(i.startsWith(n)&&i.substr(a,1)===Nr.sep){let c=new Error(`Circular symlink detected: "${i}" points to "${n}"`);return c.code=Ud,this._onError(c)}return"directory"}}catch(n){return this._onError(n),""}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function Kd(r,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=Rt.FILE_DIR_TYPE),t&&(e.type=t),r){if(typeof r!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!Fd.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${Fd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new hf(e)}var Oi=require("node:fs"),Jt=require("node:fs/promises"),Wd=require("node:os"),qe=fe(require("node:path"),1),Jv="data",gf="end",Hd="close",Po=()=>{};var Ro=process.platform,mf=Ro==="win32",Zv=Ro==="darwin",Qv=Ro==="linux",eb=Ro==="freebsd",Vd=(0,Wd.type)()==="OS400",Ve={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Xt=Ve,tb="watch",rb={lstat:Jt.lstat,stat:Jt.stat},ki="listeners",To="errHandlers",cn="rawEmitters",ib=[ki,To,cn],nb=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),sb=r=>nb.has(qe.extname(r).slice(1).toLowerCase()),pf=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},Gn=(r,e,t)=>{let i=r[e];i instanceof Set||(r[e]=i=new Set([i])),i.add(t)},ob=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},Yn=(r,e,t)=>{let i=r[e];i instanceof Set?i.delete(t):i===t&&delete r[e]},zd=r=>r instanceof Set?r.size===0:!r,Co=new Map;function qd(r,e,t,i,n){let s=(a,c)=>{t(r),n(a,c,{watchedPath:r}),c&&r!==c&&ko(qe.resolve(r,c),ki,qe.join(r,c))};try{return(0,Oi.watch)(r,{persistent:e.persistent},s)}catch(a){i(a);return}}var ko=(r,e,t,i,n)=>{let s=Co.get(r);s&&pf(s[e],a=>{a(t,i,n)})},ab=(r,e,t,i)=>{let{listener:n,errHandler:s,rawEmitter:a}=i,c=Co.get(e),u;if(!t.persistent)return u=qd(r,t,n,s,a),u?u.close.bind(u):void 0;if(c)Gn(c,ki,n),Gn(c,To,s),Gn(c,cn,a);else{if(u=qd(r,t,ko.bind(null,e,ki),s,ko.bind(null,e,cn)),!u)return;u.on(Xt.ERROR,async d=>{let p=ko.bind(null,e,To);if(c&&(c.watcherUnusable=!0),mf&&d.code==="EPERM")try{await(await(0,Jt.open)(r,"r")).close(),p(d)}catch{}else p(d)}),c={listeners:n,errHandlers:s,rawEmitters:a,watcher:u},Co.set(e,c)}return()=>{Yn(c,ki,n),Yn(c,To,s),Yn(c,cn,a),zd(c.listeners)&&(c.watcher.close(),Co.delete(e),ib.forEach(ob(c)),c.watcher=void 0,Object.freeze(c))}},df=new Map,cb=(r,e,t,i)=>{let{listener:n,rawEmitter:s}=i,a=df.get(e),c=a&&a.options;return c&&(c.persistent<t.persistent||c.interval>t.interval)&&((0,Oi.unwatchFile)(e),a=void 0),a?(Gn(a,ki,n),Gn(a,cn,s)):(a={listeners:n,rawEmitters:s,options:t,watcher:(0,Oi.watchFile)(e,t,(u,d)=>{pf(a.rawEmitters,m=>{m(Xt.CHANGE,e,{curr:u,prev:d})});let p=u.mtimeMs;(u.size!==d.size||p>d.mtimeMs||p===0)&&pf(a.listeners,m=>m(r,u))})},df.set(e,a)),()=>{Yn(a,ki,n),Yn(a,cn,s),zd(a.listeners)&&(df.delete(e),(0,Oi.unwatchFile)(e),a.options=a.watcher=void 0,Object.freeze(a))}},Oo=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let i=this.fsw.options,n=qe.dirname(e),s=qe.basename(e);this.fsw._getWatchedDir(n).add(s);let c=qe.resolve(e),u={persistent:i.persistent};t||(t=Po);let d;if(i.usePolling){let p=i.interval!==i.binaryInterval;u.interval=p&&sb(s)?i.binaryInterval:i.interval,d=cb(e,c,u,{listener:t,rawEmitter:this.fsw._emitRaw})}else d=ab(e,c,u,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return d}_handleFile(e,t,i){if(this.fsw.closed)return;let n=qe.dirname(e),s=qe.basename(e),a=this.fsw._getWatchedDir(n),c=t;if(a.has(s))return;let u=async(p,m)=>{if(this.fsw._throttle(tb,e,5)){if(!m||m.mtimeMs===0)try{let _=await(0,Jt.stat)(e);if(this.fsw.closed)return;let E=_.atimeMs,S=_.mtimeMs;if((!E||E<=S||S!==c.mtimeMs)&&this.fsw._emit(Xt.CHANGE,e,_),(Zv||Qv||eb)&&c.ino!==_.ino){this.fsw._closeFile(p),c=_;let T=this._watchWithNodeFs(e,u);T&&this.fsw._addPathCloser(p,T)}else c=_}catch{this.fsw._remove(n,s)}else if(a.has(s)){let _=m.atimeMs,E=m.mtimeMs;(!_||_<=E||E!==c.mtimeMs)&&this.fsw._emit(Xt.CHANGE,e,m),c=m}}},d=this._watchWithNodeFs(e,u);if(!(i&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Xt.ADD,e,0))return;this.fsw._emit(Xt.ADD,e,t)}return d}async _handleSymlink(e,t,i,n){if(this.fsw.closed)return;let s=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let c;try{c=await(0,Jt.realpath)(i)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(n)?this.fsw._symlinkPaths.get(s)!==c&&(this.fsw._symlinkPaths.set(s,c),this.fsw._emit(Xt.CHANGE,i,e.stats)):(a.add(n),this.fsw._symlinkPaths.set(s,c),this.fsw._emit(Xt.ADD,i,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(e,t,i,n,s,a,c){e=qe.join(e,"");let u=n?`${e}:${n}`:e;if(c=this.fsw._throttle("readdir",u,1e3),!c)return;let d=this.fsw._getWatchedDir(i.path),p=new Set,m=this.fsw._readdirp(e,{fileFilter:_=>i.filterPath(_),directoryFilter:_=>i.filterDir(_)});if(m)return m.on(Jv,async _=>{if(this.fsw.closed){m=void 0;return}let E=_.path,S=qe.join(e,E);if(p.add(E),!(_.stats.isSymbolicLink()&&await this._handleSymlink(_,e,S,E))){if(this.fsw.closed){m=void 0;return}(E===n||!n&&!d.has(E))&&(this.fsw._incrReadyCount(),S=qe.join(s,qe.relative(s,S)),this._addToNodeFs(S,t,i,a+1))}}).on(Xt.ERROR,this._boundHandleError),new Promise((_,E)=>{if(!m)return E();m.once(gf,()=>{if(this.fsw.closed){m=void 0;return}let S=c?c.clear():!1;_(void 0),d.getChildren().filter(T=>T!==e&&!p.has(T)).forEach(T=>{this.fsw._remove(e,T)}),m=void 0,S&&this._handleRead(e,!1,i,n,s,a,c)})})}async _handleDir(e,t,i,n,s,a,c){let u=this.fsw._getWatchedDir(qe.dirname(e)),d=u.has(qe.basename(e));!(i&&this.fsw.options.ignoreInitial)&&!s&&!d&&this.fsw._emit(Xt.ADD_DIR,e,t),u.add(qe.basename(e)),this.fsw._getWatchedDir(e);let p,m,_=this.fsw.options.depth;if((_==null||n<=_)&&!this.fsw._symlinkPaths.has(c)){if(!s&&(await this._handleRead(e,i,a,s,e,n,p),this.fsw.closed))return;m=this._watchWithNodeFs(e,(E,S)=>{S&&S.mtimeMs===0||this._handleRead(E,!1,a,s,e,n,p)})}return m}async _addToNodeFs(e,t,i,n,s){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let c=this.fsw._getWatchHelpers(e);i&&(c.filterPath=u=>i.filterPath(u),c.filterDir=u=>i.filterDir(u));try{let u=await rb[c.statMethod](c.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(c.watchPath,u))return a(),!1;let d=this.fsw.options.followSymlinks,p;if(u.isDirectory()){let m=qe.resolve(e),_=d?await(0,Jt.realpath)(e):e;if(this.fsw.closed||(p=await this._handleDir(c.watchPath,u,t,n,s,c,_),this.fsw.closed))return;m!==_&&_!==void 0&&this.fsw._symlinkPaths.set(m,_)}else if(u.isSymbolicLink()){let m=d?await(0,Jt.realpath)(e):e;if(this.fsw.closed)return;let _=qe.dirname(c.watchPath);if(this.fsw._getWatchedDir(_).add(c.watchPath),this.fsw._emit(Xt.ADD,c.watchPath,u),p=await this._handleDir(_,u,t,n,e,c,m),this.fsw.closed)return;m!==void 0&&this.fsw._symlinkPaths.set(qe.resolve(e),m)}else p=this._handleFile(c.watchPath,u,t);return a(),p&&this.fsw._addPathCloser(e,p),!1}catch(u){if(this.fsw._handleError(u))return a(),e}}};var yf="/",fb="//",Qd=".",ub="..",lb="string",hb=/\\/g,ep=/\/\//g,db=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,pb=/^\.[/\\]/;function Ao(r){return Array.isArray(r)?r:[r]}var _f=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function gb(r){return typeof r=="function"?r:typeof r=="string"?e=>r===e:r instanceof RegExp?e=>r.test(e):typeof r=="object"&&r!==null?e=>{if(r.path===e)return!0;if(r.recursive){let t=we.relative(r.path,e);return t?!t.startsWith("..")&&!we.isAbsolute(t):!1}return!1}:()=>!1}function mb(r){if(typeof r!="string")throw new Error("string expected");r=we.normalize(r),r=r.replace(/\\/g,"/");let e=!1;return r.startsWith("//")&&(e=!0),r=r.replace(ep,"/"),e&&(r="/"+r),r}function $d(r,e,t){let i=mb(e);for(let n=0;n<r.length;n++){let s=r[n];if(s(i,t))return!0}return!1}function yb(r,e){if(r==null)throw new TypeError("anymatch: specify first argument");let i=Ao(r).map(n=>gb(n));return e==null?(n,s)=>$d(i,n,s):$d(i,e)}var Gd=r=>{let e=Ao(r).flat();if(!e.every(t=>typeof t===lb))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(tp)},Yd=r=>{let e=r.replace(hb,yf),t=!1;return e.startsWith(fb)&&(t=!0),e=e.replace(ep,yf),t&&(e=yf+e),e},tp=r=>Yd(we.normalize(Yd(r))),Xd=(r="")=>e=>typeof e=="string"?tp(we.isAbsolute(e)?e:we.join(r,e)):e,_b=(r,e)=>we.isAbsolute(r)?r:we.join(e,r),vb=Object.freeze(new Set),vf=class{path;_removeWatcher;items;constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Qd&&e!==ub&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let i=this.path;try{await(0,Io.readdir)(i)}catch{this._removeWatcher&&this._removeWatcher(we.dirname(i),we.basename(i))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=Po,this.items=vb,Object.freeze(this)}},bb="stat",Eb="lstat",bf=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,i){this.fsw=i;let n=e;this.path=e=e.replace(pb,""),this.watchPath=n,this.fullWatchPath=we.resolve(n),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=t,this.statMethod=t?bb:Eb}entryPath(e){return we.join(this.watchPath,we.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let i=this.entryPath(e);return this.fsw._isntIgnored(i,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Ef=class extends Jd.EventEmitter{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,i={stabilityThreshold:2e3,pollInterval:100},n={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Ao(e.ignored):Ao([]),awaitWriteFinish:t===!0?i:typeof t=="object"?{...i,...t}:!1};Vd&&(n.usePolling=!0),n.atomic===void 0&&(n.atomic=!n.usePolling);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let u=s.toLowerCase();u==="false"||u==="0"?n.usePolling=!1:u==="true"||u==="1"?n.usePolling=!0:n.usePolling=!!u}let a=process.env.CHOKIDAR_INTERVAL;a&&(n.interval=Number.parseInt(a,10));let c=0;this._emitReady=()=>{c++,c>=this._readyCount&&(this._emitReady=Po,this._readyEmitted=!0,process.nextTick(()=>this.emit(Ve.READY)))},this._emitRaw=(...u)=>this.emit(Ve.RAW,...u),this._boundRemove=this._remove.bind(this),this.options=n,this._nodeFsHandler=new Oo(this),Object.freeze(n)}_addIgnoredPath(e){if(_f(e)){for(let t of this._ignoredPaths)if(_f(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let t of this._ignoredPaths)_f(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,i){let{cwd:n}=this.options;this.closed=!1,this._closePromise=void 0;let s=Gd(e);return n&&(s=s.map(a=>_b(a,n))),s.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=s.length,Promise.all(s.map(async a=>{let c=await this._nodeFsHandler._addToNodeFs(a,!i,void 0,0,t);return c&&this._emitReady(),c})).then(a=>{this.closed||a.forEach(c=>{c&&this.add(we.dirname(c),we.basename(t||c))})}),this}unwatch(e){if(this.closed)return this;let t=Gd(e),{cwd:i}=this.options;return t.forEach(n=>{!we.isAbsolute(n)&&!this._closers.has(n)&&(i&&(n=we.join(i,n)),n=we.resolve(n)),this._closePath(n),this._addIgnoredPath(n),this._watched.has(n)&&this._addIgnoredPath({path:n,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(i=>{let n=i();n instanceof Promise&&e.push(n)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,i)=>{let s=(this.options.cwd?we.relative(this.options.cwd,i):i)||Qd;e[s]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==Ve.ERROR&&this.emit(Ve.ALL,e,...t)}async _emit(e,t,i){if(this.closed)return;let n=this.options;mf&&(t=we.normalize(t)),n.cwd&&(t=we.relative(n.cwd,t));let s=[t];i!=null&&s.push(i);let a=n.awaitWriteFinish,c;if(a&&(c=this._pendingWrites.get(t)))return c.lastChange=new Date,this;if(n.atomic){if(e===Ve.UNLINK)return this._pendingUnlinks.set(t,[e,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((u,d)=>{this.emit(...u),this.emit(Ve.ALL,...u),this._pendingUnlinks.delete(d)})},typeof n.atomic=="number"?n.atomic:100),this;e===Ve.ADD&&this._pendingUnlinks.has(t)&&(e=Ve.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===Ve.ADD||e===Ve.CHANGE)&&this._readyEmitted){let u=(d,p)=>{d?(e=Ve.ERROR,s[0]=d,this.emitWithAll(e,s)):p&&(s.length>1?s[1]=p:s.push(p),this.emitWithAll(e,s))};return this._awaitWriteFinish(t,a.stabilityThreshold,e,u),this}if(e===Ve.CHANGE&&!this._throttle(Ve.CHANGE,t,50))return this;if(n.alwaysStat&&i===void 0&&(e===Ve.ADD||e===Ve.ADD_DIR||e===Ve.CHANGE)){let u=n.cwd?we.join(n.cwd,t):t,d;try{d=await(0,Io.stat)(u)}catch{}if(!d||this.closed)return;s.push(d)}return this.emitWithAll(e,s),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(Ve.ERROR,e),e||this.closed}_throttle(e,t,i){this._throttled.has(e)||this._throttled.set(e,new Map);let n=this._throttled.get(e);if(!n)throw new Error("invalid throttle");let s=n.get(t);if(s)return s.count++,!1;let a,c=()=>{let d=n.get(t),p=d?d.count:0;return n.delete(t),clearTimeout(a),d&&clearTimeout(d.timeoutObject),p};a=setTimeout(c,i);let u={timeoutObject:a,clear:c,count:0};return n.set(t,u),u}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,i,n){let s=this.options.awaitWriteFinish;if(typeof s!="object")return;let a=s.pollInterval,c,u=e;this.options.cwd&&!we.isAbsolute(e)&&(u=we.join(this.options.cwd,e));let d=new Date,p=this._pendingWrites;function m(_){(0,Zd.stat)(u,(E,S)=>{if(E||!p.has(e)){E&&E.code!=="ENOENT"&&n(E);return}let T=Number(new Date);_&&S.size!==_.size&&(p.get(e).lastChange=T);let z=p.get(e);T-z.lastChange>=t?(p.delete(e),n(void 0,S)):c=setTimeout(m,a,S)})}p.has(e)||(p.set(e,{lastChange:d,cancelWait:()=>(p.delete(e),clearTimeout(c),i)}),c=setTimeout(m,a))}_isIgnored(e,t){if(this.options.atomic&&db.test(e))return!0;if(!this._userIgnored){let{cwd:i}=this.options,s=(this.options.ignored||[]).map(Xd(i)),c=[...[...this._ignoredPaths].map(Xd(i)),...s];this._userIgnored=yb(c,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new bf(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=we.resolve(e);return this._watched.has(t)||this._watched.set(t,new vf(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,i){let n=we.join(e,t),s=we.resolve(n);if(i=i??(this._watched.has(n)||this._watched.has(s)),!this._throttle("remove",n,100))return;!i&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(n).getChildren().forEach(_=>this._remove(n,_));let u=this._getWatchedDir(e),d=u.has(t);u.remove(t),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let p=n;if(this.options.cwd&&(p=we.relative(this.options.cwd,n)),this.options.awaitWriteFinish&&this._pendingWrites.has(p)&&this._pendingWrites.get(p).cancelWait()===Ve.ADD)return;this._watched.delete(n),this._watched.delete(s);let m=i?Ve.UNLINK_DIR:Ve.UNLINK;d&&!this._isIgnored(n)&&this._emit(m,n),this._closePath(n)}_closePath(e){this._closeFile(e);let t=we.dirname(e);this._getWatchedDir(t).remove(we.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(i=>i()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let i=this._closers.get(e);i||(i=[],this._closers.set(e,i)),i.push(t)}_readdirp(e,t){if(this.closed)return;let i={type:Ve.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},n=Kd(e,i);return this._streams.add(n),n.once(Hd,()=>{n=void 0}),n.once(gf,()=>{n&&(this._streams.delete(n),n=void 0)}),n}};function rp(r,e={}){let t=new Ef(e);return t.add(r),t}var ip=fe(Pc()),dr=fe(Sr()),wb=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/*.log"],xb=300,Lo=class{watcher=null;ignoreFilter;workspaceRoot;logger;onFileChangedCallback=null;pendingEvents=new Map;pendingTypes=new Map;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,ip.default)(),this.initializeIgnoreFilter()}initializeIgnoreFilter(){this.ignoreFilter.add(wb);let e=ei.join(this.workspaceRoot,".gitignore");try{if(fn.existsSync(e)){let t=fn.readFileSync(e,"utf-8");this.ignoreFilter.add(t)}}catch{}}onFileChanged(e){this.onFileChangedCallback=e}start(){this.watcher||(this.watcher=rp(this.workspaceRoot,{ignored:e=>{let t=ei.relative(this.workspaceRoot,e);if(!t||t===".")return!1;let i=t.split(ei.sep).join("/");return this.ignoreFilter.ignores(i)},persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50}}),this.watcher.on("add",e=>this.handleEvent(e,dr.FileChangeType.CREATE)),this.watcher.on("change",e=>this.handleEvent(e,dr.FileChangeType.MODIFY)),this.watcher.on("unlink",e=>this.handleEvent(e,dr.FileChangeType.DELETE)),this.watcher.on("error",e=>this.logger.error("File watcher error",e)),this.logger.info("File watcher started"))}stop(){this.watcher?.close(),this.watcher=null;for(let e of this.pendingEvents.values())clearTimeout(e);this.pendingEvents.clear(),this.pendingTypes.clear()}handleEvent(e,t){let i=ei.relative(this.workspaceRoot,e);if(!i)return;let n=this.pendingEvents.get(i);n&&clearTimeout(n);let s=this.pendingTypes.get(i);this.pendingTypes.set(i,this.mergeTypes(s,t));let a=setTimeout(()=>{this.emit(i,this.pendingTypes.get(i)||t),this.pendingEvents.delete(i),this.pendingTypes.delete(i)},xb);this.pendingEvents.set(i,a)}mergeTypes(e,t){return e?t===dr.FileChangeType.DELETE||e===dr.FileChangeType.DELETE?dr.FileChangeType.DELETE:e===dr.FileChangeType.CREATE?dr.FileChangeType.CREATE:t:t}emit(e,t){let i={path:e,changeType:t,timestamp:new Date().toISOString(),source:"watcher"};if(t!==dr.FileChangeType.DELETE)try{let n=ei.join(this.workspaceRoot,e),s=fn.statSync(n);i.size=s.size}catch{}this.onFileChangedCallback?.(i)}dispose(){this.stop(),this.onFileChangedCallback=null}};var Sb={online:!1,viewerCount:0},No=class r{enabled=!1;state={...Sb};altScreenActive=!1;logger;refreshTimer=null;static REFRESH_INTERVAL_MS=1e3;constructor(e){this.logger=e}reservedRows(){return this.enabled&&process.stdout.isTTY?1:0}enable(){if(!process.stdout.isTTY){this.logger.warn("StatusLine: stdout is not a TTY, cannot enable");return}this.enabled=!0,this.installScrollRegion(),this.startRefreshTimer(),this.logger.info("StatusLine enabled")}startRefreshTimer(){this.stopRefreshTimer(),this.refreshTimer=setInterval(()=>{!this.enabled||this.altScreenActive||this.render()},r.REFRESH_INTERVAL_MS)}stopRefreshTimer(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null)}installScrollRegion(){let e=process.stdout.rows;!e||e<2||(process.stdout.write(`\x1B[1;${e-1}r`),process.stdout.write("\x1B[1;1H"))}resetScrollRegion(){process.stdout.write("\x1B[r")}update(e){this.state={...this.state,...e},this.render()}render(){if(!this.enabled||this.altScreenActive)return;let e=process.stdout.rows;if(!e||e<2)return;let t=this.formatLine(),i=`\x1B[1;${e-1}r\x1B7\x1B[${e};1H\x1B[2K${t}\x1B8`;process.stdout.write(i)}clear(){if(!this.enabled)return;let e=process.stdout.rows;!e||e<2||process.stdout.write(`\x1B7\x1B[${e};1H\x1B[2K\x1B8`)}disable(){this.enabled&&(this.stopRefreshTimer(),this.clear(),this.resetScrollRegion(),this.enabled=!1)}inspectPtyOutput(e){if(this.enabled){if(e.includes("\x1B[?1049h")||e.includes("\x1B[?47h")){this.altScreenActive=!0;return}(e.includes("\x1B[?1049l")||e.includes("\x1B[?47l"))&&(this.altScreenActive=!1,this.render())}}getState(){return this.state}isEnabled(){return this.enabled}isAltScreenActive(){return this.altScreenActive}formatLine(){let e=[];if(e.push(this.state.online?"\u25CF online":"\u25CB offline"),this.state.viewerCount>0){let t=this.state.viewerCount===1?"1 viewer":`${this.state.viewerCount} viewers`;e.push(t)}else e.push("no viewers");return this.state.agentName&&e.push(this.state.agentName),this.state.ptyCols&&this.state.ptyRows&&e.push(`${this.state.ptyCols}\xD7${this.state.ptyRows}`)," "+e.join(" \xB7 ")+" "}};async function Mo(r,e,t,i){if(i)return process.stderr.write(`Logging in with API key...
|
|
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=Lc.resolve(t,e);if(i!==t&&!i.startsWith(t+Lc.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=Fc});var $h=M(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.InputStreamReceiver=rt.FileTrackerService=rt.FileListService=rt.FileTransferService=rt.WebSocketService=rt.isAnswerKeystroke=rt.StatusDetector=rt.AuthService=rt.CryptoService=void 0;var bb=mu();Object.defineProperty(rt,"CryptoService",{enumerable:!0,get:function(){return bb.CryptoService}});var Eb=yu();Object.defineProperty(rt,"AuthService",{enumerable:!0,get:function(){return Eb.AuthService}});var zh=_u();Object.defineProperty(rt,"StatusDetector",{enumerable:!0,get:function(){return zh.StatusDetector}});Object.defineProperty(rt,"isAnswerKeystroke",{enumerable:!0,get:function(){return zh.isAnswerKeystroke}});var vb=Rh();Object.defineProperty(rt,"WebSocketService",{enumerable:!0,get:function(){return vb.WebSocketService}});var wb=Lh();Object.defineProperty(rt,"FileTransferService",{enumerable:!0,get:function(){return wb.FileTransferService}});var Sb=Wh();Object.defineProperty(rt,"FileListService",{enumerable:!0,get:function(){return Sb.FileListService}});var xb=Vh();Object.defineProperty(rt,"FileTrackerService",{enumerable:!0,get:function(){return xb.FileTrackerService}});var Tb=bc();Object.defineProperty(rt,"InputStreamReceiver",{enumerable:!0,get:function(){return Tb.InputStreamReceiver}})});var Un=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 Dc=Nf();Object.defineProperty(X,"LOG_LEVELS",{enumerable:!0,get:function(){return Dc.LOG_LEVELS}});Object.defineProperty(X,"shouldLog",{enumerable:!0,get:function(){return Dc.shouldLog}});Object.defineProperty(X,"formatLogLine",{enumerable:!0,get:function(){return Dc.formatLogLine}});var sn=Df();Object.defineProperty(X,"CircularBuffer",{enumerable:!0,get:function(){return sn.CircularBuffer}});Object.defineProperty(X,"getApiUrl",{enumerable:!0,get:function(){return sn.getApiUrl}});Object.defineProperty(X,"getWsUrl",{enumerable:!0,get:function(){return sn.getWsUrl}});Object.defineProperty(X,"generateCorrelationId",{enumerable:!0,get:function(){return sn.generateCorrelationId}});Object.defineProperty(X,"runWithCorrelation",{enumerable:!0,get:function(){return sn.runWithCorrelation}});Object.defineProperty(X,"getCurrentCorrelationId",{enumerable:!0,get:function(){return sn.getCurrentCorrelationId}});var Ir=$h();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=Qo();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 Kc=M((qn,Uc)=>{(function(r,e){typeof qn=="object"&&typeof Uc=="object"?Uc.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof qn=="object"?qn["electron-machine-id"]=e(require("child_process"),require("crypto")):r["electron-machine-id"]=e(r.child_process,r.crypto)})(qn,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,_,v){var T,x,H,oe=m&p.F,J=m&p.G,k=m&p.S,B=m&p.P,te=m&p.B,j=m&p.W,U=J?a:a[_]||(a[_]={}),ne=U[d],_e=J?s:k?s[_]:(s[_]||{})[d];J&&(v=_);for(T in v)x=!oe&&_e&&_e[T]!==void 0,x&&T in U||(H=x?_e[T]:v[T],U[T]=J&&typeof _e[T]!="function"?v[T]:te&&x?c(H,s):j&&_e[T]==H?(function(se){var ze=function(ve,be,he){if(this instanceof se){switch(arguments.length){case 0:return new se;case 1:return new se(ve);case 2:return new se(ve,be)}return new se(ve,be,he)}return se.apply(this,arguments)};return ze[d]=se[d],ze})(H):B&&typeof H=="function"?c(Function.call,H):H,B&&((U.virtual||(U.virtual={}))[T]=H,m&p.R&&ne&&!ne[T]&&u(ne,T,H)))};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),v=n(52),T=n(1)("iterator"),x=!([].keys&&"next"in[].keys()),H="@@iterator",oe="keys",J="values",k=function(){return this};t.exports=function(B,te,j,U,ne,_e,se){m(j,te,U);var ze,ve,be,he=function(K){if(!x&&K in Te)return Te[K];switch(K){case oe:return function(){return new j(this,K)};case J:return function(){return new j(this,K)}}return function(){return new j(this,K)}},We=te+" Iterator",ot=ne==J,Qe=!1,Te=B.prototype,it=Te[T]||Te[H]||ne&&Te[ne],$e=it||he(ne),mt=ne?ot?he("entries"):$e:void 0,L=te=="Array"&&Te.entries||it;if(L&&(be=v(L.call(new B)),be!==Object.prototype&&(_(be,We,!0),s||d(be,T)||u(be,T,k))),ot&&it&&it.name!==J&&(Qe=!0,$e=function(){return it.call(this)}),s&&!se||!x&&!Qe&&Te[T]||u(Te,T,$e),p[te]=$e,p[We]=k,ne)if(ze={values:ot?$e:he(J),keys:_e?$e:he(oe),entries:mt},se)for(ve in ze)ve in Te||c(Te,ve,ze[ve]);else a(a.P+a.F*(x||Qe),te,ze);return ze}},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),v=_.process,T=_.setImmediate,x=_.clearImmediate,H=_.MessageChannel,oe=0,J={},k="onreadystatechange",B=function(){var j=+this;if(J.hasOwnProperty(j)){var U=J[j];delete J[j],U()}},te=function(j){B.call(j.data)};T&&x||(T=function(j){for(var U=[],ne=1;arguments.length>ne;)U.push(arguments[ne++]);return J[++oe]=function(){d(typeof j=="function"?j:Function(j),U)},s(oe),oe},x=function(j){delete J[j]},n(11)(v)=="process"?s=function(j){v.nextTick(u(B,j,1))}:H?(a=new H,c=a.port2,a.port1.onmessage=te,s=u(c.postMessage,c,1)):_.addEventListener&&typeof postMessage=="function"&&!_.importScripts?(s=function(j){_.postMessage(j+"","*")},_.addEventListener("message",te,!1)):s=k in m("script")?function(j){p.appendChild(m("script"))[k]=function(){p.removeChild(this),B.call(j)}}:function(j){setTimeout(u(B,j,1),0)}),t.exports={set:T,clear:x}},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(k){return k&&k.__esModule?k:{default:k}}function a(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function c(k){return(0,T.createHash)("sha256").update(k).digest("hex")}function u(k){switch(H){case"darwin":return k.split("IOPlatformUUID")[1].split(`
|
|
32
|
+
`)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return k.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return k.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return k.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function d(k){var B=u((0,v.execSync)(J[H]).toString());return k?B:c(B)}function p(k){return new _.default(function(B,te){return(0,v.exec)(J[H],{},function(j,U,ne){if(j)return te(new Error("Error while obtaining machine id: "+j.stack));var _e=u(U.toString());return B(k?_e:c(_e))})})}Object.defineProperty(i,"__esModule",{value:!0});var m=n(35),_=s(m);i.machineIdSync=d,i.machineId=p;var v=n(70),T=n(71),x=process,H=x.platform,oe={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},J={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:oe[a()]+"\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",linux:"( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :",freebsd:"kenv -q smbios.system.uuid || sysctl -n kern.hostuuid"}},function(t,i,n){t.exports={default:n(36),__esModule:!0}},function(t,i,n){n(66),n(68),n(69),n(67),t.exports=n(6).Promise},function(t,i){t.exports=function(){}},function(t,i){t.exports=function(n,s,a,c){if(!(n instanceof s)||c!==void 0&&c in n)throw TypeError(a+": incorrect invocation!");return n}},function(t,i,n){var s=n(13),a=n(31),c=n(62);t.exports=function(u){return function(d,p,m){var _,v=s(d),T=a(v.length),x=c(m,T);if(u&&p!=p){for(;T>x;)if(_=v[x++],_!=_)return!0}else for(;T>x;x++)if((u||x in v)&&v[x]===p)return u||x||0;return!u&&-1}}},function(t,v,n){var s=n(7),a=n(44),c=n(43),u=n(3),d=n(31),p=n(64),m={},_={},v=t.exports=function(T,x,H,oe,J){var k,B,te,j,U=J?function(){return T}:p(T),ne=s(H,oe,x?2:1),_e=0;if(typeof U!="function")throw TypeError(T+" is not iterable!");if(c(U)){for(k=d(T.length);k>_e;_e++)if(j=x?ne(u(B=T[_e])[0],B[1]):ne(T[_e]),j===m||j===_)return j}else for(te=U.call(T);!(B=te.next()).done;)if(j=a(te,ne,B.value,x),j===m||j===_)return j};v.BREAK=m,v.RETURN=_},function(t,i){t.exports=function(n,s,a){var c=a===void 0;switch(s.length){case 0:return c?n():n.call(a);case 1:return c?n(s[0]):n.call(a,s[0]);case 2:return c?n(s[0],s[1]):n.call(a,s[0],s[1]);case 3:return c?n(s[0],s[1],s[2]):n.call(a,s[0],s[1],s[2]);case 4:return c?n(s[0],s[1],s[2],s[3]):n.call(a,s[0],s[1],s[2],s[3])}return n.apply(a,s)}},function(t,i,n){var s=n(11);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(a){return s(a)=="String"?a.split(""):Object(a)}},function(t,i,n){var s=n(10),a=n(1)("iterator"),c=Array.prototype;t.exports=function(u){return u!==void 0&&(s.Array===u||c[a]===u)}},function(t,i,n){var s=n(3);t.exports=function(a,c,u,d){try{return d?c(s(u)[0],u[1]):c(u)}catch(m){var p=a.return;throw p!==void 0&&s(p.call(a)),m}}},function(t,i,n){"use strict";var s=n(49),a=n(17),c=n(18),u={};n(5)(u,n(1)("iterator"),function(){return this}),t.exports=function(d,p,m){d.prototype=s(u,{next:a(1,m)}),c(d,p+" Iterator")}},function(t,i,n){var s=n(1)("iterator"),a=!1;try{var c=[7][s]();c.return=function(){a=!0},Array.from(c,function(){throw 2})}catch{}t.exports=function(u,d){if(!d&&!a)return!1;var p=!1;try{var m=[7],_=m[s]();_.next=function(){return{done:p=!0}},m[s]=function(){return _},u(m)}catch{}return p}},function(t,i){t.exports=function(n,s){return{value:s,done:!!n}}},function(t,i,n){var s=n(2),a=n(30).set,c=s.MutationObserver||s.WebKitMutationObserver,u=s.process,d=s.Promise,p=n(11)(u)=="process";t.exports=function(){var m,_,v,T=function(){var J,k;for(p&&(J=u.domain)&&J.exit();m;){k=m.fn,m=m.next;try{k()}catch(B){throw m?v():_=void 0,B}}_=void 0,J&&J.enter()};if(p)v=function(){u.nextTick(T)};else if(c){var x=!0,H=document.createTextNode("");new c(T).observe(H,{characterData:!0}),v=function(){H.data=x=!x}}else if(d&&d.resolve){var oe=d.resolve();v=function(){oe.then(T)}}else v=function(){a.call(s,T)};return function(J){var k={fn:J,next:void 0};_&&(_.next=k),m||(m=k,v()),_=k}}},function(t,i,n){var s=n(3),a=n(50),c=n(22),u=n(19)("IE_PROTO"),d=function(){},p="prototype",m=function(){var _,v=n(16)("iframe"),T=c.length,x=">";for(v.style.display="none",n(25).appendChild(v),v.src="javascript:",_=v.contentWindow.document,_.open(),_.write("<script>document.F=Object</script"+x),_.close(),m=_.F;T--;)delete m[p][c[T]];return m()};t.exports=Object.create||function(_,v){var T;return _!==null?(d[p]=s(_),T=new d,d[p]=null,T[u]=_):T=m(),v===void 0?T:a(T,v)}},function(t,i,n){var s=n(12),a=n(3),c=n(54);t.exports=n(4)?Object.defineProperties:function(u,d){a(u);for(var p,m=c(d),_=m.length,v=0;_>v;)s.f(u,p=m[v++],d[p]);return u}},function(t,i,n){var s=n(55),a=n(17),c=n(13),u=n(32),d=n(8),p=n(26),m=Object.getOwnPropertyDescriptor;i.f=n(4)?m:function(_,v){if(_=c(_),v=u(v,!0),p)try{return m(_,v)}catch{}if(d(_,v))return a(!s.f.call(_,v),_[v])}},function(t,i,n){var s=n(8),a=n(63),c=n(19)("IE_PROTO"),u=Object.prototype;t.exports=Object.getPrototypeOf||function(d){return d=a(d),s(d,c)?d[c]:typeof d.constructor=="function"&&d instanceof d.constructor?d.constructor.prototype:d instanceof Object?u:null}},function(t,i,n){var s=n(8),a=n(13),c=n(39)(!1),u=n(19)("IE_PROTO");t.exports=function(d,p){var m,_=a(d),v=0,T=[];for(m in _)m!=u&&s(_,m)&&T.push(m);for(;p.length>v;)s(_,m=p[v++])&&(~c(T,m)||T.push(m));return T}},function(t,i,n){var s=n(53),a=n(22);t.exports=Object.keys||function(c){return s(c,a)}},function(t,i){i.f={}.propertyIsEnumerable},function(t,i,n){var s=n(5);t.exports=function(a,c,u){for(var d in c)u&&a[d]?a[d]=c[d]:s(a,d,c[d]);return a}},function(t,i,n){t.exports=n(5)},function(t,i,n){var s=n(9),a=n(3),c=function(u,d){if(a(u),!s(d)&&d!==null)throw TypeError(d+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?(function(u,d,p){try{p=n(7)(Function.call,n(51).f(Object.prototype,"__proto__").set,2),p(u,[]),d=!(u instanceof Array)}catch{d=!0}return function(m,_){return c(m,_),d?m.__proto__=_:p(m,_),m}})({},!1):void 0),check:c}},function(t,i,n){"use strict";var s=n(2),a=n(6),c=n(12),u=n(4),d=n(1)("species");t.exports=function(p){var m=typeof a[p]=="function"?a[p]:s[p];u&&m&&!m[d]&&c.f(m,d,{configurable:!0,get:function(){return this}})}},function(t,i,n){var s=n(3),a=n(14),c=n(1)("species");t.exports=function(u,d){var p,m=s(u).constructor;return m===void 0||(p=s(m)[c])==null?d:a(p)}},function(t,i,n){var s=n(20),a=n(15);t.exports=function(c){return function(u,d){var p,m,_=String(a(u)),v=s(d),T=_.length;return v<0||v>=T?c?"":void 0:(p=_.charCodeAt(v),p<55296||p>56319||v+1===T||(m=_.charCodeAt(v+1))<56320||m>57343?c?_.charAt(v):p:c?_.slice(v,v+2):(p-55296<<10)+(m-56320)+65536)}}},function(t,i,n){var s=n(20),a=Math.max,c=Math.min;t.exports=function(u,d){return u=s(u),u<0?a(u+d,0):c(u,d)}},function(t,i,n){var s=n(15);t.exports=function(a){return Object(s(a))}},function(t,i,n){var s=n(21),a=n(1)("iterator"),c=n(10);t.exports=n(6).getIteratorMethod=function(u){if(u!=null)return u[a]||u["@@iterator"]||c[s(u)]}},function(t,i,n){"use strict";var s=n(37),a=n(47),c=n(10),u=n(13);t.exports=n(27)(Array,"Array",function(d,p){this._t=u(d),this._i=0,this._k=p},function(){var d=this._t,p=this._k,m=this._i++;return!d||m>=d.length?(this._t=void 0,a(1)):p=="keys"?a(0,m):p=="values"?a(0,d[m]):a(0,[m,d[m]])},"values"),c.Arguments=c.Array,s("keys"),s("values"),s("entries")},function(t,i){},function(t,i,n){"use strict";var s,a,c,u=n(28),d=n(2),p=n(7),m=n(21),_=n(23),v=n(9),T=(n(3),n(14)),x=n(38),H=n(40),oe=(n(58).set,n(60)),J=n(30).set,k=n(48)(),B="Promise",te=d.TypeError,U=d.process,j=d[B],U=d.process,ne=m(U)=="process",_e=function(){},se=!!(function(){try{var L=j.resolve(1),K=(L.constructor={})[n(1)("species")]=function(A){A(_e,_e)};return(ne||typeof PromiseRejectionEvent=="function")&&L.then(_e)instanceof K}catch{}})(),ze=function(L,K){return L===K||L===j&&K===c},ve=function(L){var K;return!(!v(L)||typeof(K=L.then)!="function")&&K},be=function(L){return ze(j,L)?new he(L):new a(L)},he=a=function(L){var K,A;this.promise=new L(function(R,Q){if(K!==void 0||A!==void 0)throw te("Bad Promise constructor");K=R,A=Q}),this.resolve=T(K),this.reject=T(A)},We=function(L){try{L()}catch(K){return{error:K}}},ot=function(L,K){if(!L._n){L._n=!0;var A=L._c;k(function(){for(var R=L._v,Q=L._s==1,Ne=0,Je=function(nt){var ht,mr,Mr=Q?nt.ok:nt.fail,ii=nt.resolve,Fr=nt.reject,Pi=nt.domain;try{Mr?(Q||(L._h==2&&it(L),L._h=1),Mr===!0?ht=R:(Pi&&Pi.enter(),ht=Mr(R),Pi&&Pi.exit()),ht===nt.promise?Fr(te("Promise-chain cycle")):(mr=ve(ht))?mr.call(ht,ii,Fr):ii(ht)):Fr(R)}catch(Jn){Fr(Jn)}};A.length>Ne;)Je(A[Ne++]);L._c=[],L._n=!1,K&&!L._h&&Qe(L)})}},Qe=function(L){J.call(d,function(){var K,A,R,Q=L._v;if(Te(L)&&(K=We(function(){ne?U.emit("unhandledRejection",Q,L):(A=d.onunhandledrejection)?A({promise:L,reason:Q}):(R=d.console)&&R.error&&R.error("Unhandled promise rejection",Q)}),L._h=ne||Te(L)?2:1),L._a=void 0,K)throw K.error})},Te=function(L){if(L._h==1)return!1;for(var K,A=L._a||L._c,R=0;A.length>R;)if(K=A[R++],K.fail||!Te(K.promise))return!1;return!0},it=function(L){J.call(d,function(){var K;ne?U.emit("rejectionHandled",L):(K=d.onrejectionhandled)&&K({promise:L,reason:L._v})})},$e=function(L){var K=this;K._d||(K._d=!0,K=K._w||K,K._v=L,K._s=2,K._a||(K._a=K._c.slice()),ot(K,!0))},mt=function(L){var K,A=this;if(!A._d){A._d=!0,A=A._w||A;try{if(A===L)throw te("Promise can't be resolved itself");(K=ve(L))?k(function(){var R={_w:A,_d:!1};try{K.call(L,p(mt,R,1),p($e,R,1))}catch(Q){$e.call(R,Q)}}):(A._v=L,A._s=1,ot(A,!1))}catch(R){$e.call({_w:A,_d:!1},R)}}};se||(j=function(L){x(this,j,B,"_h"),T(L),s.call(this);try{L(p(mt,this,1),p($e,this,1))}catch(K){$e.call(this,K)}},s=function(L){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},s.prototype=n(56)(j.prototype,{then:function(L,K){var A=be(oe(this,j));return A.ok=typeof L!="function"||L,A.fail=typeof K=="function"&&K,A.domain=ne?U.domain:void 0,this._c.push(A),this._a&&this._a.push(A),this._s&&ot(this,!1),A.promise},catch:function(L){return this.then(void 0,L)}}),he=function(){var L=new s;this.promise=L,this.resolve=p(mt,L,1),this.reject=p($e,L,1)}),_(_.G+_.W+_.F*!se,{Promise:j}),n(18)(j,B),n(59)(B),c=n(6)[B],_(_.S+_.F*!se,B,{reject:function(L){var K=be(this),A=K.reject;return A(L),K.promise}}),_(_.S+_.F*(u||!se),B,{resolve:function(L){if(L instanceof j&&ze(L.constructor,this))return L;var K=be(this),A=K.resolve;return A(L),K.promise}}),_(_.S+_.F*!(se&&n(46)(function(L){j.all(L).catch(_e)})),B,{all:function(L){var K=this,A=be(K),R=A.resolve,Q=A.reject,Ne=We(function(){var Je=[],nt=0,ht=1;H(L,!1,function(mr){var Mr=nt++,ii=!1;Je.push(void 0),ht++,K.resolve(mr).then(function(Fr){ii||(ii=!0,Je[Mr]=Fr,--ht||R(Je))},Q)}),--ht||R(Je)});return Ne&&Q(Ne.error),A.promise},race:function(L){var K=this,A=be(K),R=A.reject,Q=We(function(){H(L,!1,function(Ne){K.resolve(Ne).then(A.resolve,R)})});return Q&&R(Q.error),A.promise}})},function(t,i,n){"use strict";var s=n(61)(!0);n(27)(String,"String",function(a){this._t=String(a),this._i=0},function(){var a,c=this._t,u=this._i;return u>=c.length?{value:void 0,done:!0}:(a=s(c,u),this._i+=a.length,{value:a,done:!1})})},function(t,i,n){n(65);for(var s=n(2),a=n(5),c=n(10),u=n(1)("toStringTag"),d=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],p=0;p<5;p++){var m=d[p],_=s[m],v=_&&_.prototype;v&&!v[u]&&a(v,u,m),c[m]=c.Array}},function(t,i){t.exports=require("child_process")},function(t,i){t.exports=require("crypto")}])})});function Rb(){try{return Wc.default.statSync("/.dockerenv"),!0}catch{return!1}}function Ab(){try{return Wc.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Hc(){return qc===void 0&&(qc=Rb()||Ab()),qc}var Wc,qc,Zh=qt(()=>{Wc=de(require("node:fs"),1)});function on(){return Vc===void 0&&(Vc=Ib()||Hc()),Vc}var Qh,Vc,Ib,zc=qt(()=>{Qh=de(require("node:fs"),1);Zh();Ib=()=>{try{return Qh.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var $c,td,rd,ed,Jr,Gc=qt(()=>{$c=de(require("node:process"),1),td=de(require("node:os"),1),rd=de(require("node:fs"),1);zc();ed=()=>{if($c.default.platform!=="linux")return!1;if(td.default.release().toLowerCase().includes("microsoft"))return!on();try{return rd.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!on():!1}catch{return!1}},Jr=$c.default.env.__IS_WSL_TEST__?ed:ed()});var Yc,Vn,Lb,Nb,Xc,id=qt(()=>{Yc=de(require("node:process"),1),Vn=de(require("node:fs/promises"),1);Gc();Gc();Lb=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",i=!1;try{await Vn.default.access(t,Vn.constants.F_OK),i=!0}catch{}if(!i)return r;let n=await Vn.default.readFile(t,{encoding:"utf8"}),s=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(n);return s?(e=s.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),Nb=async()=>`${await Lb()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Xc=async()=>Jr?Nb():`${Yc.default.env.SYSTEMROOT||Yc.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Zr(r,e,t){let i=n=>Object.defineProperty(r,e,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let n=t();return i(n),n},set(n){i(n)}}),r}var nd=qt(()=>{});async function Jc(){if(od.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await Mb("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(r)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}var sd,od,ad,Mb,cd=qt(()=>{sd=require("node:util"),od=de(require("node:process"),1),ad=require("node:child_process"),Mb=(0,sd.promisify)(ad.execFile)});async function ld(r,{humanReadableOutput:e=!0,signal:t}={}){if(fd.default.platform!=="darwin")throw new Error("macOS only");let i=e?[]:["-ss"],n={};t&&(n.signal=t);let{stdout:s}=await Fb("osascript",["-e",r,i],n);return s.trim()}var fd,ud,Zc,Fb,hd=qt(()=>{fd=de(require("node:process"),1),ud=require("node:util"),Zc=require("node:child_process"),Fb=(0,ud.promisify)(Zc.execFile)});async function Qc(r){return ld(`tell application "Finder" to set app_path to application file id "${r}" as string
|
|
33
|
+
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var dd=qt(()=>{hd()});async function tf(r=Db){let{stdout:e}=await r("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(e);if(!t)throw new ef(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:i}=t.groups,n=i.lastIndexOf("."),s=i.lastIndexOf("-"),a=n===-1?void 0:i.slice(0,n),c=s===-1?void 0:i.slice(0,s);return bo[i]??bo[a]??bo[c]??{name:i,id:i}}var pd,gd,Db,bo,Yw,ef,md=qt(()=>{pd=require("node:util"),gd=require("node:child_process"),Db=(0,pd.promisify)(gd.execFile),bo={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},Yw=new Map(Object.entries(bo)),ef=class extends Error{}});async function rf(){if(Eo.default.platform==="darwin"){let r=await Jc();return{name:await Qc(r),id:r}}if(Eo.default.platform==="linux"){let{stdout:r}=await Bb("xdg-mime",["query","default","x-scheme-handler/http"]),e=r.trim();return{name:jb(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(Eo.default.platform==="win32")return tf();throw new Error("Only macOS, Linux, and Windows are supported")}var yd,Eo,_d,Bb,jb,bd=qt(()=>{yd=require("node:util"),Eo=de(require("node:process"),1),_d=require("node:child_process");cd();dd();md();Bb=(0,yd.promisify)(_d.execFile),jb=r=>r.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var Cd={};Sp(Cd,{apps:()=>Qr,default:()=>Hb,openApp:()=>Wb});async function Kb(){let r=await Xc(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=of.Buffer.from(e,"utf16le").toString("base64"),{stdout:i}=await Ub(r,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),n=i.trim(),s={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return s[n]?{id:s[n]}:{}}function Sd(r){if(typeof r=="string"||Array.isArray(r))return r;let{[vd]:e}=r;if(!e)throw new Error(`${vd} is not supported`);return e}function wo({[an]:r},{wsl:e}){if(e&&Jr)return Sd(e);if(!r)throw new Error(`${an} is not supported`);return Sd(r)}var sf,of,af,xd,Td,cf,vo,Vb,Ub,nf,Ed,an,vd,wd,zn,qb,Wb,Qr,Hb,kd=qt(()=>{sf=de(require("node:process"),1),of=require("node:buffer"),af=de(require("node:path"),1),xd=require("node:url"),Td=require("node:util"),cf=de(require("node:child_process"),1),vo=de(require("node:fs/promises"),1);id();nd();bd();zc();Vb={},Ub=(0,Td.promisify)(cf.default.execFile),nf=af.default.dirname((0,xd.fileURLToPath)(Vb.url)),Ed=af.default.join(nf,"xdg-open"),{platform:an,arch:vd}=sf.default;wd=async(r,e)=>{let t;for(let i of r)try{return await e(i)}catch(n){t=n}throw t},zn=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return wd(r.app,c=>zn({...r,app:c}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return wd(e,c=>zn({...r,app:{name:c,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let c={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},d=Jr?await Kb():await rf();if(d.id in c){let p=c[d.id];return e==="browserPrivate"&&t.push(u[p]),zn({...r,app:{name:Qr[p],arguments:t}})}throw new Error(`${d.name} is not supported as a default browser`)}let i,n=[],s={};if(an==="darwin")i="open",r.wait&&n.push("--wait-apps"),r.background&&n.push("--background"),r.newInstance&&n.push("--new"),e&&n.push("-a",e);else if(an==="win32"||Jr&&!on()&&!e){i=await Xc(),n.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),Jr||(s.windowsVerbatimArguments=!0);let c=["Start"];r.wait&&c.push("-Wait"),e?(c.push(`"\`"${e}\`""`),r.target&&t.push(r.target)):r.target&&c.push(`"${r.target}"`),t.length>0&&(t=t.map(u=>`"\`"${u}\`""`),c.push("-ArgumentList",t.join(","))),r.target=of.Buffer.from(c.join(" "),"utf16le").toString("base64")}else{if(e)i=e;else{let c=!nf||nf==="/",u=!1;try{await vo.default.access(Ed,vo.constants.X_OK),u=!0}catch{}i=sf.default.versions.electron??(an==="android"||c||!u)?"xdg-open":Ed}t.length>0&&n.push(...t),r.wait||(s.stdio="ignore",s.detached=!0)}an==="darwin"&&t.length>0&&n.push("--args",...t),r.target&&n.push(r.target);let a=cf.default.spawn(i,n,s);return r.wait?new Promise((c,u)=>{a.once("error",u),a.once("close",d=>{if(!r.allowNonzeroExitCode&&d>0){u(new Error(`Exited with code ${d}`));return}c(a)})}):(a.unref(),a)},qb=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a `target`");return zn({...e,target:r})},Wb=(r,e)=>{if(typeof r!="string"&&!Array.isArray(r))throw new TypeError("Expected a valid `name`");let{arguments:t=[]}=e??{};if(t!=null&&!Array.isArray(t))throw new TypeError("Expected `appArguments` as Array type");return zn({...e,app:{name:r,arguments:t}})};Qr={};Zr(Qr,"chrome",()=>wo({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));Zr(Qr,"brave",()=>wo({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));Zr(Qr,"firefox",()=>wo({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Zr(Qr,"edge",()=>wo({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Zr(Qr,"browser",()=>"browser");Zr(Qr,"browserPrivate",()=>"browserPrivate");Hb=qb});var _r=de(require("fs")),ss=de(require("path"));var Pf=de(require("os")),Rf=de(require("path")),is=de(require("fs"));function ns(){let r=Rf.join(Pf.homedir(),".termiq");return is.existsSync(r)||is.mkdirSync(r,{recursive:!0,mode:448}),r}var gn=class{filePath;data={};constructor(){this.filePath=ss.join(ns(),"credentials"),this.load()}async get(e){return this.data[e]}async set(e,t){this.data[e]=t,this.save()}async delete(e){delete this.data[e],this.save()}load(){try{if(_r.existsSync(this.filePath)){let e=_r.readFileSync(this.filePath,"utf-8");this.data=JSON.parse(e)}}catch{this.data={}}}save(){let e=ss.dirname(this.filePath);_r.existsSync(e)||_r.mkdirSync(e,{recursive:!0,mode:448}),_r.writeFileSync(this.filePath,JSON.stringify(this.data,null,2),{mode:384})}};var br=de(require("fs")),os=de(require("path"));var Tp={serverUrl:"https://termiq.io",agentName:"",multiViewer:!1},mn=class{config;filePath;constructor(e){this.filePath=os.join(ns(),"config.json"),this.config={...Tp,...this.loadFromFile(),...e}}getServerUrl(){return this.config.serverUrl}getAgentName(){return this.config.agentName}isAutoConnect(){return!0}getMultiViewer(){return this.config.multiViewer}async setMultiViewer(e){this.config.multiViewer=e,this.saveToFile()}async setAgentName(e){this.config.agentName=e,this.saveToFile()}loadFromFile(){try{if(br.existsSync(this.filePath)){let e=br.readFileSync(this.filePath,"utf-8");return JSON.parse(e)}}catch{}return{}}saveToFile(){let e=os.dirname(this.filePath);br.existsSync(e)||br.mkdirSync(e,{recursive:!0,mode:448}),br.writeFileSync(this.filePath,JSON.stringify(this.config,null,2))}};var bt=de(require("fs")),jc=de(require("path")),Yh=de(require("os")),_o=de(Un()),Cb="cli",Bc=jc.join(Yh.homedir(),".termiq","logs"),Xr=jc.join(Bc,"cli.log"),kb=5*1024*1024,Gh=3;function Ob(){try{if(!bt.existsSync(Xr)||bt.statSync(Xr).size<kb)return;for(let e=Gh-1;e>=1;e--){let t=`${Xr}.${e}`,i=`${Xr}.${e+1}`;bt.existsSync(t)&&(e+1>Gh?bt.unlinkSync(t):bt.renameSync(t,i))}bt.renameSync(Xr,`${Xr}.1`)}catch{}}function Pb(r){try{bt.existsSync(Bc)||bt.mkdirSync(Bc,{recursive:!0}),Ob(),bt.appendFileSync(Xr,r+`
|
|
34
|
+
`,{encoding:"utf8"})}catch{}}var Kn=class{level;toFile;constructor(e="silent",t=!1){typeof e=="boolean"?this.level=e?"info":"silent":this.level=e,this.toFile=t}static getLogFilePath(){return Xr}write(e,t,i){if(!(0,_o.shouldLog)(e,this.level))return;let n=(0,_o.formatLogLine)(e,Cb,t,i);this.toFile?Pb(n):process.stderr.write(n+`
|
|
35
|
+
`)}info(e,...t){this.write("info",e,t)}warn(e,...t){this.write("warn",e,t)}error(e,...t){this.write("error",e,t)}debug(e,...t){this.write("debug",e,t)}};var Xh=de(require("os")),Jh=de(Kc()),Wn=class{cachedId=null;name;constructor(e){this.name=e||Xh.hostname()||"CLI"}async getMachineId(){if(this.cachedId)return this.cachedId;try{this.cachedId=(0,Jh.machineIdSync)()}catch{this.cachedId=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}return this.cachedId}getMachineName(){return this.name}};var Hn=class{constructor(e){this.logger=e}info(e){this.logger.info("Notification",{message:e})}warn(e){this.logger.warn("Notification",{message:e})}error(e){this.logger.error("Notification",{message:e})}};var $n=class{async openUrl(e){let{default:t}=await Promise.resolve().then(()=>(kd(),Cd));await t(e)}};var Od=de(require("fs")),ff=de(require("path"));function So(r){let e=r?[r]:[ff.join(__dirname,"..","package.json"),ff.join(__dirname,"..","..","package.json")];for(let t of e)try{let i=JSON.parse(Od.readFileSync(t,"utf8"));if(typeof i.version=="string"&&i.version.length>0)return i.version}catch{}return"unknown"}function Pd(r,e){for(let t=0;t<r.length;t++){let i=r[t];if(i.startsWith("-")){e.has(i)&&t++;continue}return i}}var uf=new Set(["--cid","--token","--server","--log-level"]),Rd=new Set(["--help","-h","--version","-V","--verbose","-v","--watch","-w","--log-to-file","--statusline","--multi-viewer","--force"]);function Ad(r,e,t){for(let i=0;i<r.length;i++){let n=r[i];if(!n.startsWith("-"))continue;let s=n.includes("=")?n.slice(0,n.indexOf("=")):n;if(e.has(s)||t.has(s)){e.has(s)&&!n.includes("=")&&i++;continue}return n}}var sp=de(require("path")),lt=de(Un()),op=de(xr());var Id=de(require("os")),Ld=require("crypto"),Nd=de(require("node-pty")),Md=de(Un()),xo=class r{ptyProcess=null;outputBuffer=new Md.CircularBuffer(100);streamId=null;logger;onOutput=null;onExit=null;preWriteHook=null;onResize=null;onLocalClaim=null;onLocalInput=null;sigwinchEnabled=!0;sigwinchListener=null;desiredCols=null;desiredRows=null;rebroadcastTimers=[];static REBROADCAST_DELAYS_MS=[50,200,500];static PASTE_CHAR_DELAY_MS=10;writeQueue=[];draining=!1;drainTimer=null;reservedBottomRows=0;multiViewerMode=!1;constructor(e){this.logger=e}setMultiViewerMode(e){this.multiViewerMode!==e&&(this.multiViewerMode=e,this.logger.info("Multi-viewer mode",{enabled:e}))}spawn(e,t=0){let i=process.env.SHELL||(Id.platform()==="win32"?"powershell.exe":"/bin/bash"),n=process.stdout.columns||80,s=process.stdout.rows||24,a=Math.max(1,s-t);this.reservedBottomRows=t,this.ptyProcess=Nd.spawn(i,[],{name:"xterm-256color",cols:n,rows:a,cwd:e,env:{...process.env,TERMIQ_SESSION_ACTIVE:"1"}}),this.onResize?.(n,a),this.streamId=(0,Ld.randomUUID)();let c=`cli_${this.ptyProcess.pid}`;return this.ptyProcess.onData(u=>{this.preWriteHook?.(u),process.stdout.write(u),this.outputBuffer.append(u),this.onOutput?.(u)}),this.ptyProcess.onExit(({exitCode:u})=>{this.logger.info("Shell exited",String(u)),this.onExit?.(u)}),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u=>{this.multiViewerMode&&this.maybeClaimLocalControl(),this.onLocalInput?.(u.toString()),this.ptyProcess?.write(u.toString())}),this.sigwinchListener=()=>{let u=process.stdout.columns||80,d=Math.max(1,(process.stdout.rows||24)-this.reservedBottomRows);if(this.multiViewerMode){this.logger.info("Local resize claims control",{cols:u,rows:d}),this.resize(u,d),this.onLocalClaim?.(u,d);return}if(this.desiredCols!==null&&this.desiredRows!==null){this.logger.info("Local resize ignored (PWA desired-size set)",{host:{cols:u,rows:d},desired:{cols:this.desiredCols,rows:this.desiredRows}});return}if(!this.sigwinchEnabled){this.logger.info("Local resize ignored (PWA viewers attached)",{cols:u,rows:d});return}this.logger.info("Local resize applied",{cols:u,rows:d}),this.ptyProcess?.resize(u,d),this.onResize?.(u,d)},process.platform==="win32"?process.stdout.on("resize",this.sigwinchListener):process.on("SIGWINCH",this.sigwinchListener),this.logger.info("Shell spawned",i,c),c}write(e,t=!1){if(this.ptyProcess){if(!t&&!this.draining){this.ptyProcess.write(e);return}for(let i of e)this.writeQueue.push(i);this.drainWriteQueue()}}drainWriteQueue(){if(this.draining)return;this.draining=!0;let e=()=>{let t=this.writeQueue.shift();if(t===void 0||!this.ptyProcess){this.draining=!1;return}this.ptyProcess.write(t),this.drainTimer=setTimeout(e,r.PASTE_CHAR_DELAY_MS)};e()}getStreamId(){return this.streamId}getPtyCols(){return this.ptyProcess?.cols??0}getPtyRows(){return this.ptyProcess?.rows??0}resize(e,t){this.desiredCols=e,this.desiredRows=t,this.ptyProcess?.resize(e,t),this.onResize?.(e,t),this.cancelRebroadcast();for(let i of r.REBROADCAST_DELAYS_MS)this.rebroadcastTimers.push(setTimeout(()=>{this.ptyProcess&&(this.desiredCols!==e||this.desiredRows!==t||this.ptyProcess.resize(e,t))},i))}cancelRebroadcast(){for(let e of this.rebroadcastTimers)clearTimeout(e);this.rebroadcastTimers=[]}redrawNoResize(){if(this.ptyProcess){if(this.desiredCols===null||this.desiredRows===null){this.logger.info("Redraw skipped (no desired-size set yet)");return}this.ptyProcess.resize(this.desiredCols,this.desiredRows)}}maybeClaimLocalControl(){if(!this.ptyProcess)return;let e=process.stdout.columns||80,t=Math.max(1,(process.stdout.rows||24)-this.reservedBottomRows);this.ptyProcess.cols===e&&this.ptyProcess.rows===t||(this.logger.info("Local input claims control",{cols:e,rows:t}),this.resize(e,t),this.onLocalClaim?.(e,t))}setOnLocalClaim(e){this.onLocalClaim=e}setOnLocalInput(e){this.onLocalInput=e}setSigwinchEnabled(e){this.sigwinchEnabled!==e&&(this.sigwinchEnabled=e,this.logger.info("SIGWINCH listener",{enabled:e}))}getBuffer(){return this.outputBuffer.getContent()}getLastBytes(e){return this.outputBuffer.getLastBytes(e)}setOnOutput(e){this.onOutput=e}setPreWriteHook(e){this.preWriteHook=e}setOnResize(e){this.onResize=e}setOnExit(e){this.onExit=e}isAlive(){return this.ptyProcess!==null}kill(){this.ptyProcess?.kill(),this.ptyProcess=null}dispose(){this.kill(),this.cancelRebroadcast(),this.drainTimer&&(clearTimeout(this.drainTimer),this.drainTimer=null),this.writeQueue=[],this.draining=!1,this.sigwinchListener&&(process.platform==="win32"?process.stdout.removeListener("resize",this.sigwinchListener):process.removeListener("SIGWINCH",this.sigwinchListener),this.sigwinchListener=null),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()}};var ei=de(require("path")),fn=de(require("fs"));var Jd=require("node:events"),Zd=require("node:fs"),Io=require("node:fs/promises"),xe=de(require("node:path"),1);var Lr=require("node:fs/promises"),Nr=require("node:path"),jd=require("node:stream"),Rt={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},lf={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:Rt.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(lf);var Ud="READDIRP_RECURSIVE_ERROR",zb=new Set(["ENOENT","EPERM","EACCES","ELOOP",Ud]),Fd=[Rt.DIR_TYPE,Rt.EVERYTHING_TYPE,Rt.FILE_DIR_TYPE,Rt.FILE_TYPE],$b=new Set([Rt.DIR_TYPE,Rt.EVERYTHING_TYPE,Rt.FILE_DIR_TYPE]),Gb=new Set([Rt.EVERYTHING_TYPE,Rt.FILE_DIR_TYPE,Rt.FILE_TYPE]),Yb=r=>zb.has(r.code),Xb=process.platform==="win32",Dd=r=>!0,Bd=r=>{if(r===void 0)return Dd;if(typeof r=="function")return r;if(typeof r=="string"){let e=r.trim();return t=>t.basename===e}if(Array.isArray(r)){let e=r.map(t=>t.trim());return t=>e.some(i=>t.basename===i)}return Dd},hf=class extends jd.Readable{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...lf,...e},{root:i,type:n}=t;this._fileFilter=Bd(t.fileFilter),this._directoryFilter=Bd(t.directoryFilter);let s=t.lstat?Lr.lstat:Lr.stat;Xb?this._stat=a=>s(a,{bigint:!0}):this._stat=s,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:lf.depth,this._wantsDir=n?$b.has(n):!1,this._wantsFile=n?Gb.has(n):!1,this._wantsEverything=n===Rt.EVERYTHING_TYPE,this._root=(0,Nr.resolve)(i),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(i,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,i=t&&t.files;if(i&&i.length>0){let{path:n,depth:s}=t,a=i.splice(0,e).map(u=>this._formatEntry(u,n)),c=await Promise.all(a);for(let u of c){if(!u)continue;if(this.destroyed)return;let d=await this._getEntryType(u);d==="directory"&&this._directoryFilter(u)?(s<=this._maxDepth&&this.parents.push(this._exploreDir(u.fullPath,s+1)),this._wantsDir&&(this.push(u),e--)):(d==="file"||this._includeAsFile(u))&&this._fileFilter(u)&&this._wantsFile&&(this.push(u),e--)}}else{let n=this.parents.pop();if(!n){this.push(null);break}if(this.parent=await n,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let i;try{i=await(0,Lr.readdir)(e,this._rdOptions)}catch(n){this._onError(n)}return{files:i,depth:t,path:e}}async _formatEntry(e,t){let i,n=this._isDirent?e.name:e;try{let s=(0,Nr.resolve)((0,Nr.join)(t,n));i={path:(0,Nr.relative)(this._root,s),fullPath:s,basename:n},i[this._statsProp]=this._isDirent?e:await this._stat(s)}catch(s){this._onError(s);return}return i}_onError(e){Yb(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return"";let t=e[this._statsProp];if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let i=e.fullPath;try{let n=await(0,Lr.realpath)(i),s=await(0,Lr.lstat)(n);if(s.isFile())return"file";if(s.isDirectory()){let a=n.length;if(i.startsWith(n)&&i.substr(a,1)===Nr.sep){let c=new Error(`Circular symlink detected: "${i}" points to "${n}"`);return c.code=Ud,this._onError(c)}return"directory"}}catch(n){return this._onError(n),""}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function Kd(r,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=Rt.FILE_DIR_TYPE),t&&(e.type=t),r){if(typeof r!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!Fd.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${Fd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new hf(e)}var Oi=require("node:fs"),Jt=require("node:fs/promises"),Wd=require("node:os"),qe=de(require("node:path"),1),Jb="data",gf="end",Hd="close",Po=()=>{};var Ro=process.platform,mf=Ro==="win32",Zb=Ro==="darwin",Qb=Ro==="linux",eE=Ro==="freebsd",Vd=(0,Wd.type)()==="OS400",Ve={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Xt=Ve,tE="watch",rE={lstat:Jt.lstat,stat:Jt.stat},ki="listeners",To="errHandlers",cn="rawEmitters",iE=[ki,To,cn],nE=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),sE=r=>nE.has(qe.extname(r).slice(1).toLowerCase()),pf=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},Gn=(r,e,t)=>{let i=r[e];i instanceof Set||(r[e]=i=new Set([i])),i.add(t)},oE=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},Yn=(r,e,t)=>{let i=r[e];i instanceof Set?i.delete(t):i===t&&delete r[e]},zd=r=>r instanceof Set?r.size===0:!r,Co=new Map;function qd(r,e,t,i,n){let s=(a,c)=>{t(r),n(a,c,{watchedPath:r}),c&&r!==c&&ko(qe.resolve(r,c),ki,qe.join(r,c))};try{return(0,Oi.watch)(r,{persistent:e.persistent},s)}catch(a){i(a);return}}var ko=(r,e,t,i,n)=>{let s=Co.get(r);s&&pf(s[e],a=>{a(t,i,n)})},aE=(r,e,t,i)=>{let{listener:n,errHandler:s,rawEmitter:a}=i,c=Co.get(e),u;if(!t.persistent)return u=qd(r,t,n,s,a),u?u.close.bind(u):void 0;if(c)Gn(c,ki,n),Gn(c,To,s),Gn(c,cn,a);else{if(u=qd(r,t,ko.bind(null,e,ki),s,ko.bind(null,e,cn)),!u)return;u.on(Xt.ERROR,async d=>{let p=ko.bind(null,e,To);if(c&&(c.watcherUnusable=!0),mf&&d.code==="EPERM")try{await(await(0,Jt.open)(r,"r")).close(),p(d)}catch{}else p(d)}),c={listeners:n,errHandlers:s,rawEmitters:a,watcher:u},Co.set(e,c)}return()=>{Yn(c,ki,n),Yn(c,To,s),Yn(c,cn,a),zd(c.listeners)&&(c.watcher.close(),Co.delete(e),iE.forEach(oE(c)),c.watcher=void 0,Object.freeze(c))}},df=new Map,cE=(r,e,t,i)=>{let{listener:n,rawEmitter:s}=i,a=df.get(e),c=a&&a.options;return c&&(c.persistent<t.persistent||c.interval>t.interval)&&((0,Oi.unwatchFile)(e),a=void 0),a?(Gn(a,ki,n),Gn(a,cn,s)):(a={listeners:n,rawEmitters:s,options:t,watcher:(0,Oi.watchFile)(e,t,(u,d)=>{pf(a.rawEmitters,m=>{m(Xt.CHANGE,e,{curr:u,prev:d})});let p=u.mtimeMs;(u.size!==d.size||p>d.mtimeMs||p===0)&&pf(a.listeners,m=>m(r,u))})},df.set(e,a)),()=>{Yn(a,ki,n),Yn(a,cn,s),zd(a.listeners)&&(df.delete(e),(0,Oi.unwatchFile)(e),a.options=a.watcher=void 0,Object.freeze(a))}},Oo=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let i=this.fsw.options,n=qe.dirname(e),s=qe.basename(e);this.fsw._getWatchedDir(n).add(s);let c=qe.resolve(e),u={persistent:i.persistent};t||(t=Po);let d;if(i.usePolling){let p=i.interval!==i.binaryInterval;u.interval=p&&sE(s)?i.binaryInterval:i.interval,d=cE(e,c,u,{listener:t,rawEmitter:this.fsw._emitRaw})}else d=aE(e,c,u,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return d}_handleFile(e,t,i){if(this.fsw.closed)return;let n=qe.dirname(e),s=qe.basename(e),a=this.fsw._getWatchedDir(n),c=t;if(a.has(s))return;let u=async(p,m)=>{if(this.fsw._throttle(tE,e,5)){if(!m||m.mtimeMs===0)try{let _=await(0,Jt.stat)(e);if(this.fsw.closed)return;let v=_.atimeMs,T=_.mtimeMs;if((!v||v<=T||T!==c.mtimeMs)&&this.fsw._emit(Xt.CHANGE,e,_),(Zb||Qb||eE)&&c.ino!==_.ino){this.fsw._closeFile(p),c=_;let x=this._watchWithNodeFs(e,u);x&&this.fsw._addPathCloser(p,x)}else c=_}catch{this.fsw._remove(n,s)}else if(a.has(s)){let _=m.atimeMs,v=m.mtimeMs;(!_||_<=v||v!==c.mtimeMs)&&this.fsw._emit(Xt.CHANGE,e,m),c=m}}},d=this._watchWithNodeFs(e,u);if(!(i&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Xt.ADD,e,0))return;this.fsw._emit(Xt.ADD,e,t)}return d}async _handleSymlink(e,t,i,n){if(this.fsw.closed)return;let s=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let c;try{c=await(0,Jt.realpath)(i)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(n)?this.fsw._symlinkPaths.get(s)!==c&&(this.fsw._symlinkPaths.set(s,c),this.fsw._emit(Xt.CHANGE,i,e.stats)):(a.add(n),this.fsw._symlinkPaths.set(s,c),this.fsw._emit(Xt.ADD,i,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(e,t,i,n,s,a,c){e=qe.join(e,"");let u=n?`${e}:${n}`:e;if(c=this.fsw._throttle("readdir",u,1e3),!c)return;let d=this.fsw._getWatchedDir(i.path),p=new Set,m=this.fsw._readdirp(e,{fileFilter:_=>i.filterPath(_),directoryFilter:_=>i.filterDir(_)});if(m)return m.on(Jb,async _=>{if(this.fsw.closed){m=void 0;return}let v=_.path,T=qe.join(e,v);if(p.add(v),!(_.stats.isSymbolicLink()&&await this._handleSymlink(_,e,T,v))){if(this.fsw.closed){m=void 0;return}(v===n||!n&&!d.has(v))&&(this.fsw._incrReadyCount(),T=qe.join(s,qe.relative(s,T)),this._addToNodeFs(T,t,i,a+1))}}).on(Xt.ERROR,this._boundHandleError),new Promise((_,v)=>{if(!m)return v();m.once(gf,()=>{if(this.fsw.closed){m=void 0;return}let T=c?c.clear():!1;_(void 0),d.getChildren().filter(x=>x!==e&&!p.has(x)).forEach(x=>{this.fsw._remove(e,x)}),m=void 0,T&&this._handleRead(e,!1,i,n,s,a,c)})})}async _handleDir(e,t,i,n,s,a,c){let u=this.fsw._getWatchedDir(qe.dirname(e)),d=u.has(qe.basename(e));!(i&&this.fsw.options.ignoreInitial)&&!s&&!d&&this.fsw._emit(Xt.ADD_DIR,e,t),u.add(qe.basename(e)),this.fsw._getWatchedDir(e);let p,m,_=this.fsw.options.depth;if((_==null||n<=_)&&!this.fsw._symlinkPaths.has(c)){if(!s&&(await this._handleRead(e,i,a,s,e,n,p),this.fsw.closed))return;m=this._watchWithNodeFs(e,(v,T)=>{T&&T.mtimeMs===0||this._handleRead(v,!1,a,s,e,n,p)})}return m}async _addToNodeFs(e,t,i,n,s){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let c=this.fsw._getWatchHelpers(e);i&&(c.filterPath=u=>i.filterPath(u),c.filterDir=u=>i.filterDir(u));try{let u=await rE[c.statMethod](c.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(c.watchPath,u))return a(),!1;let d=this.fsw.options.followSymlinks,p;if(u.isDirectory()){let m=qe.resolve(e),_=d?await(0,Jt.realpath)(e):e;if(this.fsw.closed||(p=await this._handleDir(c.watchPath,u,t,n,s,c,_),this.fsw.closed))return;m!==_&&_!==void 0&&this.fsw._symlinkPaths.set(m,_)}else if(u.isSymbolicLink()){let m=d?await(0,Jt.realpath)(e):e;if(this.fsw.closed)return;let _=qe.dirname(c.watchPath);if(this.fsw._getWatchedDir(_).add(c.watchPath),this.fsw._emit(Xt.ADD,c.watchPath,u),p=await this._handleDir(_,u,t,n,e,c,m),this.fsw.closed)return;m!==void 0&&this.fsw._symlinkPaths.set(qe.resolve(e),m)}else p=this._handleFile(c.watchPath,u,t);return a(),p&&this.fsw._addPathCloser(e,p),!1}catch(u){if(this.fsw._handleError(u))return a(),e}}};var yf="/",fE="//",Qd=".",uE="..",lE="string",hE=/\\/g,ep=/\/\//g,dE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,pE=/^\.[/\\]/;function Ao(r){return Array.isArray(r)?r:[r]}var _f=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function gE(r){return typeof r=="function"?r:typeof r=="string"?e=>r===e:r instanceof RegExp?e=>r.test(e):typeof r=="object"&&r!==null?e=>{if(r.path===e)return!0;if(r.recursive){let t=xe.relative(r.path,e);return t?!t.startsWith("..")&&!xe.isAbsolute(t):!1}return!1}:()=>!1}function mE(r){if(typeof r!="string")throw new Error("string expected");r=xe.normalize(r),r=r.replace(/\\/g,"/");let e=!1;return r.startsWith("//")&&(e=!0),r=r.replace(ep,"/"),e&&(r="/"+r),r}function $d(r,e,t){let i=mE(e);for(let n=0;n<r.length;n++){let s=r[n];if(s(i,t))return!0}return!1}function yE(r,e){if(r==null)throw new TypeError("anymatch: specify first argument");let i=Ao(r).map(n=>gE(n));return e==null?(n,s)=>$d(i,n,s):$d(i,e)}var Gd=r=>{let e=Ao(r).flat();if(!e.every(t=>typeof t===lE))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(tp)},Yd=r=>{let e=r.replace(hE,yf),t=!1;return e.startsWith(fE)&&(t=!0),e=e.replace(ep,yf),t&&(e=yf+e),e},tp=r=>Yd(xe.normalize(Yd(r))),Xd=(r="")=>e=>typeof e=="string"?tp(xe.isAbsolute(e)?e:xe.join(r,e)):e,_E=(r,e)=>xe.isAbsolute(r)?r:xe.join(e,r),bE=Object.freeze(new Set),bf=class{path;_removeWatcher;items;constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Qd&&e!==uE&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let i=this.path;try{await(0,Io.readdir)(i)}catch{this._removeWatcher&&this._removeWatcher(xe.dirname(i),xe.basename(i))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=Po,this.items=bE,Object.freeze(this)}},EE="stat",vE="lstat",Ef=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,i){this.fsw=i;let n=e;this.path=e=e.replace(pE,""),this.watchPath=n,this.fullWatchPath=xe.resolve(n),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=t,this.statMethod=t?EE:vE}entryPath(e){return xe.join(this.watchPath,xe.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let i=this.entryPath(e);return this.fsw._isntIgnored(i,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},vf=class extends Jd.EventEmitter{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,i={stabilityThreshold:2e3,pollInterval:100},n={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Ao(e.ignored):Ao([]),awaitWriteFinish:t===!0?i:typeof t=="object"?{...i,...t}:!1};Vd&&(n.usePolling=!0),n.atomic===void 0&&(n.atomic=!n.usePolling);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let u=s.toLowerCase();u==="false"||u==="0"?n.usePolling=!1:u==="true"||u==="1"?n.usePolling=!0:n.usePolling=!!u}let a=process.env.CHOKIDAR_INTERVAL;a&&(n.interval=Number.parseInt(a,10));let c=0;this._emitReady=()=>{c++,c>=this._readyCount&&(this._emitReady=Po,this._readyEmitted=!0,process.nextTick(()=>this.emit(Ve.READY)))},this._emitRaw=(...u)=>this.emit(Ve.RAW,...u),this._boundRemove=this._remove.bind(this),this.options=n,this._nodeFsHandler=new Oo(this),Object.freeze(n)}_addIgnoredPath(e){if(_f(e)){for(let t of this._ignoredPaths)if(_f(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let t of this._ignoredPaths)_f(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,i){let{cwd:n}=this.options;this.closed=!1,this._closePromise=void 0;let s=Gd(e);return n&&(s=s.map(a=>_E(a,n))),s.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=s.length,Promise.all(s.map(async a=>{let c=await this._nodeFsHandler._addToNodeFs(a,!i,void 0,0,t);return c&&this._emitReady(),c})).then(a=>{this.closed||a.forEach(c=>{c&&this.add(xe.dirname(c),xe.basename(t||c))})}),this}unwatch(e){if(this.closed)return this;let t=Gd(e),{cwd:i}=this.options;return t.forEach(n=>{!xe.isAbsolute(n)&&!this._closers.has(n)&&(i&&(n=xe.join(i,n)),n=xe.resolve(n)),this._closePath(n),this._addIgnoredPath(n),this._watched.has(n)&&this._addIgnoredPath({path:n,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(i=>{let n=i();n instanceof Promise&&e.push(n)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,i)=>{let s=(this.options.cwd?xe.relative(this.options.cwd,i):i)||Qd;e[s]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==Ve.ERROR&&this.emit(Ve.ALL,e,...t)}async _emit(e,t,i){if(this.closed)return;let n=this.options;mf&&(t=xe.normalize(t)),n.cwd&&(t=xe.relative(n.cwd,t));let s=[t];i!=null&&s.push(i);let a=n.awaitWriteFinish,c;if(a&&(c=this._pendingWrites.get(t)))return c.lastChange=new Date,this;if(n.atomic){if(e===Ve.UNLINK)return this._pendingUnlinks.set(t,[e,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((u,d)=>{this.emit(...u),this.emit(Ve.ALL,...u),this._pendingUnlinks.delete(d)})},typeof n.atomic=="number"?n.atomic:100),this;e===Ve.ADD&&this._pendingUnlinks.has(t)&&(e=Ve.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===Ve.ADD||e===Ve.CHANGE)&&this._readyEmitted){let u=(d,p)=>{d?(e=Ve.ERROR,s[0]=d,this.emitWithAll(e,s)):p&&(s.length>1?s[1]=p:s.push(p),this.emitWithAll(e,s))};return this._awaitWriteFinish(t,a.stabilityThreshold,e,u),this}if(e===Ve.CHANGE&&!this._throttle(Ve.CHANGE,t,50))return this;if(n.alwaysStat&&i===void 0&&(e===Ve.ADD||e===Ve.ADD_DIR||e===Ve.CHANGE)){let u=n.cwd?xe.join(n.cwd,t):t,d;try{d=await(0,Io.stat)(u)}catch{}if(!d||this.closed)return;s.push(d)}return this.emitWithAll(e,s),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(Ve.ERROR,e),e||this.closed}_throttle(e,t,i){this._throttled.has(e)||this._throttled.set(e,new Map);let n=this._throttled.get(e);if(!n)throw new Error("invalid throttle");let s=n.get(t);if(s)return s.count++,!1;let a,c=()=>{let d=n.get(t),p=d?d.count:0;return n.delete(t),clearTimeout(a),d&&clearTimeout(d.timeoutObject),p};a=setTimeout(c,i);let u={timeoutObject:a,clear:c,count:0};return n.set(t,u),u}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,i,n){let s=this.options.awaitWriteFinish;if(typeof s!="object")return;let a=s.pollInterval,c,u=e;this.options.cwd&&!xe.isAbsolute(e)&&(u=xe.join(this.options.cwd,e));let d=new Date,p=this._pendingWrites;function m(_){(0,Zd.stat)(u,(v,T)=>{if(v||!p.has(e)){v&&v.code!=="ENOENT"&&n(v);return}let x=Number(new Date);_&&T.size!==_.size&&(p.get(e).lastChange=x);let H=p.get(e);x-H.lastChange>=t?(p.delete(e),n(void 0,T)):c=setTimeout(m,a,T)})}p.has(e)||(p.set(e,{lastChange:d,cancelWait:()=>(p.delete(e),clearTimeout(c),i)}),c=setTimeout(m,a))}_isIgnored(e,t){if(this.options.atomic&&dE.test(e))return!0;if(!this._userIgnored){let{cwd:i}=this.options,s=(this.options.ignored||[]).map(Xd(i)),c=[...[...this._ignoredPaths].map(Xd(i)),...s];this._userIgnored=yE(c,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Ef(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=xe.resolve(e);return this._watched.has(t)||this._watched.set(t,new bf(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,i){let n=xe.join(e,t),s=xe.resolve(n);if(i=i??(this._watched.has(n)||this._watched.has(s)),!this._throttle("remove",n,100))return;!i&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(n).getChildren().forEach(_=>this._remove(n,_));let u=this._getWatchedDir(e),d=u.has(t);u.remove(t),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let p=n;if(this.options.cwd&&(p=xe.relative(this.options.cwd,n)),this.options.awaitWriteFinish&&this._pendingWrites.has(p)&&this._pendingWrites.get(p).cancelWait()===Ve.ADD)return;this._watched.delete(n),this._watched.delete(s);let m=i?Ve.UNLINK_DIR:Ve.UNLINK;d&&!this._isIgnored(n)&&this._emit(m,n),this._closePath(n)}_closePath(e){this._closeFile(e);let t=xe.dirname(e);this._getWatchedDir(t).remove(xe.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(i=>i()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let i=this._closers.get(e);i||(i=[],this._closers.set(e,i)),i.push(t)}_readdirp(e,t){if(this.closed)return;let i={type:Ve.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},n=Kd(e,i);return this._streams.add(n),n.once(Hd,()=>{n=void 0}),n.once(gf,()=>{n&&(this._streams.delete(n),n=void 0)}),n}};function rp(r,e={}){let t=new vf(e);return t.add(r),t}var ip=de(Pc()),dr=de(xr()),wE=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/*.log"],SE=300,Lo=class{watcher=null;ignoreFilter;workspaceRoot;logger;onFileChangedCallback=null;pendingEvents=new Map;pendingTypes=new Map;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,ip.default)(),this.initializeIgnoreFilter()}initializeIgnoreFilter(){this.ignoreFilter.add(wE);let e=ei.join(this.workspaceRoot,".gitignore");try{if(fn.existsSync(e)){let t=fn.readFileSync(e,"utf-8");this.ignoreFilter.add(t)}}catch{}}onFileChanged(e){this.onFileChangedCallback=e}start(){this.watcher||(this.watcher=rp(this.workspaceRoot,{ignored:e=>{let t=ei.relative(this.workspaceRoot,e);if(!t||t===".")return!1;let i=t.split(ei.sep).join("/");return this.ignoreFilter.ignores(i)},persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50}}),this.watcher.on("add",e=>this.handleEvent(e,dr.FileChangeType.CREATE)),this.watcher.on("change",e=>this.handleEvent(e,dr.FileChangeType.MODIFY)),this.watcher.on("unlink",e=>this.handleEvent(e,dr.FileChangeType.DELETE)),this.watcher.on("error",e=>this.logger.error("File watcher error",e)),this.logger.info("File watcher started"))}stop(){this.watcher?.close(),this.watcher=null;for(let e of this.pendingEvents.values())clearTimeout(e);this.pendingEvents.clear(),this.pendingTypes.clear()}handleEvent(e,t){let i=ei.relative(this.workspaceRoot,e);if(!i)return;let n=this.pendingEvents.get(i);n&&clearTimeout(n);let s=this.pendingTypes.get(i);this.pendingTypes.set(i,this.mergeTypes(s,t));let a=setTimeout(()=>{this.emit(i,this.pendingTypes.get(i)||t),this.pendingEvents.delete(i),this.pendingTypes.delete(i)},SE);this.pendingEvents.set(i,a)}mergeTypes(e,t){return e?t===dr.FileChangeType.DELETE||e===dr.FileChangeType.DELETE?dr.FileChangeType.DELETE:e===dr.FileChangeType.CREATE?dr.FileChangeType.CREATE:t:t}emit(e,t){let i={path:e,changeType:t,timestamp:new Date().toISOString(),source:"watcher"};if(t!==dr.FileChangeType.DELETE)try{let n=ei.join(this.workspaceRoot,e),s=fn.statSync(n);i.size=s.size}catch{}this.onFileChangedCallback?.(i)}dispose(){this.stop(),this.onFileChangedCallback=null}};var xE={online:!1,viewerCount:0},No=class r{enabled=!1;state={...xE};altScreenActive=!1;logger;refreshTimer=null;static REFRESH_INTERVAL_MS=1e3;constructor(e){this.logger=e}reservedRows(){return this.enabled&&process.stdout.isTTY?1:0}enable(){if(!process.stdout.isTTY){this.logger.warn("StatusLine: stdout is not a TTY, cannot enable");return}this.enabled=!0,this.installScrollRegion(),this.startRefreshTimer(),this.logger.info("StatusLine enabled")}startRefreshTimer(){this.stopRefreshTimer(),this.refreshTimer=setInterval(()=>{!this.enabled||this.altScreenActive||this.render()},r.REFRESH_INTERVAL_MS)}stopRefreshTimer(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null)}installScrollRegion(){let e=process.stdout.rows;!e||e<2||(process.stdout.write(`\x1B[1;${e-1}r`),process.stdout.write("\x1B[1;1H"))}resetScrollRegion(){process.stdout.write("\x1B[r")}update(e){this.state={...this.state,...e},this.render()}render(){if(!this.enabled||this.altScreenActive)return;let e=process.stdout.rows;if(!e||e<2)return;let t=this.formatLine(),i=`\x1B[1;${e-1}r\x1B7\x1B[${e};1H\x1B[2K${t}\x1B8`;process.stdout.write(i)}clear(){if(!this.enabled)return;let e=process.stdout.rows;!e||e<2||process.stdout.write(`\x1B7\x1B[${e};1H\x1B[2K\x1B8`)}disable(){this.enabled&&(this.stopRefreshTimer(),this.clear(),this.resetScrollRegion(),this.enabled=!1)}inspectPtyOutput(e){if(this.enabled){if(e.includes("\x1B[?1049h")||e.includes("\x1B[?47h")){this.altScreenActive=!0;return}(e.includes("\x1B[?1049l")||e.includes("\x1B[?47l"))&&(this.altScreenActive=!1,this.render())}}getState(){return this.state}isEnabled(){return this.enabled}isAltScreenActive(){return this.altScreenActive}formatLine(){let e=[];if(e.push(this.state.online?"\u25CF online":"\u25CB offline"),this.state.viewerCount>0){let t=this.state.viewerCount===1?"1 viewer":`${this.state.viewerCount} viewers`;e.push(t)}else e.push("no viewers");return this.state.agentName&&e.push(this.state.agentName),this.state.ptyCols&&this.state.ptyRows&&e.push(`${this.state.ptyCols}\xD7${this.state.ptyRows}`)," "+e.join(" \xB7 ")+" "}};async function Mo(r,e,t,i){if(i)return process.stderr.write(`Logging in with API key...
|
|
36
36
|
`),await r.loginWithApiKey(i)?(process.stderr.write(`Login successful.
|
|
37
37
|
`),!0):(process.stderr.write(`Login failed. Check your API key.
|
|
38
38
|
`),!1);try{let n=await r.startDeviceCodeFlow();process.stderr.write(`
|
|
@@ -45,12 +45,12 @@ tell application "System Events" to get value of property list item "CFBundleNam
|
|
|
45
45
|
`),!0):(process.stderr.write(` Login failed or expired.
|
|
46
46
|
|
|
47
47
|
`),!1)}catch(n){return t.error("Login error",n),process.stderr.write(`Login error: ${n instanceof Error?n.message:String(n)}
|
|
48
|
-
`),!1}}var un=
|
|
49
|
-
`);let
|
|
50
|
-
`),await Mo(
|
|
51
|
-
`),
|
|
52
|
-
`),A(),process.exit(1)});try{await U.connect()}catch(
|
|
53
|
-
`),process.exit(1)}let
|
|
48
|
+
`),!1}}var un=de(xr());function TE(r){switch(r){case"numbered-choice":return"select";case"free-input":return"input";default:return"confirmation"}}function np(r,e,t){let i=new Date().toISOString();switch(r){case"working":return e==="idle"?{type:un.TerminalEventType.SESSION_START,timestamp:i}:null;case"waiting":return{type:un.TerminalEventType.WAITING_INPUT,timestamp:i,promptType:TE(t?.type),question:t?.question||"Confirm action?",options:t?.choices?.map(n=>n.label)};case"completed":return{type:un.TerminalEventType.SESSION_END,timestamp:i,status:"success"};case"error":return e==="working"?{type:un.TerminalEventType.SESSION_END,timestamp:i,status:"error"}:{type:un.TerminalEventType.ERROR,timestamp:i,severity:"error",message:"Command failed"};default:return null}}async function ap(r){let{storage:e,config:t,logger:i,machineId:n,notification:s,browser:a,cwd:c,watch:u,statusLine:d,multiViewer:p}=r,m=new No(i);d&&m.enable();let _=t.getServerUrl(),v=new URL(_).host,T=await n.getMachineId(),x=new lt.CryptoService(e,i,v,T);await x.initialize();let H=await x.getShortFingerprint();process.stderr.write(`Agent fingerprint: ${H} (verify in the web app; run 'termiq fingerprint' for the full safety number)
|
|
49
|
+
`);let oe=new lt.AuthService(e,x,n,t,i,s,a,v,T),J=await oe.hasValidToken();J||await oe.refreshAccessToken()||(process.stderr.write(`Not logged in. Starting login flow...
|
|
50
|
+
`),await Mo(oe,a,i)||process.exit(1),J=!0);let k;try{let{machineIdSync:R}=await Promise.resolve().then(()=>de(Kc()));k=R()}catch{k=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}let B,te=new lt.StatusDetector((R,Q,Ne)=>{if(!U.getStatus().connected)return;let Je=B;B=Q,U.updateStatus({instanceId:se,terminalId:R,status:Q,encryptedPrompt:Ne&&x.encryptPromptInfo(Ne)||void 0}).catch(()=>{});let nt=np(Q,Je,Ne);nt&&U.sendTerminalEvent(se,R,nt)}),j=p?[op.Capability.MULTI_VIEWER_RENDER]:[],U=new lt.WebSocketService(oe,x,t,i,s,k,"cli",j);p&&i.info("Multi-viewer rendering capability advertised");let ne=!1;U.onStatusChange(R=>{if(R==="connected"){if(ne)i.info("Reconnected to termiq.io");else{let Q=p?" (multi-viewer mode)":"";process.stderr.write(`Connected to termiq.io${Q}
|
|
51
|
+
`),ne=!0}m.update({online:!0})}else R==="disconnected"?(i.info("Disconnected from termiq.io (will retry)"),m.update({online:!1})):R==="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
|
+
`),A(),process.exit(1)});try{await U.connect()}catch(R){process.stderr.write(`Connection failed: ${R instanceof Error?R.message:String(R)}
|
|
53
|
+
`),process.exit(1)}let _e=sp.basename(c),se=`cli_${Date.now()}`,ze=x.encryptWorkspaceInfo({name:_e,path:c});await U.registerWorkspace({instanceId:se,encryptedInfo:ze||void 0});let ve=new xo(i);p&&ve.setMultiViewerMode(!0),ve.setPreWriteHook(R=>m.inspectPtyOutput(R));let be=null;ve.setOnResize((R,Q)=>{m.update({ptyCols:R,ptyRows:Q}),p&&be&&U.sendPtyResized(se,be,R,Q)}),ve.setOnLocalClaim((R,Q)=>{p&&be&&U.sendClaimControl(se,be,R,Q)});let he=ve.spawn(c,m.reservedRows()),We=`CLI: ${_e}`,ot=process.env.SHELL||"/bin/bash",Qe=x.encryptTerminalInfo({name:We,command:ot,cwd:c});await U.terminalCreated({instanceId:se,terminalId:he,encryptedInfo:Qe||void 0,streamId:ve.getStreamId()??void 0}),be=he,p&&U.sendPtyResized(se,he,ve.getPtyCols(),ve.getPtyRows());let Te=new lt.FileTransferService(i,"/tmp",c);Te.setCrypto(x);let it=new lt.FileTrackerService(i,c),$e=new lt.FileListService(i,c),mt=u?new Lo(i,c):null,L=U.getSocket();L&&Te.attach(L,se),it.onFileChanged((R,Q)=>{U.sendFileChangedEvent(se,R,Q)}),it.onFileViewTransfer(async(R,Q,Ne)=>{try{await Te.sendBuffer(R,Q,Ne.path.split("/").pop()||"view",Ne.mimeType||"text/plain",{purpose:"view",viewMetadata:Ne})}catch(Je){i.error("File view transfer failed",Je)}}),U.onFileViewRequest((R,Q)=>{it.handleViewRequest(R,Q)}),U.onFileListRequest((R,Q)=>{$e.handleListRequest(Q)}),$e.onResponse(R=>{U.sendFileListResponse(se,R)}),U.onFileDownloadRequest(async(R,Q,Ne)=>{try{await Te.sendFile(R,Q,void 0,void 0,Ne)}catch(Je){i.error("File download failed",Je)}}),mt&&(mt.onFileChanged(R=>{U.sendFileChangedEvent(se,he,R)}),mt.start()),te.startTracking(he),ve.setOnOutput(R=>{U.sendOutput(se,he,R),te.processOutput(he,R),it.processOutput(he,R)}),ve.setOnLocalInput(R=>{(0,lt.isAnswerKeystroke)(R)&&te.resolvePrompt(he)}),U.onInput((R,Q,Ne,Je,nt)=>{if(R===he){if(nt){let ht=te.getEmittedPromptKey(he);if(ht&&ht!==nt){i.warn("Stale answer rejected \u2014 prompt changed",{terminalId:he}),te.reEmitPrompt(he);return}}(0,lt.isAnswerKeystroke)(Q)&&te.resolvePrompt(he),ve.write(Q,Je)}}),U.setTerminalActiveCheck(R=>R===he&&ve.isAlive()),U.onResizeRequest((R,Q,Ne)=>{R===he&&(i.info("Remote resize received",{terminalId:R,cols:Q,rows:Ne}),ve.resize(Q,Ne))}),U.onClientAttached(({clientCount:R})=>{ve.setSigwinchEnabled(!1),m.update({viewerCount:R}),U.sendInputResume(he)}),U.onClientDetached(({clientCount:R})=>{R===0&&ve.setSigwinchEnabled(!0),m.update({viewerCount:R})}),U.onGetBufferRequest(R=>R===he?ve.getBuffer():null),U.onRedrawRequest(R=>{R===he&&ve.redrawNoResize()});async function K(){let R=x.encryptWorkspaceInfo({name:_e,path:c});await U.registerWorkspace({instanceId:se,encryptedInfo:R||void 0});let Q=x.encryptTerminalInfo({name:We,command:ot,cwd:c});await U.terminalCreated({instanceId:se,terminalId:he,encryptedInfo:Q||void 0,streamId:ve.getStreamId()??void 0})}U.onMetaSessionEstablished(R=>{R&&K().catch(Q=>{i.error("Failed to re-register metadata after meta session",Q)}),te.resendWaitingPrompts()}),U.onReconnect(async()=>{try{await K();let R=U.getSocket();R&&Te.attach(R,se)}catch(R){i.error("Failed to re-register on reconnect",R)}});function A(){mt?.dispose(),Te.detach(),it.dispose(),$e.dispose(),te.stopTracking(he),te.dispose(),U.disposeInputStream(he),U.terminalClosed({instanceId:se,terminalId:he}).catch(()=>{}),U.unregisterWorkspace(se).catch(()=>{}),U.disconnect(),ve.dispose()}ve.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 cp(r){await r.logout(),process.stderr.write(`Logged out.
|
|
@@ -69,8 +69,8 @@ Short fingerprint: ${t}
|
|
|
69
69
|
Compare these with the value shown in the TermIQ web app to verify
|
|
70
70
|
you are connected to THIS agent (no server-in-the-middle).
|
|
71
71
|
|
|
72
|
-
`)}var At=
|
|
73
|
-
termiq v${
|
|
72
|
+
`)}var At=de(Un()),Le=process.argv.slice(2);(Le.includes("--help")||Le.includes("-h"))&&(process.stderr.write(`
|
|
73
|
+
termiq v${So()} \u2014 Access terminals from anywhere
|
|
74
74
|
|
|
75
75
|
Usage:
|
|
76
76
|
termiq Start a shell with cloud access (default)
|
|
@@ -99,16 +99,16 @@ you are connected to THIS agent (no server-in-the-middle).
|
|
|
99
99
|
Environment:
|
|
100
100
|
TERMIQ_TOKEN API key (equivalent to --token)
|
|
101
101
|
|
|
102
|
-
`),process.exit(0));(Le.includes("--version")||Le.includes("-V"))&&(process.stdout.write(`${
|
|
102
|
+
`),process.exit(0));(Le.includes("--version")||Le.includes("-V"))&&(process.stdout.write(`${So()}
|
|
103
103
|
`),process.exit(0));var lp=Ad(Le,uf,Rd);lp&&(process.stderr.write(`Unknown flag: ${lp}
|
|
104
104
|
Run 'termiq --help' for usage.
|
|
105
|
-
`),process.exit(1));var hp=Pd(Le,uf)??"start",
|
|
105
|
+
`),process.exit(1));var hp=Pd(Le,uf)??"start",CE=Le.includes("--verbose")||Le.includes("-v"),kE=Le.includes("--watch")||Le.includes("-w"),OE=Le.includes("--log-to-file"),PE=Le.includes("--statusline"),RE=Le.includes("--multi-viewer"),AE=Le.includes("--force"),IE=Le.find(r=>r.startsWith("--token="))?.split("=")[1]||(Le.includes("--token")?Le[Le.indexOf("--token")+1]:void 0),dp=Le.find(r=>r.startsWith("--server="))?.split("=")[1]||(Le.includes("--server")?Le[Le.indexOf("--server")+1]:void 0),wf=Le.find(r=>r.startsWith("--log-level="))?.split("=")[1]||(Le.includes("--log-level")?Le[Le.indexOf("--log-level")+1]:void 0),LE=["silent","error","warn","info","debug"],NE=wf&&LE.includes(wf)?wf:CE?"info":"silent",ME=Le.find(r=>r.startsWith("--cid="))?.split("=")[1]||(Le.includes("--cid")?Le[Le.indexOf("--cid")+1]:void 0),FE=ME||(0,At.generateCorrelationId)(),DE=process.env.TERMIQ_TOKEN,gr=new Kn(NE,OE),ti=new gn,pr=new mn(dp?{serverUrl:dp}:void 0),ri=new Wn,Fo=new Hn(gr),Xn=new $n;async function BE(){switch(hp){case"start":case void 0:{process.env.TERMIQ_SESSION_ACTIVE==="1"&&!AE&&(process.stderr.write(`termiq \u0443\u0436\u0435 \u0437\u0430\u043F\u0443\u0449\u0435\u043D \u0432 \u044D\u0442\u043E\u043C \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0435 (\u0432\u044B \u0432\u043D\u0443\u0442\u0440\u0438 termiq-\u0441\u0435\u0441\u0441\u0438\u0438).
|
|
106
106
|
\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 \u0442\u0435\u043A\u0443\u0449\u0443\u044E \u0441\u0435\u0441\u0441\u0438\u044E, \u0438\u043B\u0438 --force \u0434\u043B\u044F \u0432\u043B\u043E\u0436\u0435\u043D\u043D\u043E\u0433\u043E \u0437\u0430\u043F\u0443\u0441\u043A\u0430.
|
|
107
|
-
`),process.exit(1)),
|
|
107
|
+
`),process.exit(1)),RE&&await pr.setMultiViewer(!0);let r=pr.getMultiViewer();await ap({storage:ti,config:pr,logger:gr,machineId:ri,notification:Fo,browser:Xn,cwd:process.cwd(),watch:kE,statusLine:PE,multiViewer:r});break}case"login":{let r=new URL(pr.getServerUrl()).host,e=await ri.getMachineId(),t=new At.CryptoService(ti,gr,r,e);await t.initialize();let i=new At.AuthService(ti,t,ri,pr,gr,Fo,Xn,r,e),n=await Mo(i,Xn,gr,IE||DE);process.exit(n?0:1);break}case"logout":{let r=new URL(pr.getServerUrl()).host,e=await ri.getMachineId(),t=new At.CryptoService(ti,gr,r,e);await t.initialize();let i=new At.AuthService(ti,t,ri,pr,gr,Fo,Xn,r,e);await cp(i),process.exit(0);break}case"status":{let r=new URL(pr.getServerUrl()).host,e=await ri.getMachineId(),t=new At.CryptoService(ti,gr,r,e);await t.initialize();let i=new At.AuthService(ti,t,ri,pr,gr,Fo,Xn,r,e);await fp(i,t),process.exit(0);break}case"fingerprint":{let r=new URL(pr.getServerUrl()).host,e=await ri.getMachineId(),t=new At.CryptoService(ti,gr,r,e);await t.initialize(),await up(t),process.exit(0);break}case"version":{process.stdout.write(`${So()}
|
|
108
108
|
`),process.exit(0);break}case"help":{process.stderr.write(`Run 'termiq --help' for full usage.
|
|
109
109
|
`),process.exit(0);break}default:process.stderr.write(`Unknown command: ${hp}
|
|
110
110
|
Run 'termiq --help' for usage.
|
|
111
|
-
`),process.exit(1)}}(0,At.runWithCorrelation)(
|
|
111
|
+
`),process.exit(1)}}(0,At.runWithCorrelation)(FE,()=>BE().catch(r=>{process.stderr.write(`Fatal error: ${r instanceof Error?r.message:String(r)}
|
|
112
112
|
`),process.exit(1)}));
|
|
113
113
|
/*! Bundled license information:
|
|
114
114
|
|