@termiq/cli 3.44.3 → 3.46.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.
Files changed (3) hide show
  1. package/README.md +28 -1
  2. package/dist/bin.js +66 -54
  3. package/package.json +1 -1
package/dist/bin.js CHANGED
@@ -1,66 +1,66 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Sp=Object.create;var Yo=Object.defineProperty;var Tp=Object.getOwnPropertyDescriptor;var Cp=Object.getOwnPropertyNames;var kp=Object.getPrototypeOf,Op=Object.prototype.hasOwnProperty;var Wt=(r,e)=>()=>(r&&(e=r(r=0)),e);var M=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Pp=(r,e)=>{for(var t in e)Yo(r,t,{get:e[t],enumerable:!0})},Ap=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Cp(e))!Op.call(r,i)&&i!==t&&Yo(r,i,{get:()=>e[i],enumerable:!(n=Tp(e,i))||n.enumerable});return r};var ue=(r,e,t)=>(t=r!=null?Sp(kp(r)):{},Ap(e||!r||!r.__esModule?Yo(t,"default",{value:r,enumerable:!0}):t,r));var fs=M(_i=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});_i.generateCorrelationId=Lp;_i.runWithCorrelation=Np;_i.getCurrentCorrelationId=Mp;var Ip=require("async_hooks");function Lp(){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 Mf=new Ip.AsyncLocalStorage;function Np(r,e){return Mf.run(r,e)}function Mp(){return Mf.getStore()}});var Df=M(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.LOG_LEVELS=void 0;Nn.shouldLog=Dp;Nn.formatLogLine=Bp;var Fp=fs();Nn.LOG_LEVELS=["silent","error","warn","info","debug"];var Ff={silent:0,error:1,warn:2,info:3,debug:4};function Dp(r,e){return Ff[r]<=Ff[e]}function Bp(r,e,t,n){let i={ts:new Date().toISOString(),level:r,src:e,msg:t},s=(0,Fp.getCurrentCorrelationId)();s&&(i.cid=s);let a=n;a.length>0&&typeof a[0]=="object"&&a[0]!==null&&!(a[0]instanceof Error)&&!Array.isArray(a[0])&&(i.ctx=a[0],a=a.slice(1));let c=[...a].reverse().find(u=>u instanceof Error);c&&(i.err={message:c.message,stack:c.stack,name:c.name},a=a.filter(u=>u!==c)),a.length>0&&(i.args=a);try{return JSON.stringify(i)}catch{return JSON.stringify({ts:i.ts,level:r,src:e,msg:t,_unserializable:!0})}}});var Bf=M(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.formatLogLine=Br.shouldLog=Br.LOG_LEVELS=void 0;var Xo=Df();Object.defineProperty(Br,"LOG_LEVELS",{enumerable:!0,get:function(){return Xo.LOG_LEVELS}});Object.defineProperty(Br,"shouldLog",{enumerable:!0,get:function(){return Xo.shouldLog}});Object.defineProperty(Br,"formatLogLine",{enumerable:!0,get:function(){return Xo.formatLogLine}})});var jf=M(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});us.CircularBuffer=void 0;var Jo=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}};us.CircularBuffer=Jo});var hs=M(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});ls.getApiUrl=jp;ls.getWsUrl=Up;function jp(r){return`${r.getServerUrl()}/api`}function Up(r){let e=r.getServerUrl();return e.startsWith("https://")?e.replace(/^https:\/\//,"wss://"):e.replace(/^http:\/\//,"ws://")}});var Kf=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 Kp=jf();Object.defineProperty(vt,"CircularBuffer",{enumerable:!0,get:function(){return Kp.CircularBuffer}});var Uf=hs();Object.defineProperty(vt,"getApiUrl",{enumerable:!0,get:function(){return Uf.getApiUrl}});Object.defineProperty(vt,"getWsUrl",{enumerable:!0,get:function(){return Uf.getWsUrl}});var Zo=fs();Object.defineProperty(vt,"generateCorrelationId",{enumerable:!0,get:function(){return Zo.generateCorrelationId}});Object.defineProperty(vt,"runWithCorrelation",{enumerable:!0,get:function(){return Zo.runWithCorrelation}});Object.defineProperty(vt,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Zo.getCurrentCorrelationId}})});var Wf=M(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0})});var Vf=M(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0})});var zf=M(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});ds.PLAN_LIMITS=void 0;ds.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 Gf=M($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0})});var Yf=M(Qt=>{"use strict";var qp=Qt&&Qt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),ps=Qt&&Qt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&qp(e,r,t)};Object.defineProperty(Qt,"__esModule",{value:!0});ps(Wf(),Qt);ps(Vf(),Qt);ps(zf(),Qt);ps(Gf(),Qt)});var Xf=M(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.API_VERSION=Lt.WS_NAMESPACES=Lt.TIMEOUTS=Lt.STATUS_PATTERNS=Lt.TERMINAL_STATUSES=void 0;Lt.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"}};Lt.STATUS_PATTERNS={idle:[/[❯$]\s*$/,/>\s*$/],waiting:[/\[Y\/n\]/i,/\(y\/N\)/i,/Continue\?/i,/proceed\?/i],completed:[/✓/,/Done/,/Completed/,/Success/],error:[/Error/,/Failed/,/✕/,/Exception/]};Lt.TIMEOUTS={HEARTBEAT_INTERVAL:3e4,OFFLINE_THRESHOLD:6e4,DEVICE_CODE_EXPIRY:9e5,DEVICE_CODE_POLL_INTERVAL:5e3};Lt.WS_NAMESPACES={AGENT:"/agent",CLIENT:"/client"};Lt.API_VERSION="v1"});var Jf=M(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});gs.isMultiRecipientPayload=Wp;gs.isEncryptedPayload=Hp;function Wp(r){return typeof r=="object"&&r!==null&&"v"in r&&r.v===2&&"recipients"in r&&Array.isArray(r.recipients)}function Hp(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 Qo=M(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.KX_SIG_VERSION=er.KX_FINGERPRINT_LABEL=er.KX_ACK_LABEL=er.KX_SIGN_LABEL=void 0;er.KX_SIGN_LABEL="termiq-kx-v1";er.KX_ACK_LABEL="termiq-kxack-v1";er.KX_FINGERPRINT_LABEL="termiq-fp-v1";er.KX_SIG_VERSION=1});var Ei=M((pv,ms)=>{(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")},n=new Uint8Array(16),i=new Uint8Array(32);i[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 S(f,h,l,o,g){var E,b=0;for(E=0;E<g;E++)b|=f[h+E]^l[o+E];return(1&b-1>>>8)-1}function T(f,h,l,o){return S(f,h,l,o,16)}function H(f,h,l,o){return S(f,h,l,o,32)}function de(f,h,l,o){for(var g=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,E=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,O=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,B=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,$=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,ie=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,oe=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,he=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,ae=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,fe=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ce=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,G=g,te=E,V=b,Y=O,X=B,q=Z,w=W,x=Pe,I=$,k=ie,P=oe,F=ge,ne=he,me=ae,Ee=fe,ye=ce,y,ve=0;ve<20;ve+=2)y=G+ne|0,X^=y<<7|y>>>25,y=X+G|0,I^=y<<9|y>>>23,y=I+X|0,ne^=y<<13|y>>>19,y=ne+I|0,G^=y<<18|y>>>14,y=q+te|0,k^=y<<7|y>>>25,y=k+q|0,me^=y<<9|y>>>23,y=me+k|0,te^=y<<13|y>>>19,y=te+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,Y^=y<<7|y>>>25,y=Y+ye|0,x^=y<<9|y>>>23,y=x+Y|0,F^=y<<13|y>>>19,y=F+x|0,ye^=y<<18|y>>>14,y=G+Y|0,te^=y<<7|y>>>25,y=te+G|0,V^=y<<9|y>>>23,y=V+te|0,Y^=y<<13|y>>>19,y=Y+V|0,G^=y<<18|y>>>14,y=q+X|0,w^=y<<7|y>>>25,y=w+q|0,x^=y<<9|y>>>23,y=x+w|0,X^=y<<13|y>>>19,y=X+x|0,q^=y<<18|y>>>14,y=P+k|0,F^=y<<7|y>>>25,y=F+P|0,I^=y<<9|y>>>23,y=I+F|0,k^=y<<13|y>>>19,y=k+I|0,P^=y<<18|y>>>14,y=ye+Ee|0,ne^=y<<7|y>>>25,y=ne+ye|0,me^=y<<9|y>>>23,y=me+ne|0,Ee^=y<<13|y>>>19,y=Ee+me|0,ye^=y<<18|y>>>14;G=G+g|0,te=te+E|0,V=V+b|0,Y=Y+O|0,X=X+B|0,q=q+Z|0,w=w+W|0,x=x+Pe|0,I=I+$|0,k=k+ie|0,P=P+oe|0,F=F+ge|0,ne=ne+he|0,me=me+ae|0,Ee=Ee+fe|0,ye=ye+ce|0,f[0]=G>>>0&255,f[1]=G>>>8&255,f[2]=G>>>16&255,f[3]=G>>>24&255,f[4]=te>>>0&255,f[5]=te>>>8&255,f[6]=te>>>16&255,f[7]=te>>>24&255,f[8]=V>>>0&255,f[9]=V>>>8&255,f[10]=V>>>16&255,f[11]=V>>>24&255,f[12]=Y>>>0&255,f[13]=Y>>>8&255,f[14]=Y>>>16&255,f[15]=Y>>>24&255,f[16]=X>>>0&255,f[17]=X>>>8&255,f[18]=X>>>16&255,f[19]=X>>>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]=k>>>0&255,f[37]=k>>>8&255,f[38]=k>>>16&255,f[39]=k>>>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]=ne>>>0&255,f[49]=ne>>>8&255,f[50]=ne>>>16&255,f[51]=ne>>>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 z(f,h,l,o){for(var g=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,E=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,O=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,B=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,$=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,ie=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,oe=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,he=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,ae=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,fe=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ce=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,G=g,te=E,V=b,Y=O,X=B,q=Z,w=W,x=Pe,I=$,k=ie,P=oe,F=ge,ne=he,me=ae,Ee=fe,ye=ce,y,ve=0;ve<20;ve+=2)y=G+ne|0,X^=y<<7|y>>>25,y=X+G|0,I^=y<<9|y>>>23,y=I+X|0,ne^=y<<13|y>>>19,y=ne+I|0,G^=y<<18|y>>>14,y=q+te|0,k^=y<<7|y>>>25,y=k+q|0,me^=y<<9|y>>>23,y=me+k|0,te^=y<<13|y>>>19,y=te+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,Y^=y<<7|y>>>25,y=Y+ye|0,x^=y<<9|y>>>23,y=x+Y|0,F^=y<<13|y>>>19,y=F+x|0,ye^=y<<18|y>>>14,y=G+Y|0,te^=y<<7|y>>>25,y=te+G|0,V^=y<<9|y>>>23,y=V+te|0,Y^=y<<13|y>>>19,y=Y+V|0,G^=y<<18|y>>>14,y=q+X|0,w^=y<<7|y>>>25,y=w+q|0,x^=y<<9|y>>>23,y=x+w|0,X^=y<<13|y>>>19,y=X+x|0,q^=y<<18|y>>>14,y=P+k|0,F^=y<<7|y>>>25,y=F+P|0,I^=y<<9|y>>>23,y=I+F|0,k^=y<<13|y>>>19,y=k+I|0,P^=y<<18|y>>>14,y=ye+Ee|0,ne^=y<<7|y>>>25,y=ne+ye|0,me^=y<<9|y>>>23,y=me+ne|0,Ee^=y<<13|y>>>19,y=Ee+me|0,ye^=y<<18|y>>>14;f[0]=G>>>0&255,f[1]=G>>>8&255,f[2]=G>>>16&255,f[3]=G>>>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]=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]=k>>>0&255,f[29]=k>>>8&255,f[30]=k>>>16&255,f[31]=k>>>24&255}function C(f,h,l,o){de(f,h,l,o)}function D(f,h,l,o){z(f,h,l,o)}var Q=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,E,b){var O=new Uint8Array(16),B=new Uint8Array(64),Z,W;for(W=0;W<16;W++)O[W]=0;for(W=0;W<8;W++)O[W]=E[W];for(;g>=64;){for(C(B,O,b,Q),W=0;W<64;W++)f[h+W]=l[o+W]^B[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(C(B,O,b,Q),W=0;W<g;W++)f[h+W]=l[o+W]^B[W];return 0}function U(f,h,l,o,g){var E=new Uint8Array(16),b=new Uint8Array(64),O,B;for(B=0;B<16;B++)E[B]=0;for(B=0;B<8;B++)E[B]=o[B];for(;l>=64;){for(C(b,E,g,Q),B=0;B<64;B++)f[h+B]=b[B];for(O=1,B=8;B<16;B++)O=O+(E[B]&255)|0,E[B]=O&255,O>>>=8;l-=64,h+=64}if(l>0)for(C(b,E,g,Q),B=0;B<l;B++)f[h+B]=b[B];return 0}function le(f,h,l,o,g){var E=new Uint8Array(32);D(E,o,g,Q);for(var b=new Uint8Array(8),O=0;O<8;O++)b[O]=o[O+16];return U(f,h,l,b,E)}function pe(f,h,l,o,g,E,b){var O=new Uint8Array(32);D(O,E,b,Q);for(var B=new Uint8Array(8),Z=0;Z<8;Z++)B[Z]=E[Z+16];return K(f,h,l,o,g,B,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,E,b,O,B;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,E=f[8]&255|(f[9]&255)<<8,this.r[4]=(g>>>4|E<<12)&255,this.r[5]=E>>>1&8190,b=f[10]&255|(f[11]&255)<<8,this.r[6]=(E>>>14|b<<2)&8191,O=f[12]&255|(f[13]&255)<<8,this.r[7]=(b>>>11|O<<5)&8065,B=f[14]&255|(f[15]&255)<<8,this.r[8]=(O>>>8|B<<8)&8191,this.r[9]=B>>>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,E,b,O,B,Z,W,Pe,$,ie,oe,ge,he,ae,fe,ce,G,te,V,Y=this.h[0],X=this.h[1],q=this.h[2],w=this.h[3],x=this.h[4],I=this.h[5],k=this.h[6],P=this.h[7],F=this.h[8],ne=this.h[9],me=this.r[0],Ee=this.r[1],ye=this.r[2],y=this.r[3],ve=this.r[4],Ae=this.r[5],Re=this.r[6],be=this.r[7],Ce=this.r[8],ke=this.r[9];l>=16;)g=f[h+0]&255|(f[h+1]&255)<<8,Y+=g&8191,E=f[h+2]&255|(f[h+3]&255)<<8,X+=(g>>>13|E<<3)&8191,b=f[h+4]&255|(f[h+5]&255)<<8,q+=(E>>>10|b<<6)&8191,O=f[h+6]&255|(f[h+7]&255)<<8,w+=(b>>>7|O<<9)&8191,B=f[h+8]&255|(f[h+9]&255)<<8,x+=(O>>>4|B<<12)&8191,I+=B>>>1&8191,Z=f[h+10]&255|(f[h+11]&255)<<8,k+=(B>>>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,ne+=Pe>>>5|o,$=0,ie=$,ie+=Y*me,ie+=X*(5*ke),ie+=q*(5*Ce),ie+=w*(5*be),ie+=x*(5*Re),$=ie>>>13,ie&=8191,ie+=I*(5*Ae),ie+=k*(5*ve),ie+=P*(5*y),ie+=F*(5*ye),ie+=ne*(5*Ee),$+=ie>>>13,ie&=8191,oe=$,oe+=Y*Ee,oe+=X*me,oe+=q*(5*ke),oe+=w*(5*Ce),oe+=x*(5*be),$=oe>>>13,oe&=8191,oe+=I*(5*Re),oe+=k*(5*Ae),oe+=P*(5*ve),oe+=F*(5*y),oe+=ne*(5*ye),$+=oe>>>13,oe&=8191,ge=$,ge+=Y*ye,ge+=X*Ee,ge+=q*me,ge+=w*(5*ke),ge+=x*(5*Ce),$=ge>>>13,ge&=8191,ge+=I*(5*be),ge+=k*(5*Re),ge+=P*(5*Ae),ge+=F*(5*ve),ge+=ne*(5*y),$+=ge>>>13,ge&=8191,he=$,he+=Y*y,he+=X*ye,he+=q*Ee,he+=w*me,he+=x*(5*ke),$=he>>>13,he&=8191,he+=I*(5*Ce),he+=k*(5*be),he+=P*(5*Re),he+=F*(5*Ae),he+=ne*(5*ve),$+=he>>>13,he&=8191,ae=$,ae+=Y*ve,ae+=X*y,ae+=q*ye,ae+=w*Ee,ae+=x*me,$=ae>>>13,ae&=8191,ae+=I*(5*ke),ae+=k*(5*Ce),ae+=P*(5*be),ae+=F*(5*Re),ae+=ne*(5*Ae),$+=ae>>>13,ae&=8191,fe=$,fe+=Y*Ae,fe+=X*ve,fe+=q*y,fe+=w*ye,fe+=x*Ee,$=fe>>>13,fe&=8191,fe+=I*me,fe+=k*(5*ke),fe+=P*(5*Ce),fe+=F*(5*be),fe+=ne*(5*Re),$+=fe>>>13,fe&=8191,ce=$,ce+=Y*Re,ce+=X*Ae,ce+=q*ve,ce+=w*y,ce+=x*ye,$=ce>>>13,ce&=8191,ce+=I*Ee,ce+=k*me,ce+=P*(5*ke),ce+=F*(5*Ce),ce+=ne*(5*be),$+=ce>>>13,ce&=8191,G=$,G+=Y*be,G+=X*Re,G+=q*Ae,G+=w*ve,G+=x*y,$=G>>>13,G&=8191,G+=I*ye,G+=k*Ee,G+=P*me,G+=F*(5*ke),G+=ne*(5*Ce),$+=G>>>13,G&=8191,te=$,te+=Y*Ce,te+=X*be,te+=q*Re,te+=w*Ae,te+=x*ve,$=te>>>13,te&=8191,te+=I*y,te+=k*ye,te+=P*Ee,te+=F*me,te+=ne*(5*ke),$+=te>>>13,te&=8191,V=$,V+=Y*ke,V+=X*Ce,V+=q*be,V+=w*Re,V+=x*Ae,$=V>>>13,V&=8191,V+=I*ve,V+=k*y,V+=P*ye,V+=F*Ee,V+=ne*me,$+=V>>>13,V&=8191,$=($<<2)+$|0,$=$+ie|0,ie=$&8191,$=$>>>13,oe+=$,Y=ie,X=oe,q=ge,w=he,x=ae,I=fe,k=ce,P=G,F=te,ne=V,h+=16,l-=16;this.h[0]=Y,this.h[1]=X,this.h[2]=q,this.h[3]=w,this.h[4]=x,this.h[5]=I,this.h[6]=k,this.h[7]=P,this.h[8]=F,this.h[9]=ne},se.prototype.finish=function(f,h){var l=new Uint16Array(10),o,g,E,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,E=this.h[0]+this.pad[0],this.h[0]=E&65535,b=1;b<8;b++)E=(this.h[b]+this.pad[b]|0)+(E>>>16)|0,this.h[b]=E&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 nt(f,h,l,o,g,E){var b=new se(E);return b.update(l,o,g),b.finish(f,h),0}function we(f,h,l,o,g,E){var b=new Uint8Array(16);return nt(b,0,l,o,g,E),T(f,h,b,0)}function Se(f,h,l,o,g){var E;if(l<32)return-1;for(pe(f,0,h,0,l,o,g),nt(f,16,f,32,l-32,f),E=0;E<16;E++)f[E]=0;return 0}function _e(f,h,l,o,g){var E,b=new Uint8Array(32);if(l<32||(le(b,0,32,o,g),we(h,16,h,32,l-32,b)!==0))return-1;for(pe(f,0,h,0,l,o,g),E=0;E<32;E++)f[E]=0;return 0}function We(f,h){var l;for(l=0;l<16;l++)f[l]=h[l]|0}function at(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),E=0;E<16;E++)o=g&(f[E]^h[E]),f[E]^=o,h[E]^=o}function Te(f,h){var l,o,g,E=e(),b=e();for(l=0;l<16;l++)b[l]=h[l];for(at(b),at(b),at(b),o=0;o<2;o++){for(E[0]=b[0]-65517,l=1;l<15;l++)E[l]=b[l]-65535-(E[l-1]>>16&1),E[l-1]&=65535;E[15]=b[15]-32767-(E[14]>>16&1),g=E[15]>>16&1,E[14]&=65535,Qe(b,E,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),H(l,0,o,0)}function ze(f){var h=new Uint8Array(32);return Te(h,f),h[0]&1}function yt(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 R(f,h,l){var o,g,E=0,b=0,O=0,B=0,Z=0,W=0,Pe=0,$=0,ie=0,oe=0,ge=0,he=0,ae=0,fe=0,ce=0,G=0,te=0,V=0,Y=0,X=0,q=0,w=0,x=0,I=0,k=0,P=0,F=0,ne=0,me=0,Ee=0,ye=0,y=l[0],ve=l[1],Ae=l[2],Re=l[3],be=l[4],Ce=l[5],ke=l[6],Je=l[7],Me=l[8],$e=l[9],Ge=l[10],Ye=l[11],ot=l[12],pt=l[13],gt=l[14],mt=l[15];o=h[0],E+=o*y,b+=o*ve,O+=o*Ae,B+=o*Re,Z+=o*be,W+=o*Ce,Pe+=o*ke,$+=o*Je,ie+=o*Me,oe+=o*$e,ge+=o*Ge,he+=o*Ye,ae+=o*ot,fe+=o*pt,ce+=o*gt,G+=o*mt,o=h[1],b+=o*y,O+=o*ve,B+=o*Ae,Z+=o*Re,W+=o*be,Pe+=o*Ce,$+=o*ke,ie+=o*Je,oe+=o*Me,ge+=o*$e,he+=o*Ge,ae+=o*Ye,fe+=o*ot,ce+=o*pt,G+=o*gt,te+=o*mt,o=h[2],O+=o*y,B+=o*ve,Z+=o*Ae,W+=o*Re,Pe+=o*be,$+=o*Ce,ie+=o*ke,oe+=o*Je,ge+=o*Me,he+=o*$e,ae+=o*Ge,fe+=o*Ye,ce+=o*ot,G+=o*pt,te+=o*gt,V+=o*mt,o=h[3],B+=o*y,Z+=o*ve,W+=o*Ae,Pe+=o*Re,$+=o*be,ie+=o*Ce,oe+=o*ke,ge+=o*Je,he+=o*Me,ae+=o*$e,fe+=o*Ge,ce+=o*Ye,G+=o*ot,te+=o*pt,V+=o*gt,Y+=o*mt,o=h[4],Z+=o*y,W+=o*ve,Pe+=o*Ae,$+=o*Re,ie+=o*be,oe+=o*Ce,ge+=o*ke,he+=o*Je,ae+=o*Me,fe+=o*$e,ce+=o*Ge,G+=o*Ye,te+=o*ot,V+=o*pt,Y+=o*gt,X+=o*mt,o=h[5],W+=o*y,Pe+=o*ve,$+=o*Ae,ie+=o*Re,oe+=o*be,ge+=o*Ce,he+=o*ke,ae+=o*Je,fe+=o*Me,ce+=o*$e,G+=o*Ge,te+=o*Ye,V+=o*ot,Y+=o*pt,X+=o*gt,q+=o*mt,o=h[6],Pe+=o*y,$+=o*ve,ie+=o*Ae,oe+=o*Re,ge+=o*be,he+=o*Ce,ae+=o*ke,fe+=o*Je,ce+=o*Me,G+=o*$e,te+=o*Ge,V+=o*Ye,Y+=o*ot,X+=o*pt,q+=o*gt,w+=o*mt,o=h[7],$+=o*y,ie+=o*ve,oe+=o*Ae,ge+=o*Re,he+=o*be,ae+=o*Ce,fe+=o*ke,ce+=o*Je,G+=o*Me,te+=o*$e,V+=o*Ge,Y+=o*Ye,X+=o*ot,q+=o*pt,w+=o*gt,x+=o*mt,o=h[8],ie+=o*y,oe+=o*ve,ge+=o*Ae,he+=o*Re,ae+=o*be,fe+=o*Ce,ce+=o*ke,G+=o*Je,te+=o*Me,V+=o*$e,Y+=o*Ge,X+=o*Ye,q+=o*ot,w+=o*pt,x+=o*gt,I+=o*mt,o=h[9],oe+=o*y,ge+=o*ve,he+=o*Ae,ae+=o*Re,fe+=o*be,ce+=o*Ce,G+=o*ke,te+=o*Je,V+=o*Me,Y+=o*$e,X+=o*Ge,q+=o*Ye,w+=o*ot,x+=o*pt,I+=o*gt,k+=o*mt,o=h[10],ge+=o*y,he+=o*ve,ae+=o*Ae,fe+=o*Re,ce+=o*be,G+=o*Ce,te+=o*ke,V+=o*Je,Y+=o*Me,X+=o*$e,q+=o*Ge,w+=o*Ye,x+=o*ot,I+=o*pt,k+=o*gt,P+=o*mt,o=h[11],he+=o*y,ae+=o*ve,fe+=o*Ae,ce+=o*Re,G+=o*be,te+=o*Ce,V+=o*ke,Y+=o*Je,X+=o*Me,q+=o*$e,w+=o*Ge,x+=o*Ye,I+=o*ot,k+=o*pt,P+=o*gt,F+=o*mt,o=h[12],ae+=o*y,fe+=o*ve,ce+=o*Ae,G+=o*Re,te+=o*be,V+=o*Ce,Y+=o*ke,X+=o*Je,q+=o*Me,w+=o*$e,x+=o*Ge,I+=o*Ye,k+=o*ot,P+=o*pt,F+=o*gt,ne+=o*mt,o=h[13],fe+=o*y,ce+=o*ve,G+=o*Ae,te+=o*Re,V+=o*be,Y+=o*Ce,X+=o*ke,q+=o*Je,w+=o*Me,x+=o*$e,I+=o*Ge,k+=o*Ye,P+=o*ot,F+=o*pt,ne+=o*gt,me+=o*mt,o=h[14],ce+=o*y,G+=o*ve,te+=o*Ae,V+=o*Re,Y+=o*be,X+=o*Ce,q+=o*ke,w+=o*Je,x+=o*Me,I+=o*$e,k+=o*Ge,P+=o*Ye,F+=o*ot,ne+=o*pt,me+=o*gt,Ee+=o*mt,o=h[15],G+=o*y,te+=o*ve,V+=o*Ae,Y+=o*Re,X+=o*be,q+=o*Ce,w+=o*ke,x+=o*Je,I+=o*Me,k+=o*$e,P+=o*Ge,F+=o*Ye,ne+=o*ot,me+=o*pt,Ee+=o*gt,ye+=o*mt,E+=38*te,b+=38*V,O+=38*Y,B+=38*X,Z+=38*q,W+=38*w,Pe+=38*x,$+=38*I,ie+=38*k,oe+=38*P,ge+=38*F,he+=38*ne,ae+=38*me,fe+=38*Ee,ce+=38*ye,g=1,o=E+g+65535,g=Math.floor(o/65536),E=o-g*65536,o=b+g+65535,g=Math.floor(o/65536),b=o-g*65536,o=O+g+65535,g=Math.floor(o/65536),O=o-g*65536,o=B+g+65535,g=Math.floor(o/65536),B=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=$+g+65535,g=Math.floor(o/65536),$=o-g*65536,o=ie+g+65535,g=Math.floor(o/65536),ie=o-g*65536,o=oe+g+65535,g=Math.floor(o/65536),oe=o-g*65536,o=ge+g+65535,g=Math.floor(o/65536),ge=o-g*65536,o=he+g+65535,g=Math.floor(o/65536),he=o-g*65536,o=ae+g+65535,g=Math.floor(o/65536),ae=o-g*65536,o=fe+g+65535,g=Math.floor(o/65536),fe=o-g*65536,o=ce+g+65535,g=Math.floor(o/65536),ce=o-g*65536,o=G+g+65535,g=Math.floor(o/65536),G=o-g*65536,E+=g-1+37*(g-1),g=1,o=E+g+65535,g=Math.floor(o/65536),E=o-g*65536,o=b+g+65535,g=Math.floor(o/65536),b=o-g*65536,o=O+g+65535,g=Math.floor(o/65536),O=o-g*65536,o=B+g+65535,g=Math.floor(o/65536),B=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=$+g+65535,g=Math.floor(o/65536),$=o-g*65536,o=ie+g+65535,g=Math.floor(o/65536),ie=o-g*65536,o=oe+g+65535,g=Math.floor(o/65536),oe=o-g*65536,o=ge+g+65535,g=Math.floor(o/65536),ge=o-g*65536,o=he+g+65535,g=Math.floor(o/65536),he=o-g*65536,o=ae+g+65535,g=Math.floor(o/65536),ae=o-g*65536,o=fe+g+65535,g=Math.floor(o/65536),fe=o-g*65536,o=ce+g+65535,g=Math.floor(o/65536),ce=o-g*65536,o=G+g+65535,g=Math.floor(o/65536),G=o-g*65536,E+=g-1+37*(g-1),f[0]=E,f[1]=b,f[2]=O,f[3]=B,f[4]=Z,f[5]=W,f[6]=Pe,f[7]=$,f[8]=ie,f[9]=oe,f[10]=ge,f[11]=he,f[12]=ae,f[13]=fe,f[14]=ce,f[15]=G}function A(f,h){R(f,h,h)}function ee(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=253;o>=0;o--)A(l,l),o!==2&&o!==4&&R(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--)A(l,l),o!==1&&R(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),E,b,O=e(),B=e(),Z=e(),W=e(),Pe=e(),$=e();for(b=0;b<31;b++)o[b]=h[b];for(o[31]=h[31]&127|64,o[0]&=248,yt(g,l),b=0;b<16;b++)B[b]=g[b],W[b]=O[b]=Z[b]=0;for(O[0]=W[0]=1,b=254;b>=0;--b)E=o[b>>>3]>>>(b&7)&1,Qe(O,B,E),Qe(Z,W,E),L(Pe,O,Z),j(O,O,Z),L(Z,B,W),j(B,B,W),A(W,Pe),A($,O),R(O,Z,O),R(Z,B,Pe),L(Pe,O,Z),j(O,O,Z),A(B,O),j(Z,W,$),R(O,Z,c),L(O,O,W),R(Z,Z,O),R(O,W,$),R(W,B,g),A(B,Pe),Qe(O,B,E),Qe(Z,W,E);for(b=0;b<16;b++)g[b+16]=O[b],g[b+32]=Z[b],g[b+48]=B[b],g[b+64]=W[b];var ie=g.subarray(32),oe=g.subarray(16);return ee(ie,ie),R(oe,oe,ie),Te(f,oe),0}function st(f,h){return Xe(f,h,i)}function dt(f,h){return t(h,32),st(f,h)}function yr(f,h,l){var o=new Uint8Array(32);return Xe(o,l,h),D(f,n,o,Q)}var Fr=Se,sn=_e;function Dr(f,h,l,o,g,E){var b=new Uint8Array(32);return yr(b,g,E),Fr(f,h,l,o,b)}function Rn(f,h,l,o,g,E){var b=new Uint8Array(32);return yr(b,g,E),sn(f,h,l,o,b)}var Qi=[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 kf(f,h,l,o){for(var g=new Int32Array(16),E=new Int32Array(16),b,O,B,Z,W,Pe,$,ie,oe,ge,he,ae,fe,ce,G,te,V,Y,X,q,w,x,I,k,P,F,ne=f[0],me=f[1],Ee=f[2],ye=f[3],y=f[4],ve=f[5],Ae=f[6],Re=f[7],be=h[0],Ce=h[1],ke=h[2],Je=h[3],Me=h[4],$e=h[5],Ge=h[6],Ye=h[7],ot=0;o>=128;){for(X=0;X<16;X++)q=8*X+ot,g[X]=l[q+0]<<24|l[q+1]<<16|l[q+2]<<8|l[q+3],E[X]=l[q+4]<<24|l[q+5]<<16|l[q+6]<<8|l[q+7];for(X=0;X<80;X++)if(b=ne,O=me,B=Ee,Z=ye,W=y,Pe=ve,$=Ae,ie=Re,oe=be,ge=Ce,he=ke,ae=Je,fe=Me,ce=$e,G=Ge,te=Ye,w=Re,x=Ye,I=x&65535,k=x>>>16,P=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,k+=x>>>16,P+=w&65535,F+=w>>>16,w=y&ve^~y&Ae,x=Me&$e^~Me&Ge,I+=x&65535,k+=x>>>16,P+=w&65535,F+=w>>>16,w=Qi[X*2],x=Qi[X*2+1],I+=x&65535,k+=x>>>16,P+=w&65535,F+=w>>>16,w=g[X%16],x=E[X%16],I+=x&65535,k+=x>>>16,P+=w&65535,F+=w>>>16,k+=I>>>16,P+=k>>>16,F+=P>>>16,V=P&65535|F<<16,Y=I&65535|k<<16,w=V,x=Y,I=x&65535,k=x>>>16,P=w&65535,F=w>>>16,w=(ne>>>28|be<<4)^(be>>>2|ne<<30)^(be>>>7|ne<<25),x=(be>>>28|ne<<4)^(ne>>>2|be<<30)^(ne>>>7|be<<25),I+=x&65535,k+=x>>>16,P+=w&65535,F+=w>>>16,w=ne&me^ne&Ee^me&Ee,x=be&Ce^be&ke^Ce&ke,I+=x&65535,k+=x>>>16,P+=w&65535,F+=w>>>16,k+=I>>>16,P+=k>>>16,F+=P>>>16,ie=P&65535|F<<16,te=I&65535|k<<16,w=Z,x=ae,I=x&65535,k=x>>>16,P=w&65535,F=w>>>16,w=V,x=Y,I+=x&65535,k+=x>>>16,P+=w&65535,F+=w>>>16,k+=I>>>16,P+=k>>>16,F+=P>>>16,Z=P&65535|F<<16,ae=I&65535|k<<16,me=b,Ee=O,ye=B,y=Z,ve=W,Ae=Pe,Re=$,ne=ie,Ce=oe,ke=ge,Je=he,Me=ae,$e=fe,Ge=ce,Ye=G,be=te,X%16===15)for(q=0;q<16;q++)w=g[q],x=E[q],I=x&65535,k=x>>>16,P=w&65535,F=w>>>16,w=g[(q+9)%16],x=E[(q+9)%16],I+=x&65535,k+=x>>>16,P+=w&65535,F+=w>>>16,V=g[(q+1)%16],Y=E[(q+1)%16],w=(V>>>1|Y<<31)^(V>>>8|Y<<24)^V>>>7,x=(Y>>>1|V<<31)^(Y>>>8|V<<24)^(Y>>>7|V<<25),I+=x&65535,k+=x>>>16,P+=w&65535,F+=w>>>16,V=g[(q+14)%16],Y=E[(q+14)%16],w=(V>>>19|Y<<13)^(Y>>>29|V<<3)^V>>>6,x=(Y>>>19|V<<13)^(V>>>29|Y<<3)^(Y>>>6|V<<26),I+=x&65535,k+=x>>>16,P+=w&65535,F+=w>>>16,k+=I>>>16,P+=k>>>16,F+=P>>>16,g[q]=P&65535|F<<16,E[q]=I&65535|k<<16;w=ne,x=be,I=x&65535,k=x>>>16,P=w&65535,F=w>>>16,w=f[0],x=h[0],I+=x&65535,k+=x>>>16,P+=w&65535,F+=w>>>16,k+=I>>>16,P+=k>>>16,F+=P>>>16,f[0]=ne=P&65535|F<<16,h[0]=be=I&65535|k<<16,w=me,x=Ce,I=x&65535,k=x>>>16,P=w&65535,F=w>>>16,w=f[1],x=h[1],I+=x&65535,k+=x>>>16,P+=w&65535,F+=w>>>16,k+=I>>>16,P+=k>>>16,F+=P>>>16,f[1]=me=P&65535|F<<16,h[1]=Ce=I&65535|k<<16,w=Ee,x=ke,I=x&65535,k=x>>>16,P=w&65535,F=w>>>16,w=f[2],x=h[2],I+=x&65535,k+=x>>>16,P+=w&65535,F+=w>>>16,k+=I>>>16,P+=k>>>16,F+=P>>>16,f[2]=Ee=P&65535|F<<16,h[2]=ke=I&65535|k<<16,w=ye,x=Je,I=x&65535,k=x>>>16,P=w&65535,F=w>>>16,w=f[3],x=h[3],I+=x&65535,k+=x>>>16,P+=w&65535,F+=w>>>16,k+=I>>>16,P+=k>>>16,F+=P>>>16,f[3]=ye=P&65535|F<<16,h[3]=Je=I&65535|k<<16,w=y,x=Me,I=x&65535,k=x>>>16,P=w&65535,F=w>>>16,w=f[4],x=h[4],I+=x&65535,k+=x>>>16,P+=w&65535,F+=w>>>16,k+=I>>>16,P+=k>>>16,F+=P>>>16,f[4]=y=P&65535|F<<16,h[4]=Me=I&65535|k<<16,w=ve,x=$e,I=x&65535,k=x>>>16,P=w&65535,F=w>>>16,w=f[5],x=h[5],I+=x&65535,k+=x>>>16,P+=w&65535,F+=w>>>16,k+=I>>>16,P+=k>>>16,F+=P>>>16,f[5]=ve=P&65535|F<<16,h[5]=$e=I&65535|k<<16,w=Ae,x=Ge,I=x&65535,k=x>>>16,P=w&65535,F=w>>>16,w=f[6],x=h[6],I+=x&65535,k+=x>>>16,P+=w&65535,F+=w>>>16,k+=I>>>16,P+=k>>>16,F+=P>>>16,f[6]=Ae=P&65535|F<<16,h[6]=Ge=I&65535|k<<16,w=Re,x=Ye,I=x&65535,k=x>>>16,P=w&65535,F=w>>>16,w=f[7],x=h[7],I+=x&65535,k+=x>>>16,P+=w&65535,F+=w>>>16,k+=I>>>16,P+=k>>>16,F+=P>>>16,f[7]=Re=P&65535|F<<16,h[7]=Ye=I&65535|k<<16,ot+=128,o-=128}return o}function on(f,h,l){var o=new Int32Array(8),g=new Int32Array(8),E=new Uint8Array(256),b,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,kf(o,g,h,l),l%=128,b=0;b<l;b++)E[b]=h[O-l+b];for(E[l]=128,l=256-128*(l<112?1:0),E[l-9]=0,v(E,l-8,O/536870912|0,O<<3),kf(o,g,E,l),b=0;b<8;b++)v(f,8*b,o[b],g[b]);return 0}function es(f,h){var l=e(),o=e(),g=e(),E=e(),b=e(),O=e(),B=e(),Z=e(),W=e();j(l,f[1],f[0]),j(W,h[1],h[0]),R(l,l,W),L(o,f[0],f[1]),L(W,h[0],h[1]),R(o,o,W),R(g,f[3],h[3]),R(g,g,d),R(E,f[2],h[2]),L(E,E,E),j(b,o,l),j(O,E,g),L(B,E,g),L(Z,o,l),R(f[0],b,O),R(f[1],Z,B),R(f[2],B,O),R(f[3],b,Z)}function Of(f,h,l){var o;for(o=0;o<4;o++)Qe(f[o],h[o],l)}function jo(f,h){var l=e(),o=e(),g=e();ee(g,h[2]),R(l,h[0],g),R(o,h[1],g),Te(f,o),f[31]^=ze(l)<<7}function Uo(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,Of(f,h,o),es(h,f),es(f,f),Of(f,h,o)}function ts(f,h){var l=[e(),e(),e(),e()];We(l[0],p),We(l[1],m),We(l[2],a),R(l[3],p,m),Uo(f,l,h)}function Ko(f,h,l){var o=new Uint8Array(64),g=[e(),e(),e(),e()],E;for(l||t(h,32),on(o,h,32),o[0]&=248,o[31]&=127,o[31]|=64,ts(g,o),jo(f,g),E=0;E<32;E++)h[E+32]=f[E];return 0}var rs=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 qo(f,h){var l,o,g,E;for(o=63;o>=32;--o){for(l=0,g=o-32,E=o-12;g<E;++g)h[g]+=l-16*h[o]*rs[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)*rs[g],l=h[g]>>8,h[g]&=255;for(g=0;g<32;g++)h[g]-=l*rs[g];for(o=0;o<32;o++)h[o+1]+=h[o]>>8,f[o]=h[o]&255}function Wo(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;qo(f,h)}function Pf(f,h,l,o){var g=new Uint8Array(64),E=new Uint8Array(64),b=new Uint8Array(64),O,B,Z=new Float64Array(64),W=[e(),e(),e(),e()];on(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(on(b,f.subarray(32),l+32),Wo(b),ts(W,b),jo(f,W),O=32;O<64;O++)f[O]=o[O];for(on(E,f,l+64),Wo(E),O=0;O<64;O++)Z[O]=0;for(O=0;O<32;O++)Z[O]=b[O];for(O=0;O<32;O++)for(B=0;B<32;B++)Z[O+B]+=E[O]*g[B];return qo(f.subarray(32),Z),Pe}function bp(f,h){var l=e(),o=e(),g=e(),E=e(),b=e(),O=e(),B=e();return We(f[2],a),yt(f[1],h),A(g,f[1]),R(E,g,u),j(g,g,f[2]),L(E,f[2],E),A(b,E),A(O,b),R(B,O,b),R(l,B,g),R(l,l,E),Ne(l,l),R(l,l,g),R(l,l,E),R(l,l,E),R(f[0],l,E),A(o,f[0]),R(o,o,E),it(o,g)&&R(f[0],f[0],_),A(o,f[0]),R(o,o,E),it(o,g)?-1:(ze(f[0])===h[31]>>7&&j(f[0],s,f[0]),R(f[3],f[0],f[1]),0)}function Ho(f,h,l,o){var g,E=new Uint8Array(32),b=new Uint8Array(64),O=[e(),e(),e(),e()],B=[e(),e(),e(),e()];if(l<64||bp(B,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(on(b,f,l),Wo(b),Uo(O,B,b),ts(B,h.subarray(32)),es(O,B),jo(E,O),l-=64,H(h,0,E,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 Vo=32,ns=24,hi=32,In=16,di=32,is=32,pi=32,gi=32,zo=32,Af=ns,vp=hi,wp=In,_r=64,an=32,Ln=64,$o=32,Go=64;r.lowlevel={crypto_core_hsalsa20:D,crypto_stream_xor:pe,crypto_stream:le,crypto_stream_salsa20_xor:K,crypto_stream_salsa20:U,crypto_onetimeauth:nt,crypto_onetimeauth_verify:we,crypto_verify_16:T,crypto_verify_32:H,crypto_secretbox:Se,crypto_secretbox_open:_e,crypto_scalarmult:Xe,crypto_scalarmult_base:st,crypto_box_beforenm:yr,crypto_box_afternm:Fr,crypto_box:Dr,crypto_box_open:Rn,crypto_box_keypair:dt,crypto_hash:on,crypto_sign:Pf,crypto_sign_keypair:Ko,crypto_sign_open:Ho,crypto_secretbox_KEYBYTES:Vo,crypto_secretbox_NONCEBYTES:ns,crypto_secretbox_ZEROBYTES:hi,crypto_secretbox_BOXZEROBYTES:In,crypto_scalarmult_BYTES:di,crypto_scalarmult_SCALARBYTES:is,crypto_box_PUBLICKEYBYTES:pi,crypto_box_SECRETKEYBYTES:gi,crypto_box_BEFORENMBYTES:zo,crypto_box_NONCEBYTES:Af,crypto_box_ZEROBYTES:vp,crypto_box_BOXZEROBYTES:wp,crypto_sign_BYTES:_r,crypto_sign_PUBLICKEYBYTES:an,crypto_sign_SECRETKEYBYTES:Ln,crypto_sign_SEEDBYTES:$o,crypto_hash_BYTES:Go,gf:e,D:u,L:rs,pack25519:Te,unpack25519:yt,M:R,A:L,S:A,Z:j,pow2523:Ne,add:es,set25519:We,modL:qo,scalarmult:Uo,scalarbase:ts};function Rf(f,h){if(f.length!==Vo)throw new Error("bad key size");if(h.length!==ns)throw new Error("bad nonce size")}function xp(f,h){if(f.length!==pi)throw new Error("bad public key size");if(h.length!==gi)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 If(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),Rf(l,h);for(var o=new Uint8Array(hi+f.length),g=new Uint8Array(o.length),E=0;E<f.length;E++)o[E+hi]=f[E];return Se(g,o,o.length,h,l),g.subarray(In)},r.secretbox.open=function(f,h,l){St(f,h,l),Rf(l,h);for(var o=new Uint8Array(In+f.length),g=new Uint8Array(o.length),E=0;E<f.length;E++)o[E+In]=f[E];return o.length<32||_e(g,o,o.length,h,l)!==0?null:g.subarray(hi)},r.secretbox.keyLength=Vo,r.secretbox.nonceLength=ns,r.secretbox.overheadLength=In,r.scalarMult=function(f,h){if(St(f,h),f.length!==is)throw new Error("bad n size");if(h.length!==di)throw new Error("bad p size");var l=new Uint8Array(di);return Xe(l,f,h),l},r.scalarMult.base=function(f){if(St(f),f.length!==is)throw new Error("bad n size");var h=new Uint8Array(di);return st(h,f),h},r.scalarMult.scalarLength=is,r.scalarMult.groupElementLength=di,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),xp(f,h);var l=new Uint8Array(zo);return yr(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(pi),h=new Uint8Array(gi);return dt(f,h),{publicKey:f,secretKey:h}},r.box.keyPair.fromSecretKey=function(f){if(St(f),f.length!==gi)throw new Error("bad secret key size");var h=new Uint8Array(pi);return st(h,f),{publicKey:h,secretKey:new Uint8Array(f)}},r.box.publicKeyLength=pi,r.box.secretKeyLength=gi,r.box.sharedKeyLength=zo,r.box.nonceLength=Af,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(f,h){if(St(f,h),h.length!==Ln)throw new Error("bad secret key size");var l=new Uint8Array(_r+f.length);return Pf(l,f,f.length,h),l},r.sign.open=function(f,h){if(St(f,h),h.length!==an)throw new Error("bad public key size");var l=new Uint8Array(f.length),o=Ho(l,f,f.length,h);if(o<0)return null;for(var g=new Uint8Array(o),E=0;E<g.length;E++)g[E]=l[E];return g},r.sign.detached=function(f,h){for(var l=r.sign(f,h),o=new Uint8Array(_r),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!==_r)throw new Error("bad signature size");if(l.length!==an)throw new Error("bad public key size");var o=new Uint8Array(_r+f.length),g=new Uint8Array(_r+f.length),E;for(E=0;E<_r;E++)o[E]=h[E];for(E=0;E<f.length;E++)o[E+_r]=f[E];return Ho(g,o,o.length,l)>=0},r.sign.keyPair=function(){var f=new Uint8Array(an),h=new Uint8Array(Ln);return Ko(f,h),{publicKey:f,secretKey:h}},r.sign.keyPair.fromSecretKey=function(f){if(St(f),f.length!==Ln)throw new Error("bad secret key size");for(var h=new Uint8Array(an),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!==$o)throw new Error("bad seed size");for(var h=new Uint8Array(an),l=new Uint8Array(Ln),o=0;o<32;o++)l[o]=f[o];return Ko(h,l,!0),{publicKey:h,secretKey:l}},r.sign.publicKeyLength=an,r.sign.secretKeyLength=Ln,r.sign.seedLength=$o,r.sign.signatureLength=_r,r.hash=function(f){St(f);var h=new Uint8Array(Go);return on(h,f,f.length),h},r.hash.hashLength=Go,r.verify=function(f,h){return St(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,E=new Uint8Array(o);for(g=0;g<o;g+=h)f.getRandomValues(E.subarray(g,g+Math.min(o-g,h)));for(g=0;g<o;g++)l[g]=E[g];If(E)})}else typeof require<"u"&&(f=require("crypto"),f&&f.randomBytes&&r.setPRNG(function(l,o){var g,E=f.randomBytes(o);for(g=0;g<o;g++)l[g]=E[g];If(E)}))})()})(typeof ms<"u"&&ms.exports?ms.exports:self.nacl=self.nacl||{})});var bi=M((Zf,ys)=>{(function(r,e){"use strict";typeof ys<"u"&&ys.exports?ys.exports=e():(r.nacl||(r.nacl={}),r.nacl.util=e())})(Zf,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 n,i=unescape(encodeURIComponent(t)),s=new Uint8Array(i.length);for(n=0;n<i.length;n++)s[n]=i.charCodeAt(n);return s},r.encodeUTF8=function(t){var n,i=[];for(n=0;n<t.length;n++)i.push(String.fromCharCode(t[n]));return decodeURIComponent(escape(i.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 n,i=[],s=t.length;for(n=0;n<s;n++)i.push(String.fromCharCode(t[n]));return btoa(i.join(""))},r.decodeBase64=function(t){e(t);var n,i=atob(t),s=new Uint8Array(i.length);for(n=0;n<i.length;n++)s[n]=i.charCodeAt(n);return s}),r})});var Qf=M(Ct=>{"use strict";var Vp=Ct&&Ct.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ct,"__esModule",{value:!0});Ct.concatBytes=vi;Ct.generateIdentityKeyPair=zp;Ct.identityPublicFromSecret=$p;Ct.signSessionKey=Gp;Ct.verifySessionKey=Yp;Ct.buildKxCanonical=Xp;Ct.buildKxAckCanonical=Jp;Ct.fingerprintIdentityKey=Zp;Ct.fingerprintShortHex=Qp;var tr=Vp(Ei()),Tt=bi(),_s=Qo();function vi(...r){let e=0;for(let i of r)e+=i.length;let t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}function zp(){let r=tr.default.sign.keyPair();return{identityPublicKey:(0,Tt.encodeBase64)(r.publicKey),identitySecretKey:(0,Tt.encodeBase64)(r.secretKey)}}function $p(r){let e=(0,Tt.decodeBase64)(r);if(e.length!==tr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");let t=tr.default.sign.keyPair.fromSecretKey(e);return(0,Tt.encodeBase64)(t.publicKey)}function Gp(r,e){let t=(0,Tt.decodeBase64)(e);if(t.length!==tr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");return(0,Tt.encodeBase64)(tr.default.sign.detached(r,t))}function Yp(r,e,t){try{let n=(0,Tt.decodeBase64)(e),i=(0,Tt.decodeBase64)(t);return i.length!==tr.default.sign.publicKeyLength||n.length!==tr.default.sign.signatureLength?!1:tr.default.sign.detached.verify(r,n,i)}catch{return!1}}var cn=new Uint8Array([0]);function Xp(r){let e=new TextEncoder,t=e.encode(_s.KX_SIGN_LABEL),n=e.encode(r.agentId),i=e.encode(String(r.keyVersion)),s=(0,Tt.decodeBase64)(r.boxPublicKey);return vi(t,cn,n,cn,i,cn,s)}function Jp(r){let e=new TextEncoder;return vi(e.encode(_s.KX_ACK_LABEL),cn,e.encode(r.agentId),cn,e.encode(String(r.keyVersion)),cn,(0,Tt.decodeBase64)(r.boxPublicKey),cn,(0,Tt.decodeBase64)(r.boundClientKey))}function Zp(r){let e=(0,Tt.decodeBase64)(r),t=vi(new TextEncoder().encode(_s.KX_FINGERPRINT_LABEL),e),n=tr.default.hash(t),i=[];for(let s=0;s<12;s++){let a=s*5,u=(((n[a]<<24>>>0)+(n[a+1]<<16)+(n[a+2]<<8)+n[a+3]^n[a+4])>>>0)%1e5;i.push(String(u).padStart(5,"0"))}return i.join(" ")}function Qp(r){let e=(0,Tt.decodeBase64)(r),t=vi(new TextEncoder().encode(_s.KX_FINGERPRINT_LABEL),e),n=tr.default.hash(t).slice(0,8);return Array.from(n).map(i=>i.toString(16).padStart(2,"0")).join(":").toUpperCase()}});var eu=M(Ur=>{"use strict";var eg=Ur&&Ur.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ur,"__esModule",{value:!0});Ur.encrypt=tg;Ur.decrypt=rg;Ur.encryptBinary=ng;Ur.decryptBinary=ig;var vr=eg(Ei()),jr=bi();function tg(r,e,t){let n=vr.default.randomBytes(vr.default.secretbox.nonceLength),i=new TextEncoder().encode(r),s=vr.default.secretbox(i,n,e);return{v:1,sid:t,n:(0,jr.encodeBase64)(n),c:(0,jr.encodeBase64)(s)}}function rg(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,jr.decodeBase64)(r.n),n=(0,jr.decodeBase64)(r.c);if(t.length!==vr.default.secretbox.nonceLength)throw new Error(`Invalid nonce length: ${t.length}`);let i=vr.default.secretbox.open(n,t,e);if(!i)throw new Error("Decryption failed: invalid ciphertext or wrong key");return new TextDecoder().decode(i)}function ng(r,e,t){let n=vr.default.randomBytes(vr.default.secretbox.nonceLength),i=vr.default.secretbox(r,n,e);return{v:1,sid:t,n:(0,jr.encodeBase64)(n),c:(0,jr.encodeBase64)(i)}}function ig(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,jr.decodeBase64)(r.n),n=(0,jr.decodeBase64)(r.c),i=vr.default.secretbox.open(n,t,e);if(!i)throw new Error("Decryption failed: invalid ciphertext or wrong key");return i}});var tu=M(Ht=>{"use strict";var sg=Ht&&Ht.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ht,"__esModule",{value:!0});Ht.generateKeyPair=og;Ht.deriveSharedSecret=ag;Ht.deriveMetaSid=cg;Ht.isValidPublicKey=fg;Ht.clearKey=ug;Ht.keyToBase64=lg;Ht.base64ToKey=hg;var Mn=sg(Ei()),rr=bi();function og(){let r=Mn.default.box.keyPair();return{publicKey:(0,rr.encodeBase64)(r.publicKey),secretKey:(0,rr.encodeBase64)(r.secretKey)}}function ag(r,e){let t=(0,rr.decodeBase64)(r),n=(0,rr.decodeBase64)(e);if(t.length!==Mn.default.box.publicKeyLength)throw new Error(`Invalid public key length: ${t.length}`);if(n.length!==Mn.default.box.secretKeyLength)throw new Error(`Invalid secret key length: ${n.length}`);return Mn.default.box.before(t,n)}function cg(r,e){let t=new TextEncoder().encode("termiq-meta-v1"),n=(0,rr.decodeBase64)(r),i=(0,rr.decodeBase64)(e),s=new Uint8Array(t.length+n.length+i.length);return s.set(t,0),s.set(n,t.length),s.set(i,t.length+n.length),(0,rr.encodeBase64)(Mn.default.hash(s).slice(0,32))}function fg(r){try{return(0,rr.decodeBase64)(r).length===Mn.default.box.publicKeyLength}catch{return!1}}function ug(r){r.fill(0)}function lg(r){return(0,rr.encodeBase64)(r)}function hg(r){return(0,rr.decodeBase64)(r)}});var nu=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 ru=Jf();Object.defineProperty(re,"isEncryptedPayload",{enumerable:!0,get:function(){return ru.isEncryptedPayload}});Object.defineProperty(re,"isMultiRecipientPayload",{enumerable:!0,get:function(){return ru.isMultiRecipientPayload}});var Es=Qo();Object.defineProperty(re,"KX_SIGN_LABEL",{enumerable:!0,get:function(){return Es.KX_SIGN_LABEL}});Object.defineProperty(re,"KX_ACK_LABEL",{enumerable:!0,get:function(){return Es.KX_ACK_LABEL}});Object.defineProperty(re,"KX_FINGERPRINT_LABEL",{enumerable:!0,get:function(){return Es.KX_FINGERPRINT_LABEL}});Object.defineProperty(re,"KX_SIG_VERSION",{enumerable:!0,get:function(){return Es.KX_SIG_VERSION}});var wr=Qf();Object.defineProperty(re,"generateIdentityKeyPair",{enumerable:!0,get:function(){return wr.generateIdentityKeyPair}});Object.defineProperty(re,"identityPublicFromSecret",{enumerable:!0,get:function(){return wr.identityPublicFromSecret}});Object.defineProperty(re,"signSessionKey",{enumerable:!0,get:function(){return wr.signSessionKey}});Object.defineProperty(re,"verifySessionKey",{enumerable:!0,get:function(){return wr.verifySessionKey}});Object.defineProperty(re,"buildKxCanonical",{enumerable:!0,get:function(){return wr.buildKxCanonical}});Object.defineProperty(re,"buildKxAckCanonical",{enumerable:!0,get:function(){return wr.buildKxAckCanonical}});Object.defineProperty(re,"fingerprintIdentityKey",{enumerable:!0,get:function(){return wr.fingerprintIdentityKey}});Object.defineProperty(re,"fingerprintShortHex",{enumerable:!0,get:function(){return wr.fingerprintShortHex}});Object.defineProperty(re,"concatBytes",{enumerable:!0,get:function(){return wr.concatBytes}});var bs=eu();Object.defineProperty(re,"encrypt",{enumerable:!0,get:function(){return bs.encrypt}});Object.defineProperty(re,"decrypt",{enumerable:!0,get:function(){return bs.decrypt}});Object.defineProperty(re,"encryptBinary",{enumerable:!0,get:function(){return bs.encryptBinary}});Object.defineProperty(re,"decryptBinary",{enumerable:!0,get:function(){return bs.decryptBinary}});var fn=tu();Object.defineProperty(re,"generateKeyPair",{enumerable:!0,get:function(){return fn.generateKeyPair}});Object.defineProperty(re,"deriveSharedSecret",{enumerable:!0,get:function(){return fn.deriveSharedSecret}});Object.defineProperty(re,"deriveMetaSid",{enumerable:!0,get:function(){return fn.deriveMetaSid}});Object.defineProperty(re,"isValidPublicKey",{enumerable:!0,get:function(){return fn.isValidPublicKey}});Object.defineProperty(re,"clearKey",{enumerable:!0,get:function(){return fn.clearKey}});Object.defineProperty(re,"keyToBase64",{enumerable:!0,get:function(){return fn.keyToBase64}});Object.defineProperty(re,"base64ToKey",{enumerable:!0,get:function(){return fn.base64ToKey}})});var iu=M(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.MIN_CLIENT_VERSION=kt.PROTOCOL_VERSION_MINOR=kt.PROTOCOL_VERSION_MAJOR=kt.PROTOCOL_VERSION=void 0;kt.isCompatibleVersion=dg;kt.compareVersions=pg;kt.PROTOCOL_VERSION="2.1";kt.PROTOCOL_VERSION_MAJOR=2;kt.PROTOCOL_VERSION_MINOR=1;kt.MIN_CLIENT_VERSION="2.0";function dg(r){let[e]=r.split(".").map(Number);return e===kt.PROTOCOL_VERSION_MAJOR}function pg(r,e){let[t,n]=r.split(".").map(Number),[i,s]=e.split(".").map(Number);return t!==i?t<i?-1:1:n!==s?n<s?-1:1:0}});var su=M(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.SERVER_CAPABILITIES=nr.DEFAULT_CLIENT_CAPABILITIES=nr.Capability=void 0;nr.hasCapability=gg;nr.negotiateCapabilities=mg;var Fn;(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"})(Fn||(nr.Capability=Fn={}));nr.DEFAULT_CLIENT_CAPABILITIES=[Fn.E2E_ENCRYPTION,Fn.TERMINAL_EVENTS,Fn.RELIABLE_INPUT];nr.SERVER_CAPABILITIES=Object.values(Fn);function gg(r,e){return r.includes(e)}function mg(r,e){return r.filter(t=>e.includes(t))}});var ou=M(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.DEFAULT_PRIORITY=xr.PRIORITY_NAMES=xr.Priority=void 0;xr.comparePriority=yg;var un;(function(r){r[r.CRITICAL=0]="CRITICAL",r[r.HIGH=1]="HIGH",r[r.NORMAL=2]="NORMAL",r[r.LOW=3]="LOW"})(un||(xr.Priority=un={}));xr.PRIORITY_NAMES={[un.CRITICAL]:"CRITICAL",[un.HIGH]:"HIGH",[un.NORMAL]:"NORMAL",[un.LOW]:"LOW"};xr.DEFAULT_PRIORITY=un.NORMAL;function yg(r,e){return r-e}});var au=M(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.DEFAULT_RELIABILITY=ir.RELIABILITY_NAMES=ir.Reliability=void 0;ir.requiresAck=_g;ir.requiresBuffer=Eg;var Kr;(function(r){r[r.FIRE_FORGET=0]="FIRE_FORGET",r[r.BUFFERED=1]="BUFFERED",r[r.GUARANTEED=2]="GUARANTEED"})(Kr||(ir.Reliability=Kr={}));ir.RELIABILITY_NAMES={[Kr.FIRE_FORGET]:"FIRE_FORGET",[Kr.BUFFERED]:"BUFFERED",[Kr.GUARANTEED]:"GUARANTEED"};ir.DEFAULT_RELIABILITY=Kr.FIRE_FORGET;function _g(r){return r===Kr.GUARANTEED}function Eg(r){return r>=Kr.BUFFERED}});var cu=M(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});ea.createMessage=bg;function bg(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 fu=M(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.TerminalEventType=void 0;ln.deriveStatusFromEvent=vg;ln.shouldTriggerPushNotification=wg;ln.getPushNotificationMessage=xg;var _t;(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"})(_t||(ln.TerminalEventType=_t={}));function vg(r){switch(r.type){case _t.SESSION_START:case _t.TOOL_START:case _t.MESSAGE:return"working";case _t.WAITING_INPUT:return"waiting";case _t.SESSION_END:return r.status==="success"?"completed":"error";case _t.ERROR:return r.severity==="fatal"?"error":"working";case _t.TOOL_END:return r.status==="error"?"error":"working";default:return"idle"}}function wg(r){switch(r.type){case _t.WAITING_INPUT:return!0;case _t.SESSION_END:return!0;case _t.ERROR:return r.severity!=="warning";default:return!1}}function xg(r,e){switch(r.type){case _t.WAITING_INPUT:return{title:`${e}: Input Required`,body:r.question.slice(0,100)};case _t.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 _t.ERROR:{let t=r;return t.severity==="warning"?null:{title:`${e}: Error`,body:t.message.slice(0,100)}}default:return null}}});var hu=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=Sg;Ue.getMissingChunks=Tg;Ue.isTransferComplete=Cg;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 uu;(function(r){r.PENDING="pending",r.ACTIVE="active",r.PAUSED="paused",r.COMPLETED="completed",r.FAILED="failed",r.CANCELLED="cancelled",r.EXPIRED="expired"})(uu||(Ue.TransferStatus=uu={}));var lu;(function(r){r.DOWNLOAD="download",r.UPLOAD="upload"})(lu||(Ue.TransferDirection=lu={}));function Sg(r,e=Ue.CHUNK_SIZE){return Math.ceil(r/e)}function Tg(r,e){let t=new Set(e),n=[];for(let i=0;i<r;i++)t.has(i)||n.push(i);return n}function Cg(r,e){return e.length===r}});var du=M(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.ERROR_MESSAGES=Sr.ErrorCode=void 0;Sr.createError=kg;Sr.isRetryableError=Og;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 kg(r,e={}){return{code:r,message:e.message||Sr.ERROR_MESSAGES[r],details:e.details,retryable:e.retryable??!1,retryAfter:e.retryAfter}}function Og(r){return[Ie.RATE_LIMITED,Ie.TIMEOUT,Ie.CONNECTION_LOST,Ie.SERVICE_UNAVAILABLE].includes(r)}});var yu=M(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.FileEntryType=Ot.DiffBase=Ot.FileViewType=Ot.FileChangeType=void 0;Ot.getLanguageFromPath=Pg;Ot.parseUnifiedDiff=Ag;Ot.createSimpleDiff=Rg;var qr;(function(r){r.CREATE="create",r.MODIFY="modify",r.DELETE="delete"})(qr||(Ot.FileChangeType=qr={}));var pu;(function(r){r.CONTENT="content",r.DIFF="diff"})(pu||(Ot.FileViewType=pu={}));var gu;(function(r){r.GIT="git",r.PREVIOUS="previous"})(gu||(Ot.DiffBase=gu={}));function Pg(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"},n=r.split("/").pop()?.toLowerCase()||"";return{dockerfile:"dockerfile",makefile:"makefile",".gitignore":"plaintext",".env":"plaintext",".env.local":"plaintext",".env.development":"plaintext",".env.production":"plaintext"}[n]||t[e||""]||"plaintext"}function Ag(r,e){let t=r.split(`
3
- `),n=[],i=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&&n.push(a);let _=parseInt(m[1],10),v=parseInt(m[2]||"1",10),S=parseInt(m[3],10),T=parseInt(m[4]||"1",10);a={oldStart:_,oldLines:v,newStart:S,newLines:T,lines:[]},c=_,u=S;continue}a&&(p.startsWith("+")?(a.lines.push({type:"add",content:p.slice(1),oldLineNumber:null,newLineNumber:u++}),i++):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&&n.push(a);let d;return s===0&&i>0&&n.length===1&&n[0].oldLines===0?d=qr.CREATE:i===0&&s>0&&n.length===1&&n[0].newLines===0?d=qr.DELETE:d=qr.MODIFY,{path:e,changeType:d,hunks:n,additions:i,deletions:s,isBinary:!1}}function Rg(r,e,t){let n=r.split(`
4
- `),i=e.split(`
5
- `),s=[],a=0,c=0,u=Math.max(n.length,i.length);for(let p=0;p<u;p++){let m=n[p],_=i[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=qr.CREATE:e===""?d=qr.DELETE:d=qr.MODIFY,{path:t,changeType:d,hunks:[{oldStart:1,oldLines:n.length,newStart:1,newLines:i.length,lines:s}],additions:a,deletions:c,isBinary:!1}}var mu;(function(r){r.FILE="file",r.DIRECTORY="directory"})(mu||(Ot.FileEntryType=mu={}))});var _u=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 Dn=iu();Object.defineProperty(N,"PROTOCOL_VERSION",{enumerable:!0,get:function(){return Dn.PROTOCOL_VERSION}});Object.defineProperty(N,"PROTOCOL_VERSION_MAJOR",{enumerable:!0,get:function(){return Dn.PROTOCOL_VERSION_MAJOR}});Object.defineProperty(N,"PROTOCOL_VERSION_MINOR",{enumerable:!0,get:function(){return Dn.PROTOCOL_VERSION_MINOR}});Object.defineProperty(N,"MIN_CLIENT_VERSION",{enumerable:!0,get:function(){return Dn.MIN_CLIENT_VERSION}});Object.defineProperty(N,"isCompatibleVersion",{enumerable:!0,get:function(){return Dn.isCompatibleVersion}});Object.defineProperty(N,"compareVersions",{enumerable:!0,get:function(){return Dn.compareVersions}});var wi=su();Object.defineProperty(N,"Capability",{enumerable:!0,get:function(){return wi.Capability}});Object.defineProperty(N,"DEFAULT_CLIENT_CAPABILITIES",{enumerable:!0,get:function(){return wi.DEFAULT_CLIENT_CAPABILITIES}});Object.defineProperty(N,"SERVER_CAPABILITIES",{enumerable:!0,get:function(){return wi.SERVER_CAPABILITIES}});Object.defineProperty(N,"hasCapability",{enumerable:!0,get:function(){return wi.hasCapability}});Object.defineProperty(N,"negotiateCapabilities",{enumerable:!0,get:function(){return wi.negotiateCapabilities}});var vs=ou();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 xi=au();Object.defineProperty(N,"Reliability",{enumerable:!0,get:function(){return xi.Reliability}});Object.defineProperty(N,"RELIABILITY_NAMES",{enumerable:!0,get:function(){return xi.RELIABILITY_NAMES}});Object.defineProperty(N,"DEFAULT_RELIABILITY",{enumerable:!0,get:function(){return xi.DEFAULT_RELIABILITY}});Object.defineProperty(N,"requiresAck",{enumerable:!0,get:function(){return xi.requiresAck}});Object.defineProperty(N,"requiresBuffer",{enumerable:!0,get:function(){return xi.requiresBuffer}});var Ig=cu();Object.defineProperty(N,"createMessage",{enumerable:!0,get:function(){return Ig.createMessage}});var ws=fu();Object.defineProperty(N,"TerminalEventType",{enumerable:!0,get:function(){return ws.TerminalEventType}});Object.defineProperty(N,"deriveStatusFromEvent",{enumerable:!0,get:function(){return ws.deriveStatusFromEvent}});Object.defineProperty(N,"shouldTriggerPushNotification",{enumerable:!0,get:function(){return ws.shouldTriggerPushNotification}});Object.defineProperty(N,"getPushNotificationMessage",{enumerable:!0,get:function(){return ws.getPushNotificationMessage}});var Nt=hu();Object.defineProperty(N,"CHUNK_SIZE",{enumerable:!0,get:function(){return Nt.CHUNK_SIZE}});Object.defineProperty(N,"DEFAULT_MAX_FILE_SIZE",{enumerable:!0,get:function(){return Nt.DEFAULT_MAX_FILE_SIZE}});Object.defineProperty(N,"WINDOW_SIZE",{enumerable:!0,get:function(){return Nt.WINDOW_SIZE}});Object.defineProperty(N,"ACK_TIMEOUT_MS",{enumerable:!0,get:function(){return Nt.ACK_TIMEOUT_MS}});Object.defineProperty(N,"MAX_RETRIES",{enumerable:!0,get:function(){return Nt.MAX_RETRIES}});Object.defineProperty(N,"TRANSFER_TTL_SECONDS",{enumerable:!0,get:function(){return Nt.TRANSFER_TTL_SECONDS}});Object.defineProperty(N,"CHUNK_TTL_SECONDS",{enumerable:!0,get:function(){return Nt.CHUNK_TTL_SECONDS}});Object.defineProperty(N,"TransferStatus",{enumerable:!0,get:function(){return Nt.TransferStatus}});Object.defineProperty(N,"TransferDirection",{enumerable:!0,get:function(){return Nt.TransferDirection}});Object.defineProperty(N,"calculateTotalChunks",{enumerable:!0,get:function(){return Nt.calculateTotalChunks}});Object.defineProperty(N,"getMissingChunks",{enumerable:!0,get:function(){return Nt.getMissingChunks}});Object.defineProperty(N,"isTransferComplete",{enumerable:!0,get:function(){return Nt.isTransferComplete}});var xs=du();Object.defineProperty(N,"ErrorCode",{enumerable:!0,get:function(){return xs.ErrorCode}});Object.defineProperty(N,"ERROR_MESSAGES",{enumerable:!0,get:function(){return xs.ERROR_MESSAGES}});Object.defineProperty(N,"createError",{enumerable:!0,get:function(){return xs.createError}});Object.defineProperty(N,"isRetryableError",{enumerable:!0,get:function(){return xs.isRetryableError}});var hn=yu();Object.defineProperty(N,"FileChangeType",{enumerable:!0,get:function(){return hn.FileChangeType}});Object.defineProperty(N,"FileViewType",{enumerable:!0,get:function(){return hn.FileViewType}});Object.defineProperty(N,"DiffBase",{enumerable:!0,get:function(){return hn.DiffBase}});Object.defineProperty(N,"FileEntryType",{enumerable:!0,get:function(){return hn.FileEntryType}});Object.defineProperty(N,"getLanguageFromPath",{enumerable:!0,get:function(){return hn.getLanguageFromPath}});Object.defineProperty(N,"parseUnifiedDiff",{enumerable:!0,get:function(){return hn.parseUnifiedDiff}});Object.defineProperty(N,"createSimpleDiff",{enumerable:!0,get:function(){return hn.createSimpleDiff}})});var Tr=M(sr=>{"use strict";var Lg=sr&&sr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Ss=sr&&sr.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Lg(e,r,t)};Object.defineProperty(sr,"__esModule",{value:!0});Ss(Yf(),sr);Ss(Xf(),sr);Ss(nu(),sr);Ss(_u(),sr)});var ta=M(He=>{"use strict";var Ng=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=Si;He.generateIdentityKeyPair=Mg;He.identityPublicFromSecret=Fg;He.signSessionKey=Dg;He.verifySessionKey=Bg;He.buildKxCanonical=jg;He.buildKxAckCanonical=Ug;He.fingerprintIdentityKey=Kg;He.fingerprintShortHex=qg;var or=Ng(Ei()),Pt=bi();He.KX_SIGN_LABEL="termiq-kx-v1";He.KX_ACK_LABEL="termiq-kxack-v1";He.FP_LABEL="termiq-fp-v1";function Si(...r){let e=0;for(let i of r)e+=i.length;let t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}function Mg(){let r=or.default.sign.keyPair();return{identityPublicKey:(0,Pt.encodeBase64)(r.publicKey),identitySecretKey:(0,Pt.encodeBase64)(r.secretKey)}}function Fg(r){let e=(0,Pt.decodeBase64)(r);if(e.length!==or.default.sign.secretKeyLength)throw new Error("bad identity secret key length");let t=or.default.sign.keyPair.fromSecretKey(e);return(0,Pt.encodeBase64)(t.publicKey)}function Dg(r,e){let t=(0,Pt.decodeBase64)(e);if(t.length!==or.default.sign.secretKeyLength)throw new Error("bad identity secret key length");return(0,Pt.encodeBase64)(or.default.sign.detached(r,t))}function Bg(r,e,t){try{let n=(0,Pt.decodeBase64)(e),i=(0,Pt.decodeBase64)(t);return i.length!==or.default.sign.publicKeyLength||n.length!==or.default.sign.signatureLength?!1:or.default.sign.detached.verify(r,n,i)}catch{return!1}}var dn=new Uint8Array([0]);function jg(r){let e=new TextEncoder,t=e.encode(He.KX_SIGN_LABEL),n=e.encode(r.agentId),i=e.encode(String(r.keyVersion)),s=(0,Pt.decodeBase64)(r.boxPublicKey);return Si(t,dn,n,dn,i,dn,s)}function Ug(r){let e=new TextEncoder;return Si(e.encode(He.KX_ACK_LABEL),dn,e.encode(r.agentId),dn,e.encode(String(r.keyVersion)),dn,(0,Pt.decodeBase64)(r.boxPublicKey),dn,(0,Pt.decodeBase64)(r.boundClientKey))}function Kg(r){let e=(0,Pt.decodeBase64)(r),t=Si(new TextEncoder().encode(He.FP_LABEL),e),n=or.default.hash(t),i=[];for(let s=0;s<12;s++){let a=s*5,u=(((n[a]<<24>>>0)+(n[a+1]<<16)+(n[a+2]<<8)+n[a+3]^n[a+4])>>>0)%1e5;i.push(String(u).padStart(5,"0"))}return i.join(" ")}function qg(r){let e=(0,Pt.decodeBase64)(r),t=Si(new TextEncoder().encode(He.FP_LABEL),e),n=or.default.hash(t).slice(0,8);return Array.from(n).map(i=>i.toString(16).padStart(2,"0")).join(":").toUpperCase()}});var bu=M(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});Ts.CryptoService=void 0;var et=Tr(),Wr=ta(),Wg=3600*1e3,Eu=10,ra=class{storage;logger;sessions=new Map;agentSessions=new Map;metaSessions=new Map;keyPair=null;identityKeyPair=null;publicKeyKey;secretKeyKey;keyVersionKey;identityPublicKeyKey;identitySecretKeyKey;constructor(e,t,n,i){this.storage=e,this.logger=t;let s=`termiq.${n}.${i}`;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",n,i)}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,Wr.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,Wr.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(),n=await this.getKeyVersion(),i=this.keyPair.publicKey,s=(0,Wr.buildKxCanonical)({agentId:e,keyVersion:n,boxPublicKey:i}),a=(0,Wr.signSessionKey)(s,t.identitySecretKey);return{boxPublicKey:i,identityPublicKey:t.identityPublicKey,keyVersion:n,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 n=await this.ensureIdentityKeyPair(),i=await this.getKeyVersion(),s=(0,Wr.buildKxAckCanonical)({agentId:e,keyVersion:i,boxPublicKey:this.keyPair.publicKey,boundClientKey:t});return(0,Wr.signSessionKey)(s,n.identitySecretKey)}async getSafetyNumber(){let e=await this.ensureIdentityKeyPair();return(0,Wr.fingerprintIdentityKey)(e.identityPublicKey)}async getShortFingerprint(){let e=await this.ensureIdentityKeyPair();return(0,Wr.fingerprintShortHex)(e.identityPublicKey)}async handleKeyExchange(e,t,n){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,n);try{let i=this.sessions.get(e);i||(i=new Map,this.sessions.set(e,i));let s=(0,et.deriveSharedSecret)(t,this.keyPair.secretKey),a={terminalId:e,clientPublicKey:t,sharedSecret:s,createdAt:Date.now(),sessionId:n};return i.set(n,a),this.logger.info("Key exchange completed",e,n,"total:",i.size),!0}catch(i){return this.logger.error("Key exchange failed",i),!1}}encryptOutput(e,t){let n=this.sessions.get(e);if(!n||n.size===0)return null;try{if(n.size===1){let s=n.values().next().value;return s?(0,et.encrypt)(t,s.sharedSecret,s.sessionId):null}let i=[];for(let s of n.values()){let a=(0,et.encrypt)(t,s.sharedSecret,s.sessionId);i.push({sid:a.sid,n:a.n,c:a.c})}return{v:2,recipients:i}}catch(i){return this.logger.error("Encryption failed",i),null}}decryptInput(e,t){let n=this.sessions.get(e);if(!n)return this.logger.error("No sessions for terminal",e),null;let i=n.get(t.sid);if(!i)return this.logger.error("No session for sessionId",t.sid),null;try{return(0,et.decrypt)(t,i.sharedSecret)}catch(s){return this.logger.error("Decryption failed",s),null}}encryptFileChunk(e,t){let n=this.sessions.get(e);if(!n||n.size===0)return null;let i=null;for(let s of n.values())(!i||s.createdAt>i.createdAt)&&(i=s);if(!i)return null;try{return(0,et.encryptBinary)(t,i.sharedSecret,i.sessionId)}catch(s){return this.logger.error("File chunk encryption failed",s),null}}decryptFileChunk(e,t){let n=this.sessions.get(e)?.get(t.sid);if(!n)return this.logger.error("No session for file chunk",e,t.sid),null;try{return(0,et.decryptBinary)(t,n.sharedSecret)}catch(i){return this.logger.error("File chunk decryption failed",i),null}}hasSession(e){let t=this.sessions.get(e);return t!==void 0&&t.size>0}removeSession(e,t){let n=this.sessions.get(e);if(n)if(t){let i=n.get(t);i&&((0,et.clearKey)(i.sharedSecret),n.delete(t),this.logger.info("Session removed",e,t)),n.size===0&&this.sessions.delete(e)}else{for(let i of n.values())(0,et.clearKey)(i.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 n=Date.now(),i=[];for(let[s,a]of t)n-a.createdAt>Wg&&i.push(s);for(let s of i){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((n-a.createdAt)/1e3)}s`))}if(t.size>Eu){let a=Array.from(t.entries()).sort((c,u)=>c[1].createdAt-u[1].createdAt).slice(0,t.size-Eu);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,n]of this.sessions.entries())for(let i of n.values())e.push({terminalId:t,createdAt:i.createdAt,sessionId:i.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 n=this.agentSessions.get(t);n&&(this.logger.info("Rekeying existing agent session",t),(0,et.clearKey)(n.sharedSecret));let i=(0,et.deriveSharedSecret)(e,this.keyPair.secretKey),s={sessionId:t,clientPublicKey:e,sharedSecret:i,createdAt:Date.now()};return this.agentSessions.set(t,s),this.logger.info("Agent key exchange completed",t,"total:",this.agentSessions.size),!0}catch(n){return this.logger.error("Agent key exchange failed",n),!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),n=(0,et.deriveSharedSecret)(e,this.keyPair.secretKey),i=(0,et.deriveMetaSid)(this.keyPair.publicKey,e);return this.metaSessions.set(e,{clientIdentityPub:e,sharedSecret:n,sidMeta:i}),this.logger.info("Meta key exchange completed",i,"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 n=this.metaSessions.values().next().value;return n?(0,et.encrypt)(e,n.sharedSecret,n.sidMeta):null}let t=[];for(let n of this.metaSessions.values()){let i=(0,et.encrypt)(e,n.sharedSecret,n.sidMeta);t.push({sid:i.sid,n:i.n,c:i.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")}};Ts.CryptoService=ra});var vu=M(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});Cs.AuthService=void 0;var Ti=hs(),na=class{storage;cryptoService;machineId;config;logger;notification;browser;pollingAbortController=null;tokenKey;refreshTokenKey;agentIdKey;constructor(e,t,n,i,s,a,c,u,d){this.storage=e,this.cryptoService=t,this.machineId=n,this.config=i,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,Ti.getApiUrl)(this.config),t=await this.machineId.getMachineId(),n=this.machineId.getMachineName(),i=await this.cryptoService.getPublicKey();i||(await this.cryptoService.generateIdentityKeyPair(),i=await this.cryptoService.getPublicKey()),this.logger.info("Starting device code flow",t,n);let s=await fetch(`${e}/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machineId:t,machineName:n,publicKey:i})});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,Ti.getApiUrl)(this.config),n=5e3,i=60;this.pollingAbortController=new AbortController;let s=this.pollingAbortController.signal;this.logger.info("Starting token polling");for(let a=0;a<i;a++){if(s.aborted)return this.logger.info("Polling was cancelled"),null;if(await this.sleep(n),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,Ti.getApiUrl)(this.config),n=await this.machineId.getMachineId(),i=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:n,machineName:i,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 n=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()).exp*1e3;return Date.now()<n}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,Ti.getApiUrl)(this.config);try{this.logger.info("Refreshing access token");let n=await fetch(`${t}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!n.ok)return this.logger.warn("Token refresh failed",String(n.status)),n.status===401&&await this.storage.delete(this.refreshTokenKey),null;let i=await n.json();return await this.storage.set(this.tokenKey,i.accessToken),await this.storage.set(this.refreshTokenKey,i.refreshToken),this.logger.info("Access token refreshed successfully"),i.accessToken}catch(n){return this.logger.warn("Token refresh error",n),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,Ti.getApiUrl)(this.config);try{let n=await fetch(`${t}/users/me/limits`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});return n.ok?await n.json():(this.logger.error("Failed to fetch limits",String(n.status)),null)}catch(n){let i=n instanceof Error?n.message:String(n);return this.logger.error(`Error fetching limits: ${i}`),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))}};Cs.AuthService=na});var xu=M(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.MAX_TAIL_PLAIN=Ze.MAX_TAIL_WITH_SELECTOR=Ze.MAX_LABEL_LEN=Ze.MAX_QUESTION_LEN=void 0;Ze.stripAnsi=sa;Ze.normalizeBuffer=wu;Ze.clampQuestion=ia;Ze.promptKey=Hg;Ze.extractQuestion=Vg;Ze.extractNumberedChoices=zg;Ze.MAX_QUESTION_LEN=160;Ze.MAX_LABEL_LEN=100;Ze.MAX_TAIL_WITH_SELECTOR=12;Ze.MAX_TAIL_PLAIN=2;function sa(r){return r.replace(/\x1b\[[0-9]*[GC]/g," ").replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\x1b\][^\x1b\x07]*(?:\x07|\x1b\\)/g,"").replace(/\x1b[()][AB012]/g,"").replace(/\x1b[=>]/g,"").replace(/\x1b[78DMEHc]/g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g,"")}function wu(r){return r.replace(/\r\n/g,`
2
+ "use strict";var Pp=Object.create;var Jo=Object.defineProperty;var Op=Object.getOwnPropertyDescriptor;var Rp=Object.getOwnPropertyNames;var Ap=Object.getPrototypeOf,Ip=Object.prototype.hasOwnProperty;var $t=(r,e)=>()=>(r&&(e=r(r=0)),e);var L=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Lp=(r,e)=>{for(var t in e)Jo(r,t,{get:e[t],enumerable:!0})},Np=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Rp(e))!Ip.call(r,n)&&n!==t&&Jo(r,n,{get:()=>e[n],enumerable:!(i=Op(e,n))||i.enumerable});return r};var he=(r,e,t)=>(t=r!=null?Pp(Ap(r)):{},Np(e||!r||!r.__esModule?Jo(t,"default",{value:r,enumerable:!0}):t,r));var fs=L(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.generateCorrelationId=Dp;En.runWithCorrelation=Bp;En.getCurrentCorrelationId=jp;var Fp=require("async_hooks");function Dp(){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 jf=new Fp.AsyncLocalStorage;function Bp(r,e){return jf.run(r,e)}function jp(){return jf.getStore()}});var Kf=L(Ni=>{"use strict";Object.defineProperty(Ni,"__esModule",{value:!0});Ni.LOG_LEVELS=void 0;Ni.shouldLog=Kp;Ni.formatLogLine=qp;var Up=fs();Ni.LOG_LEVELS=["silent","error","warn","info","debug"];var Uf={silent:0,error:1,warn:2,info:3,debug:4};function Kp(r,e){return Uf[r]<=Uf[e]}function qp(r,e,t,i){let n={ts:new Date().toISOString(),level:r,src:e,msg:t},s=(0,Up.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 qf=L(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.formatLogLine=Br.shouldLog=Br.LOG_LEVELS=void 0;var Zo=Kf();Object.defineProperty(Br,"LOG_LEVELS",{enumerable:!0,get:function(){return Zo.LOG_LEVELS}});Object.defineProperty(Br,"shouldLog",{enumerable:!0,get:function(){return Zo.shouldLog}});Object.defineProperty(Br,"formatLogLine",{enumerable:!0,get:function(){return Zo.formatLogLine}})});var Wf=L(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});us.CircularBuffer=void 0;var Qo=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}};us.CircularBuffer=Qo});var hs=L(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});ls.getApiUrl=Wp;ls.getWsUrl=Hp;function Wp(r){return`${r.getServerUrl()}/api`}function Hp(r){let e=r.getServerUrl();return e.startsWith("https://")?e.replace(/^https:\/\//,"wss://"):e.replace(/^http:\/\//,"ws://")}});var Vf=L(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.getCurrentCorrelationId=vt.runWithCorrelation=vt.generateCorrelationId=vt.getWsUrl=vt.getApiUrl=vt.CircularBuffer=void 0;var Vp=Wf();Object.defineProperty(vt,"CircularBuffer",{enumerable:!0,get:function(){return Vp.CircularBuffer}});var Hf=hs();Object.defineProperty(vt,"getApiUrl",{enumerable:!0,get:function(){return Hf.getApiUrl}});Object.defineProperty(vt,"getWsUrl",{enumerable:!0,get:function(){return Hf.getWsUrl}});var ea=fs();Object.defineProperty(vt,"generateCorrelationId",{enumerable:!0,get:function(){return ea.generateCorrelationId}});Object.defineProperty(vt,"runWithCorrelation",{enumerable:!0,get:function(){return ea.runWithCorrelation}});Object.defineProperty(vt,"getCurrentCorrelationId",{enumerable:!0,get:function(){return ea.getCurrentCorrelationId}})});var zf=L($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0})});var Yf=L(Gf=>{"use strict";Object.defineProperty(Gf,"__esModule",{value:!0})});var Xf=L(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});ds.PLAN_LIMITS=void 0;ds.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 Zf=L(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0})});var Qf=L(rr=>{"use strict";var $p=rr&&rr.__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]})),ps=rr&&rr.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&$p(e,r,t)};Object.defineProperty(rr,"__esModule",{value:!0});ps(zf(),rr);ps(Yf(),rr);ps(Xf(),rr);ps(Zf(),rr)});var eu=L(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.API_VERSION=Mt.WS_NAMESPACES=Mt.TIMEOUTS=Mt.STATUS_PATTERNS=Mt.TERMINAL_STATUSES=void 0;Mt.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"}};Mt.STATUS_PATTERNS={idle:[/[❯$]\s*$/,/>\s*$/],waiting:[/\[Y\/n\]/i,/\(y\/N\)/i,/Continue\?/i,/proceed\?/i],completed:[/✓/,/Done/,/Completed/,/Success/],error:[/Error/,/Failed/,/✕/,/Exception/]};Mt.TIMEOUTS={HEARTBEAT_INTERVAL:3e4,OFFLINE_THRESHOLD:6e4,DEVICE_CODE_EXPIRY:9e5,DEVICE_CODE_POLL_INTERVAL:5e3};Mt.WS_NAMESPACES={AGENT:"/agent",CLIENT:"/client"};Mt.API_VERSION="v1"});var tu=L(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});gs.isMultiRecipientPayload=zp;gs.isEncryptedPayload=Gp;function zp(r){return typeof r=="object"&&r!==null&&"v"in r&&r.v===2&&"recipients"in r&&Array.isArray(r.recipients)}function Gp(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 ta=L(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.KX_SIG_VERSION=ir.KX_FINGERPRINT_LABEL=ir.KX_ACK_LABEL=ir.KX_SIGN_LABEL=void 0;ir.KX_SIGN_LABEL="termiq-kx-v1";ir.KX_ACK_LABEL="termiq-kxack-v1";ir.KX_FINGERPRINT_LABEL="termiq-fp-v1";ir.KX_SIG_VERSION=1});var wn=L((Cw,ms)=>{(function(r){"use strict";var e=function(f){var d,l=new Float64Array(16);if(f)for(d=0;d<f.length;d++)l[d]=f[d];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]),h=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,d,l,o){f[d]=l>>24&255,f[d+1]=l>>16&255,f[d+2]=l>>8&255,f[d+3]=l&255,f[d+4]=o>>24&255,f[d+5]=o>>16&255,f[d+6]=o>>8&255,f[d+7]=o&255}function S(f,d,l,o,g){var b,w=0;for(b=0;b<g;b++)w|=f[d+b]^l[o+b];return(1&w-1>>>8)-1}function C(f,d,l,o){return S(f,d,l,o,16)}function H(f,d,l,o){return S(f,d,l,o,32)}function ne(f,d,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,w=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,P=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=d[0]&255|(d[1]&255)<<8|(d[2]&255)<<16|(d[3]&255)<<24,Oe=d[4]&255|(d[5]&255)<<8|(d[6]&255)<<16|(d[7]&255)<<24,$=d[8]&255|(d[9]&255)<<8|(d[10]&255)<<16|(d[11]&255)<<24,oe=d[12]&255|(d[13]&255)<<8|(d[14]&255)<<16|(d[15]&255)<<24,ae=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,de=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,ce=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,fe=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,G=g,Q=b,V=w,Y=P,J=D,q=Z,v=W,x=Oe,R=$,k=oe,O=ae,M=ge,ie=de,me=ce,_e=le,ye=fe,y,we=0;we<20;we+=2)y=G+ie|0,J^=y<<7|y>>>25,y=J+G|0,R^=y<<9|y>>>23,y=R+J|0,ie^=y<<13|y>>>19,y=ie+R|0,G^=y<<18|y>>>14,y=q+Q|0,k^=y<<7|y>>>25,y=k+q|0,me^=y<<9|y>>>23,y=me+k|0,Q^=y<<13|y>>>19,y=Q+me|0,q^=y<<18|y>>>14,y=O+v|0,_e^=y<<7|y>>>25,y=_e+O|0,V^=y<<9|y>>>23,y=V+_e|0,v^=y<<13|y>>>19,y=v+V|0,O^=y<<18|y>>>14,y=ye+M|0,Y^=y<<7|y>>>25,y=Y+ye|0,x^=y<<9|y>>>23,y=x+Y|0,M^=y<<13|y>>>19,y=M+x|0,ye^=y<<18|y>>>14,y=G+Y|0,Q^=y<<7|y>>>25,y=Q+G|0,V^=y<<9|y>>>23,y=V+Q|0,Y^=y<<13|y>>>19,y=Y+V|0,G^=y<<18|y>>>14,y=q+J|0,v^=y<<7|y>>>25,y=v+q|0,x^=y<<9|y>>>23,y=x+v|0,J^=y<<13|y>>>19,y=J+x|0,q^=y<<18|y>>>14,y=O+k|0,M^=y<<7|y>>>25,y=M+O|0,R^=y<<9|y>>>23,y=R+M|0,k^=y<<13|y>>>19,y=k+R|0,O^=y<<18|y>>>14,y=ye+_e|0,ie^=y<<7|y>>>25,y=ie+ye|0,me^=y<<9|y>>>23,y=me+ie|0,_e^=y<<13|y>>>19,y=_e+me|0,ye^=y<<18|y>>>14;G=G+g|0,Q=Q+b|0,V=V+w|0,Y=Y+P|0,J=J+D|0,q=q+Z|0,v=v+W|0,x=x+Oe|0,R=R+$|0,k=k+oe|0,O=O+ae|0,M=M+ge|0,ie=ie+de|0,me=me+ce|0,_e=_e+le|0,ye=ye+fe|0,f[0]=G>>>0&255,f[1]=G>>>8&255,f[2]=G>>>16&255,f[3]=G>>>24&255,f[4]=Q>>>0&255,f[5]=Q>>>8&255,f[6]=Q>>>16&255,f[7]=Q>>>24&255,f[8]=V>>>0&255,f[9]=V>>>8&255,f[10]=V>>>16&255,f[11]=V>>>24&255,f[12]=Y>>>0&255,f[13]=Y>>>8&255,f[14]=Y>>>16&255,f[15]=Y>>>24&255,f[16]=J>>>0&255,f[17]=J>>>8&255,f[18]=J>>>16&255,f[19]=J>>>24&255,f[20]=q>>>0&255,f[21]=q>>>8&255,f[22]=q>>>16&255,f[23]=q>>>24&255,f[24]=v>>>0&255,f[25]=v>>>8&255,f[26]=v>>>16&255,f[27]=v>>>24&255,f[28]=x>>>0&255,f[29]=x>>>8&255,f[30]=x>>>16&255,f[31]=x>>>24&255,f[32]=R>>>0&255,f[33]=R>>>8&255,f[34]=R>>>16&255,f[35]=R>>>24&255,f[36]=k>>>0&255,f[37]=k>>>8&255,f[38]=k>>>16&255,f[39]=k>>>24&255,f[40]=O>>>0&255,f[41]=O>>>8&255,f[42]=O>>>16&255,f[43]=O>>>24&255,f[44]=M>>>0&255,f[45]=M>>>8&255,f[46]=M>>>16&255,f[47]=M>>>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]=_e>>>0&255,f[57]=_e>>>8&255,f[58]=_e>>>16&255,f[59]=_e>>>24&255,f[60]=ye>>>0&255,f[61]=ye>>>8&255,f[62]=ye>>>16&255,f[63]=ye>>>24&255}function z(f,d,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,w=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,P=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=d[0]&255|(d[1]&255)<<8|(d[2]&255)<<16|(d[3]&255)<<24,Oe=d[4]&255|(d[5]&255)<<8|(d[6]&255)<<16|(d[7]&255)<<24,$=d[8]&255|(d[9]&255)<<8|(d[10]&255)<<16|(d[11]&255)<<24,oe=d[12]&255|(d[13]&255)<<8|(d[14]&255)<<16|(d[15]&255)<<24,ae=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,de=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,ce=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,fe=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,G=g,Q=b,V=w,Y=P,J=D,q=Z,v=W,x=Oe,R=$,k=oe,O=ae,M=ge,ie=de,me=ce,_e=le,ye=fe,y,we=0;we<20;we+=2)y=G+ie|0,J^=y<<7|y>>>25,y=J+G|0,R^=y<<9|y>>>23,y=R+J|0,ie^=y<<13|y>>>19,y=ie+R|0,G^=y<<18|y>>>14,y=q+Q|0,k^=y<<7|y>>>25,y=k+q|0,me^=y<<9|y>>>23,y=me+k|0,Q^=y<<13|y>>>19,y=Q+me|0,q^=y<<18|y>>>14,y=O+v|0,_e^=y<<7|y>>>25,y=_e+O|0,V^=y<<9|y>>>23,y=V+_e|0,v^=y<<13|y>>>19,y=v+V|0,O^=y<<18|y>>>14,y=ye+M|0,Y^=y<<7|y>>>25,y=Y+ye|0,x^=y<<9|y>>>23,y=x+Y|0,M^=y<<13|y>>>19,y=M+x|0,ye^=y<<18|y>>>14,y=G+Y|0,Q^=y<<7|y>>>25,y=Q+G|0,V^=y<<9|y>>>23,y=V+Q|0,Y^=y<<13|y>>>19,y=Y+V|0,G^=y<<18|y>>>14,y=q+J|0,v^=y<<7|y>>>25,y=v+q|0,x^=y<<9|y>>>23,y=x+v|0,J^=y<<13|y>>>19,y=J+x|0,q^=y<<18|y>>>14,y=O+k|0,M^=y<<7|y>>>25,y=M+O|0,R^=y<<9|y>>>23,y=R+M|0,k^=y<<13|y>>>19,y=k+R|0,O^=y<<18|y>>>14,y=ye+_e|0,ie^=y<<7|y>>>25,y=ie+ye|0,me^=y<<9|y>>>23,y=me+ie|0,_e^=y<<13|y>>>19,y=_e+me|0,ye^=y<<18|y>>>14;f[0]=G>>>0&255,f[1]=G>>>8&255,f[2]=G>>>16&255,f[3]=G>>>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]=ye>>>0&255,f[13]=ye>>>8&255,f[14]=ye>>>16&255,f[15]=ye>>>24&255,f[16]=v>>>0&255,f[17]=v>>>8&255,f[18]=v>>>16&255,f[19]=v>>>24&255,f[20]=x>>>0&255,f[21]=x>>>8&255,f[22]=x>>>16&255,f[23]=x>>>24&255,f[24]=R>>>0&255,f[25]=R>>>8&255,f[26]=R>>>16&255,f[27]=R>>>24&255,f[28]=k>>>0&255,f[29]=k>>>8&255,f[30]=k>>>16&255,f[31]=k>>>24&255}function T(f,d,l,o){ne(f,d,l,o)}function F(f,d,l,o){z(f,d,l,o)}var te=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function U(f,d,l,o,g,b,w){var P=new Uint8Array(16),D=new Uint8Array(64),Z,W;for(W=0;W<16;W++)P[W]=0;for(W=0;W<8;W++)P[W]=b[W];for(;g>=64;){for(T(D,P,w,te),W=0;W<64;W++)f[d+W]=l[o+W]^D[W];for(Z=1,W=8;W<16;W++)Z=Z+(P[W]&255)|0,P[W]=Z&255,Z>>>=8;g-=64,d+=64,o+=64}if(g>0)for(T(D,P,w,te),W=0;W<g;W++)f[d+W]=l[o+W]^D[W];return 0}function ee(f,d,l,o,g){var b=new Uint8Array(16),w=new Uint8Array(64),P,D;for(D=0;D<16;D++)b[D]=0;for(D=0;D<8;D++)b[D]=o[D];for(;l>=64;){for(T(w,b,g,te),D=0;D<64;D++)f[d+D]=w[D];for(P=1,D=8;D<16;D++)P=P+(b[D]&255)|0,b[D]=P&255,P>>>=8;l-=64,d+=64}if(l>0)for(T(w,b,g,te),D=0;D<l;D++)f[d+D]=w[D];return 0}function pe(f,d,l,o,g){var b=new Uint8Array(32);F(b,o,g,te);for(var w=new Uint8Array(8),P=0;P<8;P++)w[P]=o[P+16];return ee(f,d,l,w,b)}function K(f,d,l,o,g,b,w){var P=new Uint8Array(32);F(P,b,w,te);for(var D=new Uint8Array(8),Z=0;Z<8;Z++)D[Z]=b[Z+16];return U(f,d,l,o,g,D,P)}var Ne=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 d,l,o,g,b,w,P,D;d=f[0]&255|(f[1]&255)<<8,this.r[0]=d&8191,l=f[2]&255|(f[3]&255)<<8,this.r[1]=(d>>>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,w=f[10]&255|(f[11]&255)<<8,this.r[6]=(b>>>14|w<<2)&8191,P=f[12]&255|(f[13]&255)<<8,this.r[7]=(w>>>11|P<<5)&8065,D=f[14]&255|(f[15]&255)<<8,this.r[8]=(P>>>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};Ne.prototype.blocks=function(f,d,l){for(var o=this.fin?0:2048,g,b,w,P,D,Z,W,Oe,$,oe,ae,ge,de,ce,le,fe,G,Q,V,Y=this.h[0],J=this.h[1],q=this.h[2],v=this.h[3],x=this.h[4],R=this.h[5],k=this.h[6],O=this.h[7],M=this.h[8],ie=this.h[9],me=this.r[0],_e=this.r[1],ye=this.r[2],y=this.r[3],we=this.r[4],Re=this.r[5],Ae=this.r[6],be=this.r[7],Te=this.r[8],Ce=this.r[9];l>=16;)g=f[d+0]&255|(f[d+1]&255)<<8,Y+=g&8191,b=f[d+2]&255|(f[d+3]&255)<<8,J+=(g>>>13|b<<3)&8191,w=f[d+4]&255|(f[d+5]&255)<<8,q+=(b>>>10|w<<6)&8191,P=f[d+6]&255|(f[d+7]&255)<<8,v+=(w>>>7|P<<9)&8191,D=f[d+8]&255|(f[d+9]&255)<<8,x+=(P>>>4|D<<12)&8191,R+=D>>>1&8191,Z=f[d+10]&255|(f[d+11]&255)<<8,k+=(D>>>14|Z<<2)&8191,W=f[d+12]&255|(f[d+13]&255)<<8,O+=(Z>>>11|W<<5)&8191,Oe=f[d+14]&255|(f[d+15]&255)<<8,M+=(W>>>8|Oe<<8)&8191,ie+=Oe>>>5|o,$=0,oe=$,oe+=Y*me,oe+=J*(5*Ce),oe+=q*(5*Te),oe+=v*(5*be),oe+=x*(5*Ae),$=oe>>>13,oe&=8191,oe+=R*(5*Re),oe+=k*(5*we),oe+=O*(5*y),oe+=M*(5*ye),oe+=ie*(5*_e),$+=oe>>>13,oe&=8191,ae=$,ae+=Y*_e,ae+=J*me,ae+=q*(5*Ce),ae+=v*(5*Te),ae+=x*(5*be),$=ae>>>13,ae&=8191,ae+=R*(5*Ae),ae+=k*(5*Re),ae+=O*(5*we),ae+=M*(5*y),ae+=ie*(5*ye),$+=ae>>>13,ae&=8191,ge=$,ge+=Y*ye,ge+=J*_e,ge+=q*me,ge+=v*(5*Ce),ge+=x*(5*Te),$=ge>>>13,ge&=8191,ge+=R*(5*be),ge+=k*(5*Ae),ge+=O*(5*Re),ge+=M*(5*we),ge+=ie*(5*y),$+=ge>>>13,ge&=8191,de=$,de+=Y*y,de+=J*ye,de+=q*_e,de+=v*me,de+=x*(5*Ce),$=de>>>13,de&=8191,de+=R*(5*Te),de+=k*(5*be),de+=O*(5*Ae),de+=M*(5*Re),de+=ie*(5*we),$+=de>>>13,de&=8191,ce=$,ce+=Y*we,ce+=J*y,ce+=q*ye,ce+=v*_e,ce+=x*me,$=ce>>>13,ce&=8191,ce+=R*(5*Ce),ce+=k*(5*Te),ce+=O*(5*be),ce+=M*(5*Ae),ce+=ie*(5*Re),$+=ce>>>13,ce&=8191,le=$,le+=Y*Re,le+=J*we,le+=q*y,le+=v*ye,le+=x*_e,$=le>>>13,le&=8191,le+=R*me,le+=k*(5*Ce),le+=O*(5*Te),le+=M*(5*be),le+=ie*(5*Ae),$+=le>>>13,le&=8191,fe=$,fe+=Y*Ae,fe+=J*Re,fe+=q*we,fe+=v*y,fe+=x*ye,$=fe>>>13,fe&=8191,fe+=R*_e,fe+=k*me,fe+=O*(5*Ce),fe+=M*(5*Te),fe+=ie*(5*be),$+=fe>>>13,fe&=8191,G=$,G+=Y*be,G+=J*Ae,G+=q*Re,G+=v*we,G+=x*y,$=G>>>13,G&=8191,G+=R*ye,G+=k*_e,G+=O*me,G+=M*(5*Ce),G+=ie*(5*Te),$+=G>>>13,G&=8191,Q=$,Q+=Y*Te,Q+=J*be,Q+=q*Ae,Q+=v*Re,Q+=x*we,$=Q>>>13,Q&=8191,Q+=R*y,Q+=k*ye,Q+=O*_e,Q+=M*me,Q+=ie*(5*Ce),$+=Q>>>13,Q&=8191,V=$,V+=Y*Ce,V+=J*Te,V+=q*be,V+=v*Ae,V+=x*Re,$=V>>>13,V&=8191,V+=R*we,V+=k*y,V+=O*ye,V+=M*_e,V+=ie*me,$+=V>>>13,V&=8191,$=($<<2)+$|0,$=$+oe|0,oe=$&8191,$=$>>>13,ae+=$,Y=oe,J=ae,q=ge,v=de,x=ce,R=le,k=fe,O=G,M=Q,ie=V,d+=16,l-=16;this.h[0]=Y,this.h[1]=J,this.h[2]=q,this.h[3]=v,this.h[4]=x,this.h[5]=R,this.h[6]=k,this.h[7]=O,this.h[8]=M,this.h[9]=ie},Ne.prototype.finish=function(f,d){var l=new Uint16Array(10),o,g,b,w;if(this.leftover){for(w=this.leftover,this.buffer[w++]=1;w<16;w++)this.buffer[w]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(o=this.h[1]>>>13,this.h[1]&=8191,w=2;w<10;w++)this.h[w]+=o,o=this.h[w]>>>13,this.h[w]&=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,w=1;w<10;w++)l[w]=this.h[w]+o,o=l[w]>>>13,l[w]&=8191;for(l[9]-=8192,g=(o^1)-1,w=0;w<10;w++)l[w]&=g;for(g=~g,w=0;w<10;w++)this.h[w]=this.h[w]&g|l[w];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,w=1;w<8;w++)b=(this.h[w]+this.pad[w]|0)+(b>>>16)|0,this.h[w]=b&65535;f[d+0]=this.h[0]>>>0&255,f[d+1]=this.h[0]>>>8&255,f[d+2]=this.h[1]>>>0&255,f[d+3]=this.h[1]>>>8&255,f[d+4]=this.h[2]>>>0&255,f[d+5]=this.h[2]>>>8&255,f[d+6]=this.h[3]>>>0&255,f[d+7]=this.h[3]>>>8&255,f[d+8]=this.h[4]>>>0&255,f[d+9]=this.h[4]>>>8&255,f[d+10]=this.h[5]>>>0&255,f[d+11]=this.h[5]>>>8&255,f[d+12]=this.h[6]>>>0&255,f[d+13]=this.h[6]>>>8&255,f[d+14]=this.h[7]>>>0&255,f[d+15]=this.h[7]>>>8&255},Ne.prototype.update=function(f,d,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[d+o];if(l-=g,d+=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,d,g),d+=g,l-=g),l){for(o=0;o<l;o++)this.buffer[this.leftover+o]=f[d+o];this.leftover+=l}};function tt(f,d,l,o,g,b){var w=new Ne(b);return w.update(l,o,g),w.finish(f,d),0}function Se(f,d,l,o,g,b){var w=new Uint8Array(16);return tt(w,0,l,o,g,b),C(f,d,w,0)}function Me(f,d,l,o,g){var b;if(l<32)return-1;for(K(f,0,d,0,l,o,g),tt(f,16,f,32,l-32,f),b=0;b<16;b++)f[b]=0;return 0}function ve(f,d,l,o,g){var b,w=new Uint8Array(32);if(l<32||(pe(w,0,32,o,g),Se(d,16,d,32,l-32,w)!==0))return-1;for(K(f,0,d,0,l,o,g),b=0;b<32;b++)f[b]=0;return 0}function Ke(f,d){var l;for(l=0;l<16;l++)f[l]=d[l]|0}function Ee(f){var d,l,o=1;for(d=0;d<16;d++)l=f[d]+o+65535,o=Math.floor(l/65536),f[d]=l-o*65536;f[0]+=o-1+37*(o-1)}function rt(f,d,l){for(var o,g=~(l-1),b=0;b<16;b++)o=g&(f[b]^d[b]),f[b]^=o,d[b]^=o}function Fe(f,d){var l,o,g,b=e(),w=e();for(l=0;l<16;l++)w[l]=d[l];for(Ee(w),Ee(w),Ee(w),o=0;o<2;o++){for(b[0]=w[0]-65517,l=1;l<15;l++)b[l]=w[l]-65535-(b[l-1]>>16&1),b[l-1]&=65535;b[15]=w[15]-32767-(b[14]>>16&1),g=b[15]>>16&1,b[14]&=65535,rt(w,b,1-g)}for(l=0;l<16;l++)f[2*l]=w[l]&255,f[2*l+1]=w[l]>>8}function yt(f,d){var l=new Uint8Array(32),o=new Uint8Array(32);return Fe(l,f),Fe(o,d),H(l,0,o,0)}function qe(f){var d=new Uint8Array(32);return Fe(d,f),d[0]&1}function dt(f,d){var l;for(l=0;l<16;l++)f[l]=d[2*l]+(d[2*l+1]<<8);f[15]&=32767}function I(f,d,l){for(var o=0;o<16;o++)f[o]=d[o]+l[o]}function B(f,d,l){for(var o=0;o<16;o++)f[o]=d[o]-l[o]}function A(f,d,l){var o,g,b=0,w=0,P=0,D=0,Z=0,W=0,Oe=0,$=0,oe=0,ae=0,ge=0,de=0,ce=0,le=0,fe=0,G=0,Q=0,V=0,Y=0,J=0,q=0,v=0,x=0,R=0,k=0,O=0,M=0,ie=0,me=0,_e=0,ye=0,y=l[0],we=l[1],Re=l[2],Ae=l[3],be=l[4],Te=l[5],Ce=l[6],nt=l[7],De=l[8],Je=l[9],Ze=l[10],Qe=l[11],at=l[12],pt=l[13],gt=l[14],mt=l[15];o=d[0],b+=o*y,w+=o*we,P+=o*Re,D+=o*Ae,Z+=o*be,W+=o*Te,Oe+=o*Ce,$+=o*nt,oe+=o*De,ae+=o*Je,ge+=o*Ze,de+=o*Qe,ce+=o*at,le+=o*pt,fe+=o*gt,G+=o*mt,o=d[1],w+=o*y,P+=o*we,D+=o*Re,Z+=o*Ae,W+=o*be,Oe+=o*Te,$+=o*Ce,oe+=o*nt,ae+=o*De,ge+=o*Je,de+=o*Ze,ce+=o*Qe,le+=o*at,fe+=o*pt,G+=o*gt,Q+=o*mt,o=d[2],P+=o*y,D+=o*we,Z+=o*Re,W+=o*Ae,Oe+=o*be,$+=o*Te,oe+=o*Ce,ae+=o*nt,ge+=o*De,de+=o*Je,ce+=o*Ze,le+=o*Qe,fe+=o*at,G+=o*pt,Q+=o*gt,V+=o*mt,o=d[3],D+=o*y,Z+=o*we,W+=o*Re,Oe+=o*Ae,$+=o*be,oe+=o*Te,ae+=o*Ce,ge+=o*nt,de+=o*De,ce+=o*Je,le+=o*Ze,fe+=o*Qe,G+=o*at,Q+=o*pt,V+=o*gt,Y+=o*mt,o=d[4],Z+=o*y,W+=o*we,Oe+=o*Re,$+=o*Ae,oe+=o*be,ae+=o*Te,ge+=o*Ce,de+=o*nt,ce+=o*De,le+=o*Je,fe+=o*Ze,G+=o*Qe,Q+=o*at,V+=o*pt,Y+=o*gt,J+=o*mt,o=d[5],W+=o*y,Oe+=o*we,$+=o*Re,oe+=o*Ae,ae+=o*be,ge+=o*Te,de+=o*Ce,ce+=o*nt,le+=o*De,fe+=o*Je,G+=o*Ze,Q+=o*Qe,V+=o*at,Y+=o*pt,J+=o*gt,q+=o*mt,o=d[6],Oe+=o*y,$+=o*we,oe+=o*Re,ae+=o*Ae,ge+=o*be,de+=o*Te,ce+=o*Ce,le+=o*nt,fe+=o*De,G+=o*Je,Q+=o*Ze,V+=o*Qe,Y+=o*at,J+=o*pt,q+=o*gt,v+=o*mt,o=d[7],$+=o*y,oe+=o*we,ae+=o*Re,ge+=o*Ae,de+=o*be,ce+=o*Te,le+=o*Ce,fe+=o*nt,G+=o*De,Q+=o*Je,V+=o*Ze,Y+=o*Qe,J+=o*at,q+=o*pt,v+=o*gt,x+=o*mt,o=d[8],oe+=o*y,ae+=o*we,ge+=o*Re,de+=o*Ae,ce+=o*be,le+=o*Te,fe+=o*Ce,G+=o*nt,Q+=o*De,V+=o*Je,Y+=o*Ze,J+=o*Qe,q+=o*at,v+=o*pt,x+=o*gt,R+=o*mt,o=d[9],ae+=o*y,ge+=o*we,de+=o*Re,ce+=o*Ae,le+=o*be,fe+=o*Te,G+=o*Ce,Q+=o*nt,V+=o*De,Y+=o*Je,J+=o*Ze,q+=o*Qe,v+=o*at,x+=o*pt,R+=o*gt,k+=o*mt,o=d[10],ge+=o*y,de+=o*we,ce+=o*Re,le+=o*Ae,fe+=o*be,G+=o*Te,Q+=o*Ce,V+=o*nt,Y+=o*De,J+=o*Je,q+=o*Ze,v+=o*Qe,x+=o*at,R+=o*pt,k+=o*gt,O+=o*mt,o=d[11],de+=o*y,ce+=o*we,le+=o*Re,fe+=o*Ae,G+=o*be,Q+=o*Te,V+=o*Ce,Y+=o*nt,J+=o*De,q+=o*Je,v+=o*Ze,x+=o*Qe,R+=o*at,k+=o*pt,O+=o*gt,M+=o*mt,o=d[12],ce+=o*y,le+=o*we,fe+=o*Re,G+=o*Ae,Q+=o*be,V+=o*Te,Y+=o*Ce,J+=o*nt,q+=o*De,v+=o*Je,x+=o*Ze,R+=o*Qe,k+=o*at,O+=o*pt,M+=o*gt,ie+=o*mt,o=d[13],le+=o*y,fe+=o*we,G+=o*Re,Q+=o*Ae,V+=o*be,Y+=o*Te,J+=o*Ce,q+=o*nt,v+=o*De,x+=o*Je,R+=o*Ze,k+=o*Qe,O+=o*at,M+=o*pt,ie+=o*gt,me+=o*mt,o=d[14],fe+=o*y,G+=o*we,Q+=o*Re,V+=o*Ae,Y+=o*be,J+=o*Te,q+=o*Ce,v+=o*nt,x+=o*De,R+=o*Je,k+=o*Ze,O+=o*Qe,M+=o*at,ie+=o*pt,me+=o*gt,_e+=o*mt,o=d[15],G+=o*y,Q+=o*we,V+=o*Re,Y+=o*Ae,J+=o*be,q+=o*Te,v+=o*Ce,x+=o*nt,R+=o*De,k+=o*Je,O+=o*Ze,M+=o*Qe,ie+=o*at,me+=o*pt,_e+=o*gt,ye+=o*mt,b+=38*Q,w+=38*V,P+=38*Y,D+=38*J,Z+=38*q,W+=38*v,Oe+=38*x,$+=38*R,oe+=38*k,ae+=38*O,ge+=38*M,de+=38*ie,ce+=38*me,le+=38*_e,fe+=38*ye,g=1,o=b+g+65535,g=Math.floor(o/65536),b=o-g*65536,o=w+g+65535,g=Math.floor(o/65536),w=o-g*65536,o=P+g+65535,g=Math.floor(o/65536),P=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=Oe+g+65535,g=Math.floor(o/65536),Oe=o-g*65536,o=$+g+65535,g=Math.floor(o/65536),$=o-g*65536,o=oe+g+65535,g=Math.floor(o/65536),oe=o-g*65536,o=ae+g+65535,g=Math.floor(o/65536),ae=o-g*65536,o=ge+g+65535,g=Math.floor(o/65536),ge=o-g*65536,o=de+g+65535,g=Math.floor(o/65536),de=o-g*65536,o=ce+g+65535,g=Math.floor(o/65536),ce=o-g*65536,o=le+g+65535,g=Math.floor(o/65536),le=o-g*65536,o=fe+g+65535,g=Math.floor(o/65536),fe=o-g*65536,o=G+g+65535,g=Math.floor(o/65536),G=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=w+g+65535,g=Math.floor(o/65536),w=o-g*65536,o=P+g+65535,g=Math.floor(o/65536),P=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=Oe+g+65535,g=Math.floor(o/65536),Oe=o-g*65536,o=$+g+65535,g=Math.floor(o/65536),$=o-g*65536,o=oe+g+65535,g=Math.floor(o/65536),oe=o-g*65536,o=ae+g+65535,g=Math.floor(o/65536),ae=o-g*65536,o=ge+g+65535,g=Math.floor(o/65536),ge=o-g*65536,o=de+g+65535,g=Math.floor(o/65536),de=o-g*65536,o=ce+g+65535,g=Math.floor(o/65536),ce=o-g*65536,o=le+g+65535,g=Math.floor(o/65536),le=o-g*65536,o=fe+g+65535,g=Math.floor(o/65536),fe=o-g*65536,o=G+g+65535,g=Math.floor(o/65536),G=o-g*65536,b+=g-1+37*(g-1),f[0]=b,f[1]=w,f[2]=P,f[3]=D,f[4]=Z,f[5]=W,f[6]=Oe,f[7]=$,f[8]=oe,f[9]=ae,f[10]=ge,f[11]=de,f[12]=ce,f[13]=le,f[14]=fe,f[15]=G}function se(f,d){A(f,d,d)}function Pe(f,d){var l=e(),o;for(o=0;o<16;o++)l[o]=d[o];for(o=253;o>=0;o--)se(l,l),o!==2&&o!==4&&A(l,l,d);for(o=0;o<16;o++)f[o]=l[o]}function j(f,d){var l=e(),o;for(o=0;o<16;o++)l[o]=d[o];for(o=250;o>=0;o--)se(l,l),o!==1&&A(l,l,d);for(o=0;o<16;o++)f[o]=l[o]}function ue(f,d,l){var o=new Uint8Array(32),g=new Float64Array(80),b,w,P=e(),D=e(),Z=e(),W=e(),Oe=e(),$=e();for(w=0;w<31;w++)o[w]=d[w];for(o[31]=d[31]&127|64,o[0]&=248,dt(g,l),w=0;w<16;w++)D[w]=g[w],W[w]=P[w]=Z[w]=0;for(P[0]=W[0]=1,w=254;w>=0;--w)b=o[w>>>3]>>>(w&7)&1,rt(P,D,b),rt(Z,W,b),I(Oe,P,Z),B(P,P,Z),I(Z,D,W),B(D,D,W),se(W,Oe),se($,P),A(P,Z,P),A(Z,D,Oe),I(Oe,P,Z),B(P,P,Z),se(D,P),B(Z,W,$),A(P,Z,c),I(P,P,W),A(Z,Z,P),A(P,W,$),A(W,D,g),se(D,Oe),rt(P,D,b),rt(Z,W,b);for(w=0;w<16;w++)g[w+16]=P[w],g[w+32]=Z[w],g[w+48]=D[w],g[w+64]=W[w];var oe=g.subarray(32),ae=g.subarray(16);return Pe(oe,oe),A(ae,ae,oe),Fe(f,ae),0}function je(f,d){return ue(f,d,n)}function it(f,d){return t(d,32),je(f,d)}function _t(f,d,l){var o=new Uint8Array(32);return ue(o,l,d),F(f,i,o,te)}var Vt=Me,si=ve;function Dr(f,d,l,o,g,b){var w=new Uint8Array(32);return _t(w,g,b),Vt(f,d,l,o,w)}function Ai(f,d,l,o,g,b){var w=new Uint8Array(32);return _t(w,g,b),si(f,d,l,o,w)}var Qn=[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 Af(f,d,l,o){for(var g=new Int32Array(16),b=new Int32Array(16),w,P,D,Z,W,Oe,$,oe,ae,ge,de,ce,le,fe,G,Q,V,Y,J,q,v,x,R,k,O,M,ie=f[0],me=f[1],_e=f[2],ye=f[3],y=f[4],we=f[5],Re=f[6],Ae=f[7],be=d[0],Te=d[1],Ce=d[2],nt=d[3],De=d[4],Je=d[5],Ze=d[6],Qe=d[7],at=0;o>=128;){for(J=0;J<16;J++)q=8*J+at,g[J]=l[q+0]<<24|l[q+1]<<16|l[q+2]<<8|l[q+3],b[J]=l[q+4]<<24|l[q+5]<<16|l[q+6]<<8|l[q+7];for(J=0;J<80;J++)if(w=ie,P=me,D=_e,Z=ye,W=y,Oe=we,$=Re,oe=Ae,ae=be,ge=Te,de=Ce,ce=nt,le=De,fe=Je,G=Ze,Q=Qe,v=Ae,x=Qe,R=x&65535,k=x>>>16,O=v&65535,M=v>>>16,v=(y>>>14|De<<18)^(y>>>18|De<<14)^(De>>>9|y<<23),x=(De>>>14|y<<18)^(De>>>18|y<<14)^(y>>>9|De<<23),R+=x&65535,k+=x>>>16,O+=v&65535,M+=v>>>16,v=y&we^~y&Re,x=De&Je^~De&Ze,R+=x&65535,k+=x>>>16,O+=v&65535,M+=v>>>16,v=Qn[J*2],x=Qn[J*2+1],R+=x&65535,k+=x>>>16,O+=v&65535,M+=v>>>16,v=g[J%16],x=b[J%16],R+=x&65535,k+=x>>>16,O+=v&65535,M+=v>>>16,k+=R>>>16,O+=k>>>16,M+=O>>>16,V=O&65535|M<<16,Y=R&65535|k<<16,v=V,x=Y,R=x&65535,k=x>>>16,O=v&65535,M=v>>>16,v=(ie>>>28|be<<4)^(be>>>2|ie<<30)^(be>>>7|ie<<25),x=(be>>>28|ie<<4)^(ie>>>2|be<<30)^(ie>>>7|be<<25),R+=x&65535,k+=x>>>16,O+=v&65535,M+=v>>>16,v=ie&me^ie&_e^me&_e,x=be&Te^be&Ce^Te&Ce,R+=x&65535,k+=x>>>16,O+=v&65535,M+=v>>>16,k+=R>>>16,O+=k>>>16,M+=O>>>16,oe=O&65535|M<<16,Q=R&65535|k<<16,v=Z,x=ce,R=x&65535,k=x>>>16,O=v&65535,M=v>>>16,v=V,x=Y,R+=x&65535,k+=x>>>16,O+=v&65535,M+=v>>>16,k+=R>>>16,O+=k>>>16,M+=O>>>16,Z=O&65535|M<<16,ce=R&65535|k<<16,me=w,_e=P,ye=D,y=Z,we=W,Re=Oe,Ae=$,ie=oe,Te=ae,Ce=ge,nt=de,De=ce,Je=le,Ze=fe,Qe=G,be=Q,J%16===15)for(q=0;q<16;q++)v=g[q],x=b[q],R=x&65535,k=x>>>16,O=v&65535,M=v>>>16,v=g[(q+9)%16],x=b[(q+9)%16],R+=x&65535,k+=x>>>16,O+=v&65535,M+=v>>>16,V=g[(q+1)%16],Y=b[(q+1)%16],v=(V>>>1|Y<<31)^(V>>>8|Y<<24)^V>>>7,x=(Y>>>1|V<<31)^(Y>>>8|V<<24)^(Y>>>7|V<<25),R+=x&65535,k+=x>>>16,O+=v&65535,M+=v>>>16,V=g[(q+14)%16],Y=b[(q+14)%16],v=(V>>>19|Y<<13)^(Y>>>29|V<<3)^V>>>6,x=(Y>>>19|V<<13)^(V>>>29|Y<<3)^(Y>>>6|V<<26),R+=x&65535,k+=x>>>16,O+=v&65535,M+=v>>>16,k+=R>>>16,O+=k>>>16,M+=O>>>16,g[q]=O&65535|M<<16,b[q]=R&65535|k<<16;v=ie,x=be,R=x&65535,k=x>>>16,O=v&65535,M=v>>>16,v=f[0],x=d[0],R+=x&65535,k+=x>>>16,O+=v&65535,M+=v>>>16,k+=R>>>16,O+=k>>>16,M+=O>>>16,f[0]=ie=O&65535|M<<16,d[0]=be=R&65535|k<<16,v=me,x=Te,R=x&65535,k=x>>>16,O=v&65535,M=v>>>16,v=f[1],x=d[1],R+=x&65535,k+=x>>>16,O+=v&65535,M+=v>>>16,k+=R>>>16,O+=k>>>16,M+=O>>>16,f[1]=me=O&65535|M<<16,d[1]=Te=R&65535|k<<16,v=_e,x=Ce,R=x&65535,k=x>>>16,O=v&65535,M=v>>>16,v=f[2],x=d[2],R+=x&65535,k+=x>>>16,O+=v&65535,M+=v>>>16,k+=R>>>16,O+=k>>>16,M+=O>>>16,f[2]=_e=O&65535|M<<16,d[2]=Ce=R&65535|k<<16,v=ye,x=nt,R=x&65535,k=x>>>16,O=v&65535,M=v>>>16,v=f[3],x=d[3],R+=x&65535,k+=x>>>16,O+=v&65535,M+=v>>>16,k+=R>>>16,O+=k>>>16,M+=O>>>16,f[3]=ye=O&65535|M<<16,d[3]=nt=R&65535|k<<16,v=y,x=De,R=x&65535,k=x>>>16,O=v&65535,M=v>>>16,v=f[4],x=d[4],R+=x&65535,k+=x>>>16,O+=v&65535,M+=v>>>16,k+=R>>>16,O+=k>>>16,M+=O>>>16,f[4]=y=O&65535|M<<16,d[4]=De=R&65535|k<<16,v=we,x=Je,R=x&65535,k=x>>>16,O=v&65535,M=v>>>16,v=f[5],x=d[5],R+=x&65535,k+=x>>>16,O+=v&65535,M+=v>>>16,k+=R>>>16,O+=k>>>16,M+=O>>>16,f[5]=we=O&65535|M<<16,d[5]=Je=R&65535|k<<16,v=Re,x=Ze,R=x&65535,k=x>>>16,O=v&65535,M=v>>>16,v=f[6],x=d[6],R+=x&65535,k+=x>>>16,O+=v&65535,M+=v>>>16,k+=R>>>16,O+=k>>>16,M+=O>>>16,f[6]=Re=O&65535|M<<16,d[6]=Ze=R&65535|k<<16,v=Ae,x=Qe,R=x&65535,k=x>>>16,O=v&65535,M=v>>>16,v=f[7],x=d[7],R+=x&65535,k+=x>>>16,O+=v&65535,M+=v>>>16,k+=R>>>16,O+=k>>>16,M+=O>>>16,f[7]=Ae=O&65535|M<<16,d[7]=Qe=R&65535|k<<16,at+=128,o-=128}return o}function oi(f,d,l){var o=new Int32Array(8),g=new Int32Array(8),b=new Uint8Array(256),w,P=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,Af(o,g,d,l),l%=128,w=0;w<l;w++)b[w]=d[P-l+w];for(b[l]=128,l=256-128*(l<112?1:0),b[l-9]=0,E(b,l-8,P/536870912|0,P<<3),Af(o,g,b,l),w=0;w<8;w++)E(f,8*w,o[w],g[w]);return 0}function es(f,d){var l=e(),o=e(),g=e(),b=e(),w=e(),P=e(),D=e(),Z=e(),W=e();B(l,f[1],f[0]),B(W,d[1],d[0]),A(l,l,W),I(o,f[0],f[1]),I(W,d[0],d[1]),A(o,o,W),A(g,f[3],d[3]),A(g,g,h),A(b,f[2],d[2]),I(b,b,b),B(w,o,l),B(P,b,g),I(D,b,g),I(Z,o,l),A(f[0],w,P),A(f[1],Z,D),A(f[2],D,P),A(f[3],w,Z)}function If(f,d,l){var o;for(o=0;o<4;o++)rt(f[o],d[o],l)}function Ko(f,d){var l=e(),o=e(),g=e();Pe(g,d[2]),A(l,d[0],g),A(o,d[1],g),Fe(f,o),f[31]^=qe(l)<<7}function qo(f,d,l){var o,g;for(Ke(f[0],s),Ke(f[1],a),Ke(f[2],a),Ke(f[3],s),g=255;g>=0;--g)o=l[g/8|0]>>(g&7)&1,If(f,d,o),es(d,f),es(f,f),If(f,d,o)}function ts(f,d){var l=[e(),e(),e(),e()];Ke(l[0],p),Ke(l[1],m),Ke(l[2],a),A(l[3],p,m),qo(f,l,d)}function Wo(f,d,l){var o=new Uint8Array(64),g=[e(),e(),e(),e()],b;for(l||t(d,32),oi(o,d,32),o[0]&=248,o[31]&=127,o[31]|=64,ts(g,o),Ko(f,g),b=0;b<32;b++)d[b+32]=f[b];return 0}var rs=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 Ho(f,d){var l,o,g,b;for(o=63;o>=32;--o){for(l=0,g=o-32,b=o-12;g<b;++g)d[g]+=l-16*d[o]*rs[g-(o-32)],l=Math.floor((d[g]+128)/256),d[g]-=l*256;d[g]+=l,d[o]=0}for(l=0,g=0;g<32;g++)d[g]+=l-(d[31]>>4)*rs[g],l=d[g]>>8,d[g]&=255;for(g=0;g<32;g++)d[g]-=l*rs[g];for(o=0;o<32;o++)d[o+1]+=d[o]>>8,f[o]=d[o]&255}function Vo(f){var d=new Float64Array(64),l;for(l=0;l<64;l++)d[l]=f[l];for(l=0;l<64;l++)f[l]=0;Ho(f,d)}function Lf(f,d,l,o){var g=new Uint8Array(64),b=new Uint8Array(64),w=new Uint8Array(64),P,D,Z=new Float64Array(64),W=[e(),e(),e(),e()];oi(g,o,32),g[0]&=248,g[31]&=127,g[31]|=64;var Oe=l+64;for(P=0;P<l;P++)f[64+P]=d[P];for(P=0;P<32;P++)f[32+P]=g[32+P];for(oi(w,f.subarray(32),l+32),Vo(w),ts(W,w),Ko(f,W),P=32;P<64;P++)f[P]=o[P];for(oi(b,f,l+64),Vo(b),P=0;P<64;P++)Z[P]=0;for(P=0;P<32;P++)Z[P]=w[P];for(P=0;P<32;P++)for(D=0;D<32;D++)Z[P+D]+=b[P]*g[D];return Ho(f.subarray(32),Z),Oe}function Sp(f,d){var l=e(),o=e(),g=e(),b=e(),w=e(),P=e(),D=e();return Ke(f[2],a),dt(f[1],d),se(g,f[1]),A(b,g,u),B(g,g,f[2]),I(b,f[2],b),se(w,b),se(P,w),A(D,P,w),A(l,D,g),A(l,l,b),j(l,l),A(l,l,g),A(l,l,b),A(l,l,b),A(f[0],l,b),se(o,f[0]),A(o,o,b),yt(o,g)&&A(f[0],f[0],_),se(o,f[0]),A(o,o,b),yt(o,g)?-1:(qe(f[0])===d[31]>>7&&B(f[0],s,f[0]),A(f[3],f[0],f[1]),0)}function $o(f,d,l,o){var g,b=new Uint8Array(32),w=new Uint8Array(64),P=[e(),e(),e(),e()],D=[e(),e(),e(),e()];if(l<64||Sp(D,o))return-1;for(g=0;g<l;g++)f[g]=d[g];for(g=0;g<32;g++)f[g+32]=o[g];if(oi(w,f,l),Vo(w),qo(P,D,w),ts(D,d.subarray(32)),es(P,D),Ko(b,P),l-=64,H(d,0,b,0)){for(g=0;g<l;g++)f[g]=0;return-1}for(g=0;g<l;g++)f[g]=d[g+64];return l}var zo=32,is=24,pn=32,Ii=16,gn=32,ns=32,mn=32,yn=32,Go=32,Nf=is,Tp=pn,Cp=Ii,Er=64,ai=32,Li=64,Yo=32,Xo=64;r.lowlevel={crypto_core_hsalsa20:F,crypto_stream_xor:K,crypto_stream:pe,crypto_stream_salsa20_xor:U,crypto_stream_salsa20:ee,crypto_onetimeauth:tt,crypto_onetimeauth_verify:Se,crypto_verify_16:C,crypto_verify_32:H,crypto_secretbox:Me,crypto_secretbox_open:ve,crypto_scalarmult:ue,crypto_scalarmult_base:je,crypto_box_beforenm:_t,crypto_box_afternm:Vt,crypto_box:Dr,crypto_box_open:Ai,crypto_box_keypair:it,crypto_hash:oi,crypto_sign:Lf,crypto_sign_keypair:Wo,crypto_sign_open:$o,crypto_secretbox_KEYBYTES:zo,crypto_secretbox_NONCEBYTES:is,crypto_secretbox_ZEROBYTES:pn,crypto_secretbox_BOXZEROBYTES:Ii,crypto_scalarmult_BYTES:gn,crypto_scalarmult_SCALARBYTES:ns,crypto_box_PUBLICKEYBYTES:mn,crypto_box_SECRETKEYBYTES:yn,crypto_box_BEFORENMBYTES:Go,crypto_box_NONCEBYTES:Nf,crypto_box_ZEROBYTES:Tp,crypto_box_BOXZEROBYTES:Cp,crypto_sign_BYTES:Er,crypto_sign_PUBLICKEYBYTES:ai,crypto_sign_SECRETKEYBYTES:Li,crypto_sign_SEEDBYTES:Yo,crypto_hash_BYTES:Xo,gf:e,D:u,L:rs,pack25519:Fe,unpack25519:dt,M:A,A:I,S:se,Z:B,pow2523:j,add:es,set25519:Ke,modL:Ho,scalarmult:qo,scalarbase:ts};function Mf(f,d){if(f.length!==zo)throw new Error("bad key size");if(d.length!==is)throw new Error("bad nonce size")}function kp(f,d){if(f.length!==mn)throw new Error("bad public key size");if(d.length!==yn)throw new Error("bad secret key size")}function Ct(){for(var f=0;f<arguments.length;f++)if(!(arguments[f]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function Ff(f){for(var d=0;d<f.length;d++)f[d]=0}r.randomBytes=function(f){var d=new Uint8Array(f);return t(d,f),d},r.secretbox=function(f,d,l){Ct(f,d,l),Mf(l,d);for(var o=new Uint8Array(pn+f.length),g=new Uint8Array(o.length),b=0;b<f.length;b++)o[b+pn]=f[b];return Me(g,o,o.length,d,l),g.subarray(Ii)},r.secretbox.open=function(f,d,l){Ct(f,d,l),Mf(l,d);for(var o=new Uint8Array(Ii+f.length),g=new Uint8Array(o.length),b=0;b<f.length;b++)o[b+Ii]=f[b];return o.length<32||ve(g,o,o.length,d,l)!==0?null:g.subarray(pn)},r.secretbox.keyLength=zo,r.secretbox.nonceLength=is,r.secretbox.overheadLength=Ii,r.scalarMult=function(f,d){if(Ct(f,d),f.length!==ns)throw new Error("bad n size");if(d.length!==gn)throw new Error("bad p size");var l=new Uint8Array(gn);return ue(l,f,d),l},r.scalarMult.base=function(f){if(Ct(f),f.length!==ns)throw new Error("bad n size");var d=new Uint8Array(gn);return je(d,f),d},r.scalarMult.scalarLength=ns,r.scalarMult.groupElementLength=gn,r.box=function(f,d,l,o){var g=r.box.before(l,o);return r.secretbox(f,d,g)},r.box.before=function(f,d){Ct(f,d),kp(f,d);var l=new Uint8Array(Go);return _t(l,f,d),l},r.box.after=r.secretbox,r.box.open=function(f,d,l,o){var g=r.box.before(l,o);return r.secretbox.open(f,d,g)},r.box.open.after=r.secretbox.open,r.box.keyPair=function(){var f=new Uint8Array(mn),d=new Uint8Array(yn);return it(f,d),{publicKey:f,secretKey:d}},r.box.keyPair.fromSecretKey=function(f){if(Ct(f),f.length!==yn)throw new Error("bad secret key size");var d=new Uint8Array(mn);return je(d,f),{publicKey:d,secretKey:new Uint8Array(f)}},r.box.publicKeyLength=mn,r.box.secretKeyLength=yn,r.box.sharedKeyLength=Go,r.box.nonceLength=Nf,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(f,d){if(Ct(f,d),d.length!==Li)throw new Error("bad secret key size");var l=new Uint8Array(Er+f.length);return Lf(l,f,f.length,d),l},r.sign.open=function(f,d){if(Ct(f,d),d.length!==ai)throw new Error("bad public key size");var l=new Uint8Array(f.length),o=$o(l,f,f.length,d);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,d){for(var l=r.sign(f,d),o=new Uint8Array(Er),g=0;g<o.length;g++)o[g]=l[g];return o},r.sign.detached.verify=function(f,d,l){if(Ct(f,d,l),d.length!==Er)throw new Error("bad signature size");if(l.length!==ai)throw new Error("bad public key size");var o=new Uint8Array(Er+f.length),g=new Uint8Array(Er+f.length),b;for(b=0;b<Er;b++)o[b]=d[b];for(b=0;b<f.length;b++)o[b+Er]=f[b];return $o(g,o,o.length,l)>=0},r.sign.keyPair=function(){var f=new Uint8Array(ai),d=new Uint8Array(Li);return Wo(f,d),{publicKey:f,secretKey:d}},r.sign.keyPair.fromSecretKey=function(f){if(Ct(f),f.length!==Li)throw new Error("bad secret key size");for(var d=new Uint8Array(ai),l=0;l<d.length;l++)d[l]=f[32+l];return{publicKey:d,secretKey:new Uint8Array(f)}},r.sign.keyPair.fromSeed=function(f){if(Ct(f),f.length!==Yo)throw new Error("bad seed size");for(var d=new Uint8Array(ai),l=new Uint8Array(Li),o=0;o<32;o++)l[o]=f[o];return Wo(d,l,!0),{publicKey:d,secretKey:l}},r.sign.publicKeyLength=ai,r.sign.secretKeyLength=Li,r.sign.seedLength=Yo,r.sign.signatureLength=Er,r.hash=function(f){Ct(f);var d=new Uint8Array(Xo);return oi(d,f,f.length),d},r.hash.hashLength=Xo,r.verify=function(f,d){return Ct(f,d),f.length===0||d.length===0||f.length!==d.length?!1:S(f,0,d,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 d=65536;r.setPRNG(function(l,o){var g,b=new Uint8Array(o);for(g=0;g<o;g+=d)f.getRandomValues(b.subarray(g,g+Math.min(o-g,d)));for(g=0;g<o;g++)l[g]=b[g];Ff(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];Ff(b)}))})()})(typeof ms<"u"&&ms.exports?ms.exports:self.nacl=self.nacl||{})});var vn=L((ru,ys)=>{(function(r,e){"use strict";typeof ys<"u"&&ys.exports?ys.exports=e():(r.nacl||(r.nacl={}),r.nacl.util=e())})(ru,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 iu=L(Pt=>{"use strict";var Yp=Pt&&Pt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Pt,"__esModule",{value:!0});Pt.concatBytes=xn;Pt.generateIdentityKeyPair=Xp;Pt.identityPublicFromSecret=Jp;Pt.signSessionKey=Zp;Pt.verifySessionKey=Qp;Pt.buildKxCanonical=eg;Pt.buildKxAckCanonical=tg;Pt.fingerprintIdentityKey=rg;Pt.fingerprintShortHex=ig;var nr=Yp(wn()),kt=vn(),_s=ta();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 Xp(){let r=nr.default.sign.keyPair();return{identityPublicKey:(0,kt.encodeBase64)(r.publicKey),identitySecretKey:(0,kt.encodeBase64)(r.secretKey)}}function Jp(r){let e=(0,kt.decodeBase64)(r);if(e.length!==nr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");let t=nr.default.sign.keyPair.fromSecretKey(e);return(0,kt.encodeBase64)(t.publicKey)}function Zp(r,e){let t=(0,kt.decodeBase64)(e);if(t.length!==nr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");return(0,kt.encodeBase64)(nr.default.sign.detached(r,t))}function Qp(r,e,t){try{let i=(0,kt.decodeBase64)(e),n=(0,kt.decodeBase64)(t);return n.length!==nr.default.sign.publicKeyLength||i.length!==nr.default.sign.signatureLength?!1:nr.default.sign.detached.verify(r,i,n)}catch{return!1}}var ci=new Uint8Array([0]);function eg(r){let e=new TextEncoder,t=e.encode(_s.KX_SIGN_LABEL),i=e.encode(r.agentId),n=e.encode(String(r.keyVersion)),s=(0,kt.decodeBase64)(r.boxPublicKey);return xn(t,ci,i,ci,n,ci,s)}function tg(r){let e=new TextEncoder;return xn(e.encode(_s.KX_ACK_LABEL),ci,e.encode(r.agentId),ci,e.encode(String(r.keyVersion)),ci,(0,kt.decodeBase64)(r.boxPublicKey),ci,(0,kt.decodeBase64)(r.boundClientKey))}function rg(r){let e=(0,kt.decodeBase64)(r),t=xn(new TextEncoder().encode(_s.KX_FINGERPRINT_LABEL),e),i=nr.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 ig(r){let e=(0,kt.decodeBase64)(r),t=xn(new TextEncoder().encode(_s.KX_FINGERPRINT_LABEL),e),i=nr.default.hash(t).slice(0,8);return Array.from(i).map(n=>n.toString(16).padStart(2,"0")).join(":").toUpperCase()}});var nu=L(Ur=>{"use strict";var ng=Ur&&Ur.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ur,"__esModule",{value:!0});Ur.encrypt=sg;Ur.decrypt=og;Ur.encryptBinary=ag;Ur.decryptBinary=cg;var xr=ng(wn()),jr=vn();function sg(r,e,t){let i=xr.default.randomBytes(xr.default.secretbox.nonceLength),n=new TextEncoder().encode(r),s=xr.default.secretbox(n,i,e);return{v:1,sid:t,n:(0,jr.encodeBase64)(i),c:(0,jr.encodeBase64)(s)}}function og(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,jr.decodeBase64)(r.n),i=(0,jr.decodeBase64)(r.c);if(t.length!==xr.default.secretbox.nonceLength)throw new Error(`Invalid nonce length: ${t.length}`);let n=xr.default.secretbox.open(i,t,e);if(!n)throw new Error("Decryption failed: invalid ciphertext or wrong key");return new TextDecoder().decode(n)}function ag(r,e,t){let i=xr.default.randomBytes(xr.default.secretbox.nonceLength),n=xr.default.secretbox(r,i,e);return{v:1,sid:t,n:(0,jr.encodeBase64)(i),c:(0,jr.encodeBase64)(n)}}function cg(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,jr.decodeBase64)(r.n),i=(0,jr.decodeBase64)(r.c),n=xr.default.secretbox.open(i,t,e);if(!n)throw new Error("Decryption failed: invalid ciphertext or wrong key");return n}});var su=L(zt=>{"use strict";var fg=zt&&zt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(zt,"__esModule",{value:!0});zt.generateKeyPair=ug;zt.deriveSharedSecret=lg;zt.deriveMetaSid=hg;zt.isValidPublicKey=dg;zt.clearKey=pg;zt.keyToBase64=gg;zt.base64ToKey=mg;var Mi=fg(wn()),sr=vn();function ug(){let r=Mi.default.box.keyPair();return{publicKey:(0,sr.encodeBase64)(r.publicKey),secretKey:(0,sr.encodeBase64)(r.secretKey)}}function lg(r,e){let t=(0,sr.decodeBase64)(r),i=(0,sr.decodeBase64)(e);if(t.length!==Mi.default.box.publicKeyLength)throw new Error(`Invalid public key length: ${t.length}`);if(i.length!==Mi.default.box.secretKeyLength)throw new Error(`Invalid secret key length: ${i.length}`);return Mi.default.box.before(t,i)}function hg(r,e){let t=new TextEncoder().encode("termiq-meta-v1"),i=(0,sr.decodeBase64)(r),n=(0,sr.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,sr.encodeBase64)(Mi.default.hash(s).slice(0,32))}function dg(r){try{return(0,sr.decodeBase64)(r).length===Mi.default.box.publicKeyLength}catch{return!1}}function pg(r){r.fill(0)}function gg(r){return(0,sr.encodeBase64)(r)}function mg(r){return(0,sr.decodeBase64)(r)}});var au=L(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 ou=tu();Object.defineProperty(re,"isEncryptedPayload",{enumerable:!0,get:function(){return ou.isEncryptedPayload}});Object.defineProperty(re,"isMultiRecipientPayload",{enumerable:!0,get:function(){return ou.isMultiRecipientPayload}});var bs=ta();Object.defineProperty(re,"KX_SIGN_LABEL",{enumerable:!0,get:function(){return bs.KX_SIGN_LABEL}});Object.defineProperty(re,"KX_ACK_LABEL",{enumerable:!0,get:function(){return bs.KX_ACK_LABEL}});Object.defineProperty(re,"KX_FINGERPRINT_LABEL",{enumerable:!0,get:function(){return bs.KX_FINGERPRINT_LABEL}});Object.defineProperty(re,"KX_SIG_VERSION",{enumerable:!0,get:function(){return bs.KX_SIG_VERSION}});var Sr=iu();Object.defineProperty(re,"generateIdentityKeyPair",{enumerable:!0,get:function(){return Sr.generateIdentityKeyPair}});Object.defineProperty(re,"identityPublicFromSecret",{enumerable:!0,get:function(){return Sr.identityPublicFromSecret}});Object.defineProperty(re,"signSessionKey",{enumerable:!0,get:function(){return Sr.signSessionKey}});Object.defineProperty(re,"verifySessionKey",{enumerable:!0,get:function(){return Sr.verifySessionKey}});Object.defineProperty(re,"buildKxCanonical",{enumerable:!0,get:function(){return Sr.buildKxCanonical}});Object.defineProperty(re,"buildKxAckCanonical",{enumerable:!0,get:function(){return Sr.buildKxAckCanonical}});Object.defineProperty(re,"fingerprintIdentityKey",{enumerable:!0,get:function(){return Sr.fingerprintIdentityKey}});Object.defineProperty(re,"fingerprintShortHex",{enumerable:!0,get:function(){return Sr.fingerprintShortHex}});Object.defineProperty(re,"concatBytes",{enumerable:!0,get:function(){return Sr.concatBytes}});var Es=nu();Object.defineProperty(re,"encrypt",{enumerable:!0,get:function(){return Es.encrypt}});Object.defineProperty(re,"decrypt",{enumerable:!0,get:function(){return Es.decrypt}});Object.defineProperty(re,"encryptBinary",{enumerable:!0,get:function(){return Es.encryptBinary}});Object.defineProperty(re,"decryptBinary",{enumerable:!0,get:function(){return Es.decryptBinary}});var fi=su();Object.defineProperty(re,"generateKeyPair",{enumerable:!0,get:function(){return fi.generateKeyPair}});Object.defineProperty(re,"deriveSharedSecret",{enumerable:!0,get:function(){return fi.deriveSharedSecret}});Object.defineProperty(re,"deriveMetaSid",{enumerable:!0,get:function(){return fi.deriveMetaSid}});Object.defineProperty(re,"isValidPublicKey",{enumerable:!0,get:function(){return fi.isValidPublicKey}});Object.defineProperty(re,"clearKey",{enumerable:!0,get:function(){return fi.clearKey}});Object.defineProperty(re,"keyToBase64",{enumerable:!0,get:function(){return fi.keyToBase64}});Object.defineProperty(re,"base64ToKey",{enumerable:!0,get:function(){return fi.base64ToKey}})});var cu=L(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.MIN_CLIENT_VERSION=Ot.PROTOCOL_VERSION_MINOR=Ot.PROTOCOL_VERSION_MAJOR=Ot.PROTOCOL_VERSION=void 0;Ot.isCompatibleVersion=yg;Ot.compareVersions=_g;Ot.PROTOCOL_VERSION="2.1";Ot.PROTOCOL_VERSION_MAJOR=2;Ot.PROTOCOL_VERSION_MINOR=1;Ot.MIN_CLIENT_VERSION="2.0";function yg(r){let[e]=r.split(".").map(Number);return e===Ot.PROTOCOL_VERSION_MAJOR}function _g(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 fu=L(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.SERVER_CAPABILITIES=or.DEFAULT_CLIENT_CAPABILITIES=or.Capability=void 0;or.hasCapability=bg;or.negotiateCapabilities=Eg;var Fi;(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"})(Fi||(or.Capability=Fi={}));or.DEFAULT_CLIENT_CAPABILITIES=[Fi.E2E_ENCRYPTION,Fi.TERMINAL_EVENTS,Fi.RELIABLE_INPUT];or.SERVER_CAPABILITIES=Object.values(Fi);function bg(r,e){return r.includes(e)}function Eg(r,e){return r.filter(t=>e.includes(t))}});var uu=L(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.DEFAULT_PRIORITY=Tr.PRIORITY_NAMES=Tr.Priority=void 0;Tr.comparePriority=wg;var ui;(function(r){r[r.CRITICAL=0]="CRITICAL",r[r.HIGH=1]="HIGH",r[r.NORMAL=2]="NORMAL",r[r.LOW=3]="LOW"})(ui||(Tr.Priority=ui={}));Tr.PRIORITY_NAMES={[ui.CRITICAL]:"CRITICAL",[ui.HIGH]:"HIGH",[ui.NORMAL]:"NORMAL",[ui.LOW]:"LOW"};Tr.DEFAULT_PRIORITY=ui.NORMAL;function wg(r,e){return r-e}});var lu=L(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.DEFAULT_RELIABILITY=ar.RELIABILITY_NAMES=ar.Reliability=void 0;ar.requiresAck=vg;ar.requiresBuffer=xg;var Kr;(function(r){r[r.FIRE_FORGET=0]="FIRE_FORGET",r[r.BUFFERED=1]="BUFFERED",r[r.GUARANTEED=2]="GUARANTEED"})(Kr||(ar.Reliability=Kr={}));ar.RELIABILITY_NAMES={[Kr.FIRE_FORGET]:"FIRE_FORGET",[Kr.BUFFERED]:"BUFFERED",[Kr.GUARANTEED]:"GUARANTEED"};ar.DEFAULT_RELIABILITY=Kr.FIRE_FORGET;function vg(r){return r===Kr.GUARANTEED}function xg(r){return r>=Kr.BUFFERED}});var hu=L(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});ra.createMessage=Sg;function Sg(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 du=L(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.TerminalEventType=void 0;li.deriveStatusFromEvent=Tg;li.shouldTriggerPushNotification=Cg;li.getPushNotificationMessage=kg;var bt;(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"})(bt||(li.TerminalEventType=bt={}));function Tg(r){switch(r.type){case bt.SESSION_START:case bt.TOOL_START:case bt.MESSAGE:return"working";case bt.WAITING_INPUT:return"waiting";case bt.SESSION_END:return r.status==="success"?"completed":"error";case bt.ERROR:return r.severity==="fatal"?"error":"working";case bt.TOOL_END:return r.status==="error"?"error":"working";default:return"idle"}}function Cg(r){switch(r.type){case bt.WAITING_INPUT:return!0;case bt.SESSION_END:return!0;case bt.ERROR:return r.severity!=="warning";default:return!1}}function kg(r,e){switch(r.type){case bt.WAITING_INPUT:{let t=r.question;return{title:`${e}: Input Required`,body:t?t.slice(0,100):"Waiting for your input"}}case bt.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 bt.ERROR:{let t=r;return t.severity==="warning"?null:{title:`${e}: Error`,body:t.message.slice(0,100)}}default:return null}}});var mu=L($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.TransferDirection=$e.TransferStatus=$e.CHUNK_TTL_SECONDS=$e.TRANSFER_TTL_SECONDS=$e.MAX_RETRIES=$e.ACK_TIMEOUT_MS=$e.WINDOW_SIZE=$e.DEFAULT_MAX_FILE_SIZE=$e.CHUNK_SIZE=void 0;$e.calculateTotalChunks=Pg;$e.getMissingChunks=Og;$e.isTransferComplete=Rg;$e.CHUNK_SIZE=64*1024;$e.DEFAULT_MAX_FILE_SIZE=100*1024*1024;$e.WINDOW_SIZE=10;$e.ACK_TIMEOUT_MS=3e4;$e.MAX_RETRIES=3;$e.TRANSFER_TTL_SECONDS=1440*60;$e.CHUNK_TTL_SECONDS=1440*60;var pu;(function(r){r.PENDING="pending",r.ACTIVE="active",r.PAUSED="paused",r.COMPLETED="completed",r.FAILED="failed",r.CANCELLED="cancelled",r.EXPIRED="expired"})(pu||($e.TransferStatus=pu={}));var gu;(function(r){r.DOWNLOAD="download",r.UPLOAD="upload"})(gu||($e.TransferDirection=gu={}));function Pg(r,e=$e.CHUNK_SIZE){return Math.ceil(r/e)}function Og(r,e){let t=new Set(e),i=[];for(let n=0;n<r;n++)t.has(n)||i.push(n);return i}function Rg(r,e){return e.length===r}});var yu=L(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.ERROR_MESSAGES=Cr.ErrorCode=void 0;Cr.createError=Ag;Cr.isRetryableError=Ig;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||(Cr.ErrorCode=Ie={}));Cr.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 Ag(r,e={}){return{code:r,message:e.message||Cr.ERROR_MESSAGES[r],details:e.details,retryable:e.retryable??!1,retryAfter:e.retryAfter}}function Ig(r){return[Ie.RATE_LIMITED,Ie.TIMEOUT,Ie.CONNECTION_LOST,Ie.SERVICE_UNAVAILABLE].includes(r)}});var wu=L(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.FileEntryType=Rt.DiffBase=Rt.FileViewType=Rt.FileChangeType=void 0;Rt.getLanguageFromPath=Lg;Rt.parseUnifiedDiff=Ng;Rt.createSimpleDiff=Mg;var qr;(function(r){r.CREATE="create",r.MODIFY="modify",r.DELETE="delete"})(qr||(Rt.FileChangeType=qr={}));var _u;(function(r){r.CONTENT="content",r.DIFF="diff"})(_u||(Rt.FileViewType=_u={}));var bu;(function(r){r.GIT="git",r.PREVIOUS="previous"})(bu||(Rt.DiffBase=bu={}));function Lg(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 Ng(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),E=parseInt(m[2]||"1",10),S=parseInt(m[3],10),C=parseInt(m[4]||"1",10);a={oldStart:_,oldLines:E,newStart:S,newLines:C,lines:[]},c=_,u=S;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 h;return s===0&&n>0&&i.length===1&&i[0].oldLines===0?h=qr.CREATE:n===0&&s>0&&i.length===1&&i[0].newLines===0?h=qr.DELETE:h=qr.MODIFY,{path:e,changeType:h,hunks:i,additions:n,deletions:s,isBinary:!1}}function Mg(r,e,t){let i=r.split(`
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 h;return r===""?h=qr.CREATE:e===""?h=qr.DELETE:h=qr.MODIFY,{path:t,changeType:h,hunks:[{oldStart:1,oldLines:i.length,newStart:1,newLines:n.length,lines:s}],additions:a,deletions:c,isBinary:!1}}var Eu;(function(r){r.FILE="file",r.DIRECTORY="directory"})(Eu||(Rt.FileEntryType=Eu={}))});var vu=L(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 Di=cu();Object.defineProperty(N,"PROTOCOL_VERSION",{enumerable:!0,get:function(){return Di.PROTOCOL_VERSION}});Object.defineProperty(N,"PROTOCOL_VERSION_MAJOR",{enumerable:!0,get:function(){return Di.PROTOCOL_VERSION_MAJOR}});Object.defineProperty(N,"PROTOCOL_VERSION_MINOR",{enumerable:!0,get:function(){return Di.PROTOCOL_VERSION_MINOR}});Object.defineProperty(N,"MIN_CLIENT_VERSION",{enumerable:!0,get:function(){return Di.MIN_CLIENT_VERSION}});Object.defineProperty(N,"isCompatibleVersion",{enumerable:!0,get:function(){return Di.isCompatibleVersion}});Object.defineProperty(N,"compareVersions",{enumerable:!0,get:function(){return Di.compareVersions}});var Sn=fu();Object.defineProperty(N,"Capability",{enumerable:!0,get:function(){return Sn.Capability}});Object.defineProperty(N,"DEFAULT_CLIENT_CAPABILITIES",{enumerable:!0,get:function(){return Sn.DEFAULT_CLIENT_CAPABILITIES}});Object.defineProperty(N,"SERVER_CAPABILITIES",{enumerable:!0,get:function(){return Sn.SERVER_CAPABILITIES}});Object.defineProperty(N,"hasCapability",{enumerable:!0,get:function(){return Sn.hasCapability}});Object.defineProperty(N,"negotiateCapabilities",{enumerable:!0,get:function(){return Sn.negotiateCapabilities}});var ws=uu();Object.defineProperty(N,"Priority",{enumerable:!0,get:function(){return ws.Priority}});Object.defineProperty(N,"PRIORITY_NAMES",{enumerable:!0,get:function(){return ws.PRIORITY_NAMES}});Object.defineProperty(N,"DEFAULT_PRIORITY",{enumerable:!0,get:function(){return ws.DEFAULT_PRIORITY}});Object.defineProperty(N,"comparePriority",{enumerable:!0,get:function(){return ws.comparePriority}});var Tn=lu();Object.defineProperty(N,"Reliability",{enumerable:!0,get:function(){return Tn.Reliability}});Object.defineProperty(N,"RELIABILITY_NAMES",{enumerable:!0,get:function(){return Tn.RELIABILITY_NAMES}});Object.defineProperty(N,"DEFAULT_RELIABILITY",{enumerable:!0,get:function(){return Tn.DEFAULT_RELIABILITY}});Object.defineProperty(N,"requiresAck",{enumerable:!0,get:function(){return Tn.requiresAck}});Object.defineProperty(N,"requiresBuffer",{enumerable:!0,get:function(){return Tn.requiresBuffer}});var Fg=hu();Object.defineProperty(N,"createMessage",{enumerable:!0,get:function(){return Fg.createMessage}});var vs=du();Object.defineProperty(N,"TerminalEventType",{enumerable:!0,get:function(){return vs.TerminalEventType}});Object.defineProperty(N,"deriveStatusFromEvent",{enumerable:!0,get:function(){return vs.deriveStatusFromEvent}});Object.defineProperty(N,"shouldTriggerPushNotification",{enumerable:!0,get:function(){return vs.shouldTriggerPushNotification}});Object.defineProperty(N,"getPushNotificationMessage",{enumerable:!0,get:function(){return vs.getPushNotificationMessage}});var Ft=mu();Object.defineProperty(N,"CHUNK_SIZE",{enumerable:!0,get:function(){return Ft.CHUNK_SIZE}});Object.defineProperty(N,"DEFAULT_MAX_FILE_SIZE",{enumerable:!0,get:function(){return Ft.DEFAULT_MAX_FILE_SIZE}});Object.defineProperty(N,"WINDOW_SIZE",{enumerable:!0,get:function(){return Ft.WINDOW_SIZE}});Object.defineProperty(N,"ACK_TIMEOUT_MS",{enumerable:!0,get:function(){return Ft.ACK_TIMEOUT_MS}});Object.defineProperty(N,"MAX_RETRIES",{enumerable:!0,get:function(){return Ft.MAX_RETRIES}});Object.defineProperty(N,"TRANSFER_TTL_SECONDS",{enumerable:!0,get:function(){return Ft.TRANSFER_TTL_SECONDS}});Object.defineProperty(N,"CHUNK_TTL_SECONDS",{enumerable:!0,get:function(){return Ft.CHUNK_TTL_SECONDS}});Object.defineProperty(N,"TransferStatus",{enumerable:!0,get:function(){return Ft.TransferStatus}});Object.defineProperty(N,"TransferDirection",{enumerable:!0,get:function(){return Ft.TransferDirection}});Object.defineProperty(N,"calculateTotalChunks",{enumerable:!0,get:function(){return Ft.calculateTotalChunks}});Object.defineProperty(N,"getMissingChunks",{enumerable:!0,get:function(){return Ft.getMissingChunks}});Object.defineProperty(N,"isTransferComplete",{enumerable:!0,get:function(){return Ft.isTransferComplete}});var xs=yu();Object.defineProperty(N,"ErrorCode",{enumerable:!0,get:function(){return xs.ErrorCode}});Object.defineProperty(N,"ERROR_MESSAGES",{enumerable:!0,get:function(){return xs.ERROR_MESSAGES}});Object.defineProperty(N,"createError",{enumerable:!0,get:function(){return xs.createError}});Object.defineProperty(N,"isRetryableError",{enumerable:!0,get:function(){return xs.isRetryableError}});var hi=wu();Object.defineProperty(N,"FileChangeType",{enumerable:!0,get:function(){return hi.FileChangeType}});Object.defineProperty(N,"FileViewType",{enumerable:!0,get:function(){return hi.FileViewType}});Object.defineProperty(N,"DiffBase",{enumerable:!0,get:function(){return hi.DiffBase}});Object.defineProperty(N,"FileEntryType",{enumerable:!0,get:function(){return hi.FileEntryType}});Object.defineProperty(N,"getLanguageFromPath",{enumerable:!0,get:function(){return hi.getLanguageFromPath}});Object.defineProperty(N,"parseUnifiedDiff",{enumerable:!0,get:function(){return hi.parseUnifiedDiff}});Object.defineProperty(N,"createSimpleDiff",{enumerable:!0,get:function(){return hi.createSimpleDiff}})});var kr=L(cr=>{"use strict";var Dg=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]})),Ss=cr&&cr.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Dg(e,r,t)};Object.defineProperty(cr,"__esModule",{value:!0});Ss(Qf(),cr);Ss(eu(),cr);Ss(au(),cr);Ss(vu(),cr)});var ia=L(Ye=>{"use strict";var Bg=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ye,"__esModule",{value:!0});Ye.FP_LABEL=Ye.KX_ACK_LABEL=Ye.KX_SIGN_LABEL=void 0;Ye.concatBytes=Cn;Ye.generateIdentityKeyPair=jg;Ye.identityPublicFromSecret=Ug;Ye.signSessionKey=Kg;Ye.verifySessionKey=qg;Ye.buildKxCanonical=Wg;Ye.buildKxAckCanonical=Hg;Ye.fingerprintIdentityKey=Vg;Ye.fingerprintShortHex=$g;var fr=Bg(wn()),At=vn();Ye.KX_SIGN_LABEL="termiq-kx-v1";Ye.KX_ACK_LABEL="termiq-kxack-v1";Ye.FP_LABEL="termiq-fp-v1";function Cn(...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 jg(){let r=fr.default.sign.keyPair();return{identityPublicKey:(0,At.encodeBase64)(r.publicKey),identitySecretKey:(0,At.encodeBase64)(r.secretKey)}}function Ug(r){let e=(0,At.decodeBase64)(r);if(e.length!==fr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");let t=fr.default.sign.keyPair.fromSecretKey(e);return(0,At.encodeBase64)(t.publicKey)}function Kg(r,e){let t=(0,At.decodeBase64)(e);if(t.length!==fr.default.sign.secretKeyLength)throw new Error("bad identity secret key length");return(0,At.encodeBase64)(fr.default.sign.detached(r,t))}function qg(r,e,t){try{let i=(0,At.decodeBase64)(e),n=(0,At.decodeBase64)(t);return n.length!==fr.default.sign.publicKeyLength||i.length!==fr.default.sign.signatureLength?!1:fr.default.sign.detached.verify(r,i,n)}catch{return!1}}var di=new Uint8Array([0]);function Wg(r){let e=new TextEncoder,t=e.encode(Ye.KX_SIGN_LABEL),i=e.encode(r.agentId),n=e.encode(String(r.keyVersion)),s=(0,At.decodeBase64)(r.boxPublicKey);return Cn(t,di,i,di,n,di,s)}function Hg(r){let e=new TextEncoder;return Cn(e.encode(Ye.KX_ACK_LABEL),di,e.encode(r.agentId),di,e.encode(String(r.keyVersion)),di,(0,At.decodeBase64)(r.boxPublicKey),di,(0,At.decodeBase64)(r.boundClientKey))}function Vg(r){let e=(0,At.decodeBase64)(r),t=Cn(new TextEncoder().encode(Ye.FP_LABEL),e),i=fr.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 $g(r){let e=(0,At.decodeBase64)(r),t=Cn(new TextEncoder().encode(Ye.FP_LABEL),e),i=fr.default.hash(t).slice(0,8);return Array.from(i).map(n=>n.toString(16).padStart(2,"0")).join(":").toUpperCase()}});var Su=L(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});Ts.CryptoService=void 0;var st=kr(),Wr=ia(),zg=3600*1e3,xu=10,na=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,st.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,Wr.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,Wr.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,Wr.buildKxCanonical)({agentId:e,keyVersion:i,boxPublicKey:n}),a=(0,Wr.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,Wr.buildKxAckCanonical)({agentId:e,keyVersion:n,boxPublicKey:this.keyPair.publicKey,boundClientKey:t});return(0,Wr.signSessionKey)(s,i.identitySecretKey)}async getSafetyNumber(){let e=await this.ensureIdentityKeyPair();return(0,Wr.fingerprintIdentityKey)(e.identityPublicKey)}async getShortFingerprint(){let e=await this.ensureIdentityKeyPair();return(0,Wr.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,st.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,st.encrypt)(t,s.sharedSecret,s.sessionId):null}let n=[];for(let s of i.values()){let a=(0,st.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,st.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,st.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,st.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,st.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,st.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,st.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>zg&&n.push(s);for(let s of n){let a=t.get(s);a&&((0,st.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>xu){let a=Array.from(t.entries()).sort((c,u)=>c[1].createdAt-u[1].createdAt).slice(0,t.size-xu);for(let[,c]of a)(0,st.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,st.clearKey)(i.sharedSecret));let n=(0,st.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,st.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,st.deriveSharedSecret)(e,this.keyPair.secretKey),n=(0,st.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,st.encrypt)(e,i.sharedSecret,i.sidMeta):null}let t=[];for(let i of this.metaSessions.values()){let n=(0,st.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,st.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")}};Ts.CryptoService=na});var Tu=L(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});Cs.AuthService=void 0;var kn=hs(),sa=class{storage;cryptoService;machineId;config;logger;notification;browser;pollingAbortController=null;tokenKey;refreshTokenKey;agentIdKey;constructor(e,t,i,n,s,a,c,u,h){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}.${h}`;this.tokenKey=`${p}.accessToken`,this.refreshTokenKey=`${p}.refreshToken`,this.agentIdKey=`${p}.agentId`,this.logger.info("AuthService namespace",u,h)}cancelPolling(){this.pollingAbortController&&(this.logger.info("Cancelling active polling"),this.pollingAbortController.abort(),this.pollingAbortController=null)}async startDeviceCodeFlow(){this.cancelPolling();let e=(0,kn.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,kn.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 h=await c.json();if(h.error==="AGENT_LIMIT_EXCEEDED")return this.logger.warn("Agent limit exceeded",String(h.current),"/",String(h.max)),this.notification.warn(`Agent limit reached (${h.current}/${h.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,kn.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,kn.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,kn.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))}};Cs.AuthService=sa});var Cu=L(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.scanOsc=Xg;ks.classifyTitle=Zg;var Gg=4096,oa=/\x1b\]([^\x1b\x07]*)(?:\x07|\x1b\\)/g,Yg="\x1B]";function Xg(r,e=""){let t=e+r,i=[];oa.lastIndex=0;let n=0,s;for(;(s=oa.exec(t))!==null;)i.push(s[1]),n=oa.lastIndex;let a=t.slice(n),c=a.lastIndexOf(Yg),u=c===-1?"":a.slice(c),h=u.indexOf("\x1B",1);return h!==-1&&h!==u.length-1&&(u=""),u.length>Gg&&(u=""),{seqs:i,carry:u}}var Jg=/^([012]);([\s\S]*)$/;function Zg(r){let e=r.match(Jg);if(!e)return null;let t=e[2].trim();return t?t.includes("Action Required")?{agent:t.startsWith("\u270B")?"gemini":/^\[\s*[!.]\s*\]/.test(t)?"codex":null,state:"waiting",title:t}:t.startsWith("\u2726")||t.startsWith("\u23F2")?{agent:"gemini",state:"working",title:t}:t.startsWith("\u25C7")?{agent:"gemini",state:"idle",title:t}:t.startsWith("\u25D0")||t.startsWith("\u25D1")?{agent:"claude",state:"working",title:t}:t.startsWith("\u2733")?{agent:"claude",state:"unknown",title:t}:{agent:null,state:"unknown",title:t}:{agent:null,state:"unknown",title:""}}});var Ou=L(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.MAX_TAIL_PLAIN=We.MAX_TAIL_WITH_SELECTOR=We.MAX_LABEL_LEN=We.MAX_QUESTION_LEN=We.classifyTitle=We.scanOsc=void 0;We.stripAnsi=ca;We.normalizeBuffer=Pu;We.clampQuestion=aa;We.promptKey=Qg;We.extractQuestion=em;We.extractNumberedChoices=tm;var ku=Cu();Object.defineProperty(We,"scanOsc",{enumerable:!0,get:function(){return ku.scanOsc}});Object.defineProperty(We,"classifyTitle",{enumerable:!0,get:function(){return ku.classifyTitle}});We.MAX_QUESTION_LEN=160;We.MAX_LABEL_LEN=100;We.MAX_TAIL_WITH_SELECTOR=12;We.MAX_TAIL_PLAIN=2;function ca(r){return r.replace(/\x1b\[[0-9]*[GC]/g," ").replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\x1b\][^\x1b\x07]*(?:\x07|\x1b\\)/g,"").replace(/\x1b[()][AB012]/g,"").replace(/\x1b[=>]/g,"").replace(/\x1b[78DMEHc]/g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g,"")}function Pu(r){return r.replace(/\r\n/g,`
6
6
  `).replace(/\r/g,`
7
7
  `).replace(/\n{3,}/g,`
8
8
 
9
- `)}function ia(r){let e=r.replace(/\s+/g," ").trim(),t=Ze.MAX_QUESTION_LEN;return e.length<=t?e:e.slice(0,t-1).trimEnd()+"\u2026"}function Hg(r){let e=(r.choices||[]).map(t=>`${t.key}=${t.label}`).join("\xA7");return`${r.type}|${r.question}|${e}`}function Vg(r,e){let t=r.split(`
10
- `).filter(n=>n.trim());for(let n=t.length-1;n>=Math.max(0,t.length-8);n--){let i=t[n].trim();if(!i||/^[\s│┃]*(?:[❯▶▸›●>*]\s*)?\d+[.)]\s/.test(i)||/^[\s│┃]*\[/.test(i))continue;let s=sa(i).replace(/^[\s│┃┊┋┆┇╎╏]+/u,"").replace(/[\s│┃┊┋┆┇╎╏]+$/u,"").replace(/\s+/g," ");if(s.endsWith("?")||s.endsWith(":"))return ia(s.replace(/\s*\[Y\/n\]\s*$/i,"").replace(/\s*\(y\/n\)\s*$/i,"").replace(/\s*\(yes\/no\)\s*$/i,""));for(let a of e||[]){let c=s.match(a);if(c)return ia(c[1]||s)}}return null}function zg(r){let e=[],n=wu(sa(r)).split(`
11
- `),i=/^[\s│┃┊┋┆┇╎╏]*(?:[❯▶▸›●>*]\s*)?(?:(\d+)[.)]\s*|\[(\d+)\]\s*)(.+?)[\s│┃]*$/u,s=/^[\s│┃┊┋┆┇╎╏]*([❯▶▸›●])\s*(?:\d+[.)]|\[\d+\])/u,a=[],c=-1,u=-1,d=!1,p="",m=[],_=-1,v=!1,S="",T=z=>z.length*1e3+z.reduce((C,D)=>C+D.label.length,0),H=()=>{m.length>=1&&T(m)>=c&&(a=m.slice(),c=T(m),u=_,d=v,p=S)};for(let z=0;z<n.length;z++){let C=n[z],D=C.match(i);if(!D)continue;let Q=D[1]||D[2],K=D[3].replace(/\s+/g," ").trim();if(!Q||!K)continue;let U=K.length>Ze.MAX_LABEL_LEN?K.slice(0,Ze.MAX_LABEL_LEN-1)+"\u2026":K,le=parseInt(Q,10),pe=C.match(s),se=pe!==null;le===m.length+1?(m.push({key:Q,label:U}),_=z,v=v||se,pe&&(S=pe[1])):le===1?(H(),m=[{key:Q,label:U}],_=z,v=se,S=pe?pe[1]:""):(H(),m=[],_=-1,v=!1,S="")}if(H(),u>=0){let z=n.slice(u+1).filter(D=>D.trim().length>0),C=d?Ze.MAX_TAIL_WITH_SELECTOR:Ze.MAX_TAIL_PLAIN;if(z.length>C)return{choices:e,digitSelect:"enter"}}return e.push(...a),{choices:e,digitSelect:p==="\u25CF"?"immediate":"enter"}}});var Su=M(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.StatusDetector=void 0;ki.isAnswerKeystroke=$g;var Ci=xu(),ks={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]},pn={IDLE_TIMEOUT_MS:5e3,DEBOUNCE_MS:500,BUFFER_SIZE:16e3,WORKING_TIMEOUT_MS:3e4,RESOLVE_GRACE_MS:1500,PROMPT_REFRESH_MS:450},oa=class{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 n=this.states.get(e);if(!n)return;n.lastOutput=Date.now(),n.outputBuffer+=t,n.outputBuffer.length>pn.BUFFER_SIZE&&(n.outputBuffer=n.outputBuffer.slice(-pn.BUFFER_SIZE));let i=Date.now()<n.resolveGraceUntil,s=!1;if(!i){let a=this.detectPrompt(n.outputBuffer);if(a&&a.type!=="free-input"&&this.isPromptActive(n.outputBuffer)&&(s=!0,n.pendingPrompt=a,n.status==="waiting")){let c=this.promptKey(a);c!==n.lastSeenPromptKey&&(n.lastSeenPromptKey=c,this.schedulePromptRefresh(e))}}if(s)this.scheduleStatusUpdate(e,"waiting");else if(n.status==="waiting"&&!i){let a=this.analyzeOutput(n.outputBuffer);(a==="completed"||a==="error")&&this.scheduleStatusUpdate(e,a)}else{let a=this.analyzeOutput(n.outputBuffer);a&&this.scheduleStatusUpdate(e,a)}this.resetWorkingTimeout(e,n)}isPromptActive(e){let n=this.normalizeBuffer(this.stripAnsi(e)).split(`
12
- `).map(a=>a.trim()).filter(Boolean);if(n.length===0)return!1;let i=n[n.length-1],s=n.slice(-18).join(`
13
- `);return/[❯›●]/.test(s)||/\[y\/n\]|\(y\/n\)|\[y\/N\]|\(yes\/no\)/i.test(i)||/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 n=this.states.get(e);if(!n)return;n.workingTimeout&&(clearTimeout(n.workingTimeout),n.workingTimeout=null);let i;if(t!==void 0&&t!==0)i="error";else{let s=this.analyzeOutput(n.outputBuffer);s==="waiting"?i="waiting":s==="error"?i="error":s==="completed"?i="completed":i="idle"}this.scheduleStatusUpdate(e,i),(i==="completed"||i==="error")&&setTimeout(()=>{let s=this.states.get(e);s&&(s.status==="completed"||s.status==="error")&&this.scheduleStatusUpdate(e,"idle")},pn.IDLE_TIMEOUT_MS)}analyzeOutput(e){let n=this.normalizeBuffer(this.stripAnsi(e)).split(`
14
- `).slice(-10),i=n.join(`
15
- `),s=(n[n.length-1]||"").trim();for(let a of ks.waiting)if(a.test(s))return"waiting";for(let a of ks.working)if(a.test(s))return"working";for(let a of ks.completed)if(a.test(i))return"completed";for(let a of ks.idle)if(a.test(s))return"idle";return null}detectPrompt(e){let i=this.normalizeBuffer(this.stripAnsi(e)).split(`
16
- `).slice(-20),s=i.join(`
17
- `),a=i[i.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){return(0,Ci.extractNumberedChoices)(e)}extractQuestion(e){return(0,Ci.extractQuestion)(e)}stripAnsi(e){return(0,Ci.stripAnsi)(e)}normalizeBuffer(e){return(0,Ci.normalizeBuffer)(e)}scheduleStatusUpdate(e,t){let n=this.states.get(e);n&&n.status!==t&&n.pendingStatus!==t&&(n.pendingUpdate&&clearTimeout(n.pendingUpdate),n.pendingStatus=t,n.pendingUpdate=setTimeout(()=>{n.pendingStatus=null,this.emitStatus(e,t),n.pendingUpdate=null},pn.DEBOUNCE_MS))}emitStatus(e,t){let n=this.states.get(e);if(!n||n.status===t)return;n.status=t,n.lastUpdate=Date.now();let i;if(t==="waiting"){let s=this.detectPrompt(n.outputBuffer);i=s&&s.type!=="free-input"?s:n.pendingPrompt||s||void 0,n.emittedPromptKey=i?this.promptKey(i):null,n.lastSeenPromptKey=n.emittedPromptKey}else n.pendingPrompt=null,n.emittedPromptKey=null,n.lastSeenPromptKey=null,n.promptRefreshTimer&&(clearTimeout(n.promptRefreshTimer),n.promptRefreshTimer=null);this.onStatusChange(e,t,i)}getEmittedPromptKey(e){return this.states.get(e)?.emittedPromptKey??null}reEmitPrompt(e){let t=this.states.get(e);if(!t)return;let n=this.detectPrompt(t.outputBuffer),i=n&&n.type!=="free-input"?n:t.pendingPrompt||void 0;i&&(t.emittedPromptKey=this.promptKey(i),t.lastSeenPromptKey=t.emittedPromptKey,this.onStatusChange(e,"waiting",i))}promptKey(e){return(0,Ci.promptKey)(e)}schedulePromptRefresh(e){let t=this.states.get(e);t&&(t.promptRefreshTimer&&clearTimeout(t.promptRefreshTimer),t.promptRefreshTimer=setTimeout(()=>{let n=this.states.get(e);if(!n||(n.promptRefreshTimer=null,n.status!=="waiting"||Date.now()<n.resolveGraceUntil))return;let i=this.detectPrompt(n.outputBuffer),s=i&&i.type!=="free-input"?i:n.pendingPrompt;if(!s)return;let a=this.promptKey(s);a!==n.emittedPromptKey&&(n.emittedPromptKey=a,n.lastSeenPromptKey=a,this.onStatusChange(e,"waiting",s))},pn.PROMPT_REFRESH_MS))}resetWorkingTimeout(e,t){t.workingTimeout&&clearTimeout(t.workingTimeout),t.status==="working"&&(t.workingTimeout=setTimeout(()=>{let n=this.states.get(e);n&&n.status==="working"&&(this.analyzeOutput(n.outputBuffer)==="waiting"?this.emitStatus(e,"waiting"):this.onStatusChange(e,"working",void 0))},pn.WORKING_TIMEOUT_MS))}resolvePrompt(e){let t=this.states.get(e);t&&t.status==="waiting"&&(t.resolveGraceUntil=Date.now()+pn.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 n=this.detectPrompt(t.outputBuffer),i=n&&n.type!=="free-input"?n:t.pendingPrompt||void 0;i&&this.onStatusChange(e,"waiting",i)}}getStatus(e){return this.states.get(e)?.status??null}dispose(){for(let e of this.states.keys())this.stopTracking(e)}};ki.StatusDetector=oa;function $g(r){for(let e=0;e<r.length;e++){let t=r.charCodeAt(e);if(t===27){let n=r[e+1];if(n==="["||n==="O"){for(e+=2;e<r.length&&!/[A-Za-z~]/.test(r[e]);)e++;continue}if(n==="]"){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 ku=M((Mv,Cu)=>{var Bn=require("fs"),Tu=require("url"),Gg=require("child_process").spawn;Cu.exports=aa;aa.XMLHttpRequest=aa;function aa(r){"use strict";r=r||{};var e=this,t=require("http"),n=require("https"),i,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,S=!1,T={};this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.readyState=this.UNSENT,this.onreadystatechange=null,this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),this.status=null,this.statusText=null;var H=function(C){return c||C&&p.indexOf(C.toLowerCase())===-1},de=function(C){return C&&m.indexOf(C)===-1};this.open=function(C,D,Q,K,U){if(this.abort(),v=!1,S=!1,!de(C))throw new Error("SecurityError: Request method not allowed");a={method:C,url:D.toString(),async:typeof Q!="boolean"?!0:Q,user:K||null,password:U||null},z(this.OPENED)},this.setDisableHeaderCheck=function(C){c=C},this.setRequestHeader=function(C,D){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!H(C))return console.warn('Refused to set unsafe header "'+C+'"'),!1;if(_)throw new Error("INVALID_STATE_ERR: send flag is true");return d[C]=D,!0},this.getResponseHeader=function(C){return typeof C=="string"&&this.readyState>this.OPENED&&s.headers[C.toLowerCase()]&&!v?s.headers[C.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||v)return"";var C="";for(var D in s.headers)D!=="set-cookie"&&D!=="set-cookie2"&&(C+=D+": "+s.headers[D]+`\r
18
- `);return C.substr(0,C.length-2)},this.getRequestHeader=function(C){return typeof C=="string"&&d[C]?d[C]:""},this.send=function(C){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 D=!1,Q=!1,K=Tu.parse(a.url),U;switch(K.protocol){case"https:":D=!0;case"http:":U=K.hostname;break;case"file:":Q=!0;break;case void 0:case"":U="localhost";break;default:throw new Error("Protocol not supported.")}if(Q){if(a.method!=="GET")throw new Error("XMLHttpRequest: Only GET method is supported");if(a.async)Bn.readFile(unescape(K.pathname),function(R,A){R?e.handleError(R,R.errno||-1):(e.status=200,e.responseText=A.toString("utf8"),e.response=A,z(e.DONE))});else try{this.response=Bn.readFileSync(unescape(K.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,z(e.DONE)}catch(R){this.handleError(R,R.errno||-1)}return}var le=K.port||(D?443:80),pe=K.pathname+(K.search?K.search:"");if(d.Host=U,D&&le===443||le===80||(d.Host+=":"+K.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")C=null;else if(C){d["Content-Length"]=Buffer.isBuffer(C)?C.length:Buffer.byteLength(C);var nt=Object.keys(d);nt.some(function(R){return R.toLowerCase()==="content-type"})||(d["Content-Type"]="text/plain;charset=UTF-8")}else a.method==="POST"&&(d["Content-Length"]=0);var we=r.agent||!1,Se={host:U,port:le,path:pe,method:a.method,headers:d,agent:we};if(D&&(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),v=!1,a.async){var _e=D?n.request:t.request;_=!0,e.dispatchEvent("readystatechange");var We=function(R){if(s=R,s.statusCode===302||s.statusCode===303||s.statusCode===307){a.url=s.headers.location;var A=Tu.parse(a.url);U=A.hostname;var ee={hostname:A.hostname,port:A.port,path:A.path,method:s.statusCode===303?"GET":a.method,headers:d};D&&(ee.pfx=r.pfx,ee.key=r.key,ee.passphrase=r.passphrase,ee.cert=r.cert,ee.ca=r.ca,ee.ciphers=r.ciphers,ee.rejectUnauthorized=r.rejectUnauthorized!==!1),i=_e(ee,We).on("error",at),i.end();return}z(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])}_&&z(e.LOADING)}),s.on("end",function(){_&&(_=!1,z(e.DONE),e.responseText=e.response.toString("utf8"))}),s.on("error",function(Ne){e.handleError(Ne)})},at=function(R){if(i.reusedSocket&&R.code==="ECONNRESET")return _e(Se,We).on("error",at);e.handleError(R)};i=_e(Se,We).on("error",at),r.autoUnref&&i.on("socket",R=>{R.unref()}),C&&i.write(C),i.end(),e.dispatchEvent("loadstart")}else{var Qe=".node-xmlhttprequest-content-"+process.pid,Te=".node-xmlhttprequest-sync-"+process.pid;Bn.writeFileSync(Te,"","utf8");for(var it="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(D?"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('"+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+"');});"+(C?"req.write('"+JSON.stringify(C).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",ze=Gg(process.argv[0],["-e",it]),yt;Bn.existsSync(Te););if(e.responseText=Bn.readFileSync(Qe,"utf8"),ze.stdin.end(),Bn.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 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"),z(e.DONE,!0)}}},this.handleError=function(C,D){this.status=D||0,this.statusText=C,this.responseText=C.stack,v=!0,z(this.DONE)},this.abort=function(){i&&(i.abort(),i=null),d=Object.assign({},u),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),v=S=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||_)&&this.readyState!==this.DONE&&(_=!1,z(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(C,D){C in T||(T[C]=[]),T[C].push(D)},this.removeEventListener=function(C,D){C in T&&(T[C]=T[C].filter(function(Q){return Q!==D}))},this.dispatchEvent=function(C){if(typeof e["on"+C]=="function"&&(this.readyState===this.DONE&&a.async?setTimeout(function(){e["on"+C]()},0):e["on"+C]()),C in T)for(let D=0,Q=T[C].length;D<Q;D++)this.readyState===this.DONE?setTimeout(function(){T[C][D].call(e)},0):T[C][D].call(e)};var z=function(C){if(!(e.readyState===C||e.readyState===e.UNSENT&&S)&&(e.readyState=C,(a.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let D;S?D="abort":v?D="error":D="load",e.dispatchEvent(D),e.dispatchEvent("loadend")}}}});var Os=M(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.ERROR_PACKET=Hr.PACKET_TYPES_REVERSE=Hr.PACKET_TYPES=void 0;var ar=Object.create(null);Hr.PACKET_TYPES=ar;ar.open="0";ar.close="1";ar.ping="2";ar.pong="3";ar.message="4";ar.upgrade="5";ar.noop="6";var Ou=Object.create(null);Hr.PACKET_TYPES_REVERSE=Ou;Object.keys(ar).forEach(r=>{Ou[ar[r]]=r});var Yg={type:"error",data:"parser error"};Hr.ERROR_PACKET=Yg});var Au=M(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.encodePacket=void 0;jn.encodePacketToBinary=Zg;var Xg=Os(),Jg=({type:r,data:e},t,n)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?n(t?e:"b"+Pu(e,!0).toString("base64")):n(Xg.PACKET_TYPES[r]+(e||""));jn.encodePacket=Jg;var Pu=(r,e)=>Buffer.isBuffer(r)||r instanceof Uint8Array&&!e?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength),ca;function Zg(r,e){if(r.data instanceof ArrayBuffer||ArrayBuffer.isView(r.data))return e(Pu(r.data,!1));(0,jn.encodePacket)(r,!0,t=>{ca||(ca=new TextEncoder),e(ca.encode(t))})}});var Iu=M(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});As.decodePacket=void 0;var Ps=Os(),Qg=(r,e)=>{if(typeof r!="string")return{type:"message",data:Ru(r,e)};let t=r.charAt(0);if(t==="b"){let n=Buffer.from(r.substring(1),"base64");return{type:"message",data:Ru(n,e)}}return Ps.PACKET_TYPES_REVERSE[t]?r.length>1?{type:Ps.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:Ps.PACKET_TYPES_REVERSE[t]}:Ps.ERROR_PACKET};As.decodePacket=Qg;var Ru=(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 Un=M(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.decodePayload=wt.decodePacket=wt.encodePayload=wt.encodePacket=wt.protocol=void 0;wt.createPacketEncoderStream=rm;wt.createPacketDecoderStream=nm;var ua=Au();Object.defineProperty(wt,"encodePacket",{enumerable:!0,get:function(){return ua.encodePacket}});var la=Iu();Object.defineProperty(wt,"decodePacket",{enumerable:!0,get:function(){return la.decodePacket}});var Lu=Os(),Nu="",em=(r,e)=>{let t=r.length,n=new Array(t),i=0;r.forEach((s,a)=>{(0,ua.encodePacket)(s,!1,c=>{n[a]=c,++i===t&&e(n.join(Nu))})})};wt.encodePayload=em;var tm=(r,e)=>{let t=r.split(Nu),n=[];for(let i=0;i<t.length;i++){let s=(0,la.decodePacket)(t[i],e);if(n.push(s),s.type==="error")break}return n};wt.decodePayload=tm;function rm(){return new TransformStream({transform(r,e){(0,ua.encodePacketToBinary)(r,t=>{let n=t.length,i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);let s=new DataView(i.buffer);s.setUint8(0,126),s.setUint16(1,n)}else{i=new Uint8Array(9);let s=new DataView(i.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(n))}r.data&&typeof r.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(t)})}})}var fa;function Rs(r){return r.reduce((e,t)=>e+t.length,0)}function Is(r,e){if(r[0].length===e)return r.shift();let t=new Uint8Array(e),n=0;for(let i=0;i<e;i++)t[i]=r[0][n++],n===r[0].length&&(r.shift(),n=0);return r.length&&n<r[0].length&&(r[0]=r[0].slice(n)),t}function nm(r,e){fa||(fa=new TextDecoder);let t=[],n=0,i=-1,s=!1;return new TransformStream({transform(a,c){for(t.push(a);;){if(n===0){if(Rs(t)<1)break;let u=Is(t,1);s=(u[0]&128)===128,i=u[0]&127,i<126?n=3:i===126?n=1:n=2}else if(n===1){if(Rs(t)<2)break;let u=Is(t,2);i=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),n=3}else if(n===2){if(Rs(t)<8)break;let u=Is(t,8),d=new DataView(u.buffer,u.byteOffset,u.length),p=d.getUint32(0);if(p>Math.pow(2,21)-1){c.enqueue(Lu.ERROR_PACKET);break}i=p*Math.pow(2,32)+d.getUint32(4),n=3}else{if(Rs(t)<i)break;let u=Is(t,i);c.enqueue((0,la.decodePacket)(s?u:fa.decode(u),e)),n=0}if(i===0||i>r){c.enqueue(Lu.ERROR_PACKET);break}}}})}wt.protocol=4});var gn=M(Mu=>{Mu.Emitter=Et;function Et(r){if(r)return im(r)}function im(r){for(var e in Et.prototype)r[e]=Et.prototype[e];return r}Et.prototype.on=Et.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};Et.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};Et.prototype.off=Et.prototype.removeListener=Et.prototype.removeAllListeners=Et.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 n,i=0;i<t.length;i++)if(n=t[i],n===e||n.fn===e){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+r],this};Et.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,i=t.length;n<i;++n)t[n].apply(this,e)}return this};Et.prototype.emitReserved=Et.prototype.emit;Et.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};Et.prototype.hasListeners=function(r){return!!this.listeners(r).length}});var mn=M(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.CookieJar=Mt.defaultBinaryType=Mt.globalThisShim=Mt.nextTick=void 0;Mt.createCookieJar=sm;Mt.parse=Fu;Mt.nextTick=process.nextTick;Mt.globalThisShim=global;Mt.defaultBinaryType="nodebuffer";function sm(){return new Ls}function Fu(r){let e=r.split("; "),t=e[0].indexOf("=");if(t===-1)return;let n=e[0].substring(0,t).trim();if(!n.length)return;let i=e[0].substring(t+1).trim();i.charCodeAt(0)===34&&(i=i.slice(1,-1));let s={name:n,value:i};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 Ls=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let n=Fu(t);n&&this._cookies.set(n.name,n)})}get cookies(){let e=Date.now();return this._cookies.forEach((t,n)=>{var i;((i=t.expires)===null||i===void 0?void 0:i.getTime())<e&&this._cookies.delete(n)}),this._cookies.entries()}addCookies(e){let t=[];for(let[n,i]of this.cookies)t.push(`${n}=${i.value}`);t.length&&(e.setDisableHeaderCheck(!0),e.setRequestHeader("cookie",t.join("; ")))}appendCookies(e){for(let[t,n]of this.cookies)e.append("cookie",`${t}=${n.value}`)}};Mt.CookieJar=Ls});var yn=M(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.pick=om;Kn.installTimerFunctions=fm;Kn.byteLength=lm;Kn.randomString=dm;var Vr=mn();function om(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}var am=Vr.globalThisShim.setTimeout,cm=Vr.globalThisShim.clearTimeout;function fm(r,e){e.useNativeTimers?(r.setTimeoutFn=am.bind(Vr.globalThisShim),r.clearTimeoutFn=cm.bind(Vr.globalThisShim)):(r.setTimeoutFn=Vr.globalThisShim.setTimeout.bind(Vr.globalThisShim),r.clearTimeoutFn=Vr.globalThisShim.clearTimeout.bind(Vr.globalThisShim))}var um=1.33;function lm(r){return typeof r=="string"?hm(r):Math.ceil((r.byteLength||r.size)*um)}function hm(r){let e=0,t=0;for(let n=0,i=r.length;n<i;n++)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function dm(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}});var ha=M(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});Ns.encode=pm;Ns.decode=gm;function pm(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function gm(r){let e={},t=r.split("&");for(let n=0,i=t.length;n<i;n++){let s=t[n].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}});var Bu=M((Hv,Du)=>{var qn=1e3,Wn=qn*60,Hn=Wn*60,_n=Hn*24,mm=_n*7,ym=_n*365.25;Du.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return _m(r);if(t==="number"&&isFinite(r))return e.long?bm(r):Em(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function _m(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]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*ym;case"weeks":case"week":case"w":return t*mm;case"days":case"day":case"d":return t*_n;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Hn;case"minutes":case"minute":case"mins":case"min":case"m":return t*Wn;case"seconds":case"second":case"secs":case"sec":case"s":return t*qn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Em(r){var e=Math.abs(r);return e>=_n?Math.round(r/_n)+"d":e>=Hn?Math.round(r/Hn)+"h":e>=Wn?Math.round(r/Wn)+"m":e>=qn?Math.round(r/qn)+"s":r+"ms"}function bm(r){var e=Math.abs(r);return e>=_n?Ms(r,e,_n,"day"):e>=Hn?Ms(r,e,Hn,"hour"):e>=Wn?Ms(r,e,Wn,"minute"):e>=qn?Ms(r,e,qn,"second"):r+" ms"}function Ms(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var da=M((Vv,ju)=>{function vm(r){t.debug=t,t.default=t,t.coerce=u,t.disable=a,t.enable=i,t.enabled=c,t.humanize=Bu(),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,S;function T(...H){if(!T.enabled)return;let de=T,z=Number(new Date),C=z-(m||z);de.diff=C,de.prev=m,de.curr=z,m=z,H[0]=t.coerce(H[0]),typeof H[0]!="string"&&H.unshift("%O");let D=0;H[0]=H[0].replace(/%([a-zA-Z%])/g,(K,U)=>{if(K==="%%")return"%";D++;let le=t.formatters[U];if(typeof le=="function"){let pe=H[D];K=le.call(de,pe),H.splice(D,1),D--}return K}),t.formatArgs.call(de,H),(de.log||t.log).apply(de,H)}return T.namespace=p,T.useColors=t.useColors(),T.color=t.selectColor(p),T.extend=n,T.destroy=t.destroy,Object.defineProperty(T,"enabled",{enumerable:!0,configurable:!1,get:()=>_!==null?_:(v!==t.namespaces&&(v=t.namespaces,S=t.enabled(p)),S),set:H=>{_=H}}),typeof t.init=="function"&&t.init(T),T}function n(p,m){let _=t(this.namespace+(typeof m>"u"?":":m)+p);return _.log=this.log,_}function i(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,S=-1,T=0;for(;_<p.length;)if(v<m.length&&(m[v]===p[_]||m[v]==="*"))m[v]==="*"?(S=v,T=_,v++):(_++,v++);else if(S!==-1)v=S+1,T++,_=T;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}ju.exports=vm});var Uu=M((xt,Fs)=>{xt.formatArgs=xm;xt.save=Sm;xt.load=Tm;xt.useColors=wm;xt.storage=Cm();xt.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`."))}})();xt.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 wm(){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 xm(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Fs.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),r.splice(n,0,e)}xt.log=console.debug||console.log||(()=>{});function Sm(r){try{r?xt.storage.setItem("debug",r):xt.storage.removeItem("debug")}catch{}}function Tm(){let r;try{r=xt.storage.getItem("debug")||xt.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Cm(){try{return localStorage}catch{}}Fs.exports=da()(xt);var{formatters:km}=Fs.exports;km.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var qu=M((zv,Ku)=>{"use strict";Ku.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),i=e.indexOf("--");return n!==-1&&(i===-1||n<i)}});var Vu=M(($v,Hu)=>{"use strict";var Om=require("os"),Wu=require("tty"),Ft=qu(),{env:ct}=process,zr;Ft("no-color")||Ft("no-colors")||Ft("color=false")||Ft("color=never")?zr=0:(Ft("color")||Ft("colors")||Ft("color=true")||Ft("color=always"))&&(zr=1);"FORCE_COLOR"in ct&&(ct.FORCE_COLOR==="true"?zr=1:ct.FORCE_COLOR==="false"?zr=0:zr=ct.FORCE_COLOR.length===0?1:Math.min(parseInt(ct.FORCE_COLOR,10),3));function pa(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function ga(r,e){if(zr===0)return 0;if(Ft("color=16m")||Ft("color=full")||Ft("color=truecolor"))return 3;if(Ft("color=256"))return 2;if(r&&!e&&zr===void 0)return 0;let t=zr||0;if(ct.TERM==="dumb")return t;if(process.platform==="win32"){let n=Om.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in ct)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in ct)||ct.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in ct)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ct.TEAMCITY_VERSION)?1:0;if(ct.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in ct){let n=parseInt((ct.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ct.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ct.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ct.TERM)||"COLORTERM"in ct?1:t}function Pm(r){let e=ga(r,r&&r.isTTY);return pa(e)}Hu.exports={supportsColor:Pm,stdout:pa(ga(!0,Wu.isatty(1))),stderr:pa(ga(!0,Wu.isatty(2)))}});var $u=M((ft,Bs)=>{var Am=require("tty"),Ds=require("util");ft.init=Dm;ft.log=Nm;ft.formatArgs=Im;ft.save=Mm;ft.load=Fm;ft.useColors=Rm;ft.destroy=Ds.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");ft.colors=[6,2,3,4,5,1];try{let r=Vu();r&&(r.stderr||r).level>=2&&(ft.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{}ft.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(i,s)=>s.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function Rm(){return"colors"in ft.inspectOpts?!!ft.inspectOpts.colors:Am.isatty(process.stderr.fd)}function Im(r){let{namespace:e,useColors:t}=this;if(t){let n=this.color,i="\x1B[3"+(n<8?n:"8;5;"+n),s=` ${i};1m${e} \x1B[0m`;r[0]=s+r[0].split(`
9
+ `)}function aa(r){let e=r.replace(/\s+/g," ").trim(),t=We.MAX_QUESTION_LEN;return e.length<=t?e:e.slice(0,t-1).trimEnd()+"\u2026"}function Qg(r){let e=(r.choices||[]).map(t=>`${t.key}=${t.label}`).join("\xA7");return`${r.type}|${r.question}|${e}`}function em(r,e){let t=r.split(`
10
+ `).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=ca(n).replace(/^[\s│┃┊┋┆┇╎╏]+/u,"").replace(/[\s│┃┊┋┆┇╎╏]+$/u,"").replace(/\s+/g," ");if(s.endsWith("?")||s.endsWith(":"))return aa(s.replace(/\s*\[Y\/n\]\s*$/i,"").replace(/\s*\(y\/n\)\s*$/i,"").replace(/\s*\(yes\/no\)\s*$/i,""));for(let a of e||[]){let c=s.match(a);if(c)return aa(c[1]||s)}}return null}function tm(r){let e=[],i=Pu(ca(r)).split(`
11
+ `),n=/^[\s│┃┊┋┆┇╎╏]*(?:[❯▶▸›●>*]\s*)?(?:(\d+)[.)]\s*|\[(\d+)\]\s*)(.+?)[\s│┃]*$/u,s=/^[\s│┃┊┋┆┇╎╏]*([❯▶▸›●])\s*(?:\d+[.)]|\[\d+\])/u,a=[],c=-1,u=-1,h=!1,p="",m=[],_=-1,E=!1,S="",C=z=>z.length*1e3+z.reduce((T,F)=>T+F.label.length,0),H=()=>{m.length>=1&&C(m)>=c&&(a=m.slice(),c=C(m),u=_,h=E,p=S)};for(let z=0;z<i.length;z++){let T=i[z],F=T.match(n);if(!F)continue;let te=F[1]||F[2],U=F[3].replace(/\s+/g," ").trim();if(!te||!U)continue;let ee=U.length>We.MAX_LABEL_LEN?U.slice(0,We.MAX_LABEL_LEN-1)+"\u2026":U,pe=parseInt(te,10),K=T.match(s),Ne=K!==null;pe===m.length+1?(m.push({key:te,label:ee}),_=z,E=E||Ne,K&&(S=K[1])):pe===1?(H(),m=[{key:te,label:ee}],_=z,E=Ne,S=K?K[1]:""):(H(),m=[],_=-1,E=!1,S="")}if(H(),u>=0){let z=i.slice(u+1).filter(F=>F.trim().length>0),T=h?We.MAX_TAIL_WITH_SELECTOR:We.MAX_TAIL_PLAIN;if(z.length>T)return{choices:e,digitSelect:"enter"}}return e.push(...a),{choices:e,digitSelect:p==="\u25CF"?"immediate":"enter"}}});var Ru=L(Bi=>{"use strict";Object.defineProperty(Bi,"__esModule",{value:!0});Bi.StatusDetector=void 0;Bi.isTerminalReplyOnly=rm;Bi.isAnswerKeystroke=im;var pi=Ou(),Ps={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]},Hr={IDLE_TIMEOUT_MS:5e3,DEBOUNCE_MS:500,BUFFER_SIZE:16e3,WORKING_TIMEOUT_MS:3e4,RESOLVE_GRACE_MS:1500,DRIFT_DWELL_MS:2500,PROMPT_REFRESH_MS:450},fa=class{onSignalDivergence;states=new Map;onStatusChange;signalWaitingEnabled;constructor(e,t,i){this.onSignalDivergence=t,this.onStatusChange=e,this.signalWaitingEnabled=i?.signalWaiting!==!1}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,oscCarry:"",signalState:"none",signalAgent:null,agreeWaiting:0,signalOnlyWaiting:0,parserOnlyWaiting:0,lastSignalPair:"",driftTimer:null,signalConfirmedWaiting:!1,parserConfirmedWaiting:!1};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),t.driftTimer&&clearTimeout(t.driftTimer)),this.states.delete(e)}processOutput(e,t){let i=this.states.get(e);if(!i)return;i.lastOutput=Date.now(),this.readTitleSignal(i,t),i.outputBuffer+=t,i.outputBuffer.length>Hr.BUFFER_SIZE&&(i.outputBuffer=i.outputBuffer.slice(-Hr.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.parserConfirmedWaiting=!0,i.pendingPrompt=a,i.status==="waiting")){let c=this.promptKey(a);c!==i.lastSeenPromptKey&&(i.lastSeenPromptKey=c,this.schedulePromptRefresh(e))}}if(this.accountSignal(e,i,s),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(`
12
+ `).map(a=>a.trim()).filter(Boolean);if(i.length===0)return!1;let n=i[i.length-1],s=i.slice(-18).join(`
13
+ `);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")},Hr.IDLE_TIMEOUT_MS)}analyzeOutput(e){let i=this.normalizeBuffer(this.stripAnsi(e)).split(`
14
+ `).slice(-10),n=i.join(`
15
+ `),s=(i[i.length-1]||"").trim();for(let a of Ps.waiting)if(a.test(s))return"waiting";for(let a of Ps.working)if(a.test(s))return"working";for(let a of Ps.completed)if(a.test(n))return"completed";for(let a of Ps.idle)if(a.test(s))return"idle";return null}detectPrompt(e){let n=this.normalizeBuffer(this.stripAnsi(e)).split(`
16
+ `).slice(-20),s=n.join(`
17
+ `),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 h=[/\[Y\/n\]/i,/\[y\/N\]/i,/\(y\/n\)/i,/\(yes\/no\)/i];for(let _ of h)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){return(0,pi.extractNumberedChoices)(e)}extractQuestion(e){return(0,pi.extractQuestion)(e)}stripAnsi(e){return(0,pi.stripAnsi)(e)}normalizeBuffer(e){return(0,pi.normalizeBuffer)(e)}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},Hr.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.signalConfirmedWaiting=!1,i.parserConfirmedWaiting=!1,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){return(0,pi.promptKey)(e)}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))},Hr.PROMPT_REFRESH_MS))}readTitleSignal(e,t){let{seqs:i,carry:n}=(0,pi.scanOsc)(t,e.oscCarry);e.oscCarry=n;for(let s of i){let a=(0,pi.classifyTitle)(s);!a||a.state==="unknown"||(e.signalState=a.state,e.signalAgent=a.agent)}}accountSignal(e,t,i){let n=t.signalState==="waiting",s=`${n?1:0}${i?1:0}`;s!==t.lastSignalPair&&(t.lastSignalPair=s,t.driftTimer&&(clearTimeout(t.driftTimer),t.driftTimer=null),n&&i?t.agreeWaiting++:n?t.driftTimer=setTimeout(()=>{t.driftTimer=null,t.signalOnlyWaiting++,this.onSignalDivergence?.(e,t.signalAgent),this.signalWaitingEnabled&&t.status!=="waiting"&&(Date.now()<t.resolveGraceUntil||(t.signalConfirmedWaiting=!0,t.pendingPrompt={type:"free-input",question:"Waiting for your input"},this.scheduleStatusUpdate(e,"waiting")))},Hr.DRIFT_DWELL_MS):i&&t.parserOnlyWaiting++)}getWaitingSource(e){let t=this.states.get(e);if(!t||t.status!=="waiting")return null;let i=t.signalConfirmedWaiting||t.signalState==="waiting";return t.parserConfirmedWaiting&&i?"both":t.parserConfirmedWaiting?"parser":"signal"}getSignalStats(e){let t=this.states.get(e);return t?{agent:t.signalAgent,state:t.signalState,agreeWaiting:t.agreeWaiting,signalOnlyWaiting:t.signalOnlyWaiting,parserOnlyWaiting:t.parserOnlyWaiting}:null}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))},Hr.WORKING_TIMEOUT_MS))}resolvePrompt(e){let t=this.states.get(e);t&&t.status==="waiting"&&(t.resolveGraceUntil=Date.now()+Hr.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)}};Bi.StatusDetector=fa;function rm(r){return r?/^(?:\x1b\[[0-9]+;[0-9]+R|\x1b\[[?>][0-9;]*c|\x1b\[[0-9;]*n|\x1b\[\?[0-9;]*\$y|\x1b\[[IO]|\x1b\][^\x1b\x07]*(?:\x07|\x1b\\))+$/.test(r):!1}function im(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 Lu=L((Gw,Iu)=>{var ji=require("fs"),Au=require("url"),nm=require("child_process").spawn;Iu.exports=ua;ua.XMLHttpRequest=ua;function ua(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:"*/*"},h=Object.assign({},u),p=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","content-transfer-encoding","cookie","cookie2","date","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"],m=["TRACE","TRACK","CONNECT"],_=!1,E=!1,S=!1,C={};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(T){return c||T&&p.indexOf(T.toLowerCase())===-1},ne=function(T){return T&&m.indexOf(T)===-1};this.open=function(T,F,te,U,ee){if(this.abort(),E=!1,S=!1,!ne(T))throw new Error("SecurityError: Request method not allowed");a={method:T,url:F.toString(),async:typeof te!="boolean"?!0:te,user:U||null,password:ee||null},z(this.OPENED)},this.setDisableHeaderCheck=function(T){c=T},this.setRequestHeader=function(T,F){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!H(T))return console.warn('Refused to set unsafe header "'+T+'"'),!1;if(_)throw new Error("INVALID_STATE_ERR: send flag is true");return h[T]=F,!0},this.getResponseHeader=function(T){return typeof T=="string"&&this.readyState>this.OPENED&&s.headers[T.toLowerCase()]&&!E?s.headers[T.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||E)return"";var T="";for(var F in s.headers)F!=="set-cookie"&&F!=="set-cookie2"&&(T+=F+": "+s.headers[F]+`\r
18
+ `);return T.substr(0,T.length-2)},this.getRequestHeader=function(T){return typeof T=="string"&&h[T]?h[T]:""},this.send=function(T){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 F=!1,te=!1,U=Au.parse(a.url),ee;switch(U.protocol){case"https:":F=!0;case"http:":ee=U.hostname;break;case"file:":te=!0;break;case void 0:case"":ee="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)ji.readFile(unescape(U.pathname),function(A,se){A?e.handleError(A,A.errno||-1):(e.status=200,e.responseText=se.toString("utf8"),e.response=se,z(e.DONE))});else try{this.response=ji.readFileSync(unescape(U.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,z(e.DONE)}catch(A){this.handleError(A,A.errno||-1)}return}var pe=U.port||(F?443:80),K=U.pathname+(U.search?U.search:"");if(h.Host=ee,F&&pe===443||pe===80||(h.Host+=":"+U.port),a.user){typeof a.password>"u"&&(a.password="");var Ne=new Buffer(a.user+":"+a.password);h.Authorization="Basic "+Ne.toString("base64")}if(a.method==="GET"||a.method==="HEAD")T=null;else if(T){h["Content-Length"]=Buffer.isBuffer(T)?T.length:Buffer.byteLength(T);var tt=Object.keys(h);tt.some(function(A){return A.toLowerCase()==="content-type"})||(h["Content-Type"]="text/plain;charset=UTF-8")}else a.method==="POST"&&(h["Content-Length"]=0);var Se=r.agent||!1,Me={host:ee,port:pe,path:K,method:a.method,headers:h,agent:Se};if(F&&(Me.pfx=r.pfx,Me.key=r.key,Me.passphrase=r.passphrase,Me.cert=r.cert,Me.ca=r.ca,Me.ciphers=r.ciphers,Me.rejectUnauthorized=r.rejectUnauthorized!==!1),E=!1,a.async){var ve=F?i.request:t.request;_=!0,e.dispatchEvent("readystatechange");var Ke=function(A){if(s=A,s.statusCode===302||s.statusCode===303||s.statusCode===307){a.url=s.headers.location;var se=Au.parse(a.url);ee=se.hostname;var Pe={hostname:se.hostname,port:se.port,path:se.path,method:s.statusCode===303?"GET":a.method,headers:h};F&&(Pe.pfx=r.pfx,Pe.key=r.key,Pe.passphrase=r.passphrase,Pe.cert=r.cert,Pe.ca=r.ca,Pe.ciphers=r.ciphers,Pe.rejectUnauthorized=r.rejectUnauthorized!==!1),n=ve(Pe,Ke).on("error",Ee),n.end();return}z(e.HEADERS_RECEIVED),e.status=s.statusCode,s.on("data",function(j){if(j){var ue=Buffer.from(j);e.response=Buffer.concat([e.response,ue])}_&&z(e.LOADING)}),s.on("end",function(){_&&(_=!1,z(e.DONE),e.responseText=e.response.toString("utf8"))}),s.on("error",function(j){e.handleError(j)})},Ee=function(A){if(n.reusedSocket&&A.code==="ECONNRESET")return ve(Me,Ke).on("error",Ee);e.handleError(A)};n=ve(Me,Ke).on("error",Ee),r.autoUnref&&n.on("socket",A=>{A.unref()}),T&&n.write(T),n.end(),e.dispatchEvent("loadstart")}else{var rt=".node-xmlhttprequest-content-"+process.pid,Fe=".node-xmlhttprequest-sync-"+process.pid;ji.writeFileSync(Fe,"","utf8");for(var yt="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(F?"s":"")+".request;var options = "+JSON.stringify(Me)+";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('"+rt+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+Fe+"');});response.on('error', function(error) {fs.writeFileSync('"+rt+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Fe+"');});}).on('error', function(error) {fs.writeFileSync('"+rt+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Fe+"');});"+(T?"req.write('"+JSON.stringify(T).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",qe=nm(process.argv[0],["-e",yt]),dt;ji.existsSync(Fe););if(e.responseText=ji.readFileSync(rt,"utf8"),qe.stdin.end(),ji.unlinkSync(rt),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var I=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(I,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var B=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));s={statusCode:e.status,headers:B.data.headers},e.responseText=B.data.text,e.response=Buffer.from(B.data.data,"base64"),z(e.DONE,!0)}}},this.handleError=function(T,F){this.status=F||0,this.statusText=T,this.responseText=T.stack,E=!0,z(this.DONE)},this.abort=function(){n&&(n.abort(),n=null),h=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,z(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(T,F){T in C||(C[T]=[]),C[T].push(F)},this.removeEventListener=function(T,F){T in C&&(C[T]=C[T].filter(function(te){return te!==F}))},this.dispatchEvent=function(T){if(typeof e["on"+T]=="function"&&(this.readyState===this.DONE&&a.async?setTimeout(function(){e["on"+T]()},0):e["on"+T]()),T in C)for(let F=0,te=C[T].length;F<te;F++)this.readyState===this.DONE?setTimeout(function(){C[T][F].call(e)},0):C[T][F].call(e)};var z=function(T){if(!(e.readyState===T||e.readyState===e.UNSENT&&S)&&(e.readyState=T,(a.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let F;S?F="abort":E?F="error":F="load",e.dispatchEvent(F),e.dispatchEvent("loadend")}}}});var Os=L(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.ERROR_PACKET=Vr.PACKET_TYPES_REVERSE=Vr.PACKET_TYPES=void 0;var ur=Object.create(null);Vr.PACKET_TYPES=ur;ur.open="0";ur.close="1";ur.ping="2";ur.pong="3";ur.message="4";ur.upgrade="5";ur.noop="6";var Nu=Object.create(null);Vr.PACKET_TYPES_REVERSE=Nu;Object.keys(ur).forEach(r=>{Nu[ur[r]]=r});var sm={type:"error",data:"parser error"};Vr.ERROR_PACKET=sm});var Fu=L(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.encodePacket=void 0;Ui.encodePacketToBinary=cm;var om=Os(),am=({type:r,data:e},t,i)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?i(t?e:"b"+Mu(e,!0).toString("base64")):i(om.PACKET_TYPES[r]+(e||""));Ui.encodePacket=am;var Mu=(r,e)=>Buffer.isBuffer(r)||r instanceof Uint8Array&&!e?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength),la;function cm(r,e){if(r.data instanceof ArrayBuffer||ArrayBuffer.isView(r.data))return e(Mu(r.data,!1));(0,Ui.encodePacket)(r,!0,t=>{la||(la=new TextEncoder),e(la.encode(t))})}});var Bu=L(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});As.decodePacket=void 0;var Rs=Os(),fm=(r,e)=>{if(typeof r!="string")return{type:"message",data:Du(r,e)};let t=r.charAt(0);if(t==="b"){let i=Buffer.from(r.substring(1),"base64");return{type:"message",data:Du(i,e)}}return Rs.PACKET_TYPES_REVERSE[t]?r.length>1?{type:Rs.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:Rs.PACKET_TYPES_REVERSE[t]}:Rs.ERROR_PACKET};As.decodePacket=fm;var Du=(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 Ki=L(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.decodePayload=xt.decodePacket=xt.encodePayload=xt.encodePacket=xt.protocol=void 0;xt.createPacketEncoderStream=hm;xt.createPacketDecoderStream=dm;var da=Fu();Object.defineProperty(xt,"encodePacket",{enumerable:!0,get:function(){return da.encodePacket}});var pa=Bu();Object.defineProperty(xt,"decodePacket",{enumerable:!0,get:function(){return pa.decodePacket}});var ju=Os(),Uu="",um=(r,e)=>{let t=r.length,i=new Array(t),n=0;r.forEach((s,a)=>{(0,da.encodePacket)(s,!1,c=>{i[a]=c,++n===t&&e(i.join(Uu))})})};xt.encodePayload=um;var lm=(r,e)=>{let t=r.split(Uu),i=[];for(let n=0;n<t.length;n++){let s=(0,pa.decodePacket)(t[n],e);if(i.push(s),s.type==="error")break}return i};xt.decodePayload=lm;function hm(){return new TransformStream({transform(r,e){(0,da.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 ha;function Is(r){return r.reduce((e,t)=>e+t.length,0)}function Ls(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 dm(r,e){ha||(ha=new TextDecoder);let t=[],i=0,n=-1,s=!1;return new TransformStream({transform(a,c){for(t.push(a);;){if(i===0){if(Is(t)<1)break;let u=Ls(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(Is(t)<2)break;let u=Ls(t,2);n=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),i=3}else if(i===2){if(Is(t)<8)break;let u=Ls(t,8),h=new DataView(u.buffer,u.byteOffset,u.length),p=h.getUint32(0);if(p>Math.pow(2,21)-1){c.enqueue(ju.ERROR_PACKET);break}n=p*Math.pow(2,32)+h.getUint32(4),i=3}else{if(Is(t)<n)break;let u=Ls(t,n);c.enqueue((0,pa.decodePacket)(s?u:ha.decode(u),e)),i=0}if(n===0||n>r){c.enqueue(ju.ERROR_PACKET);break}}}})}xt.protocol=4});var gi=L(Ku=>{Ku.Emitter=Et;function Et(r){if(r)return pm(r)}function pm(r){for(var e in Et.prototype)r[e]=Et.prototype[e];return r}Et.prototype.on=Et.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};Et.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};Et.prototype.off=Et.prototype.removeListener=Et.prototype.removeAllListeners=Et.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};Et.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};Et.prototype.emitReserved=Et.prototype.emit;Et.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};Et.prototype.hasListeners=function(r){return!!this.listeners(r).length}});var mi=L(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.CookieJar=Dt.defaultBinaryType=Dt.globalThisShim=Dt.nextTick=void 0;Dt.createCookieJar=gm;Dt.parse=qu;Dt.nextTick=process.nextTick;Dt.globalThisShim=global;Dt.defaultBinaryType="nodebuffer";function gm(){return new Ns}function qu(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(),h=c[1].trim();switch(u){case"Expires":s.expires=new Date(h);break;case"Max-Age":let p=new Date;p.setUTCSeconds(p.getUTCSeconds()+parseInt(h,10)),s.expires=p;break;default:}}return s}var Ns=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let i=qu(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}`)}};Dt.CookieJar=Ns});var yi=L(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});qi.pick=mm;qi.installTimerFunctions=bm;qi.byteLength=wm;qi.randomString=xm;var $r=mi();function mm(r,...e){return e.reduce((t,i)=>(r.hasOwnProperty(i)&&(t[i]=r[i]),t),{})}var ym=$r.globalThisShim.setTimeout,_m=$r.globalThisShim.clearTimeout;function bm(r,e){e.useNativeTimers?(r.setTimeoutFn=ym.bind($r.globalThisShim),r.clearTimeoutFn=_m.bind($r.globalThisShim)):(r.setTimeoutFn=$r.globalThisShim.setTimeout.bind($r.globalThisShim),r.clearTimeoutFn=$r.globalThisShim.clearTimeout.bind($r.globalThisShim))}var Em=1.33;function wm(r){return typeof r=="string"?vm(r):Math.ceil((r.byteLength||r.size)*Em)}function vm(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 xm(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}});var ga=L(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.encode=Sm;Ms.decode=Tm;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 Tm(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 Hu=L((iv,Wu)=>{var Wi=1e3,Hi=Wi*60,Vi=Hi*60,_i=Vi*24,Cm=_i*7,km=_i*365.25;Wu.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return Pm(r);if(t==="number"&&isFinite(r))return e.long?Rm(r):Om(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Pm(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*km;case"weeks":case"week":case"w":return t*Cm;case"days":case"day":case"d":return t*_i;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Vi;case"minutes":case"minute":case"mins":case"min":case"m":return t*Hi;case"seconds":case"second":case"secs":case"sec":case"s":return t*Wi;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Om(r){var e=Math.abs(r);return e>=_i?Math.round(r/_i)+"d":e>=Vi?Math.round(r/Vi)+"h":e>=Hi?Math.round(r/Hi)+"m":e>=Wi?Math.round(r/Wi)+"s":r+"ms"}function Rm(r){var e=Math.abs(r);return e>=_i?Fs(r,e,_i,"day"):e>=Vi?Fs(r,e,Vi,"hour"):e>=Hi?Fs(r,e,Hi,"minute"):e>=Wi?Fs(r,e,Wi,"second"):r+" ms"}function Fs(r,e,t,i){var n=e>=t*1.5;return Math.round(r/t)+" "+i+(n?"s":"")}});var ma=L((nv,Vu)=>{function Am(r){t.debug=t,t.default=t,t.coerce=u,t.disable=a,t.enable=n,t.enabled=c,t.humanize=Hu(),t.destroy=h,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 C(...H){if(!C.enabled)return;let ne=C,z=Number(new Date),T=z-(m||z);ne.diff=T,ne.prev=m,ne.curr=z,m=z,H[0]=t.coerce(H[0]),typeof H[0]!="string"&&H.unshift("%O");let F=0;H[0]=H[0].replace(/%([a-zA-Z%])/g,(U,ee)=>{if(U==="%%")return"%";F++;let pe=t.formatters[ee];if(typeof pe=="function"){let K=H[F];U=pe.call(ne,K),H.splice(F,1),F--}return U}),t.formatArgs.call(ne,H),(ne.log||t.log).apply(ne,H)}return C.namespace=p,C.useColors=t.useColors(),C.color=t.selectColor(p),C.extend=i,C.destroy=t.destroy,Object.defineProperty(C,"enabled",{enumerable:!0,configurable:!1,get:()=>_!==null?_:(E!==t.namespaces&&(E=t.namespaces,S=t.enabled(p)),S),set:H=>{_=H}}),typeof t.init=="function"&&t.init(C),C}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,C=0;for(;_<p.length;)if(E<m.length&&(m[E]===p[_]||m[E]==="*"))m[E]==="*"?(S=E,C=_,E++):(_++,E++);else if(S!==-1)E=S+1,C++,_=C;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 h(){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}Vu.exports=Am});var $u=L((St,Ds)=>{St.formatArgs=Lm;St.save=Nm;St.load=Mm;St.useColors=Im;St.storage=Fm();St.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`."))}})();St.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 Im(){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 Lm(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ds.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)}St.log=console.debug||console.log||(()=>{});function Nm(r){try{r?St.storage.setItem("debug",r):St.storage.removeItem("debug")}catch{}}function Mm(){let r;try{r=St.storage.getItem("debug")||St.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Fm(){try{return localStorage}catch{}}Ds.exports=ma()(St);var{formatters:Dm}=Ds.exports;Dm.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Gu=L((sv,zu)=>{"use strict";zu.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=L((ov,Xu)=>{"use strict";var Bm=require("os"),Yu=require("tty"),Bt=Gu(),{env:ct}=process,zr;Bt("no-color")||Bt("no-colors")||Bt("color=false")||Bt("color=never")?zr=0:(Bt("color")||Bt("colors")||Bt("color=true")||Bt("color=always"))&&(zr=1);"FORCE_COLOR"in ct&&(ct.FORCE_COLOR==="true"?zr=1:ct.FORCE_COLOR==="false"?zr=0:zr=ct.FORCE_COLOR.length===0?1:Math.min(parseInt(ct.FORCE_COLOR,10),3));function ya(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function _a(r,e){if(zr===0)return 0;if(Bt("color=16m")||Bt("color=full")||Bt("color=truecolor"))return 3;if(Bt("color=256"))return 2;if(r&&!e&&zr===void 0)return 0;let t=zr||0;if(ct.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 ct)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(i=>i in ct)||ct.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in ct)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ct.TEAMCITY_VERSION)?1:0;if(ct.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in ct){let i=parseInt((ct.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ct.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ct.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ct.TERM)||"COLORTERM"in ct?1:t}function jm(r){let e=_a(r,r&&r.isTTY);return ya(e)}Xu.exports={supportsColor:jm,stdout:ya(_a(!0,Yu.isatty(1))),stderr:ya(_a(!0,Yu.isatty(2)))}});var Qu=L((ft,js)=>{var Um=require("tty"),Bs=require("util");ft.init=zm;ft.log=Hm;ft.formatArgs=qm;ft.save=Vm;ft.load=$m;ft.useColors=Km;ft.destroy=Bs.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");ft.colors=[6,2,3,4,5,1];try{let r=Ju();r&&(r.stderr||r).level>=2&&(ft.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{}ft.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 Km(){return"colors"in ft.inspectOpts?!!ft.inspectOpts.colors:Um.isatty(process.stderr.fd)}function qm(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(i+"m+"+Bs.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=Lm()+e+" "+r[0]}function Lm(){return ft.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Nm(...r){return process.stderr.write(Ds.formatWithOptions(ft.inspectOpts,...r)+`
21
- `)}function Mm(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function Fm(){return process.env.DEBUG}function Dm(r){r.inspectOpts={};let e=Object.keys(ft.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=ft.inspectOpts[e[t]]}Bs.exports=da()(ft);var{formatters:zu}=Bs.exports;zu.o=function(r){return this.inspectOpts.colors=this.useColors,Ds.inspect(r,this.inspectOpts).split(`
22
- `).map(e=>e.trim()).join(" ")};zu.O=function(r){return this.inspectOpts.colors=this.useColors,Ds.inspect(r,this.inspectOpts)}});var Dt=M((Gv,ma)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?ma.exports=Uu():ma.exports=$u()});var Oi=M($r=>{"use strict";var Bm=$r&&$r.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty($r,"__esModule",{value:!0});$r.Transport=$r.TransportError=void 0;var jm=Un(),Um=gn(),Km=yn(),qm=ha(),Wm=Bm(Dt()),Hm=(0,Wm.default)("engine.io-client:transport"),js=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}};$r.TransportError=js;var ya=class extends Um.Emitter{constructor(e){super(),this.writable=!1,(0,Km.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new js(e,t,n)),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):Hm("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=(0,jm.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,qm.encode)(e);return t.length?"?"+t:""}};$r.Transport=ya});var Ea=M(Vn=>{"use strict";var Vm=Vn&&Vn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Vn,"__esModule",{value:!0});Vn.Polling=void 0;var zm=Oi(),$m=yn(),Gu=Un(),Gm=Vm(Dt()),Vt=(0,Gm.default)("engine.io-client:polling"),_a=class extends zm.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{Vt("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let n=0;this._polling&&(Vt("we are currently polling - waiting to pause"),n++,this.once("pollComplete",function(){Vt("pre-pause polling complete"),--n||t()})),this.writable||(Vt("we are currently writing - waiting to pause"),n++,this.once("drain",function(){Vt("pre-pause writing complete"),--n||t()}))}else t()}_poll(){Vt("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Vt("polling got data %s",e);let t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};(0,Gu.decodePayload)(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Vt('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{Vt("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Vt("transport open - closing"),e()):(Vt("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,Gu.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,$m.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};Vn.Polling=_a});var Xu=M(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});Us.hasCORS=void 0;var Yu=!1;try{Yu=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}Us.hasCORS=Yu});var wa=M(cr=>{"use strict";var Ym=cr&&cr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(cr,"__esModule",{value:!0});cr.XHR=cr.Request=cr.BaseXHR=void 0;var Xm=Ea(),Jm=gn(),Ju=yn(),Qu=mn(),Zm=Xu(),Qm=Ym(Dt()),ba=(0,Qm.default)("engine.io-client:polling");function ey(){}var Ks=class extends Xm.Polling{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(i,s)=>{this.onError("xhr post error",i,s)})}doPoll(){ba("xhr poll");let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}};cr.BaseXHR=Ks;var Cr=class r extends Jm.Emitter{constructor(e,t,n){super(),this.createRequest=e,(0,Ju.installTimerFunctions)(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var e;let t=(0,Ju.pick)(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let n=this._xhr=this.createRequest(t);try{ba("xhr open %s: %s",this._method,this._uri),n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&n.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var i;n.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},ba("xhr data %s",this._data),n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},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=ey,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()}};cr.Request=Cr;Cr.requestsCount=0;Cr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Zu);else if(typeof addEventListener=="function"){let r="onpagehide"in Qu.globalThisShim?"pagehide":"unload";addEventListener(r,Zu,!1)}}function Zu(){for(let r in Cr.requests)Cr.requests.hasOwnProperty(r)&&Cr.requests[r].abort()}var ty=(function(){let r=el({xdomain:!1});return r&&r.responseType!==null})(),va=class extends Ks{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=ty&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Cr(el,this.uri(),e)}};cr.XHR=va;function el(r){let e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Zm.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new Qu.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}});var Sa=M(fr=>{"use strict";var ry=fr&&fr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),ny=fr&&fr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),iy=fr&&fr.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&ry(e,r,t);return ny(e,r),e};Object.defineProperty(fr,"__esModule",{value:!0});fr.XHR=void 0;var tl=iy(ku()),rl=wa(),sy=tl.default||tl,xa=class extends rl.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 rl.Request(n=>new sy(n),this.uri(),e)}};fr.XHR=xa});var kr=M((ew,sl)=>{"use strict";var nl=["nodebuffer","arraybuffer","fragments"],il=typeof Blob<"u";il&&nl.push("blob");sl.exports={BINARY_TYPES:nl,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:il,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Pi=M((tw,qs)=>{"use strict";var{EMPTY_BUFFER:oy}=kr(),Ta=Buffer[Symbol.species];function ay(r,e){if(r.length===0)return oy;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let i=0;i<r.length;i++){let s=r[i];t.set(s,n),n+=s.length}return n<e?new Ta(t.buffer,t.byteOffset,n):t}function ol(r,e,t,n,i){for(let s=0;s<i;s++)t[n+s]=r[s]^e[s&3]}function al(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function cy(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Ca(r){if(Ca.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Ta(r):ArrayBuffer.isView(r)?e=new Ta(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Ca.readOnly=!1),e}qs.exports={concat:ay,mask:ol,toArrayBuffer:cy,toBuffer:Ca,unmask:al};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");qs.exports.mask=function(e,t,n,i,s){s<48?ol(e,t,n,i,s):r.mask(e,t,n,i,s)},qs.exports.unmask=function(e,t){e.length<32?al(e,t):r.unmask(e,t)}}catch{}});var ul=M((rw,fl)=>{"use strict";var cl=Symbol("kDone"),ka=Symbol("kRun"),Oa=class{constructor(e){this[cl]=()=>{this.pending--,this[ka]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ka]()}[ka](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[cl])}}};fl.exports=Oa});var Ri=M((nw,pl)=>{"use strict";var Ai=require("zlib"),ll=Pi(),fy=ul(),{kStatusCode:hl}=kr(),uy=Buffer[Symbol.species],ly=Buffer.from([0,0,255,255]),Hs=Symbol("permessage-deflate"),Or=Symbol("total-length"),zn=Symbol("callback"),Gr=Symbol("buffers"),$n=Symbol("error"),Ws,Pa=class{constructor(e,t,n){if(this._maxPayload=n|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,!Ws){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ws=new fy(i)}}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[zn];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,n=e.find(i=>!(t.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>i.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}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(n=>{let i=t[n];if(i.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(i=i[0],n==="client_max_window_bits"){if(i!==!0){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else if(n==="server_max_window_bits"){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=s}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=i})}),e}decompress(e,t,n){Ws.add(i=>{this._decompress(e,t,(s,a)=>{i(),n(s,a)})})}compress(e,t,n){Ws.add(i=>{this._compress(e,t,(s,a)=>{i(),n(s,a)})})}_decompress(e,t,n){let i=this._isServer?"client":"server";if(!this._inflate){let s=`${i}_max_window_bits`,a=typeof this.params[s]!="number"?Ai.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=Ai.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[Hs]=this,this._inflate[Or]=0,this._inflate[Gr]=[],this._inflate.on("error",dy),this._inflate.on("data",dl)}this._inflate[zn]=n,this._inflate.write(e),t&&this._inflate.write(ly),this._inflate.flush(()=>{let s=this._inflate[$n];if(s){this._inflate.close(),this._inflate=null,n(s);return}let a=ll.concat(this._inflate[Gr],this._inflate[Or]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Or]=0,this._inflate[Gr]=[],t&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),n(null,a)})}_compress(e,t,n){let i=this._isServer?"server":"client";if(!this._deflate){let s=`${i}_max_window_bits`,a=typeof this.params[s]!="number"?Ai.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=Ai.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[Or]=0,this._deflate[Gr]=[],this._deflate.on("data",hy)}this._deflate[zn]=n,this._deflate.write(e),this._deflate.flush(Ai.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=ll.concat(this._deflate[Gr],this._deflate[Or]);t&&(s=new uy(s.buffer,s.byteOffset,s.length-4)),this._deflate[zn]=null,this._deflate[Or]=0,this._deflate[Gr]=[],t&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),n(null,s)})}};pl.exports=Pa;function hy(r){this[Gr].push(r),this[Or]+=r.length}function dl(r){if(this[Or]+=r.length,this[Hs]._maxPayload<1||this[Or]<=this[Hs]._maxPayload){this[Gr].push(r);return}this[$n]=new RangeError("Max payload size exceeded"),this[$n].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[$n][hl]=1009,this.removeListener("data",dl),this.reset()}function dy(r){if(this[Hs]._inflate=null,this[$n]){this[zn](this[$n]);return}r[hl]=1007,this[zn](r)}});var Gn=M((iw,Vs)=>{"use strict";var{isUtf8:gl}=require("buffer"),{hasBlob:py}=kr(),gy=[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 my(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Aa(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 yy(r){return py&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Vs.exports={isBlob:yy,isValidStatusCode:my,isValidUTF8:Aa,tokenChars:gy};if(gl)Vs.exports.isValidUTF8=function(r){return r.length<24?Aa(r):gl(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Vs.exports.isValidUTF8=function(e){return e.length<32?Aa(e):r(e)}}catch{}});var Ma=M((sw,wl)=>{"use strict";var{Writable:_y}=require("stream"),ml=Ri(),{BINARY_TYPES:Ey,EMPTY_BUFFER:yl,kStatusCode:by,kWebSocket:vy}=kr(),{concat:Ra,toArrayBuffer:wy,unmask:xy}=Pi(),{isValidStatusCode:Sy,isValidUTF8:_l}=Gn(),zs=Buffer[Symbol.species],Bt=0,El=1,bl=2,vl=3,Ia=4,La=5,$s=6,Na=class extends _y{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Ey[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[vy]=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=Bt}_write(e,t,n){if(this._opcode===8&&this._state==Bt)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new zs(n.buffer,n.byteOffset+e,n.length-e),new zs(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],i=t.length-e;e>=n.length?t.set(this._buffers.shift(),i):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),i),this._buffers[0]=new zs(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Bt:this.getInfo(e);break;case El:this.getPayloadLength16(e);break;case bl:this.getPayloadLength64(e);break;case vl:this.getMask();break;case Ia:this.getData(e);break;case La:case $s: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 i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let n=(t[0]&64)===64;if(n&&!this._extensions[ml.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=El:this._payloadLength===127?this._state=bl: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),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=n*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=vl:this._state=Ia}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ia}getData(e){let t=yl;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&&xy(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=La,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[ml.extensionName].decompress(e,this._fin,(i,s)=>{if(i)return t(i);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===Bt&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Bt;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=Ra(n,t):this._binaryType==="arraybuffer"?i=wy(Ra(n,t)):this._binaryType==="blob"?i=new Blob(n):i=n,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=Bt):(this._state=$s,setImmediate(()=>{this.emit("message",i,!0),this._state=Bt,this.startLoop(e)}))}else{let i=Ra(n,t);if(!this._skipUTF8Validation&&!_l(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===La||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=Bt):(this._state=$s,setImmediate(()=>{this.emit("message",i,!1),this._state=Bt,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,yl),this.end();else{let n=e.readUInt16BE(0);if(!Sy(n)){let s=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(s);return}let i=new zs(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!_l(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(s);return}this._loop=!1,this.emit("conclude",n,i),this.end()}this._state=Bt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Bt):(this._state=$s,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Bt,this.startLoop(t)}))}createError(e,t,n,i,s){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=s,a[by]=i,a}};wl.exports=Na});var Ba=M((aw,Tl)=>{"use strict";var{Duplex:ow}=require("stream"),{randomFillSync:Ty}=require("crypto"),xl=Ri(),{EMPTY_BUFFER:Cy,kWebSocket:ky,NOOP:Oy}=kr(),{isBlob:Yn,isValidStatusCode:Py}=Gn(),{mask:Sl,toBuffer:En}=Pi(),jt=Symbol("kByteLength"),Ay=Buffer.alloc(4),Gs=8*1024,bn,Xn=Gs,zt=0,Ry=1,Iy=2,Fa=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=zt,this.onerror=Oy,this[ky]=void 0}static frame(e,t){let n,i=!1,s=2,a=!1;t.mask&&(n=t.maskBuffer||Ay,t.generateMask?t.generateMask(n):(Xn===Gs&&(bn===void 0&&(bn=Buffer.alloc(Gs)),Ty(bn,0,Gs),Xn=0),n[0]=bn[Xn++],n[1]=bn[Xn++],n[2]=bn[Xn++],n[3]=bn[Xn++]),a=(n[0]|n[1]|n[2]|n[3])===0,s=6);let c;typeof e=="string"?(!t.mask||a)&&t[jt]!==void 0?c=t[jt]:(e=Buffer.from(e),c=e.length):(c=e.length,i=t.mask&&t.readOnly&&!a);let u=c;c>=65536?(s+=8,u=127):c>125&&(s+=2,u=126);let d=Buffer.allocUnsafe(i?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]=n[0],d[s-3]=n[1],d[s-2]=n[2],d[s-1]=n[3],a?[d,e]:i?(Sl(e,n,d,s,c),[d]):(Sl(e,n,e,0,c),[d,e])):[d,e]}close(e,t,n,i){let s;if(e===void 0)s=Cy;else{if(typeof e!="number"||!Py(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={[jt]:s.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==zt?this.enqueue([this.dispatch,s,!1,a,i]):this.sendFrame(r.frame(s,a),i)}ping(e,t,n){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):Yn(e)?(i=e.size,s=!1):(e=En(e),i=e.length,s=En.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[jt]:i,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};Yn(e)?this._state!==zt?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==zt?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}pong(e,t,n){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):Yn(e)?(i=e.size,s=!1):(e=En(e),i=e.length,s=En.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[jt]:i,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};Yn(e)?this._state!==zt?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==zt?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}send(e,t,n){let i=this._extensions[xl.extensionName],s=t.binary?2:1,a=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):Yn(e)?(c=e.size,u=!1):(e=En(e),c=e.length,u=En.readOnly),this._firstFragment?(this._firstFragment=!1,a&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=c>=i._threshold),this._compress=a):(a=!1,s=0),t.fin&&(this._firstFragment=!0);let d={[jt]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:u,rsv1:a};Yn(e)?this._state!==zt?this.enqueue([this.getBlobData,e,this._compress,d,n]):this.getBlobData(e,this._compress,d,n):this._state!==zt?this.enqueue([this.dispatch,e,this._compress,d,n]):this.dispatch(e,this._compress,d,n)}getBlobData(e,t,n,i){this._bufferedBytes+=n[jt],this._state=Iy,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(Da,this,c,i);return}this._bufferedBytes-=n[jt];let a=En(s);t?this.dispatch(a,t,n,i):(this._state=zt,this.sendFrame(r.frame(a,n),i),this.dequeue())}).catch(s=>{process.nextTick(Ly,this,s,i)})}dispatch(e,t,n,i){if(!t){this.sendFrame(r.frame(e,n),i);return}let s=this._extensions[xl.extensionName];this._bufferedBytes+=n[jt],this._state=Ry,s.compress(e,n.fin,(a,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");Da(this,u,i);return}this._bufferedBytes-=n[jt],this._state=zt,n.readOnly=!1,this.sendFrame(r.frame(c,n),i),this.dequeue()})}dequeue(){for(;this._state===zt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][jt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][jt],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)}};Tl.exports=Fa;function Da(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let i=r._queue[n],s=i[i.length-1];typeof s=="function"&&s(e)}}function Ly(r,e,t){Da(r,e,t),r.onerror(e)}});var Nl=M((cw,Ll)=>{"use strict";var{kForOnEventAttribute:Ii,kListener:ja}=kr(),Cl=Symbol("kCode"),kl=Symbol("kData"),Ol=Symbol("kError"),Pl=Symbol("kMessage"),Al=Symbol("kReason"),Jn=Symbol("kTarget"),Rl=Symbol("kType"),Il=Symbol("kWasClean"),Pr=class{constructor(e){this[Jn]=null,this[Rl]=e}get target(){return this[Jn]}get type(){return this[Rl]}};Object.defineProperty(Pr.prototype,"target",{enumerable:!0});Object.defineProperty(Pr.prototype,"type",{enumerable:!0});var vn=class extends Pr{constructor(e,t={}){super(e),this[Cl]=t.code===void 0?0:t.code,this[Al]=t.reason===void 0?"":t.reason,this[Il]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Cl]}get reason(){return this[Al]}get wasClean(){return this[Il]}};Object.defineProperty(vn.prototype,"code",{enumerable:!0});Object.defineProperty(vn.prototype,"reason",{enumerable:!0});Object.defineProperty(vn.prototype,"wasClean",{enumerable:!0});var Zn=class extends Pr{constructor(e,t={}){super(e),this[Ol]=t.error===void 0?null:t.error,this[Pl]=t.message===void 0?"":t.message}get error(){return this[Ol]}get message(){return this[Pl]}};Object.defineProperty(Zn.prototype,"error",{enumerable:!0});Object.defineProperty(Zn.prototype,"message",{enumerable:!0});var Li=class extends Pr{constructor(e,t={}){super(e),this[kl]=t.data===void 0?null:t.data}get data(){return this[kl]}};Object.defineProperty(Li.prototype,"data",{enumerable:!0});var Ny={addEventListener(r,e,t={}){for(let i of this.listeners(r))if(!t[Ii]&&i[ja]===e&&!i[Ii])return;let n;if(r==="message")n=function(s,a){let c=new Li("message",{data:a?s:s.toString()});c[Jn]=this,Ys(e,this,c)};else if(r==="close")n=function(s,a){let c=new vn("close",{code:s,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Jn]=this,Ys(e,this,c)};else if(r==="error")n=function(s){let a=new Zn("error",{error:s,message:s.message});a[Jn]=this,Ys(e,this,a)};else if(r==="open")n=function(){let s=new Pr("open");s[Jn]=this,Ys(e,this,s)};else return;n[Ii]=!!t[Ii],n[ja]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[ja]===e&&!t[Ii]){this.removeListener(r,t);break}}};Ll.exports={CloseEvent:vn,ErrorEvent:Zn,Event:Pr,EventTarget:Ny,MessageEvent:Li};function Ys(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var Ua=M((fw,Ml)=>{"use strict";var{tokenChars:Ni}=Gn();function ur(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function My(r){let e=Object.create(null),t=Object.create(null),n=!1,i=!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&&Ni[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?(ur(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&&Ni[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),ur(t,r.slice(u,p),!0),d===44&&(ur(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(i){if(Ni[d]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);u===-1?u=m:n||(n=!0),i=!1}else if(s)if(Ni[d]===1)u===-1&&(u=m);else if(d===34&&u!==-1)s=!1,p=m;else if(d===92)i=!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&&Ni[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);n&&(v=v.replace(/\\/g,""),n=!1),ur(t,c,v),d===44&&(ur(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?ur(e,_,t):(c===void 0?ur(t,_,!0):n?ur(t,c,_.replace(/\\/g,"")):ur(t,c,_),ur(e,a,t)),e}function Fy(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(i=>{let s=n[i];return Array.isArray(s)||(s=[s]),s.map(a=>a===!0?i:`${i}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Ml.exports={format:Fy,parse:My}});var Qs=M((hw,$l)=>{"use strict";var Dy=require("events"),By=require("https"),jy=require("http"),Bl=require("net"),Uy=require("tls"),{randomBytes:Ky,createHash:qy}=require("crypto"),{Duplex:uw,Readable:lw}=require("stream"),{URL:Ka}=require("url"),Yr=Ri(),Wy=Ma(),Hy=Ba(),{isBlob:Vy}=Gn(),{BINARY_TYPES:Fl,EMPTY_BUFFER:Xs,GUID:zy,kForOnEventAttribute:qa,kListener:$y,kStatusCode:Gy,kWebSocket:ut,NOOP:jl}=kr(),{EventTarget:{addEventListener:Yy,removeEventListener:Xy}}=Nl(),{format:Jy,parse:Zy}=Ua(),{toBuffer:Qy}=Pi(),e_=30*1e3,Ul=Symbol("kAborted"),Wa=[8,13],Ar=["CONNECTING","OPEN","CLOSING","CLOSED"],t_=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ke=class r extends Dy{constructor(e,t,n){super(),this._binaryType=Fl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Xs,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?(n=t,t=[]):t=[t]),Kl(this,e,t,n)):(this._autoPong=n.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Fl.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,n){let i=new Wy({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),s=new Hy(e,this._extensions,n.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[ut]=this,s[ut]=this,e[ut]=this,i.on("conclude",i_),i.on("drain",s_),i.on("error",o_),i.on("message",a_),i.on("ping",c_),i.on("pong",f_),s.onerror=u_,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Hl),e.on("data",Zs),e.on("end",Vl),e.on("error",zl),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[Yr.extensionName]&&this._extensions[Yr.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){At(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,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Wl(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ha(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Xs,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ha(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Xs,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ha(this,e,n);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Yr.extensionName]||(i.compress=!1),this._sender.send(e||Xs,i,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){At(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:Ar.indexOf("CONNECTING")});Object.defineProperty(Ke.prototype,"CONNECTING",{enumerable:!0,value:Ar.indexOf("CONNECTING")});Object.defineProperty(Ke,"OPEN",{enumerable:!0,value:Ar.indexOf("OPEN")});Object.defineProperty(Ke.prototype,"OPEN",{enumerable:!0,value:Ar.indexOf("OPEN")});Object.defineProperty(Ke,"CLOSING",{enumerable:!0,value:Ar.indexOf("CLOSING")});Object.defineProperty(Ke.prototype,"CLOSING",{enumerable:!0,value:Ar.indexOf("CLOSING")});Object.defineProperty(Ke,"CLOSED",{enumerable:!0,value:Ar.indexOf("CLOSED")});Object.defineProperty(Ke.prototype,"CLOSED",{enumerable:!0,value:Ar.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[qa])return e[$y];return null},set(e){for(let t of this.listeners(r))if(t[qa]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[qa]:!0})}})});Ke.prototype.addEventListener=Yy;Ke.prototype.removeEventListener=Xy;$l.exports=Ke;function Kl(r,e,t,n){let i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:Wa[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,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=i.autoPong,!Wa.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Wa.join(", ")})`);let s;if(e instanceof Ka)s=e;else try{s=new Ka(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;Js(r,T);return}let d=a?443:80,p=Ky(16).toString("base64"),m=a?By.request:jy.request,_=new Set,v;if(i.createConnection=i.createConnection||(a?n_:r_),i.defaultPort=i.defaultPort||d,i.port=s.port||d,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(v=new Yr(i.perMessageDeflate!==!0?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=Jy({[Yr.extensionName]:v.offer()})),t.length){for(let T of t){if(typeof T!="string"||!t_.test(T)||_.has(T))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(T)}i.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(s.username||s.password)&&(i.auth=`${s.username}:${s.password}`),c){let T=i.path.split(":");i.socketPath=T[0],i.path=T[1]}let S;if(i.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=a,r._originalHostOrSocketPath=c?i.socketPath:s.host;let T=n&&n.headers;if(n={...n,headers:{}},T)for(let[H,de]of Object.entries(T))n.headers[H.toLowerCase()]=de}else if(r.listenerCount("redirect")===0){let T=c?r._originalIpc?i.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:s.host===r._originalHostOrSocketPath;(!T||r._originalSecure&&!a)&&(delete i.headers.authorization,delete i.headers.cookie,T||delete i.headers.host,i.auth=void 0)}i.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),S=r._req=m(i),r._redirects&&r.emit("redirect",r.url,S)}else S=r._req=m(i);i.timeout&&S.on("timeout",()=>{At(r,S,"Opening handshake has timed out")}),S.on("error",T=>{S===null||S[Ul]||(S=r._req=null,Js(r,T))}),S.on("response",T=>{let H=T.headers.location,de=T.statusCode;if(H&&i.followRedirects&&de>=300&&de<400){if(++r._redirects>i.maxRedirects){At(r,S,"Maximum redirects exceeded");return}S.abort();let z;try{z=new Ka(H,e)}catch{let D=new SyntaxError(`Invalid URL: ${H}`);Js(r,D);return}Kl(r,z,t,n)}else r.emit("unexpected-response",S,T)||At(r,S,`Unexpected server response: ${T.statusCode}`)}),S.on("upgrade",(T,H,de)=>{if(r.emit("upgrade",T),r.readyState!==Ke.CONNECTING)return;S=r._req=null;let z=T.headers.upgrade;if(z===void 0||z.toLowerCase()!=="websocket"){At(r,H,"Invalid Upgrade header");return}let C=qy("sha1").update(p+zy).digest("base64");if(T.headers["sec-websocket-accept"]!==C){At(r,H,"Invalid Sec-WebSocket-Accept header");return}let D=T.headers["sec-websocket-protocol"],Q;if(D!==void 0?_.size?_.has(D)||(Q="Server sent an invalid subprotocol"):Q="Server sent a subprotocol but none was requested":_.size&&(Q="Server sent no subprotocol"),Q){At(r,H,Q);return}D&&(r._protocol=D);let K=T.headers["sec-websocket-extensions"];if(K!==void 0){if(!v){At(r,H,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let U;try{U=Zy(K)}catch{At(r,H,"Invalid Sec-WebSocket-Extensions header");return}let le=Object.keys(U);if(le.length!==1||le[0]!==Yr.extensionName){At(r,H,"Server indicated an extension that was not requested");return}try{v.accept(U[Yr.extensionName])}catch{At(r,H,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Yr.extensionName]=v}r.setSocket(H,de,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(S,r):S.end()}function Js(r,e){r._readyState=Ke.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function r_(r){return r.path=r.socketPath,Bl.connect(r)}function n_(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Bl.isIP(r.host)?"":r.host),Uy.connect(r)}function At(r,e,t){r._readyState=Ke.CLOSING;let n=new Error(t);Error.captureStackTrace(n,At),e.setHeader?(e[Ul]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Js,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function Ha(r,e,t){if(e){let n=Vy(e)?e.size:Qy(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${Ar[r.readyState]})`);process.nextTick(t,n)}}function i_(r,e){let t=this[ut];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[ut]!==void 0&&(t._socket.removeListener("data",Zs),process.nextTick(ql,t._socket),r===1005?t.close():t.close(r,e))}function s_(){let r=this[ut];r.isPaused||r._socket.resume()}function o_(r){let e=this[ut];e._socket[ut]!==void 0&&(e._socket.removeListener("data",Zs),process.nextTick(ql,e._socket),e.close(r[Gy])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Dl(){this[ut].emitClose()}function a_(r,e){this[ut].emit("message",r,e)}function c_(r){let e=this[ut];e._autoPong&&e.pong(r,!this._isServer,jl),e.emit("ping",r)}function f_(r){this[ut].emit("pong",r)}function ql(r){r.resume()}function u_(r){let e=this[ut];e.readyState!==Ke.CLOSED&&(e.readyState===Ke.OPEN&&(e._readyState=Ke.CLOSING,Wl(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Wl(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),e_)}function Hl(){let r=this[ut];this.removeListener("close",Hl),this.removeListener("data",Zs),this.removeListener("end",Vl),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[ut]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Dl),r._receiver.on("finish",Dl))}function Zs(r){this[ut]._receiver.write(r)||this.pause()}function Vl(){let r=this[ut];r._readyState=Ke.CLOSING,r._receiver.end(),this.end()}function zl(){let r=this[ut];this.removeListener("error",zl),this.on("error",jl),r&&(r._readyState=Ke.CLOSING,this.destroy())}});var Jl=M((pw,Xl)=>{"use strict";var dw=Qs(),{Duplex:l_}=require("stream");function Gl(r){r.emit("close")}function h_(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Yl(r){this.removeListener("error",Yl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function d_(r,e){let t=!0,n=new l_({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(s,a){let c=!a&&n._readableState.objectMode?s.toString():s;n.push(c)||r.pause()}),r.once("error",function(s){n.destroyed||(t=!1,n.destroy(s))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(i,s){if(r.readyState===r.CLOSED){s(i),process.nextTick(Gl,n);return}let a=!1;r.once("error",function(u){a=!0,s(u)}),r.once("close",function(){a||s(i),process.nextTick(Gl,n)}),t&&r.terminate()},n._final=function(i){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(i)});return}r._socket!==null&&(r._socket._writableState.finished?(i(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){i()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(i,s,a){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(i,s,a)});return}r.send(i,a)},n.on("end",h_),n.on("error",Yl),n}Xl.exports=d_});var Ql=M((gw,Zl)=>{"use strict";var{tokenChars:p_}=Gn();function g_(r){let e=new Set,t=-1,n=-1,i=0;for(i;i<r.length;i++){let a=r.charCodeAt(i);if(n===-1&&p_[a]===1)t===-1&&(t=i);else if(i!==0&&(a===32||a===9))n===-1&&t!==-1&&(n=i);else if(a===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${i}`);n===-1&&(n=i);let c=r.slice(t,n);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let s=r.slice(t,i);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}Zl.exports={parse:g_}});var oh=M((yw,sh)=>{"use strict";var m_=require("events"),eo=require("http"),{Duplex:mw}=require("stream"),{createHash:y_}=require("crypto"),eh=Ua(),wn=Ri(),__=Ql(),E_=Qs(),{GUID:b_,kWebSocket:v_}=kr(),w_=/^[+/0-9A-Za-z]{22}==$/,th=0,rh=1,ih=2,Va=class extends m_{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:E_,...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=eo.createServer((n,i)=>{let s=eo.STATUS_CODES[426];i.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),i.end(s)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=x_(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,s,a)=>{this.handleUpgrade(i,s,a,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=th}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===ih){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Mi,this);return}if(e&&this.once("close",e),this._state!==rh)if(this._state=rh,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(Mi,this):process.nextTick(Mi,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Mi(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,n,i){t.on("error",nh);let s=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){xn(this,e,t,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){xn(this,e,t,400,"Invalid Upgrade header");return}if(s===void 0||!w_.test(s)){xn(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){xn(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Fi(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=__.parse(u)}catch{xn(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 wn(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let v=eh.parse(p);v[wn.extensionName]&&(_.accept(v[wn.extensionName]),m[wn.extensionName]=_)}catch{xn(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,S,T,H)=>{if(!v)return Fi(t,S||401,T,H);this.completeUpgrade(m,s,d,e,t,n,i)});return}if(!this.options.verifyClient(_))return Fi(t,401)}this.completeUpgrade(m,s,d,e,t,n,i)}completeUpgrade(e,t,n,i,s,a,c){if(!s.readable||!s.writable)return s.destroy();if(s[v_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>th)return Fi(s,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${y_("sha1").update(t+b_).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let m=this.options.handleProtocols?this.options.handleProtocols(n,i):n.values().next().value;m&&(d.push(`Sec-WebSocket-Protocol: ${m}`),p._protocol=m)}if(e[wn.extensionName]){let m=e[wn.extensionName].params,_=eh.format({[wn.extensionName]:[m]});d.push(`Sec-WebSocket-Extensions: ${_}`),p._extensions=e}this.emit("headers",d,i),s.write(d.concat(`\r
20
+ `+s),r.push(n+"m+"+js.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=Wm()+e+" "+r[0]}function Wm(){return ft.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Hm(...r){return process.stderr.write(Bs.formatWithOptions(ft.inspectOpts,...r)+`
21
+ `)}function Vm(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function $m(){return process.env.DEBUG}function zm(r){r.inspectOpts={};let e=Object.keys(ft.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=ft.inspectOpts[e[t]]}js.exports=ma()(ft);var{formatters:Zu}=js.exports;Zu.o=function(r){return this.inspectOpts.colors=this.useColors,Bs.inspect(r,this.inspectOpts).split(`
22
+ `).map(e=>e.trim()).join(" ")};Zu.O=function(r){return this.inspectOpts.colors=this.useColors,Bs.inspect(r,this.inspectOpts)}});var jt=L((av,ba)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?ba.exports=$u():ba.exports=Qu()});var Pn=L(Gr=>{"use strict";var Gm=Gr&&Gr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Gr,"__esModule",{value:!0});Gr.Transport=Gr.TransportError=void 0;var Ym=Ki(),Xm=gi(),Jm=yi(),Zm=ga(),Qm=Gm(jt()),ey=(0,Qm.default)("engine.io-client:transport"),Us=class extends Error{constructor(e,t,i){super(e),this.description=t,this.context=i,this.type="TransportError"}};Gr.TransportError=Us;var Ea=class extends Xm.Emitter{constructor(e){super(),this.writable=!1,(0,Jm.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 Us(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):ey("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=(0,Ym.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,Zm.encode)(e);return t.length?"?"+t:""}};Gr.Transport=Ea});var va=L($i=>{"use strict";var ty=$i&&$i.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty($i,"__esModule",{value:!0});$i.Polling=void 0;var ry=Pn(),iy=yi(),el=Ki(),ny=ty(jt()),Gt=(0,ny.default)("engine.io-client:polling"),wa=class extends ry.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{Gt("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let i=0;this._polling&&(Gt("we are currently polling - waiting to pause"),i++,this.once("pollComplete",function(){Gt("pre-pause polling complete"),--i||t()})),this.writable||(Gt("we are currently writing - waiting to pause"),i++,this.once("drain",function(){Gt("pre-pause writing complete"),--i||t()}))}else t()}_poll(){Gt("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Gt("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,el.decodePayload)(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Gt('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{Gt("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Gt("transport open - closing"),e()):(Gt("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,el.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,iy.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};$i.Polling=wa});var rl=L(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.hasCORS=void 0;var tl=!1;try{tl=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}Ks.hasCORS=tl});var Ta=L(lr=>{"use strict";var sy=lr&&lr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(lr,"__esModule",{value:!0});lr.XHR=lr.Request=lr.BaseXHR=void 0;var oy=va(),ay=gi(),il=yi(),sl=mi(),cy=rl(),fy=sy(jt()),xa=(0,fy.default)("engine.io-client:polling");function uy(){}var qs=class extends oy.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(){xa("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}};lr.BaseXHR=qs;var Pr=class r extends ay.Emitter{constructor(e,t,i){super(),this.createRequest=e,(0,il.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,il.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{xa("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))},xa("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=uy,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()}};lr.Request=Pr;Pr.requestsCount=0;Pr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",nl);else if(typeof addEventListener=="function"){let r="onpagehide"in sl.globalThisShim?"pagehide":"unload";addEventListener(r,nl,!1)}}function nl(){for(let r in Pr.requests)Pr.requests.hasOwnProperty(r)&&Pr.requests[r].abort()}var ly=(function(){let r=ol({xdomain:!1});return r&&r.responseType!==null})(),Sa=class extends qs{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=ly&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Pr(ol,this.uri(),e)}};lr.XHR=Sa;function ol(r){let e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||cy.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new sl.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}});var ka=L(hr=>{"use strict";var hy=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]})),dy=hr&&hr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),py=hr&&hr.__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)&&hy(e,r,t);return dy(e,r),e};Object.defineProperty(hr,"__esModule",{value:!0});hr.XHR=void 0;var al=py(Lu()),cl=Ta(),gy=al.default||al,Ca=class extends cl.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 cl.Request(i=>new gy(i),this.uri(),e)}};hr.XHR=Ca});var Or=L((dv,ll)=>{"use strict";var fl=["nodebuffer","arraybuffer","fragments"],ul=typeof Blob<"u";ul&&fl.push("blob");ll.exports={BINARY_TYPES:fl,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ul,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var On=L((pv,Ws)=>{"use strict";var{EMPTY_BUFFER:my}=Or(),Pa=Buffer[Symbol.species];function yy(r,e){if(r.length===0)return my;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 Pa(t.buffer,t.byteOffset,i):t}function hl(r,e,t,i,n){for(let s=0;s<n;s++)t[i+s]=r[s]^e[s&3]}function dl(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function _y(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Oa(r){if(Oa.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Pa(r):ArrayBuffer.isView(r)?e=new Pa(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Oa.readOnly=!1),e}Ws.exports={concat:yy,mask:hl,toArrayBuffer:_y,toBuffer:Oa,unmask:dl};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");Ws.exports.mask=function(e,t,i,n,s){s<48?hl(e,t,i,n,s):r.mask(e,t,i,n,s)},Ws.exports.unmask=function(e,t){e.length<32?dl(e,t):r.unmask(e,t)}}catch{}});var ml=L((gv,gl)=>{"use strict";var pl=Symbol("kDone"),Ra=Symbol("kRun"),Aa=class{constructor(e){this[pl]=()=>{this.pending--,this[Ra]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ra]()}[Ra](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[pl])}}};gl.exports=Aa});var An=L((mv,El)=>{"use strict";var Rn=require("zlib"),yl=On(),by=ml(),{kStatusCode:_l}=Or(),Ey=Buffer[Symbol.species],wy=Buffer.from([0,0,255,255]),Vs=Symbol("permessage-deflate"),Rr=Symbol("total-length"),zi=Symbol("callback"),Yr=Symbol("buffers"),Gi=Symbol("error"),Hs,Ia=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,!Hs){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Hs=new by(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[zi];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){Hs.add(n=>{this._decompress(e,t,(s,a)=>{n(),i(s,a)})})}compress(e,t,i){Hs.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"?Rn.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=Rn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[Vs]=this,this._inflate[Rr]=0,this._inflate[Yr]=[],this._inflate.on("error",xy),this._inflate.on("data",bl)}this._inflate[zi]=i,this._inflate.write(e),t&&this._inflate.write(wy),this._inflate.flush(()=>{let s=this._inflate[Gi];if(s){this._inflate.close(),this._inflate=null,i(s);return}let a=yl.concat(this._inflate[Yr],this._inflate[Rr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Rr]=0,this._inflate[Yr]=[],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"?Rn.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=Rn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[Rr]=0,this._deflate[Yr]=[],this._deflate.on("data",vy)}this._deflate[zi]=i,this._deflate.write(e),this._deflate.flush(Rn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=yl.concat(this._deflate[Yr],this._deflate[Rr]);t&&(s=new Ey(s.buffer,s.byteOffset,s.length-4)),this._deflate[zi]=null,this._deflate[Rr]=0,this._deflate[Yr]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),i(null,s)})}};El.exports=Ia;function vy(r){this[Yr].push(r),this[Rr]+=r.length}function bl(r){if(this[Rr]+=r.length,this[Vs]._maxPayload<1||this[Rr]<=this[Vs]._maxPayload){this[Yr].push(r);return}this[Gi]=new RangeError("Max payload size exceeded"),this[Gi].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Gi][_l]=1009,this.removeListener("data",bl),this.reset()}function xy(r){if(this[Vs]._inflate=null,this[Gi]){this[zi](this[Gi]);return}r[_l]=1007,this[zi](r)}});var Yi=L((yv,$s)=>{"use strict";var{isUtf8:wl}=require("buffer"),{hasBlob:Sy}=Or(),Ty=[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 Cy(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function La(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 ky(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")}$s.exports={isBlob:ky,isValidStatusCode:Cy,isValidUTF8:La,tokenChars:Ty};if(wl)$s.exports.isValidUTF8=function(r){return r.length<24?La(r):wl(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");$s.exports.isValidUTF8=function(e){return e.length<32?La(e):r(e)}}catch{}});var Ba=L((_v,Pl)=>{"use strict";var{Writable:Py}=require("stream"),vl=An(),{BINARY_TYPES:Oy,EMPTY_BUFFER:xl,kStatusCode:Ry,kWebSocket:Ay}=Or(),{concat:Na,toArrayBuffer:Iy,unmask:Ly}=On(),{isValidStatusCode:Ny,isValidUTF8:Sl}=Yi(),zs=Buffer[Symbol.species],Ut=0,Tl=1,Cl=2,kl=3,Ma=4,Fa=5,Gs=6,Da=class extends Py{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Oy[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Ay]=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=Ut}_write(e,t,i){if(this._opcode===8&&this._state==Ut)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 zs(i.buffer,i.byteOffset+e,i.length-e),new zs(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 zs(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 Ut:this.getInfo(e);break;case Tl:this.getPayloadLength16(e);break;case Cl:this.getPayloadLength64(e);break;case kl:this.getMask();break;case Ma:this.getData(e);break;case Fa:case Gs: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[vl.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=Tl:this._payloadLength===127?this._state=Cl: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=kl:this._state=Ma}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ma}getData(e){let t=xl;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&&Ly(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Fa,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[vl.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===Ut&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Ut;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=Na(i,t):this._binaryType==="arraybuffer"?n=Iy(Na(i,t)):this._binaryType==="blob"?n=new Blob(i):n=i,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=Ut):(this._state=Gs,setImmediate(()=>{this.emit("message",n,!0),this._state=Ut,this.startLoop(e)}))}else{let n=Na(i,t);if(!this._skipUTF8Validation&&!Sl(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Fa||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=Ut):(this._state=Gs,setImmediate(()=>{this.emit("message",n,!1),this._state=Ut,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,xl),this.end();else{let i=e.readUInt16BE(0);if(!Ny(i)){let s=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(s);return}let n=new zs(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Sl(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=Ut;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ut):(this._state=Gs,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ut,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[Ry]=n,a}};Pl.exports=Da});var Ka=L((Ev,Al)=>{"use strict";var{Duplex:bv}=require("stream"),{randomFillSync:My}=require("crypto"),Ol=An(),{EMPTY_BUFFER:Fy,kWebSocket:Dy,NOOP:By}=Or(),{isBlob:Xi,isValidStatusCode:jy}=Yi(),{mask:Rl,toBuffer:bi}=On(),Kt=Symbol("kByteLength"),Uy=Buffer.alloc(4),Ys=8*1024,Ei,Ji=Ys,Yt=0,Ky=1,qy=2,ja=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=Yt,this.onerror=By,this[Dy]=void 0}static frame(e,t){let i,n=!1,s=2,a=!1;t.mask&&(i=t.maskBuffer||Uy,t.generateMask?t.generateMask(i):(Ji===Ys&&(Ei===void 0&&(Ei=Buffer.alloc(Ys)),My(Ei,0,Ys),Ji=0),i[0]=Ei[Ji++],i[1]=Ei[Ji++],i[2]=Ei[Ji++],i[3]=Ei[Ji++]),a=(i[0]|i[1]|i[2]|i[3])===0,s=6);let c;typeof e=="string"?(!t.mask||a)&&t[Kt]!==void 0?c=t[Kt]:(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 h=Buffer.allocUnsafe(n?c+s:s);return h[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(h[0]|=64),h[1]=u,u===126?h.writeUInt16BE(c,2):u===127&&(h[2]=h[3]=0,h.writeUIntBE(c,4,6)),t.mask?(h[1]|=128,h[s-4]=i[0],h[s-3]=i[1],h[s-2]=i[2],h[s-1]=i[3],a?[h,e]:n?(Rl(e,i,h,s,c),[h]):(Rl(e,i,e,0,c),[h,e])):[h,e]}close(e,t,i,n){let s;if(e===void 0)s=Fy;else{if(typeof e!="number"||!jy(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={[Kt]:s.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Yt?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):Xi(e)?(n=e.size,s=!1):(e=bi(e),n=e.length,s=bi.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Kt]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};Xi(e)?this._state!==Yt?this.enqueue([this.getBlobData,e,!1,a,i]):this.getBlobData(e,!1,a,i):this._state!==Yt?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):Xi(e)?(n=e.size,s=!1):(e=bi(e),n=e.length,s=bi.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Kt]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};Xi(e)?this._state!==Yt?this.enqueue([this.getBlobData,e,!1,a,i]):this.getBlobData(e,!1,a,i):this._state!==Yt?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(r.frame(e,a),i)}send(e,t,i){let n=this._extensions[Ol.extensionName],s=t.binary?2:1,a=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):Xi(e)?(c=e.size,u=!1):(e=bi(e),c=e.length,u=bi.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 h={[Kt]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:u,rsv1:a};Xi(e)?this._state!==Yt?this.enqueue([this.getBlobData,e,this._compress,h,i]):this.getBlobData(e,this._compress,h,i):this._state!==Yt?this.enqueue([this.dispatch,e,this._compress,h,i]):this.dispatch(e,this._compress,h,i)}getBlobData(e,t,i,n){this._bufferedBytes+=i[Kt],this._state=qy,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(Ua,this,c,n);return}this._bufferedBytes-=i[Kt];let a=bi(s);t?this.dispatch(a,t,i,n):(this._state=Yt,this.sendFrame(r.frame(a,i),n),this.dequeue())}).catch(s=>{process.nextTick(Wy,this,s,n)})}dispatch(e,t,i,n){if(!t){this.sendFrame(r.frame(e,i),n);return}let s=this._extensions[Ol.extensionName];this._bufferedBytes+=i[Kt],this._state=Ky,s.compress(e,i.fin,(a,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");Ua(this,u,n);return}this._bufferedBytes-=i[Kt],this._state=Yt,i.readOnly=!1,this.sendFrame(r.frame(c,i),n),this.dequeue()})}dequeue(){for(;this._state===Yt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Kt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Kt],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)}};Al.exports=ja;function Ua(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 Wy(r,e,t){Ua(r,e,t),r.onerror(e)}});var Ul=L((wv,jl)=>{"use strict";var{kForOnEventAttribute:In,kListener:qa}=Or(),Il=Symbol("kCode"),Ll=Symbol("kData"),Nl=Symbol("kError"),Ml=Symbol("kMessage"),Fl=Symbol("kReason"),Zi=Symbol("kTarget"),Dl=Symbol("kType"),Bl=Symbol("kWasClean"),Ar=class{constructor(e){this[Zi]=null,this[Dl]=e}get target(){return this[Zi]}get type(){return this[Dl]}};Object.defineProperty(Ar.prototype,"target",{enumerable:!0});Object.defineProperty(Ar.prototype,"type",{enumerable:!0});var wi=class extends Ar{constructor(e,t={}){super(e),this[Il]=t.code===void 0?0:t.code,this[Fl]=t.reason===void 0?"":t.reason,this[Bl]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Il]}get reason(){return this[Fl]}get wasClean(){return this[Bl]}};Object.defineProperty(wi.prototype,"code",{enumerable:!0});Object.defineProperty(wi.prototype,"reason",{enumerable:!0});Object.defineProperty(wi.prototype,"wasClean",{enumerable:!0});var Qi=class extends Ar{constructor(e,t={}){super(e),this[Nl]=t.error===void 0?null:t.error,this[Ml]=t.message===void 0?"":t.message}get error(){return this[Nl]}get message(){return this[Ml]}};Object.defineProperty(Qi.prototype,"error",{enumerable:!0});Object.defineProperty(Qi.prototype,"message",{enumerable:!0});var Ln=class extends Ar{constructor(e,t={}){super(e),this[Ll]=t.data===void 0?null:t.data}get data(){return this[Ll]}};Object.defineProperty(Ln.prototype,"data",{enumerable:!0});var Hy={addEventListener(r,e,t={}){for(let n of this.listeners(r))if(!t[In]&&n[qa]===e&&!n[In])return;let i;if(r==="message")i=function(s,a){let c=new Ln("message",{data:a?s:s.toString()});c[Zi]=this,Xs(e,this,c)};else if(r==="close")i=function(s,a){let c=new wi("close",{code:s,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Zi]=this,Xs(e,this,c)};else if(r==="error")i=function(s){let a=new Qi("error",{error:s,message:s.message});a[Zi]=this,Xs(e,this,a)};else if(r==="open")i=function(){let s=new Ar("open");s[Zi]=this,Xs(e,this,s)};else return;i[In]=!!t[In],i[qa]=e,t.once?this.once(r,i):this.on(r,i)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[qa]===e&&!t[In]){this.removeListener(r,t);break}}};jl.exports={CloseEvent:wi,ErrorEvent:Qi,Event:Ar,EventTarget:Hy,MessageEvent:Ln};function Xs(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var Wa=L((vv,Kl)=>{"use strict";var{tokenChars:Nn}=Yi();function dr(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function Vy(r){let e=Object.create(null),t=Object.create(null),i=!1,n=!1,s=!1,a,c,u=-1,h=-1,p=-1,m=0;for(;m<r.length;m++)if(h=r.charCodeAt(m),a===void 0)if(p===-1&&Nn[h]===1)u===-1&&(u=m);else if(m!==0&&(h===32||h===9))p===-1&&u!==-1&&(p=m);else if(h===59||h===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m);let E=r.slice(u,p);h===44?(dr(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&&Nn[h]===1)u===-1&&(u=m);else if(h===32||h===9)p===-1&&u!==-1&&(p=m);else if(h===59||h===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${m}`);p===-1&&(p=m),dr(t,r.slice(u,p),!0),h===44&&(dr(e,a,t),t=Object.create(null),a=void 0),u=p=-1}else if(h===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(Nn[h]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);u===-1?u=m:i||(i=!0),n=!1}else if(s)if(Nn[h]===1)u===-1&&(u=m);else if(h===34&&u!==-1)s=!1,p=m;else if(h===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(h===34&&r.charCodeAt(m-1)===61)s=!0;else if(p===-1&&Nn[h]===1)u===-1&&(u=m);else if(u!==-1&&(h===32||h===9))p===-1&&(p=m);else if(h===59||h===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),dr(t,c,E),h===44&&(dr(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||h===32||h===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=m);let _=r.slice(u,p);return a===void 0?dr(e,_,t):(c===void 0?dr(t,_,!0):i?dr(t,c,_.replace(/\\/g,"")):dr(t,c,_),dr(e,a,t)),e}function $y(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(", ")}Kl.exports={format:$y,parse:Vy}});var eo=L((Tv,Ql)=>{"use strict";var zy=require("events"),Gy=require("https"),Yy=require("http"),Hl=require("net"),Xy=require("tls"),{randomBytes:Jy,createHash:Zy}=require("crypto"),{Duplex:xv,Readable:Sv}=require("stream"),{URL:Ha}=require("url"),Xr=An(),Qy=Ba(),e_=Ka(),{isBlob:t_}=Yi(),{BINARY_TYPES:ql,EMPTY_BUFFER:Js,GUID:r_,kForOnEventAttribute:Va,kListener:i_,kStatusCode:n_,kWebSocket:ut,NOOP:Vl}=Or(),{EventTarget:{addEventListener:s_,removeEventListener:o_}}=Ul(),{format:a_,parse:c_}=Wa(),{toBuffer:f_}=On(),u_=30*1e3,$l=Symbol("kAborted"),$a=[8,13],Ir=["CONNECTING","OPEN","CLOSING","CLOSED"],l_=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ze=class r extends zy{constructor(e,t,i){super(),this._binaryType=ql[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Js,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]),zl(this,e,t,i)):(this._autoPong=i.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ql.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 Qy({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),s=new e_(e,this._extensions,i.generateMask);this._receiver=n,this._sender=s,this._socket=e,n[ut]=this,s[ut]=this,e[ut]=this,n.on("conclude",p_),n.on("drain",g_),n.on("error",m_),n.on("message",y_),n.on("ping",__),n.on("pong",b_),s.onerror=E_,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Xl),e.on("data",Qs),e.on("end",Jl),e.on("error",Zl),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[Xr.extensionName]&&this._extensions[Xr.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){It(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())}),Yl(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){za(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Js,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){za(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Js,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){za(this,e,i);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Xr.extensionName]||(n.compress=!1),this._sender.send(e||Js,n,i)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){It(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(ze,"CONNECTING",{enumerable:!0,value:Ir.indexOf("CONNECTING")});Object.defineProperty(ze.prototype,"CONNECTING",{enumerable:!0,value:Ir.indexOf("CONNECTING")});Object.defineProperty(ze,"OPEN",{enumerable:!0,value:Ir.indexOf("OPEN")});Object.defineProperty(ze.prototype,"OPEN",{enumerable:!0,value:Ir.indexOf("OPEN")});Object.defineProperty(ze,"CLOSING",{enumerable:!0,value:Ir.indexOf("CLOSING")});Object.defineProperty(ze.prototype,"CLOSING",{enumerable:!0,value:Ir.indexOf("CLOSING")});Object.defineProperty(ze,"CLOSED",{enumerable:!0,value:Ir.indexOf("CLOSED")});Object.defineProperty(ze.prototype,"CLOSED",{enumerable:!0,value:Ir.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(ze.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(ze.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Va])return e[i_];return null},set(e){for(let t of this.listeners(r))if(t[Va]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[Va]:!0})}})});ze.prototype.addEventListener=s_;ze.prototype.removeEventListener=o_;Ql.exports=ze;function zl(r,e,t,i){let n={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:$a[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,!$a.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${$a.join(", ")})`);let s;if(e instanceof Ha)s=e;else try{s=new Ha(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 C=new SyntaxError(u);if(r._redirects===0)throw C;Zs(r,C);return}let h=a?443:80,p=Jy(16).toString("base64"),m=a?Gy.request:Yy.request,_=new Set,E;if(n.createConnection=n.createConnection||(a?d_:h_),n.defaultPort=n.defaultPort||h,n.port=s.port||h,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 Xr(n.perMessageDeflate!==!0?n.perMessageDeflate:{},!1,n.maxPayload),n.headers["Sec-WebSocket-Extensions"]=a_({[Xr.extensionName]:E.offer()})),t.length){for(let C of t){if(typeof C!="string"||!l_.test(C)||_.has(C))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(C)}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 C=n.path.split(":");n.socketPath=C[0],n.path=C[1]}let S;if(n.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=a,r._originalHostOrSocketPath=c?n.socketPath:s.host;let C=i&&i.headers;if(i={...i,headers:{}},C)for(let[H,ne]of Object.entries(C))i.headers[H.toLowerCase()]=ne}else if(r.listenerCount("redirect")===0){let C=c?r._originalIpc?n.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:s.host===r._originalHostOrSocketPath;(!C||r._originalSecure&&!a)&&(delete n.headers.authorization,delete n.headers.cookie,C||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",()=>{It(r,S,"Opening handshake has timed out")}),S.on("error",C=>{S===null||S[$l]||(S=r._req=null,Zs(r,C))}),S.on("response",C=>{let H=C.headers.location,ne=C.statusCode;if(H&&n.followRedirects&&ne>=300&&ne<400){if(++r._redirects>n.maxRedirects){It(r,S,"Maximum redirects exceeded");return}S.abort();let z;try{z=new Ha(H,e)}catch{let F=new SyntaxError(`Invalid URL: ${H}`);Zs(r,F);return}zl(r,z,t,i)}else r.emit("unexpected-response",S,C)||It(r,S,`Unexpected server response: ${C.statusCode}`)}),S.on("upgrade",(C,H,ne)=>{if(r.emit("upgrade",C),r.readyState!==ze.CONNECTING)return;S=r._req=null;let z=C.headers.upgrade;if(z===void 0||z.toLowerCase()!=="websocket"){It(r,H,"Invalid Upgrade header");return}let T=Zy("sha1").update(p+r_).digest("base64");if(C.headers["sec-websocket-accept"]!==T){It(r,H,"Invalid Sec-WebSocket-Accept header");return}let F=C.headers["sec-websocket-protocol"],te;if(F!==void 0?_.size?_.has(F)||(te="Server sent an invalid subprotocol"):te="Server sent a subprotocol but none was requested":_.size&&(te="Server sent no subprotocol"),te){It(r,H,te);return}F&&(r._protocol=F);let U=C.headers["sec-websocket-extensions"];if(U!==void 0){if(!E){It(r,H,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ee;try{ee=c_(U)}catch{It(r,H,"Invalid Sec-WebSocket-Extensions header");return}let pe=Object.keys(ee);if(pe.length!==1||pe[0]!==Xr.extensionName){It(r,H,"Server indicated an extension that was not requested");return}try{E.accept(ee[Xr.extensionName])}catch{It(r,H,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Xr.extensionName]=E}r.setSocket(H,ne,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(S,r):S.end()}function Zs(r,e){r._readyState=ze.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function h_(r){return r.path=r.socketPath,Hl.connect(r)}function d_(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Hl.isIP(r.host)?"":r.host),Xy.connect(r)}function It(r,e,t){r._readyState=ze.CLOSING;let i=new Error(t);Error.captureStackTrace(i,It),e.setHeader?(e[$l]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Zs,r,i)):(e.destroy(i),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function za(r,e,t){if(e){let i=t_(e)?e.size:f_(e).length;r._socket?r._sender._bufferedBytes+=i:r._bufferedAmount+=i}if(t){let i=new Error(`WebSocket is not open: readyState ${r.readyState} (${Ir[r.readyState]})`);process.nextTick(t,i)}}function p_(r,e){let t=this[ut];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[ut]!==void 0&&(t._socket.removeListener("data",Qs),process.nextTick(Gl,t._socket),r===1005?t.close():t.close(r,e))}function g_(){let r=this[ut];r.isPaused||r._socket.resume()}function m_(r){let e=this[ut];e._socket[ut]!==void 0&&(e._socket.removeListener("data",Qs),process.nextTick(Gl,e._socket),e.close(r[n_])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Wl(){this[ut].emitClose()}function y_(r,e){this[ut].emit("message",r,e)}function __(r){let e=this[ut];e._autoPong&&e.pong(r,!this._isServer,Vl),e.emit("ping",r)}function b_(r){this[ut].emit("pong",r)}function Gl(r){r.resume()}function E_(r){let e=this[ut];e.readyState!==ze.CLOSED&&(e.readyState===ze.OPEN&&(e._readyState=ze.CLOSING,Yl(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Yl(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),u_)}function Xl(){let r=this[ut];this.removeListener("close",Xl),this.removeListener("data",Qs),this.removeListener("end",Jl),r._readyState=ze.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[ut]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Wl),r._receiver.on("finish",Wl))}function Qs(r){this[ut]._receiver.write(r)||this.pause()}function Jl(){let r=this[ut];r._readyState=ze.CLOSING,r._receiver.end(),this.end()}function Zl(){let r=this[ut];this.removeListener("error",Zl),this.on("error",Vl),r&&(r._readyState=ze.CLOSING,this.destroy())}});var ih=L((kv,rh)=>{"use strict";var Cv=eo(),{Duplex:w_}=require("stream");function eh(r){r.emit("close")}function v_(){!this.destroyed&&this._writableState.finished&&this.destroy()}function th(r){this.removeListener("error",th),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function x_(r,e){let t=!0,i=new w_({...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(eh,i);return}let a=!1;r.once("error",function(u){a=!0,s(u)}),r.once("close",function(){a||s(n),process.nextTick(eh,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",v_),i.on("error",th),i}rh.exports=x_});var sh=L((Pv,nh)=>{"use strict";var{tokenChars:S_}=Yi();function T_(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}nh.exports={parse:T_}});var hh=L((Rv,lh)=>{"use strict";var C_=require("events"),to=require("http"),{Duplex:Ov}=require("stream"),{createHash:k_}=require("crypto"),oh=Wa(),vi=An(),P_=sh(),O_=eo(),{GUID:R_,kWebSocket:A_}=Or(),I_=/^[+/0-9A-Za-z]{22}==$/,ah=0,ch=1,uh=2,Ga=class extends C_{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:O_,...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=to.createServer((i,n)=>{let s=to.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=L_(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=ah}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===uh){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Mn,this);return}if(e&&this.once("close",e),this._state!==ch)if(this._state=ch,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(Mn,this):process.nextTick(Mn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Mn(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",fh);let s=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){xi(this,e,t,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){xi(this,e,t,400,"Invalid Upgrade header");return}if(s===void 0||!I_.test(s)){xi(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){xi(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Fn(t,400);return}let u=e.headers["sec-websocket-protocol"],h=new Set;if(u!==void 0)try{h=P_.parse(u)}catch{xi(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 vi(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let E=oh.parse(p);E[vi.extensionName]&&(_.accept(E[vi.extensionName]),m[vi.extensionName]=_)}catch{xi(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,C,H)=>{if(!E)return Fn(t,S||401,C,H);this.completeUpgrade(m,s,h,e,t,i,n)});return}if(!this.options.verifyClient(_))return Fn(t,401)}this.completeUpgrade(m,s,h,e,t,i,n)}completeUpgrade(e,t,i,n,s,a,c){if(!s.readable||!s.writable)return s.destroy();if(s[A_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>ah)return Fn(s,503);let h=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${k_("sha1").update(t+R_).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&&(h.push(`Sec-WebSocket-Protocol: ${m}`),p._protocol=m)}if(e[vi.extensionName]){let m=e[vi.extensionName].params,_=oh.format({[vi.extensionName]:[m]});h.push(`Sec-WebSocket-Extensions: ${_}`),p._extensions=e}this.emit("headers",h,n),s.write(h.concat(`\r
23
23
  `).join(`\r
24
- `)),s.removeListener("error",nh),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(Mi,this)})),c(p,i)}};sh.exports=Va;function x_(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let n of Object.keys(e))r.removeListener(n,e[n])}}function Mi(r){r._state=ih,r.emit("close")}function nh(){this.destroy()}function Fi(r,e,t,n){t=t||eo.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...n},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${eo.STATUS_CODES[e]}\r
25
- `+Object.keys(n).map(i=>`${i}: ${n[i]}`).join(`\r
24
+ `)),s.removeListener("error",fh),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(Mn,this)})),c(p,n)}};lh.exports=Ga;function L_(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 Mn(r){r._state=uh,r.emit("close")}function fh(){this.destroy()}function Fn(r,e,t,i){t=t||to.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} ${to.STATUS_CODES[e]}\r
25
+ `+Object.keys(i).map(n=>`${n}: ${i[n]}`).join(`\r
26
26
  `)+`\r
27
27
  \r
28
- `+t)}function xn(r,e,t,n,i,s){if(r.listenerCount("wsClientError")){let a=new Error(i);Error.captureStackTrace(a,xn),r.emit("wsClientError",a,t,e)}else Fi(t,n,i,s)}});var ch=M((_w,ah)=>{"use strict";var Rr=Qs();Rr.createWebSocketStream=Jl();Rr.Server=oh();Rr.Receiver=Ma();Rr.Sender=Ba();Rr.WebSocket=Rr;Rr.WebSocketServer=Rr.Server;ah.exports=Rr});var Ya=M(Xr=>{"use strict";var S_=Xr&&Xr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xr,"__esModule",{value:!0});Xr.WS=Xr.BaseWS=void 0;var T_=Oi(),fh=yn(),C_=Un(),$a=mn(),k_=S_(Dt()),O_=(0,k_.default)("engine.io-client:websocket"),uh=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",to=class extends T_.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,n=uh?{}:(0,fh.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(i){return this.emitReserved("error",i)}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 n=e[t],i=t===e.length-1;(0,C_.encodePacket)(n,this.supportsBinary,s=>{try{this.doWrite(n,s)}catch{O_("websocket closed before onclose event")}i&&(0,$a.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,fh.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}};Xr.BaseWS=to;var za=$a.globalThisShim.WebSocket||$a.globalThisShim.MozWebSocket,Ga=class extends to{createSocket(e,t,n){return uh?new za(e,t,n):t?new za(e,t):new za(e)}doWrite(e,t){this.ws.send(t)}};Xr.WS=Ga});var Ja=M(lr=>{"use strict";var P_=lr&&lr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),A_=lr&&lr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),R_=lr&&lr.__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)&&P_(e,r,t);return A_(e,r),e};Object.defineProperty(lr,"__esModule",{value:!0});lr.WS=void 0;var I_=R_(ch()),L_=Ya(),Xa=class extends L_.BaseWS{createSocket(e,t,n){var i;if(!((i=this.socket)===null||i===void 0)&&i._cookieJar){n.headers=n.headers||{},n.headers.cookie=typeof n.headers.cookie=="string"?[n.headers.cookie]:n.headers.cookie||[];for(let[s,a]of this.socket._cookieJar.cookies)n.headers.cookie.push(`${s}=${a.value}`)}return new I_.WebSocket(e,t,n)}doWrite(e,t){let n={};e.options&&(n.compress=e.options.compress),this.opts.perMessageDeflate&&(typeof t=="string"?Buffer.byteLength(t):t.length)<this.opts.perMessageDeflate.threshold&&(n.compress=!1),this.ws.send(t,n)}};lr.WS=Xa});var Qa=M(Qn=>{"use strict";var N_=Qn&&Qn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Qn,"__esModule",{value:!0});Qn.WT=void 0;var M_=Oi(),F_=mn(),lh=Un(),D_=N_(Dt()),Di=(0,D_.default)("engine.io-client:webtransport"),Za=class extends M_.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(()=>{Di("transport closed gracefully"),this.onClose()}).catch(e=>{Di("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=(0,lh.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),i=(0,lh.createPacketEncoderStream)();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();let s=()=>{n.read().then(({done:c,value:u})=>{if(c){Di("session is closed");return}Di("received chunk: %o",u),this.onPacket(u),s()}).catch(c=>{Di("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 n=e[t],i=t===e.length-1;this._writer.write(n).then(()=>{i&&(0,F_.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};Qn.WT=Za});var ec=M(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.transports=void 0;var B_=Sa(),j_=Ja(),U_=Qa();ro.transports={websocket:j_.WS,webtransport:U_.WT,polling:B_.XHR}});var rc=M(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.parse=W_;var K_=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,q_=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function W_(r){if(r.length>8e3)throw"URI too long";let e=r,t=r.indexOf("["),n=r.indexOf("]");t!=-1&&n!=-1&&(r=r.substring(0,t)+r.substring(t,n).replace(/:/g,";")+r.substring(n,r.length));let i=K_.exec(r||""),s={},a=14;for(;a--;)s[q_[a]]=i[a]||"";return t!=-1&&n!=-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=H_(s,s.path),s.queryKey=V_(s,s.query),s}function H_(r,e){let t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function V_(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,s){i&&(t[i]=s)}),t}});var oc=M(hr=>{"use strict";var z_=hr&&hr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(hr,"__esModule",{value:!0});hr.Socket=hr.SocketWithUpgrade=hr.SocketWithoutUpgrade=void 0;var $_=ec(),hh=yn(),G_=ha(),dh=rc(),Y_=gn(),ph=Un(),nc=mn(),X_=z_(Dt()),De=(0,X_.default)("engine.io-client:socket"),ic=typeof addEventListener=="function"&&typeof removeEventListener=="function",Bi=[];ic&&addEventListener("offline",()=>{De("closing %d connection(s) because the network was lost",Bi.length),Bi.forEach(r=>r())},!1);var Sn=class r extends Y_.Emitter{constructor(e,t){if(super(),this.binaryType=nc.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 n=(0,dh.parse)(e);t.hostname=n.host,t.secure=n.protocol==="https"||n.protocol==="wss",t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=(0,dh.parse)(t.host).host);(0,hh.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(n=>{let i=n.prototype.name;this.transports.push(i),this._transportsByName[i]=n}),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,G_.decode)(this.opts.query)),ic&&(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"})},Bi.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,nc.createCookieJar)()),this._open()}createTransport(e){De('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=ph.protocol,t.transport=e,this.id&&(t.sid=this.id);let n=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",n),new this._transportsByName[e](n)}_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 n=0;n<this.writeBuffer.length;n++){let i=this.writeBuffer[n].data;if(i&&(t+=(0,hh.byteLength)(i)),n>0&&t>this._maxPayload)return De("only send %d out of %d packets",n,this.writeBuffer.length),this.writeBuffer.slice(0,n);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,nc.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,i){if(typeof t=="function"&&(i=t,t=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;let s={type:e,data:t,options:n};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),i&&this.once("flush",i),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()},n=()=>{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?n():e()}):this.upgrading?n():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(),ic&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let n=Bi.indexOf(this._offlineEventListener);n!==-1&&(De("removing listener for the 'offline' event"),Bi.splice(n,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};hr.SocketWithoutUpgrade=Sn;Sn.protocol=ph.protocol;var no=class extends Sn{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),n=!1;Sn.priorWebsocketSuccess=!1;let i=()=>{n||(De('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",m=>{if(!n)if(m.type==="pong"&&m.data==="probe"){if(De('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Sn.priorWebsocketSuccess=t.name==="websocket",De('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{n||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(){n||(n=!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",i),t.removeListener("error",a),t.removeListener("close",c),this.off("close",u),this.off("upgrading",d)};t.once("open",i),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(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}};hr.SocketWithUpgrade=no;var sc=class extends no{constructor(e,t={}){let n=typeof e=="object"?e:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(i=>$_.transports[i]).filter(i=>!!i)),super(e,n)}};hr.Socket=sc});var gh=M(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.Fetch=void 0;var J_=Ea(),ac=class extends J_.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(n=>{if(!n.ok)return this.onError("fetch write error",n.status,n);t()}).catch(n=>{this.onError("fetch write error",n)})}_fetch(e){var t;let n=e!==void 0,i=new Headers(this.opts.extraHeaders);return n&&i.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(i),fetch(this.uri(),{method:n?"POST":"GET",body:n?e:null,headers:i,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})}};io.Fetch=ac});var so=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 mh=oc();Object.defineProperty(Oe,"Socket",{enumerable:!0,get:function(){return mh.Socket}});var yh=oc();Object.defineProperty(Oe,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return yh.SocketWithoutUpgrade}});Object.defineProperty(Oe,"SocketWithUpgrade",{enumerable:!0,get:function(){return yh.SocketWithUpgrade}});Oe.protocol=mh.Socket.protocol;var _h=Oi();Object.defineProperty(Oe,"Transport",{enumerable:!0,get:function(){return _h.Transport}});Object.defineProperty(Oe,"TransportError",{enumerable:!0,get:function(){return _h.TransportError}});var Z_=ec();Object.defineProperty(Oe,"transports",{enumerable:!0,get:function(){return Z_.transports}});var Q_=yn();Object.defineProperty(Oe,"installTimerFunctions",{enumerable:!0,get:function(){return Q_.installTimerFunctions}});var e0=rc();Object.defineProperty(Oe,"parse",{enumerable:!0,get:function(){return e0.parse}});var t0=mn();Object.defineProperty(Oe,"nextTick",{enumerable:!0,get:function(){return t0.nextTick}});var r0=gh();Object.defineProperty(Oe,"Fetch",{enumerable:!0,get:function(){return r0.Fetch}});var n0=Sa();Object.defineProperty(Oe,"NodeXHR",{enumerable:!0,get:function(){return n0.XHR}});var i0=wa();Object.defineProperty(Oe,"XHR",{enumerable:!0,get:function(){return i0.XHR}});var s0=Ja();Object.defineProperty(Oe,"NodeWebSocket",{enumerable:!0,get:function(){return s0.WS}});var o0=Ya();Object.defineProperty(Oe,"WebSocket",{enumerable:!0,get:function(){return o0.WS}});var a0=Qa();Object.defineProperty(Oe,"WebTransport",{enumerable:!0,get:function(){return a0.WT}})});var bh=M(ji=>{"use strict";var c0=ji&&ji.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ji,"__esModule",{value:!0});ji.url=l0;var f0=so(),u0=c0(Dt()),Eh=(0,u0.default)("socket.io-client:url");function l0(r,e="",t){let n=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)||(Eh("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),Eh("parse %s",r),n=(0,f0.parse)(r)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";let s=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+s+":"+n.port+e,n.href=n.protocol+"://"+s+(t&&t.port===n.port?"":":"+n.port),n}});var cc=M(ao=>{"use strict";Object.defineProperty(ao,"__esModule",{value:!0});ao.isBinary=wh;ao.hasBinary=oo;var h0=typeof ArrayBuffer=="function",d0=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,vh=Object.prototype.toString,p0=typeof Blob=="function"||typeof Blob<"u"&&vh.call(Blob)==="[object BlobConstructor]",g0=typeof File=="function"||typeof File<"u"&&vh.call(File)==="[object FileConstructor]";function wh(r){return h0&&(r instanceof ArrayBuffer||d0(r))||p0&&r instanceof Blob||g0&&r instanceof File}function oo(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(oo(r[t]))return!0;return!1}if(wh(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return oo(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&oo(r[t]))return!0;return!1}});var xh=M(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.deconstructPacket=y0;co.reconstructPacket=_0;var m0=cc();function y0(r){let e=[],t=r.data,n=r;return n.data=fc(t,e),n.attachments=e.length,{packet:n,buffers:e}}function fc(r,e){if(!r)return r;if((0,m0.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 n=0;n<r.length;n++)t[n]=fc(r[n],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){let t={};for(let n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=fc(r[n],e));return t}return r}function _0(r,e){return r.data=uc(r.data,e),delete r.attachments,r}function uc(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]=uc(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=uc(r[t],e));return r}});var uo=M($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.Decoder=$t.Encoder=$t.PacketType=$t.protocol=void 0;$t.isPacketValid=T0;var E0=gn(),Sh=xh(),Th=cc(),b0=Dt(),lc=(0,b0.default)("socket.io-parser"),Ch=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];$t.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||($t.PacketType=Fe={}));var hc=class{constructor(e){this.replacer=e}encode(e){return lc("encoding packet %j",e),(e.type===Fe.EVENT||e.type===Fe.ACK)&&(0,Th.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)),lc("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,Sh.deconstructPacket)(e),n=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(n),i}};$t.Encoder=hc;var dc=class r extends E0.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 n=t.type===Fe.BINARY_EVENT;n||t.type===Fe.BINARY_ACK?(t.type=n?Fe.EVENT:Fe.ACK,this.reconstructor=new pc(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,Th.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,n={type:Number(e.charAt(0))};if(Fe[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Fe.BINARY_EVENT||n.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");n.attachments=Number(a)}if(e.charAt(t+1)==="/"){let s=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(s,t)}else n.nsp="/";let i=e.charAt(t+1);if(i!==""&&Number(i)==i){let s=t+1;for(;++t;){let a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}n.id=Number(e.substring(s,t+1))}if(e.charAt(++t)){let s=this.tryParse(e.substr(t));if(r.isPayloadValid(n.type,s))n.data=s;else throw new Error("invalid payload")}return lc("decoded %s as %j",e,n),n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Fe.CONNECT:return fo(t);case Fe.DISCONNECT:return t===void 0;case Fe.CONNECT_ERROR:return typeof t=="string"||fo(t);case Fe.EVENT:case Fe.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Ch.indexOf(t[0])===-1);case Fe.ACK:case Fe.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};$t.Decoder=dc;var pc=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,Sh.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function v0(r){return typeof r=="string"}var w0=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function x0(r){return r===void 0||w0(r)}function fo(r){return Object.prototype.toString.call(r)==="[object Object]"}function S0(r,e){switch(r){case Fe.CONNECT:return e===void 0||fo(e);case Fe.DISCONNECT:return e===void 0;case Fe.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Ch.indexOf(e[0])===-1);case Fe.ACK:return Array.isArray(e);case Fe.CONNECT_ERROR:return typeof e=="string"||fo(e);default:return!1}}function T0(r){return v0(r.nsp)&&x0(r.id)&&S0(r.type,r.data)}});var mc=M(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});gc.on=C0;function C0(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var _c=M(ei=>{"use strict";var k0=ei&&ei.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ei,"__esModule",{value:!0});ei.Socket=void 0;var Gt=uo(),lo=mc(),O0=gn(),P0=k0(Dt()),tt=(0,P0.default)("socket.io-client:socket"),A0=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),yc=class extends O0.Emitter{constructor(e,t,n){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,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[(0,lo.on)(e,"open",this.onopen.bind(this)),(0,lo.on)(e,"packet",this.onpacket.bind(this)),(0,lo.on)(e,"error",this.onerror.bind(this)),(0,lo.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 n,i,s;if(A0.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:Gt.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=(i=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||i===void 0?void 0:i.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 n;let i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===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,i),t.call(this,new Error("operation has timed out"))},i),a=(...c)=>{this.io.clearTimeoutFn(s),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((n,i)=>{let s=(a,c)=>a?i(a):n(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 n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...s)=>n!==this._queue[0]?tt("packet [%d] already acknowledged",n.id):(i!==null?n.tryCount>this._opts.retries&&(tt("packet [%d] is discarded after %d tries",n.id,n.tryCount),this._queue.shift(),t&&t(i)):(tt("packet [%d] was successfully sent",n.id),this._queue.shift(),t&&t(null,...s)),n.pending=!1,this._drainQueue())),this._queue.push(n),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:Gt.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(n=>String(n.id)===e)){let n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Gt.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 Gt.PacketType.EVENT:case Gt.PacketType.BINARY_EVENT:this.onevent(e);break;case Gt.PacketType.ACK:case Gt.PacketType.BINARY_ACK:this.onack(e);break;case Gt.PacketType.DISCONNECT:this.ondisconnect();break;case Gt.PacketType.CONNECT_ERROR:this.destroy();let n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);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 n of t)n.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,n=!1;return function(...i){n||(n=!0,tt("sending ack %j",i),t.packet({type:Gt.PacketType.ACK,id:e,data:i}))}}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:Gt.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 n=0;n<t.length;n++)if(e===t[n])return t.splice(n,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 n=0;n<t.length;n++)if(e===t[n])return t.splice(n,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 n of t)n.apply(this,e.data)}}};ei.Socket=yc});var kh=M(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.Backoff=ti;function ti(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}ti.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};ti.prototype.reset=function(){this.attempts=0};ti.prototype.setMin=function(r){this.ms=r};ti.prototype.setMax=function(r){this.max=r};ti.prototype.setJitter=function(r){this.jitter=r}});var Oh=M(Ut=>{"use strict";var R0=Ut&&Ut.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),I0=Ut&&Ut.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),L0=Ut&&Ut.__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)&&R0(e,r,t);return I0(e,r),e},N0=Ut&&Ut.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ut,"__esModule",{value:!0});Ut.Manager=void 0;var bc=so(),M0=_c(),F0=L0(uo()),Tn=mc(),D0=kh(),B0=gn(),j0=N0(Dt()),lt=(0,j0.default)("socket.io-client:manager"),vc=class extends B0.Emitter{constructor(e,t){var n;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,bc.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((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new D0.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 i=t.parser||F0;this.encoder=new i.Encoder,this.decoder=new i.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(lt("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;lt("opening %s",this.uri),this.engine=new bc.Socket(this.uri,this.opts);let t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;let i=(0,Tn.on)(t,"open",function(){n.onopen(),e&&e()}),s=c=>{lt("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,Tn.on)(t,"error",s);if(this._timeout!==!1){let c=this._timeout;lt("connect attempt will timeout after %d",c);let u=this.setTimeoutFn(()=>{lt("connect attempt timed out after %d",c),i(),s(new Error("timeout")),t.close()},c);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(i),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){lt("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,Tn.on)(e,"ping",this.onping.bind(this)),(0,Tn.on)(e,"data",this.ondata.bind(this)),(0,Tn.on)(e,"error",this.onerror.bind(this)),(0,Tn.on)(e,"close",this.onclose.bind(this)),(0,Tn.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,bc.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){lt("error",e),this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new M0.Socket(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let n of t)if(this.nsps[n].active){lt("socket %s is still active, skipping close",n);return}this._close()}_packet(e){lt("writing packet %j",e);let t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){lt("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){lt("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;lt("closed due to %s",e),this.cleanup(),(n=this.engine)===null||n===void 0||n.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)lt("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();lt("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(lt("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(lt("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):(lt("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};Ut.Manager=vc});var Ih=M((Be,Rh)=>{"use strict";var U0=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=Cn;Be.connect=Cn;Be.default=Cn;var K0=bh(),ho=Oh();Object.defineProperty(Be,"Manager",{enumerable:!0,get:function(){return ho.Manager}});var Ah=_c();Object.defineProperty(Be,"Socket",{enumerable:!0,get:function(){return Ah.Socket}});var q0=U0(Dt()),Ph=(0,q0.default)("socket.io-client"),Ui={};function Cn(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,K0.url)(r,e.path||"/socket.io"),n=t.source,i=t.id,s=t.path,a=Ui[i]&&s in Ui[i].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||a,u;return c?(Ph("ignoring socket cache for %s",n),u=new ho.Manager(n,e)):(Ui[i]||(Ph("new io instance for %s",n),Ui[i]=new ho.Manager(n,e)),u=Ui[i]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(Cn,{Manager:ho.Manager,Socket:Ah.Socket,io:Cn,connect:Cn});var W0=uo();Object.defineProperty(Be,"protocol",{enumerable:!0,get:function(){return W0.protocol}});var ri=so();Object.defineProperty(Be,"Fetch",{enumerable:!0,get:function(){return ri.Fetch}});Object.defineProperty(Be,"NodeXHR",{enumerable:!0,get:function(){return ri.NodeXHR}});Object.defineProperty(Be,"XHR",{enumerable:!0,get:function(){return ri.XHR}});Object.defineProperty(Be,"NodeWebSocket",{enumerable:!0,get:function(){return ri.NodeWebSocket}});Object.defineProperty(Be,"WebSocket",{enumerable:!0,get:function(){return ri.WebSocket}});Object.defineProperty(Be,"WebTransport",{enumerable:!0,get:function(){return ri.WebTransport}});Rh.exports=Cn});var xc=M(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.InputStreamReceiver=void 0;var H0=64,V0=30,z0=4,$0=256,G0=16,wc=class{streamId;lastAppliedSeq=0;cb;windowSize;ackThrottleMs;ackTimer=null;framesSinceAck=0;lastResendFrom=0;resendSuppressed=0;constructor(e,t,n={}){this.streamId=e,this.cb=t,this.windowSize=Math.max(1,n.windowSize??H0),this.ackThrottleMs=Math.max(0,n.ackThrottleMs??V0)}get appliedSeq(){return this.lastAppliedSeq}receive(e,t,n,i){if(e<=this.lastAppliedSeq){this.flushAck();return}if(e===this.lastAppliedSeq+1){try{this.cb.onApply(t,n,i)}catch{}this.lastAppliedSeq=e,this.scheduleAck();return}this.flushAck();let s=Math.max(this.windowSize*z0,$0);e-this.lastAppliedSeq>s||this.maybeResend(this.lastAppliedSeq+1)}maybeResend(e){if(e===this.lastResendFrom){if(++this.resendSuppressed<G0)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)}};po.InputStreamReceiver=wc});var Fh=M(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});go.WebSocketService=void 0;var Y0=Ih(),Lh=Tr(),Nh=hs(),Mh=fs(),X0=xc(),Sc=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,n,i,s,a,c="vscode",u=[]){this.authService=e,this.cryptoService=t,this.config=n,this.logger=i,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,Nh.getWsUrl)(this.config);this.logger.info("Connecting to WebSocket",t),this.statusChangeHandler?.("connecting");let n=await this.cryptoService.getPublicKey();return new Promise((i,s)=>{let a=Array.from(new Set([...Lh.DEFAULT_CLIENT_CAPABILITIES,...this.extraCapabilities]));this.socket=(0,Y0.io)(`${t}/agent`,{auth:{token:e,protocolVersion:Lh.PROTOCOL_VERSION,deviceId:this.deviceId,platform:this.platform,capabilities:a,publicKey:n},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,i()}),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,n,i){this.socket?.connected&&this.socket.emit("agent:ptyResized",{instanceId:e,terminalId:t,cols:n,rows:i})}sendClaimControl(e,t,n,i){this.socket?.connected&&this.socket.emit("agent:claimControl",{instanceId:e,terminalId:t,cols:n,rows:i})}sendOutput(e,t,n){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:n});return}let i=this.cryptoService.encryptOutput(t,n);if(!i){this.attachedClientCount>0&&this.signalInvalidSession(e,t);return}let s={instanceId:e,terminalId:t,encrypted:i};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:n,data:i}of t){let s=this.cryptoService.encryptOutput(e,i);if(!s){this.signalInvalidSession(n,e);continue}let a={instanceId:n,terminalId:e,encrypted:s};this.socket?.emit("terminal:output",a)}}}signalInvalidSession(e,t){let n=Date.now(),i=this.invalidSessionSignalAt.get(t)??0;n-i<this.INVALID_SESSION_SIGNAL_THROTTLE_MS||(this.invalidSessionSignalAt.set(t,n),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,n){let i={instanceId:e,terminalId:t,event:n};this.socket?.emit("terminal:event",i)}hasCapability(e){return this.negotiatedCapabilities.includes(e)}sendFileChangedEvent(e,t,n){let i={instanceId:e,terminalId:t,event:n};this.socket?.emit("file:changed",i)}sendFileListResponse(e,t){let n={instanceId:e,response:t};this.socket?.emit("file:list:response",n)}sendAgentRename(e){this.socket?.emit("agent:rename",{name:e})}isRemoteRenameInProgress(){return this.isRemoteRename}getSocket(){return this.socket}emit(e,t){let n=(0,Mh.generateCorrelationId)(),i=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:n}:t;return(0,Mh.runWithCorrelation)(n,()=>new Promise((s,a)=>{if(!this.socket?.connected){a(new Error("WebSocket not connected"));return}this.socket.emit(e,i,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 n=this.cryptoService.decryptInput(e.terminalId,e.encrypted);if(!n){this.logger.error("Failed to decrypt terminal input",e.terminalId),this.signalInvalidSession(e.instanceId,e.terminalId);return}t=n}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 n=this.getOrCreateInputReceiver(e.terminalId,e.streamId,e.instanceId,e.dbTerminalId);if(!n)return;n.receive(e.seq,t,e.paste,e.answerFor);return}this.inputHandler?.(e.terminalId,t,e.dbTerminalId,void 0,e.answerFor)}getOrCreateInputReceiver(e,t,n,i){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 i&&(s.routeId=i),n&&(s.instanceId=n),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 X0.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:i??e,instanceId:n??""}),a}setTerminalActiveCheck(e){this.terminalActiveCheck=e}routeIdFor(e){return this.inputReceivers.get(e)?.routeId??e}sendInputAck(e,t,n){let i=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:ack",{instanceId:i,terminalId:e,streamId:t,ackSeq:n})}sendInputResend(e,t,n){let i=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:resend",{instanceId:i,terminalId:e,streamId:t,fromSeq:n})}sendInputResume(e){let t=this.inputReceivers.get(e);if(!t)return;let{streamId:n,lastAckSeq:i}=t.receiver.resumeState();this.socket?.emit("input:resume",{instanceId:t.instanceId,terminalId:e,streamId:n,lastAckSeq:i})}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(n){this.logger.warn("Reconnect failed",n),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,Nh.getApiUrl)(this.config)}/health`,n=new AbortController,i=setTimeout(()=>n.abort(),5e3),s=await fetch(t,{method:"GET",signal:n.signal});return clearTimeout(i),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)}};go.WebSocketService=Sc});var jh=M(Yt=>{"use strict";var J0=Yt&&Yt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Z0=Yt&&Yt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Cc=Yt&&Yt.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&J0(t,e,n[i]);return Z0(t,e),t}})();Object.defineProperty(Yt,"__esModule",{value:!0});Yt.FileTransferService=void 0;Yt.resolveUploadPath=Bh;var mo=Cc(require("fs")),kn=Cc(require("path")),Dh=Cc(require("crypto")),je=Tr();function Bh(r,e,t){let n=kn.basename(t),i=(e??"").trim()||".";if(kn.isAbsolute(i))return kn.resolve(i,n);let s=kn.resolve(r,i),a=s===r||s.startsWith(r+kn.sep)?s:r;return kn.resolve(a,n)}var Tc=class{socket=null;activeTransfers=new Map;instanceId="";logger;fallbackDir;workspaceRoot=null;cryptoService=null;constructor(e,t="/tmp",n=null){this.logger=e,this.fallbackDir=t,this.workspaceRoot=n}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,n,i,s){let a=mo.readFileSync(t),c=t.split("/").pop()||"file";return this.initAndSendChunks(e,a,c,{mimeType:this.getMimeType(c),requestId:s,onProgress:n,onComplete:i})}async sendBuffer(e,t,n,i,s){return this.initAndSendChunks(e,t,n,{mimeType:i,purpose:s?.purpose,viewMetadata:s?.viewMetadata,requestId:s?.requestId,onProgress:s?.onProgress,onComplete:s?.onComplete})}async initAndSendChunks(e,t,n,i){if(!this.socket)throw new Error("Socket not connected");let s=t.length,a=(0,je.calculateTotalChunks)(s),c=this.calculateChecksum(t),u=Dh.randomUUID(),d={id:u,terminalId:e,filename:n,size:s,totalChunks:a,direction:je.TransferDirection.DOWNLOAD,status:je.TransferStatus.PENDING,deliveredChunks:new Set,pendingChunks:new Map,checksum:c,checksumAlgorithm:"sha256",onProgress:i.onProgress?(m,_)=>i.onProgress(u,m,_):void 0,onComplete:i.onComplete?(m,_)=>i.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:n,size:s,totalChunks:a,mimeType:i.mimeType||"application/octet-stream",checksum:c,direction:je.TransferDirection.DOWNLOAD,instanceId:this.instanceId};return i.requestId&&(p.requestId=i.requestId),i.purpose&&(p.purpose=i.purpose),i.viewMetadata&&(p.viewMetadata=i.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,n,i,s,a,c,u="sha256",d,p){let m={id:e,terminalId:t,filename:n,filePath:c,size:i,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 n=this.activeTransfers.get(e);if(n){for(let i of n.ackTimeouts.values())clearTimeout(i);if(n.status=je.TransferStatus.CANCELLED,n.onComplete?.(!1,t),this.socket){let i={transferId:e,reason:t};this.socket.emit("file:cancel",i)}this.activeTransfers.delete(e)}}async resumeTransfer(e){let t=this.activeTransfers.get(e);!t||!this.socket||this.socket.emit("file:sync",{transferId:e},n=>{if(n.status===je.TransferStatus.EXPIRED){t.onComplete?.(!1,"Transfer expired"),this.activeTransfers.delete(e);return}if(n.deliveredChunks)for(let i of n.deliveredChunks)t.deliveredChunks.add(i);if(t.direction===je.TransferDirection.DOWNLOAD&&n.missingChunks){t.status=je.TransferStatus.ACTIVE;for(let i of n.missingChunks)this.sendChunk(t,i)}})}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 n of t.ackTimeouts.values())clearTimeout(n);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 n=0;n<Math.min(je.WINDOW_SIZE,t.totalChunks);n++)t.deliveredChunks.has(n)||this.sendChunk(t,n)}sendChunk(e,t){if(!this.socket||!e.chunks)return;let n=e.chunks[t];if(!n)return;let i=e.pendingChunks.get(t),s={seq:t,data:n,retries:i?i.retries:0,sentAt:Date.now()};e.pendingChunks.set(t,s);let a=this.cryptoService?.encryptFileChunk(e.terminalId,new Uint8Array(n.buffer,n.byteOffset,n.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 n=t.ackTimeouts.get(e.seq);n&&(clearTimeout(n),t.ackTimeouts.delete(e.seq)),t.deliveredChunks.add(e.seq),t.pendingChunks.delete(e.seq),t.onProgress?.(t.deliveredChunks.size,t.totalChunks);let i=e.seq+je.WINDOW_SIZE;i<t.totalChunks&&!t.deliveredChunks.has(i)&&this.sendChunk(t,i),t.deliveredChunks.size===t.totalChunks&&this.finishSending(t)}handleAckTimeout(e,t){let n=this.activeTransfers.get(e);if(!n)return;let i=n.pendingChunks.get(t);i&&(i.retries<je.MAX_RETRIES?(i.retries++,this.sendChunk(n,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 n=e.encrypted?this.cryptoService?.decryptFileChunk(t.terminalId,e.encrypted):null;if(!n){this.cancelTransfer(e.transferId,"Chunk decryption failed (no E2E session?)");return}if(t.chunks[e.seq]=Buffer.from(n),t.deliveredChunks.add(e.seq),this.socket){let i={transferId:e.transferId,seq:e.seq};this.socket.emit("file:chunk:ack",i)}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 i=kn.dirname(e.filePath);mo.existsSync(i)||mo.mkdirSync(i,{recursive:!0}),mo.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(i){let s=i instanceof Error?i.message:String(i);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 n of t.ackTimeouts.values())clearTimeout(n);this.activeTransfers.delete(e.transferId)}}handleProgress(e){let t=this.activeTransfers.get(e.transferId);t&&t.onProgress?.(e.deliveredChunks,e.totalChunks)}handleIncomingFileInit(e,t){let n=Bh(this.workspaceRoot??this.fallbackDir,e.targetPath,e.filename);this.receiveFile(e.transferId,e.terminalId,e.filename,e.size,e.totalChunks,e.checksum,n,e.checksumAlgorithm||"sha256").then(()=>t({accepted:!0})).catch(i=>t({accepted:!1,error:i.message}))}calculateChecksum(e,t="sha256"){return t==="fnv1a"?this.fnv1aHash(e):Dh.createHash("sha256").update(e).digest("hex")}fnv1aHash(e){let t=2166136261;for(let i=0;i<e.length;i++)t^=e[i],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"}};Yt.FileTransferService=Tc});var Lc=M((Bw,Eo)=>{function qh(r){return Array.isArray(r)?r:[r]}var Q0=void 0,Oc="",Uh=" ",kc="\\",eE=/^\s+$/,tE=/(?:[^\\]|^)\\$/,rE=/^\\!/,nE=/^\\#/,iE=/\r?\n/g,sE=/^\.{0,2}\/|^\.{1,2}$/,oE=/\/$/,ni="/",Wh="node-ignore";typeof Symbol<"u"&&(Wh=Symbol.for("node-ignore"));var Hh=Wh,ii=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),aE=/([0-z])-([0-z])/g,Vh=()=>!1,cE=r=>r.replace(aE,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:Oc),fE=r=>{let{length:e}=r;return r.slice(0,e-e%2)},uE=[[/^\uFEFF/,()=>Oc],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?Uh:Oc)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+Uh}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let n=t.replace(/\\\*/g,"[^\\/]*");return e+n}],[/\\\\\\(?=[$.|*+(){^])/g,()=>kc],[/\\\\/g,()=>kc],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,n,i)=>e===kc?`\\[${t}${fE(n)}${i}`:i==="]"&&n.length%2===0?`[${cE(t)}${n}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],lE=/(^|\\\/)?\\\*$/,Ki="regex",yo="checkRegex",Kh="_",hE={[Ki](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[yo](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},dE=r=>uE.reduce((e,[t,n])=>e.replace(t,n.bind(r)),r),_o=r=>typeof r=="string",pE=r=>r&&_o(r)&&!eE.test(r)&&!tE.test(r)&&r.indexOf("#")!==0,gE=r=>r.split(iE).filter(Boolean),Pc=class{constructor(e,t,n,i,s,a){this.pattern=e,this.mark=t,this.negative=s,ii(this,"body",n),ii(this,"ignoreCase",i),ii(this,"regexPrefix",a)}get regex(){let e=Kh+Ki;return this[e]?this[e]:this._make(Ki,e)}get checkRegex(){let e=Kh+yo;return this[e]?this[e]:this._make(yo,e)}_make(e,t){let n=this.regexPrefix.replace(lE,hE[e]),i=this.ignoreCase?new RegExp(n,"i"):new RegExp(n);return ii(this,t,i)}},mE=({pattern:r,mark:e},t)=>{let n=!1,i=r;i.indexOf("!")===0&&(n=!0,i=i.substr(1)),i=i.replace(rE,"!").replace(nE,"#");let s=dE(i);return new Pc(r,e,i,t,n,s)},Ac=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[Hh]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(_o(e)&&(e={pattern:e}),pE(e.pattern)){let t=mE(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,qh(_o(e)?gE(e):e).forEach(this._add,this),this._added}test(e,t,n){let i=!1,s=!1,a;this._rules.forEach(u=>{let{negative:d}=u;s===d&&i!==s||d&&!i&&!s&&!t||!u[n].test(e)||(i=!d,s=d,a=d?Q0:u)});let c={ignored:i,unignored:s};return a&&(c.rule=a),c}},yE=(r,e)=>{throw new e(r)},Ir=(r,e,t)=>_o(r)?r?Ir.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),zh=r=>sE.test(r);Ir.isNotRelative=zh;Ir.convert=r=>r;var Rc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){ii(this,Hh,!0),this._rules=new Ac(t),this._strictPathCheck=!n,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,n,i){let s=e&&Ir.convert(e);return Ir(s,e,this._strictPathCheck?yE:Vh),this._t(s,t,n,i)}checkIgnore(e){if(!oE.test(e))return this.test(e);let t=e.split(ni).filter(Boolean);if(t.pop(),t.length){let n=this._t(t.join(ni)+ni,this._testCache,!0,t);if(n.ignored)return n}return this._rules.test(e,!1,yo)}_t(e,t,n,i){if(e in t)return t[e];if(i||(i=e.split(ni).filter(Boolean)),i.pop(),!i.length)return t[e]=this._rules.test(e,n,Ki);let s=this._t(i.join(ni)+ni,t,n,i);return t[e]=s.ignored?s:this._rules.test(e,n,Ki)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return qh(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},Ic=r=>new Rc(r),_E=r=>Ir(r&&Ir.convert(r),r,Vh),$h=()=>{let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");Ir.convert=r;let e=/^[a-z]:\//i;Ir.isNotRelative=t=>e.test(t)||zh(t)};typeof process<"u"&&process.platform==="win32"&&$h();Eo.exports=Ic;Ic.default=Ic;Eo.exports.isPathValid=_E;ii(Eo.exports,Symbol.for("setupWindows"),$h)});var Yh=M(Kt=>{"use strict";var EE=Kt&&Kt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),bE=Kt&&Kt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Gh=Kt&&Kt.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&EE(t,e,n[i]);return bE(t,e),t}})(),vE=Kt&&Kt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Kt,"__esModule",{value:!0});Kt.FileListService=void 0;var si=Gh(require("path")),Nc=Gh(require("fs/promises")),wE=vE(Lc()),Mc=Tr(),xE=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],Fc=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,wE.default)(),this.ignoreFilter.add(xE),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=si.join(this.workspaceRoot,".gitignore");try{let t=await Nc.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),n=await this.listDirectory(t,e.path);this.sendResponse({requestId:e.requestId,path:e.path,entries:n})}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 n=await Nc.readdir(e,{withFileTypes:!0}),i=[];for(let s of n){let a=t==="."||t===""?s.name:si.join(t,s.name);if(this.shouldHide(a,s.isDirectory()))continue;let c=si.join(e,s.name),u={name:s.name,path:a,type:s.isDirectory()?Mc.FileEntryType.DIRECTORY:Mc.FileEntryType.FILE};if(!s.isDirectory())try{let d=await Nc.stat(c);u.size=d.size,u.modified=d.mtime.toISOString()}catch{}i.push(u)}return i.sort((s,a)=>s.type!==a.type?s.type===Mc.FileEntryType.DIRECTORY?-1:1:s.name.localeCompare(a.name))}shouldHide(e,t){let n=e.split(si.sep).join("/"),i=t?`${n}/`:n;return this.ignoreFilter.ignores(i)}resolvePath(e){if(!this.workspaceRoot)throw new Error("No workspace root");if(e==="."||e==="")return this.workspaceRoot;let t=si.resolve(this.workspaceRoot,e);if(t!==this.workspaceRoot&&!t.startsWith(this.workspaceRoot+si.sep))throw new Error("Path outside workspace");return t}sendResponse(e){this.onResponseCallback?.(e)}dispose(){this.onResponseCallback=null}};Kt.FileListService=Fc});var Jh=M(dr=>{"use strict";var SE=dr&&dr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),TE=dr&&dr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Xh=dr&&dr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&SE(t,e,n[i]);return TE(t,e),t}})();Object.defineProperty(dr,"__esModule",{value:!0});dr.FileTrackerService=void 0;var Dc=Xh(require("path")),On=Xh(require("fs/promises")),CE=require("child_process"),kE=require("util"),Xt=Tr(),Bc=(0,kE.promisify)(CE.execFile),jc={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},Uc=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 n=this.outputBuffers.get(e)||"";n+=t,n.length>10240&&(n=n.slice(-10240)),this.outputBuffers.set(e,n);try{await this.parseToolCalls(e,n)}catch(i){this.logger.error("Error parsing tool calls",i)}}async parseToolCalls(e,t){let n=this.stripAnsi(t),i=n.match(jc.toolStart);if(i){let a=i[1],c=i[2],u=`${a}_${Date.now()}_${c}`;this.pendingToolCalls.has(u)||await this.handleToolStart(e,u,a,{file_path:c})}let s=n.match(jc.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(jc.toolError.test(n))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,n,i){if(!this.isFileModifyingTool(n))return;let s=this.extractFilePath(n,i);if(!s)return;let a=this.resolveFilePath(s),c={toolId:t,toolName:n,filePath:s,timestamp:new Date().toISOString()};this.pendingToolCalls.set(t,c);let u;try{u=await On.readFile(a,"utf-8")}catch{u=void 0}let d={path:s,changeType:u===void 0?Xt.FileChangeType.CREATE:Xt.FileChangeType.MODIFY,toolName:n,toolId:t,timestamp:c.timestamp,previousContent:u},p=this.trackedFiles.get(e)||[];p.push(d),this.trackedFiles.set(e,p)}async handleToolEnd(e,t,n,i){if(!this.isFileModifyingTool(n)||!this.pendingToolCalls.get(t))return;if(this.pendingToolCalls.delete(t),i==="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 On.stat(u);c.size=p.size}catch{c.changeType=Xt.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 n=this.resolveFilePath(t.path),i=this.getViewableMimeType(t.path);if(i&&this.onFileViewTransferCallback){try{let a=await On.readFile(n),c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:i};this.onFileViewTransferCallback(e,Buffer.from(a),c)}catch(a){let c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:i,error:a instanceof Error?a.message:"Unknown error"};this.onFileViewTransferCallback(e,Buffer.alloc(0),c)}return}let s;try{t.type===Xt.FileViewType.CONTENT?s=await this.getFileContent(t,n):s=await this.getFileDiff(e,t,n)}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===Xt.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 n=e.maxSize||1048576,i=await On.stat(t),s=await On.readFile(t,"utf-8"),a=!1,c=s;return s.length>n&&(c=s.slice(0,n),a=!0),{requestId:e.requestId,path:e.path,type:Xt.FileViewType.CONTENT,content:c,language:(0,Xt.getLanguageFromPath)(e.path),size:i.size,truncated:a}}async getFileDiff(e,t,n){let i=t.diffBase||Xt.DiffBase.GIT,s;return i===Xt.DiffBase.GIT?s=await this.getGitDiff(n):s=await this.getPreviousDiff(e,t.path,n),{requestId:t.requestId,path:t.path,type:Xt.FileViewType.DIFF,content:s,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await Bc("git",["diff","--cached","--",e],{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:n}=await Bc("git",["diff","--",e],{cwd:this.workspaceRoot});if(n.trim())return n;let{stdout:i}=await Bc("git",["status","--porcelain","--",e],{cwd:this.workspaceRoot});if(i.startsWith("??")||i.startsWith("A ")){let a=(await On.readFile(e,"utf-8")).split(`
29
- `),c=Dc.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
- `)}return"(no changes)"}catch{throw new Error("Git not available")}}async getPreviousDiff(e,t,n){let a=(this.trackedFiles.get(e)||[]).find(d=>d.path===t&&d.previousContent!==void 0)?.previousContent||"",c;try{c=await On.readFile(n,"utf-8")}catch{c=""}let u=(0,Xt.createSimpleDiff)(a,c,t);return this.diffContentToUnifiedText(u)}diffContentToUnifiedText(e){let t=[];t.push(`--- a/${e.path}`),t.push(`+++ b/${e.path}`);for(let n of e.hunks){t.push(`@@ -${n.oldStart},${n.oldLines} +${n.newStart},${n.newLines} @@`);for(let i of n.lines)switch(i.type){case"add":t.push(`+${i.content}`);break;case"remove":t.push(`-${i.content}`);break;case"context":t.push(` ${i.content}`);break}}return t.join(`
31
- `)}clearTerminal(e){this.trackedFiles.delete(e),this.outputBuffers.delete(e)}getChangedFiles(e){return(this.trackedFiles.get(e)||[]).map(n=>({path:n.path,changeType:n.changeType,timestamp:n.timestamp,source:"tool-call",toolName:n.toolName,toolId:n.toolId,size:n.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 n=Dc.resolve(t,e);if(n!==t&&!n.startsWith(t+Dc.sep))throw new Error("Path escapes workspace root");return n}dispose(){this.trackedFiles.clear(),this.pendingToolCalls.clear(),this.onFileChangedCallback=null,this.onFileViewTransferCallback=null}};dr.FileTrackerService=Uc});var Qh=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 OE=bu();Object.defineProperty(rt,"CryptoService",{enumerable:!0,get:function(){return OE.CryptoService}});var PE=vu();Object.defineProperty(rt,"AuthService",{enumerable:!0,get:function(){return PE.AuthService}});var Zh=Su();Object.defineProperty(rt,"StatusDetector",{enumerable:!0,get:function(){return Zh.StatusDetector}});Object.defineProperty(rt,"isAnswerKeystroke",{enumerable:!0,get:function(){return Zh.isAnswerKeystroke}});var AE=Fh();Object.defineProperty(rt,"WebSocketService",{enumerable:!0,get:function(){return AE.WebSocketService}});var RE=jh();Object.defineProperty(rt,"FileTransferService",{enumerable:!0,get:function(){return RE.FileTransferService}});var IE=Yh();Object.defineProperty(rt,"FileListService",{enumerable:!0,get:function(){return IE.FileListService}});var LE=Jh();Object.defineProperty(rt,"FileTrackerService",{enumerable:!0,get:function(){return LE.FileTrackerService}});var NE=xc();Object.defineProperty(rt,"InputStreamReceiver",{enumerable:!0,get:function(){return NE.InputStreamReceiver}})});var qi=M(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.FP_LABEL=J.KX_ACK_LABEL=J.KX_SIGN_LABEL=J.concatBytes=J.fingerprintShortHex=J.fingerprintIdentityKey=J.buildKxAckCanonical=J.buildKxCanonical=J.verifySessionKey=J.signSessionKey=J.identityPublicFromSecret=J.generateIdentityKeyPair=J.InputStreamReceiver=J.FileTrackerService=J.FileListService=J.FileTransferService=J.WebSocketService=J.isAnswerKeystroke=J.StatusDetector=J.AuthService=J.CryptoService=J.getCurrentCorrelationId=J.runWithCorrelation=J.generateCorrelationId=J.getWsUrl=J.getApiUrl=J.CircularBuffer=J.formatLogLine=J.shouldLog=J.LOG_LEVELS=void 0;var Kc=Bf();Object.defineProperty(J,"LOG_LEVELS",{enumerable:!0,get:function(){return Kc.LOG_LEVELS}});Object.defineProperty(J,"shouldLog",{enumerable:!0,get:function(){return Kc.shouldLog}});Object.defineProperty(J,"formatLogLine",{enumerable:!0,get:function(){return Kc.formatLogLine}});var oi=Kf();Object.defineProperty(J,"CircularBuffer",{enumerable:!0,get:function(){return oi.CircularBuffer}});Object.defineProperty(J,"getApiUrl",{enumerable:!0,get:function(){return oi.getApiUrl}});Object.defineProperty(J,"getWsUrl",{enumerable:!0,get:function(){return oi.getWsUrl}});Object.defineProperty(J,"generateCorrelationId",{enumerable:!0,get:function(){return oi.generateCorrelationId}});Object.defineProperty(J,"runWithCorrelation",{enumerable:!0,get:function(){return oi.runWithCorrelation}});Object.defineProperty(J,"getCurrentCorrelationId",{enumerable:!0,get:function(){return oi.getCurrentCorrelationId}});var Lr=Qh();Object.defineProperty(J,"CryptoService",{enumerable:!0,get:function(){return Lr.CryptoService}});Object.defineProperty(J,"AuthService",{enumerable:!0,get:function(){return Lr.AuthService}});Object.defineProperty(J,"StatusDetector",{enumerable:!0,get:function(){return Lr.StatusDetector}});Object.defineProperty(J,"isAnswerKeystroke",{enumerable:!0,get:function(){return Lr.isAnswerKeystroke}});Object.defineProperty(J,"WebSocketService",{enumerable:!0,get:function(){return Lr.WebSocketService}});Object.defineProperty(J,"FileTransferService",{enumerable:!0,get:function(){return Lr.FileTransferService}});Object.defineProperty(J,"FileListService",{enumerable:!0,get:function(){return Lr.FileListService}});Object.defineProperty(J,"FileTrackerService",{enumerable:!0,get:function(){return Lr.FileTrackerService}});Object.defineProperty(J,"InputStreamReceiver",{enumerable:!0,get:function(){return Lr.InputStreamReceiver}});var qt=ta();Object.defineProperty(J,"generateIdentityKeyPair",{enumerable:!0,get:function(){return qt.generateIdentityKeyPair}});Object.defineProperty(J,"identityPublicFromSecret",{enumerable:!0,get:function(){return qt.identityPublicFromSecret}});Object.defineProperty(J,"signSessionKey",{enumerable:!0,get:function(){return qt.signSessionKey}});Object.defineProperty(J,"verifySessionKey",{enumerable:!0,get:function(){return qt.verifySessionKey}});Object.defineProperty(J,"buildKxCanonical",{enumerable:!0,get:function(){return qt.buildKxCanonical}});Object.defineProperty(J,"buildKxAckCanonical",{enumerable:!0,get:function(){return qt.buildKxAckCanonical}});Object.defineProperty(J,"fingerprintIdentityKey",{enumerable:!0,get:function(){return qt.fingerprintIdentityKey}});Object.defineProperty(J,"fingerprintShortHex",{enumerable:!0,get:function(){return qt.fingerprintShortHex}});Object.defineProperty(J,"concatBytes",{enumerable:!0,get:function(){return qt.concatBytes}});Object.defineProperty(J,"KX_SIGN_LABEL",{enumerable:!0,get:function(){return qt.KX_SIGN_LABEL}});Object.defineProperty(J,"KX_ACK_LABEL",{enumerable:!0,get:function(){return qt.KX_ACK_LABEL}});Object.defineProperty(J,"FP_LABEL",{enumerable:!0,get:function(){return qt.FP_LABEL}})});var Vc=M((Hi,Hc)=>{(function(r,e){typeof Hi=="object"&&typeof Hc=="object"?Hc.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof Hi=="object"?Hi["electron-machine-id"]=e(require("child_process"),require("crypto")):r["electron-machine-id"]=e(r.child_process,r.crypto)})(Hi,function(r,e){return(function(t){function n(s){if(i[s])return i[s].exports;var a=i[s]={exports:{},id:s,loaded:!1};return t[s].call(a.exports,a,a.exports,n),a.loaded=!0,a.exports}var i={};return n.m=t,n.c=i,n.p="",n(0)})([function(t,n,i){t.exports=i(34)},function(t,n,i){var s=i(29)("wks"),a=i(33),c=i(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,n){var i=t.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=i)},function(t,n,i){var s=i(9);t.exports=function(a){if(!s(a))throw TypeError(a+" is not an object!");return a}},function(t,n,i){t.exports=!i(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(t,n,i){var s=i(12),a=i(17);t.exports=i(4)?function(c,u,d){return s.f(c,u,a(1,d))}:function(c,u,d){return c[u]=d,c}},function(t,n){var i=t.exports={version:"2.4.0"};typeof __e=="number"&&(__e=i)},function(t,n,i){var s=i(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,n){var i={}.hasOwnProperty;t.exports=function(s,a){return i.call(s,a)}},function(t,n){t.exports=function(i){return typeof i=="object"?i!==null:typeof i=="function"}},function(t,n){t.exports={}},function(t,n){var i={}.toString;t.exports=function(s){return i.call(s).slice(8,-1)}},function(t,n,i){var s=i(3),a=i(26),c=i(32),u=Object.defineProperty;n.f=i(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,n,i){var s=i(42),a=i(15);t.exports=function(c){return s(a(c))}},function(t,n){t.exports=function(i){if(typeof i!="function")throw TypeError(i+" is not a function!");return i}},function(t,n){t.exports=function(i){if(i==null)throw TypeError("Can't call method on "+i);return i}},function(t,n,i){var s=i(9),a=i(2).document,c=s(a)&&s(a.createElement);t.exports=function(u){return c?a.createElement(u):{}}},function(t,n){t.exports=function(i,s){return{enumerable:!(1&i),configurable:!(2&i),writable:!(4&i),value:s}}},function(t,n,i){var s=i(12).f,a=i(8),c=i(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,n,i){var s=i(29)("keys"),a=i(33);t.exports=function(c){return s[c]||(s[c]=a(c))}},function(t,n){var i=Math.ceil,s=Math.floor;t.exports=function(a){return isNaN(a=+a)?0:(a>0?s:i)(a)}},function(t,n,i){var s=i(11),a=i(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,n){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,n,i){var s=i(2),a=i(6),c=i(7),u=i(5),d="prototype",p=function(m,_,v){var S,T,H,de=m&p.F,z=m&p.G,C=m&p.S,D=m&p.P,Q=m&p.B,K=m&p.W,U=z?a:a[_]||(a[_]={}),le=U[d],pe=z?s:C?s[_]:(s[_]||{})[d];z&&(v=_);for(S in v)T=!de&&pe&&pe[S]!==void 0,T&&S in U||(H=T?pe[S]:v[S],U[S]=z&&typeof pe[S]!="function"?v[S]:Q&&T?c(H,s):K&&pe[S]==H?(function(se){var nt=function(we,Se,_e){if(this instanceof se){switch(arguments.length){case 0:return new se;case 1:return new se(we);case 2:return new se(we,Se)}return new se(we,Se,_e)}return se.apply(this,arguments)};return nt[d]=se[d],nt})(H):D&&typeof H=="function"?c(Function.call,H):H,D&&((U.virtual||(U.virtual={}))[S]=H,m&p.R&&le&&!le[S]&&u(le,S,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,n){t.exports=function(i){try{return!!i()}catch{return!0}}},function(t,n,i){t.exports=i(2).document&&document.documentElement},function(t,n,i){t.exports=!i(4)&&!i(24)(function(){return Object.defineProperty(i(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(t,n,i){"use strict";var s=i(28),a=i(23),c=i(57),u=i(5),d=i(8),p=i(10),m=i(45),_=i(18),v=i(52),S=i(1)("iterator"),T=!([].keys&&"next"in[].keys()),H="@@iterator",de="keys",z="values",C=function(){return this};t.exports=function(D,Q,K,U,le,pe,se){m(K,Q,U);var nt,we,Se,_e=function(j){if(!T&&j in Te)return Te[j];switch(j){case de:return function(){return new K(this,j)};case z:return function(){return new K(this,j)}}return function(){return new K(this,j)}},We=Q+" Iterator",at=le==z,Qe=!1,Te=D.prototype,it=Te[S]||Te[H]||le&&Te[le],ze=it||_e(le),yt=le?at?_e("entries"):ze:void 0,L=Q=="Array"&&Te.entries||it;if(L&&(Se=v(L.call(new D)),Se!==Object.prototype&&(_(Se,We,!0),s||d(Se,S)||u(Se,S,C))),at&&it&&it.name!==z&&(Qe=!0,ze=function(){return it.call(this)}),s&&!se||!T&&!Qe&&Te[S]||u(Te,S,ze),p[Q]=ze,p[We]=C,le)if(nt={values:at?ze:_e(z),keys:pe?ze:_e(de),entries:yt},se)for(we in nt)we in Te||c(Te,we,nt[we]);else a(a.P+a.F*(T||Qe),Q,nt);return nt}},function(t,n){t.exports=!0},function(t,n,i){var s=i(2),a="__core-js_shared__",c=s[a]||(s[a]={});t.exports=function(u){return c[u]||(c[u]={})}},function(t,n,i){var s,a,c,u=i(7),d=i(41),p=i(25),m=i(16),_=i(2),v=_.process,S=_.setImmediate,T=_.clearImmediate,H=_.MessageChannel,de=0,z={},C="onreadystatechange",D=function(){var K=+this;if(z.hasOwnProperty(K)){var U=z[K];delete z[K],U()}},Q=function(K){D.call(K.data)};S&&T||(S=function(K){for(var U=[],le=1;arguments.length>le;)U.push(arguments[le++]);return z[++de]=function(){d(typeof K=="function"?K:Function(K),U)},s(de),de},T=function(K){delete z[K]},i(11)(v)=="process"?s=function(K){v.nextTick(u(D,K,1))}:H?(a=new H,c=a.port2,a.port1.onmessage=Q,s=u(c.postMessage,c,1)):_.addEventListener&&typeof postMessage=="function"&&!_.importScripts?(s=function(K){_.postMessage(K+"","*")},_.addEventListener("message",Q,!1)):s=C in m("script")?function(K){p.appendChild(m("script"))[C]=function(){p.removeChild(this),D.call(K)}}:function(K){setTimeout(u(D,K,1),0)}),t.exports={set:S,clear:T}},function(t,n,i){var s=i(20),a=Math.min;t.exports=function(c){return c>0?a(s(c),9007199254740991):0}},function(t,n,i){var s=i(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,n){var i=0,s=Math.random();t.exports=function(a){return"Symbol(".concat(a===void 0?"":a,")_",(++i+s).toString(36))}},function(t,n,i){"use strict";function s(C){return C&&C.__esModule?C:{default:C}}function a(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function c(C){return(0,S.createHash)("sha256").update(C).digest("hex")}function u(C){switch(H){case"darwin":return C.split("IOPlatformUUID")[1].split(`
32
- `)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return C.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return C.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return C.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function d(C){var D=u((0,v.execSync)(z[H]).toString());return C?D:c(D)}function p(C){return new _.default(function(D,Q){return(0,v.exec)(z[H],{},function(K,U,le){if(K)return Q(new Error("Error while obtaining machine id: "+K.stack));var pe=u(U.toString());return D(C?pe:c(pe))})})}Object.defineProperty(n,"__esModule",{value:!0});var m=i(35),_=s(m);n.machineIdSync=d,n.machineId=p;var v=i(70),S=i(71),T=process,H=T.platform,de={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},z={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:de[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,n,i){t.exports={default:i(36),__esModule:!0}},function(t,n,i){i(66),i(68),i(69),i(67),t.exports=i(6).Promise},function(t,n){t.exports=function(){}},function(t,n){t.exports=function(i,s,a,c){if(!(i instanceof s)||c!==void 0&&c in i)throw TypeError(a+": incorrect invocation!");return i}},function(t,n,i){var s=i(13),a=i(31),c=i(62);t.exports=function(u){return function(d,p,m){var _,v=s(d),S=a(v.length),T=c(m,S);if(u&&p!=p){for(;S>T;)if(_=v[T++],_!=_)return!0}else for(;S>T;T++)if((u||T in v)&&v[T]===p)return u||T||0;return!u&&-1}}},function(t,v,i){var s=i(7),a=i(44),c=i(43),u=i(3),d=i(31),p=i(64),m={},_={},v=t.exports=function(S,T,H,de,z){var C,D,Q,K,U=z?function(){return S}:p(S),le=s(H,de,T?2:1),pe=0;if(typeof U!="function")throw TypeError(S+" is not iterable!");if(c(U)){for(C=d(S.length);C>pe;pe++)if(K=T?le(u(D=S[pe])[0],D[1]):le(S[pe]),K===m||K===_)return K}else for(Q=U.call(S);!(D=Q.next()).done;)if(K=a(Q,le,D.value,T),K===m||K===_)return K};v.BREAK=m,v.RETURN=_},function(t,n){t.exports=function(i,s,a){var c=a===void 0;switch(s.length){case 0:return c?i():i.call(a);case 1:return c?i(s[0]):i.call(a,s[0]);case 2:return c?i(s[0],s[1]):i.call(a,s[0],s[1]);case 3:return c?i(s[0],s[1],s[2]):i.call(a,s[0],s[1],s[2]);case 4:return c?i(s[0],s[1],s[2],s[3]):i.call(a,s[0],s[1],s[2],s[3])}return i.apply(a,s)}},function(t,n,i){var s=i(11);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(a){return s(a)=="String"?a.split(""):Object(a)}},function(t,n,i){var s=i(10),a=i(1)("iterator"),c=Array.prototype;t.exports=function(u){return u!==void 0&&(s.Array===u||c[a]===u)}},function(t,n,i){var s=i(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,n,i){"use strict";var s=i(49),a=i(17),c=i(18),u={};i(5)(u,i(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,n,i){var s=i(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,n){t.exports=function(i,s){return{value:s,done:!!i}}},function(t,n,i){var s=i(2),a=i(30).set,c=s.MutationObserver||s.WebKitMutationObserver,u=s.process,d=s.Promise,p=i(11)(u)=="process";t.exports=function(){var m,_,v,S=function(){var z,C;for(p&&(z=u.domain)&&z.exit();m;){C=m.fn,m=m.next;try{C()}catch(D){throw m?v():_=void 0,D}}_=void 0,z&&z.enter()};if(p)v=function(){u.nextTick(S)};else if(c){var T=!0,H=document.createTextNode("");new c(S).observe(H,{characterData:!0}),v=function(){H.data=T=!T}}else if(d&&d.resolve){var de=d.resolve();v=function(){de.then(S)}}else v=function(){a.call(s,S)};return function(z){var C={fn:z,next:void 0};_&&(_.next=C),m||(m=C,v()),_=C}}},function(t,n,i){var s=i(3),a=i(50),c=i(22),u=i(19)("IE_PROTO"),d=function(){},p="prototype",m=function(){var _,v=i(16)("iframe"),S=c.length,T=">";for(v.style.display="none",i(25).appendChild(v),v.src="javascript:",_=v.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(_,v){var S;return _!==null?(d[p]=s(_),S=new d,d[p]=null,S[u]=_):S=m(),v===void 0?S:a(S,v)}},function(t,n,i){var s=i(12),a=i(3),c=i(54);t.exports=i(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,n,i){var s=i(55),a=i(17),c=i(13),u=i(32),d=i(8),p=i(26),m=Object.getOwnPropertyDescriptor;n.f=i(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,n,i){var s=i(8),a=i(63),c=i(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,n,i){var s=i(8),a=i(13),c=i(39)(!1),u=i(19)("IE_PROTO");t.exports=function(d,p){var m,_=a(d),v=0,S=[];for(m in _)m!=u&&s(_,m)&&S.push(m);for(;p.length>v;)s(_,m=p[v++])&&(~c(S,m)||S.push(m));return S}},function(t,n,i){var s=i(53),a=i(22);t.exports=Object.keys||function(c){return s(c,a)}},function(t,n){n.f={}.propertyIsEnumerable},function(t,n,i){var s=i(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,n,i){t.exports=i(5)},function(t,n,i){var s=i(9),a=i(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=i(7)(Function.call,i(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,n,i){"use strict";var s=i(2),a=i(6),c=i(12),u=i(4),d=i(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,n,i){var s=i(3),a=i(14),c=i(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,n,i){var s=i(20),a=i(15);t.exports=function(c){return function(u,d){var p,m,_=String(a(u)),v=s(d),S=_.length;return v<0||v>=S?c?"":void 0:(p=_.charCodeAt(v),p<55296||p>56319||v+1===S||(m=_.charCodeAt(v+1))<56320||m>57343?c?_.charAt(v):p:c?_.slice(v,v+2):(p-55296<<10)+(m-56320)+65536)}}},function(t,n,i){var s=i(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,n,i){var s=i(15);t.exports=function(a){return Object(s(a))}},function(t,n,i){var s=i(21),a=i(1)("iterator"),c=i(10);t.exports=i(6).getIteratorMethod=function(u){if(u!=null)return u[a]||u["@@iterator"]||c[s(u)]}},function(t,n,i){"use strict";var s=i(37),a=i(47),c=i(10),u=i(13);t.exports=i(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,n){},function(t,n,i){"use strict";var s,a,c,u=i(28),d=i(2),p=i(7),m=i(21),_=i(23),v=i(9),S=(i(3),i(14)),T=i(38),H=i(40),de=(i(58).set,i(60)),z=i(30).set,C=i(48)(),D="Promise",Q=d.TypeError,U=d.process,K=d[D],U=d.process,le=m(U)=="process",pe=function(){},se=!!(function(){try{var L=K.resolve(1),j=(L.constructor={})[i(1)("species")]=function(R){R(pe,pe)};return(le||typeof PromiseRejectionEvent=="function")&&L.then(pe)instanceof j}catch{}})(),nt=function(L,j){return L===j||L===K&&j===c},we=function(L){var j;return!(!v(L)||typeof(j=L.then)!="function")&&j},Se=function(L){return nt(K,L)?new _e(L):new a(L)},_e=a=function(L){var j,R;this.promise=new L(function(A,ee){if(j!==void 0||R!==void 0)throw Q("Bad Promise constructor");j=A,R=ee}),this.resolve=S(j),this.reject=S(R)},We=function(L){try{L()}catch(j){return{error:j}}},at=function(L,j){if(!L._n){L._n=!0;var R=L._c;C(function(){for(var A=L._v,ee=L._s==1,Ne=0,Xe=function(st){var dt,yr,Fr=ee?st.ok:st.fail,sn=st.resolve,Dr=st.reject,Rn=st.domain;try{Fr?(ee||(L._h==2&&it(L),L._h=1),Fr===!0?dt=A:(Rn&&Rn.enter(),dt=Fr(A),Rn&&Rn.exit()),dt===st.promise?Dr(Q("Promise-chain cycle")):(yr=we(dt))?yr.call(dt,sn,Dr):sn(dt)):Dr(A)}catch(Qi){Dr(Qi)}};R.length>Ne;)Xe(R[Ne++]);L._c=[],L._n=!1,j&&!L._h&&Qe(L)})}},Qe=function(L){z.call(d,function(){var j,R,A,ee=L._v;if(Te(L)&&(j=We(function(){le?U.emit("unhandledRejection",ee,L):(R=d.onunhandledrejection)?R({promise:L,reason:ee}):(A=d.console)&&A.error&&A.error("Unhandled promise rejection",ee)}),L._h=le||Te(L)?2:1),L._a=void 0,j)throw j.error})},Te=function(L){if(L._h==1)return!1;for(var j,R=L._a||L._c,A=0;R.length>A;)if(j=R[A++],j.fail||!Te(j.promise))return!1;return!0},it=function(L){z.call(d,function(){var j;le?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()),at(j,!0))},yt=function(L){var j,R=this;if(!R._d){R._d=!0,R=R._w||R;try{if(R===L)throw Q("Promise can't be resolved itself");(j=we(L))?C(function(){var A={_w:R,_d:!1};try{j.call(L,p(yt,A,1),p(ze,A,1))}catch(ee){ze.call(A,ee)}}):(R._v=L,R._s=1,at(R,!1))}catch(A){ze.call({_w:R,_d:!1},A)}}};se||(K=function(L){T(this,K,D,"_h"),S(L),s.call(this);try{L(p(yt,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=i(56)(K.prototype,{then:function(L,j){var R=Se(de(this,K));return R.ok=typeof L!="function"||L,R.fail=typeof j=="function"&&j,R.domain=le?U.domain:void 0,this._c.push(R),this._a&&this._a.push(R),this._s&&at(this,!1),R.promise},catch:function(L){return this.then(void 0,L)}}),_e=function(){var L=new s;this.promise=L,this.resolve=p(yt,L,1),this.reject=p(ze,L,1)}),_(_.G+_.W+_.F*!se,{Promise:K}),i(18)(K,D),i(59)(D),c=i(6)[D],_(_.S+_.F*!se,D,{reject:function(L){var j=Se(this),R=j.reject;return R(L),j.promise}}),_(_.S+_.F*(u||!se),D,{resolve:function(L){if(L instanceof K&&nt(L.constructor,this))return L;var j=Se(this),R=j.resolve;return R(L),j.promise}}),_(_.S+_.F*!(se&&i(46)(function(L){K.all(L).catch(pe)})),D,{all:function(L){var j=this,R=Se(j),A=R.resolve,ee=R.reject,Ne=We(function(){var Xe=[],st=0,dt=1;H(L,!1,function(yr){var Fr=st++,sn=!1;Xe.push(void 0),dt++,j.resolve(yr).then(function(Dr){sn||(sn=!0,Xe[Fr]=Dr,--dt||A(Xe))},ee)}),--dt||A(Xe)});return Ne&&ee(Ne.error),R.promise},race:function(L){var j=this,R=Se(j),A=R.reject,ee=We(function(){H(L,!1,function(Ne){j.resolve(Ne).then(R.resolve,A)})});return ee&&A(ee.error),R.promise}})},function(t,n,i){"use strict";var s=i(61)(!0);i(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,n,i){i(65);for(var s=i(2),a=i(5),c=i(10),u=i(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,n){t.exports=require("child_process")},function(t,n){t.exports=require("crypto")}])})});function jE(){try{return $c.default.statSync("/.dockerenv"),!0}catch{return!1}}function UE(){try{return $c.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Gc(){return zc===void 0&&(zc=jE()||UE()),zc}var $c,zc,id=Wt(()=>{$c=ue(require("node:fs"),1)});function ai(){return Yc===void 0&&(Yc=KE()||Gc()),Yc}var sd,Yc,KE,Xc=Wt(()=>{sd=ue(require("node:fs"),1);id();KE=()=>{try{return sd.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var Jc,ad,cd,od,Zr,Zc=Wt(()=>{Jc=ue(require("node:process"),1),ad=ue(require("node:os"),1),cd=ue(require("node:fs"),1);Xc();od=()=>{if(Jc.default.platform!=="linux")return!1;if(ad.default.release().toLowerCase().includes("microsoft"))return!ai();try{return cd.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!ai():!1}catch{return!1}},Zr=Jc.default.env.__IS_WSL_TEST__?od:od()});var Qc,$i,qE,WE,ef,fd=Wt(()=>{Qc=ue(require("node:process"),1),$i=ue(require("node:fs/promises"),1);Zc();Zc();qE=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",n=!1;try{await $i.default.access(t,$i.constants.F_OK),n=!0}catch{}if(!n)return r;let i=await $i.default.readFile(t,{encoding:"utf8"}),s=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return s?(e=s.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),WE=async()=>`${await qE()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,ef=async()=>Zr?WE():`${Qc.default.env.SYSTEMROOT||Qc.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Qr(r,e,t){let n=i=>Object.defineProperty(r,e,{value:i,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let i=t();return n(i),i},set(i){n(i)}}),r}var ud=Wt(()=>{});async function tf(){if(hd.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await HE("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 ld,hd,dd,HE,pd=Wt(()=>{ld=require("node:util"),hd=ue(require("node:process"),1),dd=require("node:child_process"),HE=(0,ld.promisify)(dd.execFile)});async function yd(r,{humanReadableOutput:e=!0,signal:t}={}){if(gd.default.platform!=="darwin")throw new Error("macOS only");let n=e?[]:["-ss"],i={};t&&(i.signal=t);let{stdout:s}=await VE("osascript",["-e",r,n],i);return s.trim()}var gd,md,rf,VE,_d=Wt(()=>{gd=ue(require("node:process"),1),md=require("node:util"),rf=require("node:child_process"),VE=(0,md.promisify)(rf.execFile)});async function nf(r){return yd(`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 Ed=Wt(()=>{_d()});async function of(r=zE){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 sf(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:n}=t.groups,i=n.lastIndexOf("."),s=n.lastIndexOf("-"),a=i===-1?void 0:n.slice(0,i),c=s===-1?void 0:n.slice(0,s);return vo[n]??vo[a]??vo[c]??{name:n,id:n}}var bd,vd,zE,vo,sx,sf,wd=Wt(()=>{bd=require("node:util"),vd=require("node:child_process"),zE=(0,bd.promisify)(vd.execFile),vo={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"}},sx=new Map(Object.entries(vo)),sf=class extends Error{}});async function af(){if(wo.default.platform==="darwin"){let r=await tf();return{name:await nf(r),id:r}}if(wo.default.platform==="linux"){let{stdout:r}=await $E("xdg-mime",["query","default","x-scheme-handler/http"]),e=r.trim();return{name:GE(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(wo.default.platform==="win32")return of();throw new Error("Only macOS, Linux, and Windows are supported")}var xd,wo,Sd,$E,GE,Td=Wt(()=>{xd=require("node:util"),wo=ue(require("node:process"),1),Sd=require("node:child_process");pd();Ed();wd();$E=(0,xd.promisify)(Sd.execFile),GE=r=>r.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var Id={};Pp(Id,{apps:()=>en,default:()=>QE,openApp:()=>ZE});async function XE(){let r=await ef(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=uf.Buffer.from(e,"utf16le").toString("base64"),{stdout:n}=await YE(r,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),i=n.trim(),s={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return s[i]?{id:s[i]}:{}}function Pd(r){if(typeof r=="string"||Array.isArray(r))return r;let{[kd]:e}=r;if(!e)throw new Error(`${kd} is not supported`);return e}function So({[ci]:r},{wsl:e}){if(e&&Zr)return Pd(e);if(!r)throw new Error(`${ci} is not supported`);return Pd(r)}var ff,uf,lf,Ad,Rd,hf,xo,eb,YE,cf,Cd,ci,kd,Od,Gi,JE,ZE,en,QE,Ld=Wt(()=>{ff=ue(require("node:process"),1),uf=require("node:buffer"),lf=ue(require("node:path"),1),Ad=require("node:url"),Rd=require("node:util"),hf=ue(require("node:child_process"),1),xo=ue(require("node:fs/promises"),1);fd();ud();Td();Xc();eb={},YE=(0,Rd.promisify)(hf.default.execFile),cf=lf.default.dirname((0,Ad.fileURLToPath)(eb.url)),Cd=lf.default.join(cf,"xdg-open"),{platform:ci,arch:kd}=ff.default;Od=async(r,e)=>{let t;for(let n of r)try{return await e(n)}catch(i){t=i}throw t},Gi=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return Od(r.app,c=>Gi({...r,app:c}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return Od(e,c=>Gi({...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=Zr?await XE():await af();if(d.id in c){let p=c[d.id];return e==="browserPrivate"&&t.push(u[p]),Gi({...r,app:{name:en[p],arguments:t}})}throw new Error(`${d.name} is not supported as a default browser`)}let n,i=[],s={};if(ci==="darwin")n="open",r.wait&&i.push("--wait-apps"),r.background&&i.push("--background"),r.newInstance&&i.push("--new"),e&&i.push("-a",e);else if(ci==="win32"||Zr&&!ai()&&!e){n=await ef(),i.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),Zr||(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=uf.Buffer.from(c.join(" "),"utf16le").toString("base64")}else{if(e)n=e;else{let c=!cf||cf==="/",u=!1;try{await xo.default.access(Cd,xo.constants.X_OK),u=!0}catch{}n=ff.default.versions.electron??(ci==="android"||c||!u)?"xdg-open":Cd}t.length>0&&i.push(...t),r.wait||(s.stdio="ignore",s.detached=!0)}ci==="darwin"&&t.length>0&&i.push("--args",...t),r.target&&i.push(r.target);let a=hf.default.spawn(n,i,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)},JE=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a `target`");return Gi({...e,target:r})},ZE=(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 Gi({...e,app:{name:r,arguments:t}})};en={};Qr(en,"chrome",()=>So({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"]}}));Qr(en,"brave",()=>So({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"]}}));Qr(en,"firefox",()=>So({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Qr(en,"edge",()=>So({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Qr(en,"browser",()=>"browser");Qr(en,"browserPrivate",()=>"browserPrivate");QE=JE});var Er=ue(require("fs")),as=ue(require("path"));var Lf=ue(require("os")),Nf=ue(require("path")),ss=ue(require("fs"));function os(){let r=Nf.join(Lf.homedir(),".termiq");return ss.existsSync(r)||ss.mkdirSync(r,{recursive:!0,mode:448}),r}var mi=class{filePath;data={};constructor(){this.filePath=as.join(os(),"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(Er.existsSync(this.filePath)){let e=Er.readFileSync(this.filePath,"utf-8");this.data=JSON.parse(e)}}catch{this.data={}}}save(){let e=as.dirname(this.filePath);Er.existsSync(e)||Er.mkdirSync(e,{recursive:!0,mode:448}),Er.writeFileSync(this.filePath,JSON.stringify(this.data,null,2),{mode:384})}};var br=ue(require("fs")),cs=ue(require("path"));var Rp={serverUrl:"https://termiq.io",agentName:"",multiViewer:!1},yi=class{config;filePath;constructor(e){this.filePath=cs.join(os(),"config.json"),this.config={...Rp,...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=cs.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=ue(require("fs")),Wc=ue(require("path")),td=ue(require("os")),bo=ue(qi()),ME="cli",qc=Wc.join(td.homedir(),".termiq","logs"),Jr=Wc.join(qc,"cli.log"),FE=5*1024*1024,ed=3;function DE(){try{if(!bt.existsSync(Jr)||bt.statSync(Jr).size<FE)return;for(let e=ed-1;e>=1;e--){let t=`${Jr}.${e}`,n=`${Jr}.${e+1}`;bt.existsSync(t)&&(e+1>ed?bt.unlinkSync(t):bt.renameSync(t,n))}bt.renameSync(Jr,`${Jr}.1`)}catch{}}function BE(r){try{bt.existsSync(qc)||bt.mkdirSync(qc,{recursive:!0}),DE(),bt.appendFileSync(Jr,r+`
34
- `,{encoding:"utf8"})}catch{}}var Wi=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 Jr}write(e,t,n){if(!(0,bo.shouldLog)(e,this.level))return;let i=(0,bo.formatLogLine)(e,ME,t,n);this.toFile?BE(i):process.stderr.write(i+`
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 rd=ue(require("os")),nd=ue(Vc()),Vi=class{cachedId=null;name;constructor(e){this.name=e||rd.hostname()||"CLI"}async getMachineId(){if(this.cachedId)return this.cachedId;try{this.cachedId=(0,nd.machineIdSync)()}catch{this.cachedId=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}return this.cachedId}getMachineName(){return this.name}};var zi=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 Yi=class{async openUrl(e){let{default:t}=await Promise.resolve().then(()=>(Ld(),Id));await t(e)}};var Nd=ue(require("fs")),df=ue(require("path"));function To(r){let e=r?[r]:[df.join(__dirname,"..","package.json"),df.join(__dirname,"..","..","package.json")];for(let t of e)try{let n=JSON.parse(Nd.readFileSync(t,"utf8"));if(typeof n.version=="string"&&n.version.length>0)return n.version}catch{}return"unknown"}function Md(r,e){for(let t=0;t<r.length;t++){let n=r[t];if(n.startsWith("-")){e.has(n)&&t++;continue}return n}}var pf=new Set(["--cid","--token","--server","--log-level"]),Fd=new Set(["--help","-h","--version","-V","--verbose","-v","--watch","-w","--log-to-file","--statusline","--multi-viewer","--force"]);function Dd(r,e,t){for(let n=0;n<r.length;n++){let i=r[n];if(!i.startsWith("-"))continue;let s=i.includes("=")?i.slice(0,i.indexOf("=")):i;if(e.has(s)||t.has(s)){e.has(s)&&!i.includes("=")&&n++;continue}return i}}var lp=ue(require("path")),ht=ue(qi()),hp=ue(Tr());var Bd=ue(require("os")),jd=require("crypto"),Ud=ue(require("node-pty")),Kd=ue(qi()),Co=class r{ptyProcess=null;outputBuffer=new Kd.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 n=process.env.SHELL||(Bd.platform()==="win32"?"powershell.exe":"/bin/bash"),i=process.stdout.columns||80,s=process.stdout.rows||24,a=Math.max(1,s-t);this.reservedBottomRows=t,this.ptyProcess=Ud.spawn(n,[],{name:"xterm-256color",cols:i,rows:a,cwd:e,env:{...process.env,TERMIQ_SESSION_ACTIVE:"1"}}),this.onResize?.(i,a),this.streamId=(0,jd.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",n,c),c}write(e,t=!1){if(this.ptyProcess){if(!t&&!this.draining){this.ptyProcess.write(e);return}for(let n of e)this.writeQueue.push(n);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 n of r.REBROADCAST_DELAYS_MS)this.rebroadcastTimers.push(setTimeout(()=>{this.ptyProcess&&(this.desiredCols!==e||this.desiredRows!==t||this.ptyProcess.resize(e,t))},n))}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 tn=ue(require("path")),ui=ue(require("fs"));var np=require("node:events"),ip=require("node:fs"),No=require("node:fs/promises"),xe=ue(require("node:path"),1);var Nr=require("node:fs/promises"),Mr=require("node:path"),Vd=require("node:stream"),Rt={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},gf={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:Rt.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(gf);var zd="READDIRP_RECURSIVE_ERROR",tb=new Set(["ENOENT","EPERM","EACCES","ELOOP",zd]),qd=[Rt.DIR_TYPE,Rt.EVERYTHING_TYPE,Rt.FILE_DIR_TYPE,Rt.FILE_TYPE],rb=new Set([Rt.DIR_TYPE,Rt.EVERYTHING_TYPE,Rt.FILE_DIR_TYPE]),nb=new Set([Rt.EVERYTHING_TYPE,Rt.FILE_DIR_TYPE,Rt.FILE_TYPE]),ib=r=>tb.has(r.code),sb=process.platform==="win32",Wd=r=>!0,Hd=r=>{if(r===void 0)return Wd;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(n=>t.basename===n)}return Wd},mf=class extends Vd.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={...gf,...e},{root:n,type:i}=t;this._fileFilter=Hd(t.fileFilter),this._directoryFilter=Hd(t.directoryFilter);let s=t.lstat?Nr.lstat:Nr.stat;sb?this._stat=a=>s(a,{bigint:!0}):this._stat=s,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:gf.depth,this._wantsDir=i?rb.has(i):!1,this._wantsFile=i?nb.has(i):!1,this._wantsEverything=i===Rt.EVERYTHING_TYPE,this._root=(0,Mr.resolve)(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,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,n=t&&t.files;if(n&&n.length>0){let{path:i,depth:s}=t,a=n.splice(0,e).map(u=>this._formatEntry(u,i)),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 i=this.parents.pop();if(!i){this.push(null);break}if(this.parent=await i,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await(0,Nr.readdir)(e,this._rdOptions)}catch(i){this._onError(i)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,i=this._isDirent?e.name:e;try{let s=(0,Mr.resolve)((0,Mr.join)(t,i));n={path:(0,Mr.relative)(this._root,s),fullPath:s,basename:i},n[this._statsProp]=this._isDirent?e:await this._stat(s)}catch(s){this._onError(s);return}return n}_onError(e){ib(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 n=e.fullPath;try{let i=await(0,Nr.realpath)(n),s=await(0,Nr.lstat)(i);if(s.isFile())return"file";if(s.isDirectory()){let a=i.length;if(n.startsWith(i)&&n.substr(a,1)===Mr.sep){let c=new Error(`Circular symlink detected: "${n}" points to "${i}"`);return c.code=zd,this._onError(c)}return"directory"}}catch(i){return this._onError(i),""}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function $d(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&&!qd.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${qd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new mf(e)}var An=require("node:fs"),Zt=require("node:fs/promises"),Yd=require("node:os"),qe=ue(require("node:path"),1),ob="data",Ef="end",Xd="close",Ro=()=>{};var Io=process.platform,bf=Io==="win32",ab=Io==="darwin",cb=Io==="linux",fb=Io==="freebsd",Jd=(0,Yd.type)()==="OS400",Ve={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Jt=Ve,ub="watch",lb={lstat:Zt.lstat,stat:Zt.stat},Pn="listeners",ko="errHandlers",fi="rawEmitters",hb=[Pn,ko,fi],db=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"]),pb=r=>db.has(qe.extname(r).slice(1).toLowerCase()),_f=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},Xi=(r,e,t)=>{let n=r[e];n instanceof Set||(r[e]=n=new Set([n])),n.add(t)},gb=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},Ji=(r,e,t)=>{let n=r[e];n instanceof Set?n.delete(t):n===t&&delete r[e]},Zd=r=>r instanceof Set?r.size===0:!r,Oo=new Map;function Gd(r,e,t,n,i){let s=(a,c)=>{t(r),i(a,c,{watchedPath:r}),c&&r!==c&&Po(qe.resolve(r,c),Pn,qe.join(r,c))};try{return(0,An.watch)(r,{persistent:e.persistent},s)}catch(a){n(a);return}}var Po=(r,e,t,n,i)=>{let s=Oo.get(r);s&&_f(s[e],a=>{a(t,n,i)})},mb=(r,e,t,n)=>{let{listener:i,errHandler:s,rawEmitter:a}=n,c=Oo.get(e),u;if(!t.persistent)return u=Gd(r,t,i,s,a),u?u.close.bind(u):void 0;if(c)Xi(c,Pn,i),Xi(c,ko,s),Xi(c,fi,a);else{if(u=Gd(r,t,Po.bind(null,e,Pn),s,Po.bind(null,e,fi)),!u)return;u.on(Jt.ERROR,async d=>{let p=Po.bind(null,e,ko);if(c&&(c.watcherUnusable=!0),bf&&d.code==="EPERM")try{await(await(0,Zt.open)(r,"r")).close(),p(d)}catch{}else p(d)}),c={listeners:i,errHandlers:s,rawEmitters:a,watcher:u},Oo.set(e,c)}return()=>{Ji(c,Pn,i),Ji(c,ko,s),Ji(c,fi,a),Zd(c.listeners)&&(c.watcher.close(),Oo.delete(e),hb.forEach(gb(c)),c.watcher=void 0,Object.freeze(c))}},yf=new Map,yb=(r,e,t,n)=>{let{listener:i,rawEmitter:s}=n,a=yf.get(e),c=a&&a.options;return c&&(c.persistent<t.persistent||c.interval>t.interval)&&((0,An.unwatchFile)(e),a=void 0),a?(Xi(a,Pn,i),Xi(a,fi,s)):(a={listeners:i,rawEmitters:s,options:t,watcher:(0,An.watchFile)(e,t,(u,d)=>{_f(a.rawEmitters,m=>{m(Jt.CHANGE,e,{curr:u,prev:d})});let p=u.mtimeMs;(u.size!==d.size||p>d.mtimeMs||p===0)&&_f(a.listeners,m=>m(r,u))})},yf.set(e,a)),()=>{Ji(a,Pn,i),Ji(a,fi,s),Zd(a.listeners)&&(yf.delete(e),(0,An.unwatchFile)(e),a.options=a.watcher=void 0,Object.freeze(a))}},Ao=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,i=qe.dirname(e),s=qe.basename(e);this.fsw._getWatchedDir(i).add(s);let c=qe.resolve(e),u={persistent:n.persistent};t||(t=Ro);let d;if(n.usePolling){let p=n.interval!==n.binaryInterval;u.interval=p&&pb(s)?n.binaryInterval:n.interval,d=yb(e,c,u,{listener:t,rawEmitter:this.fsw._emitRaw})}else d=mb(e,c,u,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return d}_handleFile(e,t,n){if(this.fsw.closed)return;let i=qe.dirname(e),s=qe.basename(e),a=this.fsw._getWatchedDir(i),c=t;if(a.has(s))return;let u=async(p,m)=>{if(this.fsw._throttle(ub,e,5)){if(!m||m.mtimeMs===0)try{let _=await(0,Zt.stat)(e);if(this.fsw.closed)return;let v=_.atimeMs,S=_.mtimeMs;if((!v||v<=S||S!==c.mtimeMs)&&this.fsw._emit(Jt.CHANGE,e,_),(ab||cb||fb)&&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(i,s)}else if(a.has(s)){let _=m.atimeMs,v=m.mtimeMs;(!_||_<=v||v!==c.mtimeMs)&&this.fsw._emit(Jt.CHANGE,e,m),c=m}}},d=this._watchWithNodeFs(e,u);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Jt.ADD,e,0))return;this.fsw._emit(Jt.ADD,e,t)}return d}async _handleSymlink(e,t,n,i){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,Zt.realpath)(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(i)?this.fsw._symlinkPaths.get(s)!==c&&(this.fsw._symlinkPaths.set(s,c),this.fsw._emit(Jt.CHANGE,n,e.stats)):(a.add(i),this.fsw._symlinkPaths.set(s,c),this.fsw._emit(Jt.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(e,t,n,i,s,a,c){e=qe.join(e,"");let u=i?`${e}:${i}`:e;if(c=this.fsw._throttle("readdir",u,1e3),!c)return;let d=this.fsw._getWatchedDir(n.path),p=new Set,m=this.fsw._readdirp(e,{fileFilter:_=>n.filterPath(_),directoryFilter:_=>n.filterDir(_)});if(m)return m.on(ob,async _=>{if(this.fsw.closed){m=void 0;return}let v=_.path,S=qe.join(e,v);if(p.add(v),!(_.stats.isSymbolicLink()&&await this._handleSymlink(_,e,S,v))){if(this.fsw.closed){m=void 0;return}(v===i||!i&&!d.has(v))&&(this.fsw._incrReadyCount(),S=qe.join(s,qe.relative(s,S)),this._addToNodeFs(S,t,n,a+1))}}).on(Jt.ERROR,this._boundHandleError),new Promise((_,v)=>{if(!m)return v();m.once(Ef,()=>{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,n,i,s,a,c)})})}async _handleDir(e,t,n,i,s,a,c){let u=this.fsw._getWatchedDir(qe.dirname(e)),d=u.has(qe.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!s&&!d&&this.fsw._emit(Jt.ADD_DIR,e,t),u.add(qe.basename(e)),this.fsw._getWatchedDir(e);let p,m,_=this.fsw.options.depth;if((_==null||i<=_)&&!this.fsw._symlinkPaths.has(c)){if(!s&&(await this._handleRead(e,n,a,s,e,i,p),this.fsw.closed))return;m=this._watchWithNodeFs(e,(v,S)=>{S&&S.mtimeMs===0||this._handleRead(v,!1,a,s,e,i,p)})}return m}async _addToNodeFs(e,t,n,i,s){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let c=this.fsw._getWatchHelpers(e);n&&(c.filterPath=u=>n.filterPath(u),c.filterDir=u=>n.filterDir(u));try{let u=await lb[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,Zt.realpath)(e):e;if(this.fsw.closed||(p=await this._handleDir(c.watchPath,u,t,i,s,c,_),this.fsw.closed))return;m!==_&&_!==void 0&&this.fsw._symlinkPaths.set(m,_)}else if(u.isSymbolicLink()){let m=d?await(0,Zt.realpath)(e):e;if(this.fsw.closed)return;let _=qe.dirname(c.watchPath);if(this.fsw._getWatchedDir(_).add(c.watchPath),this.fsw._emit(Jt.ADD,c.watchPath,u),p=await this._handleDir(_,u,t,i,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 vf="/",_b="//",sp=".",Eb="..",bb="string",vb=/\\/g,op=/\/\//g,wb=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,xb=/^\.[/\\]/;function Lo(r){return Array.isArray(r)?r:[r]}var wf=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function Sb(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 Tb(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(op,"/"),e&&(r="/"+r),r}function Qd(r,e,t){let n=Tb(e);for(let i=0;i<r.length;i++){let s=r[i];if(s(n,t))return!0}return!1}function Cb(r,e){if(r==null)throw new TypeError("anymatch: specify first argument");let n=Lo(r).map(i=>Sb(i));return e==null?(i,s)=>Qd(n,i,s):Qd(n,e)}var ep=r=>{let e=Lo(r).flat();if(!e.every(t=>typeof t===bb))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(ap)},tp=r=>{let e=r.replace(vb,vf),t=!1;return e.startsWith(_b)&&(t=!0),e=e.replace(op,vf),t&&(e=vf+e),e},ap=r=>tp(xe.normalize(tp(r))),rp=(r="")=>e=>typeof e=="string"?ap(xe.isAbsolute(e)?e:xe.join(r,e)):e,kb=(r,e)=>xe.isAbsolute(r)?r:xe.join(e,r),Ob=Object.freeze(new Set),xf=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!==sp&&e!==Eb&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await(0,No.readdir)(n)}catch{this._removeWatcher&&this._removeWatcher(xe.dirname(n),xe.basename(n))}}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=Ro,this.items=Ob,Object.freeze(this)}},Pb="stat",Ab="lstat",Sf=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,n){this.fsw=n;let i=e;this.path=e=e.replace(xb,""),this.watchPath=i,this.fullWatchPath=xe.resolve(i),this.dirParts=[],this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=t,this.statMethod=t?Pb:Ab}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 n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Tf=class extends np.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,n={stabilityThreshold:2e3,pollInterval:100},i={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Lo(e.ignored):Lo([]),awaitWriteFinish:t===!0?n:typeof t=="object"?{...n,...t}:!1};Jd&&(i.usePolling=!0),i.atomic===void 0&&(i.atomic=!i.usePolling);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let u=s.toLowerCase();u==="false"||u==="0"?i.usePolling=!1:u==="true"||u==="1"?i.usePolling=!0:i.usePolling=!!u}let a=process.env.CHOKIDAR_INTERVAL;a&&(i.interval=Number.parseInt(a,10));let c=0;this._emitReady=()=>{c++,c>=this._readyCount&&(this._emitReady=Ro,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=i,this._nodeFsHandler=new Ao(this),Object.freeze(i)}_addIgnoredPath(e){if(wf(e)){for(let t of this._ignoredPaths)if(wf(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)wf(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:i}=this.options;this.closed=!1,this._closePromise=void 0;let s=ep(e);return i&&(s=s.map(a=>kb(a,i))),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,!n,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=ep(e),{cwd:n}=this.options;return t.forEach(i=>{!xe.isAbsolute(i)&&!this._closers.has(i)&&(n&&(i=xe.join(n,i)),i=xe.resolve(i)),this._closePath(i),this._addIgnoredPath(i),this._watched.has(i)&&this._addIgnoredPath({path:i,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(n=>{let i=n();i instanceof Promise&&e.push(i)})),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,n)=>{let s=(this.options.cwd?xe.relative(this.options.cwd,n):n)||sp;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,n){if(this.closed)return;let i=this.options;bf&&(t=xe.normalize(t)),i.cwd&&(t=xe.relative(i.cwd,t));let s=[t];n!=null&&s.push(n);let a=i.awaitWriteFinish,c;if(a&&(c=this._pendingWrites.get(t)))return c.lastChange=new Date,this;if(i.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 i.atomic=="number"?i.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(i.alwaysStat&&n===void 0&&(e===Ve.ADD||e===Ve.ADD_DIR||e===Ve.CHANGE)){let u=i.cwd?xe.join(i.cwd,t):t,d;try{d=await(0,No.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,n){this._throttled.has(e)||this._throttled.set(e,new Map);let i=this._throttled.get(e);if(!i)throw new Error("invalid throttle");let s=i.get(t);if(s)return s.count++,!1;let a,c=()=>{let d=i.get(t),p=d?d.count:0;return i.delete(t),clearTimeout(a),d&&clearTimeout(d.timeoutObject),p};a=setTimeout(c,n);let u={timeoutObject:a,clear:c,count:0};return i.set(t,u),u}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,i){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,ip.stat)(u,(v,S)=>{if(v||!p.has(e)){v&&v.code!=="ENOENT"&&i(v);return}let T=Number(new Date);_&&S.size!==_.size&&(p.get(e).lastChange=T);let H=p.get(e);T-H.lastChange>=t?(p.delete(e),i(void 0,S)):c=setTimeout(m,a,S)})}p.has(e)||(p.set(e,{lastChange:d,cancelWait:()=>(p.delete(e),clearTimeout(c),n)}),c=setTimeout(m,a))}_isIgnored(e,t){if(this.options.atomic&&wb.test(e))return!0;if(!this._userIgnored){let{cwd:n}=this.options,s=(this.options.ignored||[]).map(rp(n)),c=[...[...this._ignoredPaths].map(rp(n)),...s];this._userIgnored=Cb(c,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Sf(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=xe.resolve(e);return this._watched.has(t)||this._watched.set(t,new xf(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let i=xe.join(e,t),s=xe.resolve(i);if(n=n??(this._watched.has(i)||this._watched.has(s)),!this._throttle("remove",i,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(i).getChildren().forEach(_=>this._remove(i,_));let u=this._getWatchedDir(e),d=u.has(t);u.remove(t),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let p=i;if(this.options.cwd&&(p=xe.relative(this.options.cwd,i)),this.options.awaitWriteFinish&&this._pendingWrites.has(p)&&this._pendingWrites.get(p).cancelWait()===Ve.ADD)return;this._watched.delete(i),this._watched.delete(s);let m=n?Ve.UNLINK_DIR:Ve.UNLINK;d&&!this._isIgnored(i)&&this._emit(m,i),this._closePath(i)}_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(n=>n()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n={type:Ve.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},i=$d(e,n);return this._streams.add(i),i.once(Xd,()=>{i=void 0}),i.once(Ef,()=>{i&&(this._streams.delete(i),i=void 0)}),i}};function cp(r,e={}){let t=new Tf(e);return t.add(r),t}var fp=ue(Lc()),pr=ue(Tr()),Rb=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/*.log"],Ib=300,Mo=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,fp.default)(),this.initializeIgnoreFilter()}initializeIgnoreFilter(){this.ignoreFilter.add(Rb);let e=tn.join(this.workspaceRoot,".gitignore");try{if(ui.existsSync(e)){let t=ui.readFileSync(e,"utf-8");this.ignoreFilter.add(t)}}catch{}}onFileChanged(e){this.onFileChangedCallback=e}start(){this.watcher||(this.watcher=cp(this.workspaceRoot,{ignored:e=>{let t=tn.relative(this.workspaceRoot,e);if(!t||t===".")return!1;let n=t.split(tn.sep).join("/");return this.ignoreFilter.ignores(n)},persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50}}),this.watcher.on("add",e=>this.handleEvent(e,pr.FileChangeType.CREATE)),this.watcher.on("change",e=>this.handleEvent(e,pr.FileChangeType.MODIFY)),this.watcher.on("unlink",e=>this.handleEvent(e,pr.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 n=tn.relative(this.workspaceRoot,e);if(!n)return;let i=this.pendingEvents.get(n);i&&clearTimeout(i);let s=this.pendingTypes.get(n);this.pendingTypes.set(n,this.mergeTypes(s,t));let a=setTimeout(()=>{this.emit(n,this.pendingTypes.get(n)||t),this.pendingEvents.delete(n),this.pendingTypes.delete(n)},Ib);this.pendingEvents.set(n,a)}mergeTypes(e,t){return e?t===pr.FileChangeType.DELETE||e===pr.FileChangeType.DELETE?pr.FileChangeType.DELETE:e===pr.FileChangeType.CREATE?pr.FileChangeType.CREATE:t:t}emit(e,t){let n={path:e,changeType:t,timestamp:new Date().toISOString(),source:"watcher"};if(t!==pr.FileChangeType.DELETE)try{let i=tn.join(this.workspaceRoot,e),s=ui.statSync(i);n.size=s.size}catch{}this.onFileChangedCallback?.(n)}dispose(){this.stop(),this.onFileChangedCallback=null}};var Lb={online:!1,viewerCount:0},Fo=class r{enabled=!1;state={...Lb};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(),n=`\x1B[1;${e-1}r\x1B7\x1B[${e};1H\x1B[2K${t}\x1B8`;process.stdout.write(n)}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 Do(r,e,t,n){if(n)return process.stderr.write(`Logging in with API key...
36
- `),await r.loginWithApiKey(n)?(process.stderr.write(`Login successful.
28
+ `+t)}function xi(r,e,t,i,n,s){if(r.listenerCount("wsClientError")){let a=new Error(n);Error.captureStackTrace(a,xi),r.emit("wsClientError",a,t,e)}else Fn(t,i,n,s)}});var ph=L((Av,dh)=>{"use strict";var Lr=eo();Lr.createWebSocketStream=ih();Lr.Server=hh();Lr.Receiver=Ba();Lr.Sender=Ka();Lr.WebSocket=Lr;Lr.WebSocketServer=Lr.Server;dh.exports=Lr});var Za=L(Jr=>{"use strict";var N_=Jr&&Jr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Jr,"__esModule",{value:!0});Jr.WS=Jr.BaseWS=void 0;var M_=Pn(),gh=yi(),F_=Ki(),Xa=mi(),D_=N_(jt()),B_=(0,D_.default)("engine.io-client:websocket"),mh=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",ro=class extends M_.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,i=mh?{}:(0,gh.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,F_.encodePacket)(i,this.supportsBinary,s=>{try{this.doWrite(i,s)}catch{B_("websocket closed before onclose event")}n&&(0,Xa.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,gh.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}};Jr.BaseWS=ro;var Ya=Xa.globalThisShim.WebSocket||Xa.globalThisShim.MozWebSocket,Ja=class extends ro{createSocket(e,t,i){return mh?new Ya(e,t,i):t?new Ya(e,t):new Ya(e)}doWrite(e,t){this.ws.send(t)}};Jr.WS=Ja});var ec=L(pr=>{"use strict";var j_=pr&&pr.__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]})),U_=pr&&pr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),K_=pr&&pr.__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)&&j_(e,r,t);return U_(e,r),e};Object.defineProperty(pr,"__esModule",{value:!0});pr.WS=void 0;var q_=K_(ph()),W_=Za(),Qa=class extends W_.BaseWS{createSocket(e,t,i){var n;if(!((n=this.socket)===null||n===void 0)&&n._cookieJar){i.headers=i.headers||{},i.headers.cookie=typeof i.headers.cookie=="string"?[i.headers.cookie]:i.headers.cookie||[];for(let[s,a]of this.socket._cookieJar.cookies)i.headers.cookie.push(`${s}=${a.value}`)}return new q_.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)}};pr.WS=Qa});var rc=L(en=>{"use strict";var H_=en&&en.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(en,"__esModule",{value:!0});en.WT=void 0;var V_=Pn(),$_=mi(),yh=Ki(),z_=H_(jt()),Dn=(0,z_.default)("engine.io-client:webtransport"),tc=class extends V_.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(()=>{Dn("transport closed gracefully"),this.onClose()}).catch(e=>{Dn("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=(0,yh.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),n=(0,yh.createPacketEncoderStream)();n.readable.pipeTo(e.writable),this._writer=n.writable.getWriter();let s=()=>{i.read().then(({done:c,value:u})=>{if(c){Dn("session is closed");return}Dn("received chunk: %o",u),this.onPacket(u),s()}).catch(c=>{Dn("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,$_.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};en.WT=tc});var ic=L(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.transports=void 0;var G_=ka(),Y_=ec(),X_=rc();io.transports={websocket:Y_.WS,webtransport:X_.WT,polling:G_.XHR}});var sc=L(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.parse=Q_;var J_=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Z_=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Q_(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=J_.exec(r||""),s={},a=14;for(;a--;)s[Z_[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=e0(s,s.path),s.queryKey=t0(s,s.query),s}function e0(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 t0(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(i,n,s){n&&(t[n]=s)}),t}});var fc=L(gr=>{"use strict";var r0=gr&&gr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(gr,"__esModule",{value:!0});gr.Socket=gr.SocketWithUpgrade=gr.SocketWithoutUpgrade=void 0;var i0=ic(),_h=yi(),n0=ga(),bh=sc(),s0=gi(),Eh=Ki(),oc=mi(),o0=r0(jt()),Ue=(0,o0.default)("engine.io-client:socket"),ac=typeof addEventListener=="function"&&typeof removeEventListener=="function",Bn=[];ac&&addEventListener("offline",()=>{Ue("closing %d connection(s) because the network was lost",Bn.length),Bn.forEach(r=>r())},!1);var Si=class r extends s0.Emitter{constructor(e,t){if(super(),this.binaryType=oc.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,bh.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,bh.parse)(t.host).host);(0,_h.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,n0.decode)(this.opts.query)),ac&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(Ue("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Bn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,oc.createCookieJar)()),this._open()}createTransport(e){Ue('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Eh.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 Ue("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){Ue("setting transport %s",e.name),this.transport&&(Ue("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(){Ue("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(Ue('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 Ue('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();Ue("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,_h.byteLength)(n)),i>0&&t>this._maxPayload)return Ue("only send %d out of %d packets",i,this.writeBuffer.length),this.writeBuffer.slice(0,i);t+=2}return Ue("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&&(Ue("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,oc.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"),Ue("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(Ue("socket error %j",e),r.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return Ue("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(Ue('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ac&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let i=Bn.indexOf(this._offlineEventListener);i!==-1&&(Ue("removing listener for the 'offline' event"),Bn.splice(i,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};gr.SocketWithoutUpgrade=Si;Si.protocol=Eh.protocol;var no=class extends Si{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){Ue("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){Ue('probing transport "%s"',e);let t=this.createTransport(e),i=!1;Si.priorWebsocketSuccess=!1;let n=()=>{i||(Ue('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(Ue('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Si.priorWebsocketSuccess=t.name==="websocket",Ue('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{i||this.readyState!=="closed"&&(Ue("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{Ue('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(),Ue('probe transport "%s" failed because of error: %s',e,m),this.emitReserved("upgradeError",_)};function c(){a("transport closed")}function u(){a("socket closed")}function h(m){t&&m.name!==t.name&&(Ue('"%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",h)};t.once("open",n),t.once("error",a),t.once("close",c),this.once("close",u),this.once("upgrading",h),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}};gr.SocketWithUpgrade=no;var cc=class extends no{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=>i0.transports[n]).filter(n=>!!n)),super(e,i)}};gr.Socket=cc});var wh=L(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.Fetch=void 0;var a0=va(),uc=class extends a0.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})}};so.Fetch=uc});var oo=L(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.WebTransport=ke.WebSocket=ke.NodeWebSocket=ke.XHR=ke.NodeXHR=ke.Fetch=ke.nextTick=ke.parse=ke.installTimerFunctions=ke.transports=ke.TransportError=ke.Transport=ke.protocol=ke.SocketWithUpgrade=ke.SocketWithoutUpgrade=ke.Socket=void 0;var vh=fc();Object.defineProperty(ke,"Socket",{enumerable:!0,get:function(){return vh.Socket}});var xh=fc();Object.defineProperty(ke,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return xh.SocketWithoutUpgrade}});Object.defineProperty(ke,"SocketWithUpgrade",{enumerable:!0,get:function(){return xh.SocketWithUpgrade}});ke.protocol=vh.Socket.protocol;var Sh=Pn();Object.defineProperty(ke,"Transport",{enumerable:!0,get:function(){return Sh.Transport}});Object.defineProperty(ke,"TransportError",{enumerable:!0,get:function(){return Sh.TransportError}});var c0=ic();Object.defineProperty(ke,"transports",{enumerable:!0,get:function(){return c0.transports}});var f0=yi();Object.defineProperty(ke,"installTimerFunctions",{enumerable:!0,get:function(){return f0.installTimerFunctions}});var u0=sc();Object.defineProperty(ke,"parse",{enumerable:!0,get:function(){return u0.parse}});var l0=mi();Object.defineProperty(ke,"nextTick",{enumerable:!0,get:function(){return l0.nextTick}});var h0=wh();Object.defineProperty(ke,"Fetch",{enumerable:!0,get:function(){return h0.Fetch}});var d0=ka();Object.defineProperty(ke,"NodeXHR",{enumerable:!0,get:function(){return d0.XHR}});var p0=Ta();Object.defineProperty(ke,"XHR",{enumerable:!0,get:function(){return p0.XHR}});var g0=ec();Object.defineProperty(ke,"NodeWebSocket",{enumerable:!0,get:function(){return g0.WS}});var m0=Za();Object.defineProperty(ke,"WebSocket",{enumerable:!0,get:function(){return m0.WS}});var y0=rc();Object.defineProperty(ke,"WebTransport",{enumerable:!0,get:function(){return y0.WT}})});var Ch=L(jn=>{"use strict";var _0=jn&&jn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(jn,"__esModule",{value:!0});jn.url=w0;var b0=oo(),E0=_0(jt()),Th=(0,E0.default)("socket.io-client:url");function w0(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)||(Th("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),Th("parse %s",r),i=(0,b0.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 lc=L(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.isBinary=Ph;co.hasBinary=ao;var v0=typeof ArrayBuffer=="function",x0=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,kh=Object.prototype.toString,S0=typeof Blob=="function"||typeof Blob<"u"&&kh.call(Blob)==="[object BlobConstructor]",T0=typeof File=="function"||typeof File<"u"&&kh.call(File)==="[object FileConstructor]";function Ph(r){return v0&&(r instanceof ArrayBuffer||x0(r))||S0&&r instanceof Blob||T0&&r instanceof File}function ao(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,i=r.length;t<i;t++)if(ao(r[t]))return!0;return!1}if(Ph(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return ao(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&ao(r[t]))return!0;return!1}});var Oh=L(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.deconstructPacket=k0;fo.reconstructPacket=P0;var C0=lc();function k0(r){let e=[],t=r.data,i=r;return i.data=hc(t,e),i.attachments=e.length,{packet:i,buffers:e}}function hc(r,e){if(!r)return r;if((0,C0.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]=hc(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]=hc(r[i],e));return t}return r}function P0(r,e){return r.data=dc(r.data,e),delete r.attachments,r}function dc(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]=dc(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=dc(r[t],e));return r}});var lo=L(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.Decoder=Xt.Encoder=Xt.PacketType=Xt.protocol=void 0;Xt.isPacketValid=M0;var O0=gi(),Rh=Oh(),Ah=lc(),R0=jt(),pc=(0,R0.default)("socket.io-parser"),Ih=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];Xt.protocol=5;var Be;(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"})(Be||(Xt.PacketType=Be={}));var gc=class{constructor(e){this.replacer=e}encode(e){return pc("encoding packet %j",e),(e.type===Be.EVENT||e.type===Be.ACK)&&(0,Ah.hasBinary)(e)?this.encodeAsBinary({type:e.type===Be.EVENT?Be.BINARY_EVENT:Be.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Be.BINARY_EVENT||e.type===Be.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)),pc("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,Rh.deconstructPacket)(e),i=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(i),n}};Xt.Encoder=gc;var mc=class r extends O0.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===Be.BINARY_EVENT;i||t.type===Be.BINARY_ACK?(t.type=i?Be.EVENT:Be.ACK,this.reconstructor=new yc(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,Ah.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(Be[i.type]===void 0)throw new Error("unknown packet type "+i.type);if(i.type===Be.BINARY_EVENT||i.type===Be.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 pc("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 Be.CONNECT:return uo(t);case Be.DISCONNECT:return t===void 0;case Be.CONNECT_ERROR:return typeof t=="string"||uo(t);case Be.EVENT:case Be.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Ih.indexOf(t[0])===-1);case Be.ACK:case Be.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};Xt.Decoder=mc;var yc=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,Rh.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function A0(r){return typeof r=="string"}var I0=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function L0(r){return r===void 0||I0(r)}function uo(r){return Object.prototype.toString.call(r)==="[object Object]"}function N0(r,e){switch(r){case Be.CONNECT:return e===void 0||uo(e);case Be.DISCONNECT:return e===void 0;case Be.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Ih.indexOf(e[0])===-1);case Be.ACK:return Array.isArray(e);case Be.CONNECT_ERROR:return typeof e=="string"||uo(e);default:return!1}}function M0(r){return A0(r.nsp)&&L0(r.id)&&N0(r.type,r.data)}});var bc=L(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.on=F0;function F0(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var wc=L(tn=>{"use strict";var D0=tn&&tn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(tn,"__esModule",{value:!0});tn.Socket=void 0;var Jt=lo(),ho=bc(),B0=gi(),j0=D0(jt()),ot=(0,j0.default)("socket.io-client:socket"),U0=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Ec=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,ho.on)(e,"open",this.onopen.bind(this)),(0,ho.on)(e,"packet",this.onpacket.bind(this)),(0,ho.on)(e,"error",this.onerror.bind(this)),(0,ho.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(U0.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:Jt.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let p=this.ids++;ot("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?ot("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&&(ot("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));ot("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]?ot("packet [%d] already acknowledged",i.id):(n!==null?i.tryCount>this._opts.retries&&(ot("packet [%d] is discarded after %d tries",i.id,i.tryCount),this._queue.shift(),t&&t(n)):(ot("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(ot("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){ot("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,ot("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(){ot("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Jt.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){ot("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 Jt.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 Jt.PacketType.EVENT:case Jt.PacketType.BINARY_EVENT:this.onevent(e);break;case Jt.PacketType.ACK:case Jt.PacketType.BINARY_ACK:this.onack(e);break;case Jt.PacketType.DISCONNECT:this.ondisconnect();break;case Jt.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||[];ot("emitting event %j",t),e.id!=null&&(ot("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,ot("sending ack %j",n),t.packet({type:Jt.PacketType.ACK,id:e,data:n}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){ot("bad ack %s",e.id);return}delete this.acks[e.id],ot("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){ot("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(){ot("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&&(ot("performing disconnect (%s)",this.nsp),this.packet({type:Jt.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)}}};tn.Socket=Ec});var Lh=L(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.Backoff=rn;function rn(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}rn.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};rn.prototype.reset=function(){this.attempts=0};rn.prototype.setMin=function(r){this.ms=r};rn.prototype.setMax=function(r){this.max=r};rn.prototype.setJitter=function(r){this.jitter=r}});var Nh=L(qt=>{"use strict";var K0=qt&&qt.__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]})),q0=qt&&qt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),W0=qt&&qt.__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)&&K0(e,r,t);return q0(e,r),e},H0=qt&&qt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(qt,"__esModule",{value:!0});qt.Manager=void 0;var xc=oo(),V0=wc(),$0=W0(lo()),Ti=bc(),z0=Lh(),G0=gi(),Y0=H0(jt()),lt=(0,Y0.default)("socket.io-client:manager"),Sc=class extends G0.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,xc.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 z0.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||$0;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(lt("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;lt("opening %s",this.uri),this.engine=new xc.Socket(this.uri,this.opts);let t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;let n=(0,Ti.on)(t,"open",function(){i.onopen(),e&&e()}),s=c=>{lt("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,Ti.on)(t,"error",s);if(this._timeout!==!1){let c=this._timeout;lt("connect attempt will timeout after %d",c);let u=this.setTimeoutFn(()=>{lt("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(){lt("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,Ti.on)(e,"ping",this.onping.bind(this)),(0,Ti.on)(e,"data",this.ondata.bind(this)),(0,Ti.on)(e,"error",this.onerror.bind(this)),(0,Ti.on)(e,"close",this.onclose.bind(this)),(0,Ti.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,xc.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){lt("error",e),this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new V0.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){lt("socket %s is still active, skipping close",i);return}this._close()}_packet(e){lt("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(){lt("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){lt("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var i;lt("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)lt("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();lt("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let i=this.setTimeoutFn(()=>{e.skipReconnect||(lt("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(n=>{n?(lt("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",n)):(lt("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)}};qt.Manager=Sc});var Bh=L((He,Dh)=>{"use strict";var X0=He&&He.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(He,"__esModule",{value:!0});He.WebTransport=He.WebSocket=He.NodeWebSocket=He.XHR=He.NodeXHR=He.Fetch=He.Socket=He.Manager=He.protocol=void 0;He.io=Ci;He.connect=Ci;He.default=Ci;var J0=Ch(),po=Nh();Object.defineProperty(He,"Manager",{enumerable:!0,get:function(){return po.Manager}});var Fh=wc();Object.defineProperty(He,"Socket",{enumerable:!0,get:function(){return Fh.Socket}});var Z0=X0(jt()),Mh=(0,Z0.default)("socket.io-client"),Un={};function Ci(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,J0.url)(r,e.path||"/socket.io"),i=t.source,n=t.id,s=t.path,a=Un[n]&&s in Un[n].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||a,u;return c?(Mh("ignoring socket cache for %s",i),u=new po.Manager(i,e)):(Un[n]||(Mh("new io instance for %s",i),Un[n]=new po.Manager(i,e)),u=Un[n]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(Ci,{Manager:po.Manager,Socket:Fh.Socket,io:Ci,connect:Ci});var Q0=lo();Object.defineProperty(He,"protocol",{enumerable:!0,get:function(){return Q0.protocol}});var nn=oo();Object.defineProperty(He,"Fetch",{enumerable:!0,get:function(){return nn.Fetch}});Object.defineProperty(He,"NodeXHR",{enumerable:!0,get:function(){return nn.NodeXHR}});Object.defineProperty(He,"XHR",{enumerable:!0,get:function(){return nn.XHR}});Object.defineProperty(He,"NodeWebSocket",{enumerable:!0,get:function(){return nn.NodeWebSocket}});Object.defineProperty(He,"WebSocket",{enumerable:!0,get:function(){return nn.WebSocket}});Object.defineProperty(He,"WebTransport",{enumerable:!0,get:function(){return nn.WebTransport}});Dh.exports=Ci});var Cc=L(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});go.InputStreamReceiver=void 0;var eb=64,tb=30,rb=4,ib=256,nb=16,Tc=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??eb),this.ackThrottleMs=Math.max(0,i.ackThrottleMs??tb)}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*rb,ib);e-this.lastAppliedSeq>s||this.maybeResend(this.lastAppliedSeq+1)}maybeResend(e){if(e===this.lastResendFrom){if(++this.resendSuppressed<nb)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)}};go.InputStreamReceiver=Tc});var qh=L(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.WebSocketService=void 0;var sb=Bh(),jh=kr(),Uh=hs(),Kh=fs(),ob=Cc(),kc=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,Uh.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([...jh.DEFAULT_CLIENT_CAPABILITIES,...this.extraCapabilities]));this.socket=(0,sb.io)(`${t}/agent`,{auth:{token:e,protocolVersion:jh.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(h){this.logger.error("Key exchange error",h),u?.({success:!1,error:String(h)})}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),h={agentId:c.agentId,sessionId:c.sessionId,ok:u,error:u?void 0:"Key exchange failed"};this.socket?.emit("agent:keyExchangeAck",h)}catch(u){this.logger.error("Agent key exchange error",u);let h={agentId:c.agentId,sessionId:c.sessionId,ok:!1,error:String(u)};this.socket?.emit("agent:keyExchangeAck",h)}}),this.socket.on("meta:keyExchange",async(c,u)=>{let{ok:h,isNew:p}=await this.cryptoService.handleMetaKeyExchange(c.clientIdentityPub),m=await this.cryptoService.getPublicKey()||void 0;u?.({ok:h,agentPublicKey:m}),h&&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 h=this.getBufferHandler(c.terminalId);if(h===null){u?.({success:!1,error:"Terminal not found"});return}let p=this.cryptoService.encryptOutput(c.terminalId,h);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,Kh.generateCorrelationId)(),n=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:i}:t;return(0,Kh.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 ob.InputStreamReceiver(t,{onApply:(c,u,h)=>this.inputHandler?.(e,c,this.routeIdFor(e),u,h),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,Uh.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)}};mo.WebSocketService=kc});var Vh=L(Zt=>{"use strict";var ab=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]})),cb=Zt&&Zt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Oc=Zt&&Zt.__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"&&ab(t,e,i[n]);return cb(t,e),t}})();Object.defineProperty(Zt,"__esModule",{value:!0});Zt.FileTransferService=void 0;Zt.resolveUploadPath=Hh;var yo=Oc(require("fs")),ki=Oc(require("path")),Wh=Oc(require("crypto")),Ve=kr();function Hh(r,e,t){let i=ki.basename(t),n=(e??"").trim()||".";if(ki.isAbsolute(n))return ki.resolve(n,i);let s=ki.resolve(r,n),a=s===r||s.startsWith(r+ki.sep)?s:r;return ki.resolve(a,i)}var Pc=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=yo.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,Ve.calculateTotalChunks)(s),c=this.calculateChecksum(t),u=Wh.randomUUID(),h={id:u,terminalId:e,filename:i,size:s,totalChunks:a,direction:Ve.TransferDirection.DOWNLOAD,status:Ve.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};h.chunks=[];for(let m=0;m<a;m++){let _=m*Ve.CHUNK_SIZE,E=Math.min(_+Ve.CHUNK_SIZE,s);h.chunks.push(t.subarray(_,E))}this.activeTransfers.set(u,h);let p={transferId:u,terminalId:e,filename:i,size:s,totalChunks:a,mimeType:n.mimeType||"application/octet-stream",checksum:c,direction:Ve.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?(h.status=Ve.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",h,p){let m={id:e,terminalId:t,filename:i,filePath:c,size:n,totalChunks:s,direction:Ve.TransferDirection.UPLOAD,status:Ve.TransferStatus.ACTIVE,deliveredChunks:new Set,pendingChunks:new Map,chunks:new Array(s).fill(null),checksum:a,checksumAlgorithm:u,onProgress:h?(_,E)=>h(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=Ve.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===Ve.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===Ve.TransferDirection.DOWNLOAD&&i.missingChunks){t.status=Ve.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=Ve.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(Ve.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,h=>{h&&!h.success&&this.cancelTransfer(e.id,h.error||"Server rejected chunk")});let u=setTimeout(()=>{this.handleAckTimeout(e.id,t)},Ve.ACK_TIMEOUT_MS);e.ackTimeouts.set(t,u)}handleChunkAck(e){let t=this.activeTransfers.get(e.transferId);if(!t||t.status===Ve.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+Ve.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<Ve.MAX_RETRIES?(n.retries++,this.sendChunk(i,t)):this.cancelTransfer(e,"Max retries exceeded"))}finishSending(e){if(!this.socket)return;e.status=Ve.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=Ve.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=ki.dirname(e.filePath);yo.existsSync(n)||yo.mkdirSync(n,{recursive:!0}),yo.writeFileSync(e.filePath,t),e.status=Ve.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=Ve.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=Ve.TransferStatus.COMPLETED,t.onComplete?.(!0)):(t.status=Ve.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=Hh(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):Wh.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"}};Zt.FileTransferService=Pc});var Fc=L((Jv,Eo)=>{function Gh(r){return Array.isArray(r)?r:[r]}var fb=void 0,Ac="",$h=" ",Rc="\\",ub=/^\s+$/,lb=/(?:[^\\]|^)\\$/,hb=/^\\!/,db=/^\\#/,pb=/\r?\n/g,gb=/^\.{0,2}\/|^\.{1,2}$/,mb=/\/$/,sn="/",Yh="node-ignore";typeof Symbol<"u"&&(Yh=Symbol.for("node-ignore"));var Xh=Yh,on=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),yb=/([0-z])-([0-z])/g,Jh=()=>!1,_b=r=>r.replace(yb,(e,t,i)=>t.charCodeAt(0)<=i.charCodeAt(0)?e:Ac),bb=r=>{let{length:e}=r;return r.slice(0,e-e%2)},Eb=[[/^\uFEFF/,()=>Ac],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?$h:Ac)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+$h}],[/[\\$.|*+(){^]/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,()=>Rc],[/\\\\/g,()=>Rc],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,i,n)=>e===Rc?`\\[${t}${bb(i)}${n}`:n==="]"&&i.length%2===0?`[${_b(t)}${i}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],wb=/(^|\\\/)?\\\*$/,Kn="regex",_o="checkRegex",zh="_",vb={[Kn](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[_o](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},xb=r=>Eb.reduce((e,[t,i])=>e.replace(t,i.bind(r)),r),bo=r=>typeof r=="string",Sb=r=>r&&bo(r)&&!ub.test(r)&&!lb.test(r)&&r.indexOf("#")!==0,Tb=r=>r.split(pb).filter(Boolean),Ic=class{constructor(e,t,i,n,s,a){this.pattern=e,this.mark=t,this.negative=s,on(this,"body",i),on(this,"ignoreCase",n),on(this,"regexPrefix",a)}get regex(){let e=zh+Kn;return this[e]?this[e]:this._make(Kn,e)}get checkRegex(){let e=zh+_o;return this[e]?this[e]:this._make(_o,e)}_make(e,t){let i=this.regexPrefix.replace(wb,vb[e]),n=this.ignoreCase?new RegExp(i,"i"):new RegExp(i);return on(this,t,n)}},Cb=({pattern:r,mark:e},t)=>{let i=!1,n=r;n.indexOf("!")===0&&(i=!0,n=n.substr(1)),n=n.replace(hb,"!").replace(db,"#");let s=xb(n);return new Ic(r,e,n,t,i,s)},Lc=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[Xh]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(bo(e)&&(e={pattern:e}),Sb(e.pattern)){let t=Cb(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,Gh(bo(e)?Tb(e):e).forEach(this._add,this),this._added}test(e,t,i){let n=!1,s=!1,a;this._rules.forEach(u=>{let{negative:h}=u;s===h&&n!==s||h&&!n&&!s&&!t||!u[i].test(e)||(n=!h,s=h,a=h?fb:u)});let c={ignored:n,unignored:s};return a&&(c.rule=a),c}},kb=(r,e)=>{throw new e(r)},Nr=(r,e,t)=>bo(r)?r?Nr.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),Zh=r=>gb.test(r);Nr.isNotRelative=Zh;Nr.convert=r=>r;var Nc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:i=!1}={}){on(this,Xh,!0),this._rules=new Lc(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&&Nr.convert(e);return Nr(s,e,this._strictPathCheck?kb:Jh),this._t(s,t,i,n)}checkIgnore(e){if(!mb.test(e))return this.test(e);let t=e.split(sn).filter(Boolean);if(t.pop(),t.length){let i=this._t(t.join(sn)+sn,this._testCache,!0,t);if(i.ignored)return i}return this._rules.test(e,!1,_o)}_t(e,t,i,n){if(e in t)return t[e];if(n||(n=e.split(sn).filter(Boolean)),n.pop(),!n.length)return t[e]=this._rules.test(e,i,Kn);let s=this._t(n.join(sn)+sn,t,i,n);return t[e]=s.ignored?s:this._rules.test(e,i,Kn)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return Gh(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},Mc=r=>new Nc(r),Pb=r=>Nr(r&&Nr.convert(r),r,Jh),Qh=()=>{let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");Nr.convert=r;let e=/^[a-z]:\//i;Nr.isNotRelative=t=>e.test(t)||Zh(t)};typeof process<"u"&&process.platform==="win32"&&Qh();Eo.exports=Mc;Mc.default=Mc;Eo.exports.isPathValid=Pb;on(Eo.exports,Symbol.for("setupWindows"),Qh)});var td=L(Wt=>{"use strict";var Ob=Wt&&Wt.__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]})),Rb=Wt&&Wt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),ed=Wt&&Wt.__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"&&Ob(t,e,i[n]);return Rb(t,e),t}})(),Ab=Wt&&Wt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Wt,"__esModule",{value:!0});Wt.FileListService=void 0;var an=ed(require("path")),Dc=ed(require("fs/promises")),Ib=Ab(Fc()),Bc=kr(),Lb=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],jc=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,Ib.default)(),this.ignoreFilter.add(Lb),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=an.join(this.workspaceRoot,".gitignore");try{let t=await Dc.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 Dc.readdir(e,{withFileTypes:!0}),n=[];for(let s of i){let a=t==="."||t===""?s.name:an.join(t,s.name);if(this.shouldHide(a,s.isDirectory()))continue;let c=an.join(e,s.name),u={name:s.name,path:a,type:s.isDirectory()?Bc.FileEntryType.DIRECTORY:Bc.FileEntryType.FILE};if(!s.isDirectory())try{let h=await Dc.stat(c);u.size=h.size,u.modified=h.mtime.toISOString()}catch{}n.push(u)}return n.sort((s,a)=>s.type!==a.type?s.type===Bc.FileEntryType.DIRECTORY?-1:1:s.name.localeCompare(a.name))}shouldHide(e,t){let i=e.split(an.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=an.resolve(this.workspaceRoot,e);if(t!==this.workspaceRoot&&!t.startsWith(this.workspaceRoot+an.sep))throw new Error("Path outside workspace");return t}sendResponse(e){this.onResponseCallback?.(e)}dispose(){this.onResponseCallback=null}};Wt.FileListService=jc});var id=L(mr=>{"use strict";var Nb=mr&&mr.__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=mr&&mr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),rd=mr&&mr.__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"&&Nb(t,e,i[n]);return Mb(t,e),t}})();Object.defineProperty(mr,"__esModule",{value:!0});mr.FileTrackerService=void 0;var Uc=rd(require("path")),Pi=rd(require("fs/promises")),Fb=require("child_process"),Db=require("util"),Qt=kr(),Kc=(0,Db.promisify)(Fb.execFile),qc={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},Wc=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(qc.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(qc.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(qc.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 Pi.readFile(a,"utf-8")}catch{u=void 0}let h={path:s,changeType:u===void 0?Qt.FileChangeType.CREATE:Qt.FileChangeType.MODIFY,toolName:i,toolId:t,timestamp:c.timestamp,previousContent:u},p=this.trackedFiles.get(e)||[];p.push(h),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 Pi.stat(u);c.size=p.size}catch{c.changeType=Qt.FileChangeType.DELETE,c.size=void 0}let h={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,h)}async handleViewRequest(e,t){let i=this.resolveFilePath(t.path),n=this.getViewableMimeType(t.path);if(n&&this.onFileViewTransferCallback){try{let a=await Pi.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===Qt.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===Qt.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 Pi.stat(t),s=await Pi.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:Qt.FileViewType.CONTENT,content:c,language:(0,Qt.getLanguageFromPath)(e.path),size:n.size,truncated:a}}async getFileDiff(e,t,i){let n=t.diffBase||Qt.DiffBase.GIT,s;return n===Qt.DiffBase.GIT?s=await this.getGitDiff(i):s=await this.getPreviousDiff(e,t.path,i),{requestId:t.requestId,path:t.path,type:Qt.FileViewType.DIFF,content:s,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await Kc("git",["diff","--cached","--",e],{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:i}=await Kc("git",["diff","--",e],{cwd:this.workspaceRoot});if(i.trim())return i;let{stdout:n}=await Kc("git",["status","--porcelain","--",e],{cwd:this.workspaceRoot});if(n.startsWith("??")||n.startsWith("A ")){let a=(await Pi.readFile(e,"utf-8")).split(`
29
+ `),c=Uc.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
+ `)}return"(no changes)"}catch{throw new Error("Git not available")}}async getPreviousDiff(e,t,i){let a=(this.trackedFiles.get(e)||[]).find(h=>h.path===t&&h.previousContent!==void 0)?.previousContent||"",c;try{c=await Pi.readFile(i,"utf-8")}catch{c=""}let u=(0,Qt.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=Uc.resolve(t,e);if(i!==t&&!i.startsWith(t+Uc.sep))throw new Error("Path escapes workspace root");return i}dispose(){this.trackedFiles.clear(),this.pendingToolCalls.clear(),this.onFileChangedCallback=null,this.onFileViewTransferCallback=null}};mr.FileTrackerService=Wc});var nd=L(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.InputStreamReceiver=et.FileTrackerService=et.FileListService=et.FileTransferService=et.WebSocketService=et.isTerminalReplyOnly=et.isAnswerKeystroke=et.StatusDetector=et.AuthService=et.CryptoService=void 0;var Bb=Su();Object.defineProperty(et,"CryptoService",{enumerable:!0,get:function(){return Bb.CryptoService}});var jb=Tu();Object.defineProperty(et,"AuthService",{enumerable:!0,get:function(){return jb.AuthService}});var Hc=Ru();Object.defineProperty(et,"StatusDetector",{enumerable:!0,get:function(){return Hc.StatusDetector}});Object.defineProperty(et,"isAnswerKeystroke",{enumerable:!0,get:function(){return Hc.isAnswerKeystroke}});Object.defineProperty(et,"isTerminalReplyOnly",{enumerable:!0,get:function(){return Hc.isTerminalReplyOnly}});var Ub=qh();Object.defineProperty(et,"WebSocketService",{enumerable:!0,get:function(){return Ub.WebSocketService}});var Kb=Vh();Object.defineProperty(et,"FileTransferService",{enumerable:!0,get:function(){return Kb.FileTransferService}});var qb=td();Object.defineProperty(et,"FileListService",{enumerable:!0,get:function(){return qb.FileListService}});var Wb=id();Object.defineProperty(et,"FileTrackerService",{enumerable:!0,get:function(){return Wb.FileTrackerService}});var Hb=Cc();Object.defineProperty(et,"InputStreamReceiver",{enumerable:!0,get:function(){return Hb.InputStreamReceiver}})});var qn=L(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.isTerminalReplyOnly=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 Vc=qf();Object.defineProperty(X,"LOG_LEVELS",{enumerable:!0,get:function(){return Vc.LOG_LEVELS}});Object.defineProperty(X,"shouldLog",{enumerable:!0,get:function(){return Vc.shouldLog}});Object.defineProperty(X,"formatLogLine",{enumerable:!0,get:function(){return Vc.formatLogLine}});var cn=Vf();Object.defineProperty(X,"CircularBuffer",{enumerable:!0,get:function(){return cn.CircularBuffer}});Object.defineProperty(X,"getApiUrl",{enumerable:!0,get:function(){return cn.getApiUrl}});Object.defineProperty(X,"getWsUrl",{enumerable:!0,get:function(){return cn.getWsUrl}});Object.defineProperty(X,"generateCorrelationId",{enumerable:!0,get:function(){return cn.generateCorrelationId}});Object.defineProperty(X,"runWithCorrelation",{enumerable:!0,get:function(){return cn.runWithCorrelation}});Object.defineProperty(X,"getCurrentCorrelationId",{enumerable:!0,get:function(){return cn.getCurrentCorrelationId}});var yr=nd();Object.defineProperty(X,"CryptoService",{enumerable:!0,get:function(){return yr.CryptoService}});Object.defineProperty(X,"AuthService",{enumerable:!0,get:function(){return yr.AuthService}});Object.defineProperty(X,"StatusDetector",{enumerable:!0,get:function(){return yr.StatusDetector}});Object.defineProperty(X,"isAnswerKeystroke",{enumerable:!0,get:function(){return yr.isAnswerKeystroke}});Object.defineProperty(X,"isTerminalReplyOnly",{enumerable:!0,get:function(){return yr.isTerminalReplyOnly}});Object.defineProperty(X,"WebSocketService",{enumerable:!0,get:function(){return yr.WebSocketService}});Object.defineProperty(X,"FileTransferService",{enumerable:!0,get:function(){return yr.FileTransferService}});Object.defineProperty(X,"FileListService",{enumerable:!0,get:function(){return yr.FileListService}});Object.defineProperty(X,"FileTrackerService",{enumerable:!0,get:function(){return yr.FileTrackerService}});Object.defineProperty(X,"InputStreamReceiver",{enumerable:!0,get:function(){return yr.InputStreamReceiver}});var Ht=ia();Object.defineProperty(X,"generateIdentityKeyPair",{enumerable:!0,get:function(){return Ht.generateIdentityKeyPair}});Object.defineProperty(X,"identityPublicFromSecret",{enumerable:!0,get:function(){return Ht.identityPublicFromSecret}});Object.defineProperty(X,"signSessionKey",{enumerable:!0,get:function(){return Ht.signSessionKey}});Object.defineProperty(X,"verifySessionKey",{enumerable:!0,get:function(){return Ht.verifySessionKey}});Object.defineProperty(X,"buildKxCanonical",{enumerable:!0,get:function(){return Ht.buildKxCanonical}});Object.defineProperty(X,"buildKxAckCanonical",{enumerable:!0,get:function(){return Ht.buildKxAckCanonical}});Object.defineProperty(X,"fingerprintIdentityKey",{enumerable:!0,get:function(){return Ht.fingerprintIdentityKey}});Object.defineProperty(X,"fingerprintShortHex",{enumerable:!0,get:function(){return Ht.fingerprintShortHex}});Object.defineProperty(X,"concatBytes",{enumerable:!0,get:function(){return Ht.concatBytes}});Object.defineProperty(X,"KX_SIGN_LABEL",{enumerable:!0,get:function(){return Ht.KX_SIGN_LABEL}});Object.defineProperty(X,"KX_ACK_LABEL",{enumerable:!0,get:function(){return Ht.KX_ACK_LABEL}});Object.defineProperty(X,"FP_LABEL",{enumerable:!0,get:function(){return Ht.FP_LABEL}})});var Yc=L((Hn,Gc)=>{(function(r,e){typeof Hn=="object"&&typeof Gc=="object"?Gc.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof Hn=="object"?Hn["electron-machine-id"]=e(require("child_process"),require("crypto")):r["electron-machine-id"]=e(r.child_process,r.crypto)})(Hn,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",h=t.exports=function(p){return s[p]||(s[p]=u&&c[p]||(u?c:a)("Symbol."+p))};h.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,h){return s.f(c,u,a(1,h))}:function(c,u,h){return c[u]=h,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(h){return a.call(c,h)};case 2:return function(h,p){return a.call(c,h,p)};case 3:return function(h,p,m){return a.call(c,h,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(h,p,m){if(s(h),p=c(p,!0),s(m),a)try{return u(h,p,m)}catch{}if("get"in m||"set"in m)throw TypeError("Accessors not supported!");return"value"in m&&(h[p]=m.value),h}},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,h,p){u&&!a(u=p?u:u.prototype,c)&&s(u,c,{configurable:!0,value:h})}},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(h,p){try{return h[p]}catch{}};t.exports=function(h){var p,m,_;return h===void 0?"Undefined":h===null?"Null":typeof(m=u(p=Object(h),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),h="prototype",p=function(m,_,E){var S,C,H,ne=m&p.F,z=m&p.G,T=m&p.S,F=m&p.P,te=m&p.B,U=m&p.W,ee=z?a:a[_]||(a[_]={}),pe=ee[h],K=z?s:T?s[_]:(s[_]||{})[h];z&&(E=_);for(S in E)C=!ne&&K&&K[S]!==void 0,C&&S in ee||(H=C?K[S]:E[S],ee[S]=z&&typeof K[S]!="function"?E[S]:te&&C?c(H,s):U&&K[S]==H?(function(Ne){var tt=function(Se,Me,ve){if(this instanceof Ne){switch(arguments.length){case 0:return new Ne;case 1:return new Ne(Se);case 2:return new Ne(Se,Me)}return new Ne(Se,Me,ve)}return Ne.apply(this,arguments)};return tt[h]=Ne[h],tt})(H):F&&typeof H=="function"?c(Function.call,H):H,F&&((ee.virtual||(ee.virtual={}))[S]=H,m&p.R&&pe&&!pe[S]&&u(pe,S,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),h=n(8),p=n(10),m=n(45),_=n(18),E=n(52),S=n(1)("iterator"),C=!([].keys&&"next"in[].keys()),H="@@iterator",ne="keys",z="values",T=function(){return this};t.exports=function(F,te,U,ee,pe,K,Ne){m(U,te,ee);var tt,Se,Me,ve=function(B){if(!C&&B in Fe)return Fe[B];switch(B){case ne:return function(){return new U(this,B)};case z:return function(){return new U(this,B)}}return function(){return new U(this,B)}},Ke=te+" Iterator",Ee=pe==z,rt=!1,Fe=F.prototype,yt=Fe[S]||Fe[H]||pe&&Fe[pe],qe=yt||ve(pe),dt=pe?Ee?ve("entries"):qe:void 0,I=te=="Array"&&Fe.entries||yt;if(I&&(Me=E(I.call(new F)),Me!==Object.prototype&&(_(Me,Ke,!0),s||h(Me,S)||u(Me,S,T))),Ee&&yt&&yt.name!==z&&(rt=!0,qe=function(){return yt.call(this)}),s&&!Ne||!C&&!rt&&Fe[S]||u(Fe,S,qe),p[te]=qe,p[Ke]=T,pe)if(tt={values:Ee?qe:ve(z),keys:K?qe:ve(ne),entries:dt},Ne)for(Se in tt)Se in Fe||c(Fe,Se,tt[Se]);else a(a.P+a.F*(C||rt),te,tt);return tt}},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),h=n(41),p=n(25),m=n(16),_=n(2),E=_.process,S=_.setImmediate,C=_.clearImmediate,H=_.MessageChannel,ne=0,z={},T="onreadystatechange",F=function(){var U=+this;if(z.hasOwnProperty(U)){var ee=z[U];delete z[U],ee()}},te=function(U){F.call(U.data)};S&&C||(S=function(U){for(var ee=[],pe=1;arguments.length>pe;)ee.push(arguments[pe++]);return z[++ne]=function(){h(typeof U=="function"?U:Function(U),ee)},s(ne),ne},C=function(U){delete z[U]},n(11)(E)=="process"?s=function(U){E.nextTick(u(F,U,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(U){_.postMessage(U+"","*")},_.addEventListener("message",te,!1)):s=T in m("script")?function(U){p.appendChild(m("script"))[T]=function(){p.removeChild(this),F.call(U)}}:function(U){setTimeout(u(F,U,1),0)}),t.exports={set:S,clear:C}},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,h;if(c&&typeof(u=a.toString)=="function"&&!s(h=u.call(a))||typeof(u=a.valueOf)=="function"&&!s(h=u.call(a))||!c&&typeof(u=a.toString)=="function"&&!s(h=u.call(a)))return h;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(T){return T&&T.__esModule?T:{default:T}}function a(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function c(T){return(0,S.createHash)("sha256").update(T).digest("hex")}function u(T){switch(H){case"darwin":return T.split("IOPlatformUUID")[1].split(`
32
+ `)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return T.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return T.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return T.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function h(T){var F=u((0,E.execSync)(z[H]).toString());return T?F:c(F)}function p(T){return new _.default(function(F,te){return(0,E.exec)(z[H],{},function(U,ee,pe){if(U)return te(new Error("Error while obtaining machine id: "+U.stack));var K=u(ee.toString());return F(T?K:c(K))})})}Object.defineProperty(i,"__esModule",{value:!0});var m=n(35),_=s(m);i.machineIdSync=h,i.machineId=p;var E=n(70),S=n(71),C=process,H=C.platform,ne={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},z={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:ne[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(h,p,m){var _,E=s(h),S=a(E.length),C=c(m,S);if(u&&p!=p){for(;S>C;)if(_=E[C++],_!=_)return!0}else for(;S>C;C++)if((u||C in E)&&E[C]===p)return u||C||0;return!u&&-1}}},function(t,E,n){var s=n(7),a=n(44),c=n(43),u=n(3),h=n(31),p=n(64),m={},_={},E=t.exports=function(S,C,H,ne,z){var T,F,te,U,ee=z?function(){return S}:p(S),pe=s(H,ne,C?2:1),K=0;if(typeof ee!="function")throw TypeError(S+" is not iterable!");if(c(ee)){for(T=h(S.length);T>K;K++)if(U=C?pe(u(F=S[K])[0],F[1]):pe(S[K]),U===m||U===_)return U}else for(te=ee.call(S);!(F=te.next()).done;)if(U=a(te,pe,F.value,C),U===m||U===_)return U};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,h){try{return h?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(h,p,m){h.prototype=s(u,{next:a(1,m)}),c(h,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,h){if(!h&&!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,h=s.Promise,p=n(11)(u)=="process";t.exports=function(){var m,_,E,S=function(){var z,T;for(p&&(z=u.domain)&&z.exit();m;){T=m.fn,m=m.next;try{T()}catch(F){throw m?E():_=void 0,F}}_=void 0,z&&z.enter()};if(p)E=function(){u.nextTick(S)};else if(c){var C=!0,H=document.createTextNode("");new c(S).observe(H,{characterData:!0}),E=function(){H.data=C=!C}}else if(h&&h.resolve){var ne=h.resolve();E=function(){ne.then(S)}}else E=function(){a.call(s,S)};return function(z){var T={fn:z,next:void 0};_&&(_.next=T),m||(m=T,E()),_=T}}},function(t,i,n){var s=n(3),a=n(50),c=n(22),u=n(19)("IE_PROTO"),h=function(){},p="prototype",m=function(){var _,E=n(16)("iframe"),S=c.length,C=">";for(E.style.display="none",n(25).appendChild(E),E.src="javascript:",_=E.contentWindow.document,_.open(),_.write("<script>document.F=Object</script"+C),_.close(),m=_.F;S--;)delete m[p][c[S]];return m()};t.exports=Object.create||function(_,E){var S;return _!==null?(h[p]=s(_),S=new h,h[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,h){a(u);for(var p,m=c(h),_=m.length,E=0;_>E;)s.f(u,p=m[E++],h[p]);return u}},function(t,i,n){var s=n(55),a=n(17),c=n(13),u=n(32),h=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(h(_,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(h){return h=a(h),s(h,c)?h[c]:typeof h.constructor=="function"&&h instanceof h.constructor?h.constructor.prototype:h 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(h,p){var m,_=a(h),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 h in c)u&&a[h]?a[h]=c[h]:s(a,h,c[h]);return a}},function(t,i,n){t.exports=n(5)},function(t,i,n){var s=n(9),a=n(3),c=function(u,h){if(a(u),!s(h)&&h!==null)throw TypeError(h+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?(function(u,h,p){try{p=n(7)(Function.call,n(51).f(Object.prototype,"__proto__").set,2),p(u,[]),h=!(u instanceof Array)}catch{h=!0}return function(m,_){return c(m,_),h?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),h=n(1)("species");t.exports=function(p){var m=typeof a[p]=="function"?a[p]:s[p];u&&m&&!m[h]&&c.f(m,h,{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,h){var p,m=s(u).constructor;return m===void 0||(p=s(m)[c])==null?h:a(p)}},function(t,i,n){var s=n(20),a=n(15);t.exports=function(c){return function(u,h){var p,m,_=String(a(u)),E=s(h),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,h){return u=s(u),u<0?a(u+h,0):c(u,h)}},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(h,p){this._t=u(h),this._i=0,this._k=p},function(){var h=this._t,p=this._k,m=this._i++;return!h||m>=h.length?(this._t=void 0,a(1)):p=="keys"?a(0,m):p=="values"?a(0,h[m]):a(0,[m,h[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),h=n(2),p=n(7),m=n(21),_=n(23),E=n(9),S=(n(3),n(14)),C=n(38),H=n(40),ne=(n(58).set,n(60)),z=n(30).set,T=n(48)(),F="Promise",te=h.TypeError,ee=h.process,U=h[F],ee=h.process,pe=m(ee)=="process",K=function(){},Ne=!!(function(){try{var I=U.resolve(1),B=(I.constructor={})[n(1)("species")]=function(A){A(K,K)};return(pe||typeof PromiseRejectionEvent=="function")&&I.then(K)instanceof B}catch{}})(),tt=function(I,B){return I===B||I===U&&B===c},Se=function(I){var B;return!(!E(I)||typeof(B=I.then)!="function")&&B},Me=function(I){return tt(U,I)?new ve(I):new a(I)},ve=a=function(I){var B,A;this.promise=new I(function(se,Pe){if(B!==void 0||A!==void 0)throw te("Bad Promise constructor");B=se,A=Pe}),this.resolve=S(B),this.reject=S(A)},Ke=function(I){try{I()}catch(B){return{error:B}}},Ee=function(I,B){if(!I._n){I._n=!0;var A=I._c;T(function(){for(var se=I._v,Pe=I._s==1,j=0,ue=function(je){var it,_t,Vt=Pe?je.ok:je.fail,si=je.resolve,Dr=je.reject,Ai=je.domain;try{Vt?(Pe||(I._h==2&&yt(I),I._h=1),Vt===!0?it=se:(Ai&&Ai.enter(),it=Vt(se),Ai&&Ai.exit()),it===je.promise?Dr(te("Promise-chain cycle")):(_t=Se(it))?_t.call(it,si,Dr):si(it)):Dr(se)}catch(Qn){Dr(Qn)}};A.length>j;)ue(A[j++]);I._c=[],I._n=!1,B&&!I._h&&rt(I)})}},rt=function(I){z.call(h,function(){var B,A,se,Pe=I._v;if(Fe(I)&&(B=Ke(function(){pe?ee.emit("unhandledRejection",Pe,I):(A=h.onunhandledrejection)?A({promise:I,reason:Pe}):(se=h.console)&&se.error&&se.error("Unhandled promise rejection",Pe)}),I._h=pe||Fe(I)?2:1),I._a=void 0,B)throw B.error})},Fe=function(I){if(I._h==1)return!1;for(var B,A=I._a||I._c,se=0;A.length>se;)if(B=A[se++],B.fail||!Fe(B.promise))return!1;return!0},yt=function(I){z.call(h,function(){var B;pe?ee.emit("rejectionHandled",I):(B=h.onrejectionhandled)&&B({promise:I,reason:I._v})})},qe=function(I){var B=this;B._d||(B._d=!0,B=B._w||B,B._v=I,B._s=2,B._a||(B._a=B._c.slice()),Ee(B,!0))},dt=function(I){var B,A=this;if(!A._d){A._d=!0,A=A._w||A;try{if(A===I)throw te("Promise can't be resolved itself");(B=Se(I))?T(function(){var se={_w:A,_d:!1};try{B.call(I,p(dt,se,1),p(qe,se,1))}catch(Pe){qe.call(se,Pe)}}):(A._v=I,A._s=1,Ee(A,!1))}catch(se){qe.call({_w:A,_d:!1},se)}}};Ne||(U=function(I){C(this,U,F,"_h"),S(I),s.call(this);try{I(p(dt,this,1),p(qe,this,1))}catch(B){qe.call(this,B)}},s=function(I){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)(U.prototype,{then:function(I,B){var A=Me(ne(this,U));return A.ok=typeof I!="function"||I,A.fail=typeof B=="function"&&B,A.domain=pe?ee.domain:void 0,this._c.push(A),this._a&&this._a.push(A),this._s&&Ee(this,!1),A.promise},catch:function(I){return this.then(void 0,I)}}),ve=function(){var I=new s;this.promise=I,this.resolve=p(dt,I,1),this.reject=p(qe,I,1)}),_(_.G+_.W+_.F*!Ne,{Promise:U}),n(18)(U,F),n(59)(F),c=n(6)[F],_(_.S+_.F*!Ne,F,{reject:function(I){var B=Me(this),A=B.reject;return A(I),B.promise}}),_(_.S+_.F*(u||!Ne),F,{resolve:function(I){if(I instanceof U&&tt(I.constructor,this))return I;var B=Me(this),A=B.resolve;return A(I),B.promise}}),_(_.S+_.F*!(Ne&&n(46)(function(I){U.all(I).catch(K)})),F,{all:function(I){var B=this,A=Me(B),se=A.resolve,Pe=A.reject,j=Ke(function(){var ue=[],je=0,it=1;H(I,!1,function(_t){var Vt=je++,si=!1;ue.push(void 0),it++,B.resolve(_t).then(function(Dr){si||(si=!0,ue[Vt]=Dr,--it||se(ue))},Pe)}),--it||se(ue)});return j&&Pe(j.error),A.promise},race:function(I){var B=this,A=Me(B),se=A.reject,Pe=Ke(function(){H(I,!1,function(j){B.resolve(j).then(A.resolve,se)})});return Pe&&se(Pe.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"),h=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],p=0;p<5;p++){var m=h[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 Yb(){try{return Jc.default.statSync("/.dockerenv"),!0}catch{return!1}}function Xb(){try{return Jc.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Zc(){return Xc===void 0&&(Xc=Yb()||Xb()),Xc}var Jc,Xc,fd=$t(()=>{Jc=he(require("node:fs"),1)});function fn(){return Qc===void 0&&(Qc=Jb()||Zc()),Qc}var ud,Qc,Jb,ef=$t(()=>{ud=he(require("node:fs"),1);fd();Jb=()=>{try{return ud.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var tf,hd,dd,ld,Qr,rf=$t(()=>{tf=he(require("node:process"),1),hd=he(require("node:os"),1),dd=he(require("node:fs"),1);ef();ld=()=>{if(tf.default.platform!=="linux")return!1;if(hd.default.release().toLowerCase().includes("microsoft"))return!fn();try{return dd.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!fn():!1}catch{return!1}},Qr=tf.default.env.__IS_WSL_TEST__?ld:ld()});var nf,zn,Zb,Qb,sf,pd=$t(()=>{nf=he(require("node:process"),1),zn=he(require("node:fs/promises"),1);rf();rf();Zb=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",i=!1;try{await zn.default.access(t,zn.constants.F_OK),i=!0}catch{}if(!i)return r;let n=await zn.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}})(),Qb=async()=>`${await Zb()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,sf=async()=>Qr?Qb():`${nf.default.env.SYSTEMROOT||nf.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function ei(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 gd=$t(()=>{});async function of(){if(yd.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await eE("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 md,yd,_d,eE,bd=$t(()=>{md=require("node:util"),yd=he(require("node:process"),1),_d=require("node:child_process"),eE=(0,md.promisify)(_d.execFile)});async function vd(r,{humanReadableOutput:e=!0,signal:t}={}){if(Ed.default.platform!=="darwin")throw new Error("macOS only");let i=e?[]:["-ss"],n={};t&&(n.signal=t);let{stdout:s}=await tE("osascript",["-e",r,i],n);return s.trim()}var Ed,wd,af,tE,xd=$t(()=>{Ed=he(require("node:process"),1),wd=require("node:util"),af=require("node:child_process"),tE=(0,wd.promisify)(af.execFile)});async function cf(r){return vd(`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 Sd=$t(()=>{xd()});async function uf(r=rE){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 ff(`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 vo[i]??vo[a]??vo[c]??{name:i,id:i}}var Td,Cd,rE,vo,_x,ff,kd=$t(()=>{Td=require("node:util"),Cd=require("node:child_process"),rE=(0,Td.promisify)(Cd.execFile),vo={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"}},_x=new Map(Object.entries(vo)),ff=class extends Error{}});async function lf(){if(xo.default.platform==="darwin"){let r=await of();return{name:await cf(r),id:r}}if(xo.default.platform==="linux"){let{stdout:r}=await iE("xdg-mime",["query","default","x-scheme-handler/http"]),e=r.trim();return{name:nE(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(xo.default.platform==="win32")return uf();throw new Error("Only macOS, Linux, and Windows are supported")}var Pd,xo,Od,iE,nE,Rd=$t(()=>{Pd=require("node:util"),xo=he(require("node:process"),1),Od=require("node:child_process");bd();Sd();kd();iE=(0,Pd.promisify)(Od.execFile),nE=r=>r.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var Dd={};Lp(Dd,{apps:()=>ti,default:()=>fE,openApp:()=>cE});async function oE(){let r=await sf(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=pf.Buffer.from(e,"utf16le").toString("base64"),{stdout:i}=await sE(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 Nd(r){if(typeof r=="string"||Array.isArray(r))return r;let{[Id]:e}=r;if(!e)throw new Error(`${Id} is not supported`);return e}function To({[un]:r},{wsl:e}){if(e&&Qr)return Nd(e);if(!r)throw new Error(`${un} is not supported`);return Nd(r)}var df,pf,gf,Md,Fd,mf,So,uE,sE,hf,Ad,un,Id,Ld,Gn,aE,cE,ti,fE,Bd=$t(()=>{df=he(require("node:process"),1),pf=require("node:buffer"),gf=he(require("node:path"),1),Md=require("node:url"),Fd=require("node:util"),mf=he(require("node:child_process"),1),So=he(require("node:fs/promises"),1);pd();gd();Rd();ef();uE={},sE=(0,Fd.promisify)(mf.default.execFile),hf=gf.default.dirname((0,Md.fileURLToPath)(uE.url)),Ad=gf.default.join(hf,"xdg-open"),{platform:un,arch:Id}=df.default;Ld=async(r,e)=>{let t;for(let i of r)try{return await e(i)}catch(n){t=n}throw t},Gn=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return Ld(r.app,c=>Gn({...r,app:c}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return Ld(e,c=>Gn({...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"},h=Qr?await oE():await lf();if(h.id in c){let p=c[h.id];return e==="browserPrivate"&&t.push(u[p]),Gn({...r,app:{name:ti[p],arguments:t}})}throw new Error(`${h.name} is not supported as a default browser`)}let i,n=[],s={};if(un==="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(un==="win32"||Qr&&!fn()&&!e){i=await sf(),n.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),Qr||(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=pf.Buffer.from(c.join(" "),"utf16le").toString("base64")}else{if(e)i=e;else{let c=!hf||hf==="/",u=!1;try{await So.default.access(Ad,So.constants.X_OK),u=!0}catch{}i=df.default.versions.electron??(un==="android"||c||!u)?"xdg-open":Ad}t.length>0&&n.push(...t),r.wait||(s.stdio="ignore",s.detached=!0)}un==="darwin"&&t.length>0&&n.push("--args",...t),r.target&&n.push(r.target);let a=mf.default.spawn(i,n,s);return r.wait?new Promise((c,u)=>{a.once("error",u),a.once("close",h=>{if(!r.allowNonzeroExitCode&&h>0){u(new Error(`Exited with code ${h}`));return}c(a)})}):(a.unref(),a)},aE=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a `target`");return Gn({...e,target:r})},cE=(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 Gn({...e,app:{name:r,arguments:t}})};ti={};ei(ti,"chrome",()=>To({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"]}}));ei(ti,"brave",()=>To({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"]}}));ei(ti,"firefox",()=>To({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));ei(ti,"edge",()=>To({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));ei(ti,"browser",()=>"browser");ei(ti,"browserPrivate",()=>"browserPrivate");fE=aE});var wr=he(require("fs")),as=he(require("path"));var Df=he(require("os")),Bf=he(require("path")),ss=he(require("fs"));function os(){let r=Bf.join(Df.homedir(),".termiq");return ss.existsSync(r)||ss.mkdirSync(r,{recursive:!0,mode:448}),r}var _n=class{filePath;data={};constructor(){this.filePath=as.join(os(),"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(wr.existsSync(this.filePath)){let e=wr.readFileSync(this.filePath,"utf-8");this.data=JSON.parse(e)}}catch{this.data={}}}save(){let e=as.dirname(this.filePath);wr.existsSync(e)||wr.mkdirSync(e,{recursive:!0,mode:448}),wr.writeFileSync(this.filePath,JSON.stringify(this.data,null,2),{mode:384})}};var vr=he(require("fs")),cs=he(require("path"));var Mp={serverUrl:"https://termiq.io",agentName:"",multiViewer:!1,pushPromptText:!1,signalWaiting:!0},bn=class{config;filePath;constructor(e){this.filePath=cs.join(os(),"config.json"),this.config={...Mp,...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()}getPushPromptText(){return this.config.pushPromptText}async setPushPromptText(e){this.config.pushPromptText=e,this.saveToFile()}getSignalWaiting(){return this.config.signalWaiting}async setSignalWaiting(e){this.config.signalWaiting=e,this.saveToFile()}async setAgentName(e){this.config.agentName=e,this.saveToFile()}loadFromFile(){try{if(vr.existsSync(this.filePath)){let e=vr.readFileSync(this.filePath,"utf-8");return JSON.parse(e)}}catch{}return{}}saveToFile(){let e=cs.dirname(this.filePath);vr.existsSync(e)||vr.mkdirSync(e,{recursive:!0,mode:448}),vr.writeFileSync(this.filePath,JSON.stringify(this.config,null,2))}};var wt=he(require("fs")),zc=he(require("path")),od=he(require("os")),wo=he(qn()),Vb="cli",$c=zc.join(od.homedir(),".termiq","logs"),Zr=zc.join($c,"cli.log"),$b=5*1024*1024,sd=3;function zb(){try{if(!wt.existsSync(Zr)||wt.statSync(Zr).size<$b)return;for(let e=sd-1;e>=1;e--){let t=`${Zr}.${e}`,i=`${Zr}.${e+1}`;wt.existsSync(t)&&(e+1>sd?wt.unlinkSync(t):wt.renameSync(t,i))}wt.renameSync(Zr,`${Zr}.1`)}catch{}}function Gb(r){try{wt.existsSync($c)||wt.mkdirSync($c,{recursive:!0}),zb(),wt.appendFileSync(Zr,r+`
34
+ `,{encoding:"utf8"})}catch{}}var Wn=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 Zr}write(e,t,i){if(!(0,wo.shouldLog)(e,this.level))return;let n=(0,wo.formatLogLine)(e,Vb,t,i);this.toFile?Gb(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 ad=he(require("os")),cd=he(Yc()),Vn=class{cachedId=null;name;constructor(e){this.name=e||ad.hostname()||"CLI"}async getMachineId(){if(this.cachedId)return this.cachedId;try{this.cachedId=(0,cd.machineIdSync)()}catch{this.cachedId=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}return this.cachedId}getMachineName(){return this.name}};var $n=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 Yn=class{async openUrl(e){let{default:t}=await Promise.resolve().then(()=>(Bd(),Dd));await t(e)}};var jd=he(require("fs")),yf=he(require("path"));function Co(r){let e=r?[r]:[yf.join(__dirname,"..","package.json"),yf.join(__dirname,"..","..","package.json")];for(let t of e)try{let i=JSON.parse(jd.readFileSync(t,"utf8"));if(typeof i.version=="string"&&i.version.length>0)return i.version}catch{}return"unknown"}function Ud(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 _f=new Set(["--cid","--token","--server","--log-level"]),Kd=new Set(["--help","-h","--version","-V","--verbose","-v","--watch","-w","--log-to-file","--statusline","--multi-viewer","--force"]);function qd(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 gp=he(require("path")),ht=he(qn()),mp=he(kr());var Wd=he(require("os")),Hd=require("crypto"),Vd=he(require("node-pty")),Po=he(qn()),ko=class r{ptyProcess=null;outputBuffer=new Po.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||(Wd.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=Vd.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,Hd.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=>{let h=u.toString();this.multiViewerMode&&!(0,Po.isTerminalReplyOnly)(h)&&this.maybeClaimLocalControl(),this.onLocalInput?.(h),this.ptyProcess?.write(h)}),this.sigwinchListener=()=>{let u=process.stdout.columns||80,h=Math.max(1,(process.stdout.rows||24)-this.reservedBottomRows);if(this.multiViewerMode){this.logger.info("Local resize claims control",{cols:u,rows:h}),this.resize(u,h),this.onLocalClaim?.(u,h);return}if(this.desiredCols!==null&&this.desiredRows!==null){this.logger.info("Local resize ignored (PWA desired-size set)",{host:{cols:u,rows:h},desired:{cols:this.desiredCols,rows:this.desiredRows}});return}if(!this.sigwinchEnabled){this.logger.info("Local resize ignored (PWA viewers attached)",{cols:u,rows:h});return}this.logger.info("Local resize applied",{cols:u,rows:h}),this.ptyProcess?.resize(u,h),this.onResize?.(u,h)},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){if(this.desiredCols=e,this.desiredRows=t,this.ptyProcess&&this.ptyProcess.cols===e&&this.ptyProcess.rows===t){this.cancelRebroadcast();return}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.cols===e&&this.ptyProcess.rows===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 ri=he(require("path")),hn=he(require("fs"));var ap=require("node:events"),cp=require("node:fs"),Fo=require("node:fs/promises"),xe=he(require("node:path"),1);var Mr=require("node:fs/promises"),Fr=require("node:path"),Yd=require("node:stream"),Lt={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},bf={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:Lt.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(bf);var Xd="READDIRP_RECURSIVE_ERROR",lE=new Set(["ENOENT","EPERM","EACCES","ELOOP",Xd]),$d=[Lt.DIR_TYPE,Lt.EVERYTHING_TYPE,Lt.FILE_DIR_TYPE,Lt.FILE_TYPE],hE=new Set([Lt.DIR_TYPE,Lt.EVERYTHING_TYPE,Lt.FILE_DIR_TYPE]),dE=new Set([Lt.EVERYTHING_TYPE,Lt.FILE_DIR_TYPE,Lt.FILE_TYPE]),pE=r=>lE.has(r.code),gE=process.platform==="win32",zd=r=>!0,Gd=r=>{if(r===void 0)return zd;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 zd},Ef=class extends Yd.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={...bf,...e},{root:i,type:n}=t;this._fileFilter=Gd(t.fileFilter),this._directoryFilter=Gd(t.directoryFilter);let s=t.lstat?Mr.lstat:Mr.stat;gE?this._stat=a=>s(a,{bigint:!0}):this._stat=s,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:bf.depth,this._wantsDir=n?hE.has(n):!1,this._wantsFile=n?dE.has(n):!1,this._wantsEverything=n===Lt.EVERYTHING_TYPE,this._root=(0,Fr.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 h=await this._getEntryType(u);h==="directory"&&this._directoryFilter(u)?(s<=this._maxDepth&&this.parents.push(this._exploreDir(u.fullPath,s+1)),this._wantsDir&&(this.push(u),e--)):(h==="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,Mr.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,Fr.resolve)((0,Fr.join)(t,n));i={path:(0,Fr.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){pE(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,Mr.realpath)(i),s=await(0,Mr.lstat)(n);if(s.isFile())return"file";if(s.isDirectory()){let a=n.length;if(i.startsWith(n)&&i.substr(a,1)===Fr.sep){let c=new Error(`Circular symlink detected: "${i}" points to "${n}"`);return c.code=Xd,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 Jd(r,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=Lt.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&&!$d.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${$d.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new Ef(e)}var Ri=require("node:fs"),tr=require("node:fs/promises"),Qd=require("node:os"),Ge=he(require("node:path"),1),mE="data",xf="end",ep="close",Lo=()=>{};var No=process.platform,Sf=No==="win32",yE=No==="darwin",_E=No==="linux",bE=No==="freebsd",tp=(0,Qd.type)()==="OS400",Xe={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},er=Xe,EE="watch",wE={lstat:tr.lstat,stat:tr.stat},Oi="listeners",Oo="errHandlers",ln="rawEmitters",vE=[Oi,Oo,ln],xE=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=>xE.has(Ge.extname(r).slice(1).toLowerCase()),vf=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},Xn=(r,e,t)=>{let i=r[e];i instanceof Set||(r[e]=i=new Set([i])),i.add(t)},TE=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},Jn=(r,e,t)=>{let i=r[e];i instanceof Set?i.delete(t):i===t&&delete r[e]},rp=r=>r instanceof Set?r.size===0:!r,Ro=new Map;function Zd(r,e,t,i,n){let s=(a,c)=>{t(r),n(a,c,{watchedPath:r}),c&&r!==c&&Ao(Ge.resolve(r,c),Oi,Ge.join(r,c))};try{return(0,Ri.watch)(r,{persistent:e.persistent},s)}catch(a){i(a);return}}var Ao=(r,e,t,i,n)=>{let s=Ro.get(r);s&&vf(s[e],a=>{a(t,i,n)})},CE=(r,e,t,i)=>{let{listener:n,errHandler:s,rawEmitter:a}=i,c=Ro.get(e),u;if(!t.persistent)return u=Zd(r,t,n,s,a),u?u.close.bind(u):void 0;if(c)Xn(c,Oi,n),Xn(c,Oo,s),Xn(c,ln,a);else{if(u=Zd(r,t,Ao.bind(null,e,Oi),s,Ao.bind(null,e,ln)),!u)return;u.on(er.ERROR,async h=>{let p=Ao.bind(null,e,Oo);if(c&&(c.watcherUnusable=!0),Sf&&h.code==="EPERM")try{await(await(0,tr.open)(r,"r")).close(),p(h)}catch{}else p(h)}),c={listeners:n,errHandlers:s,rawEmitters:a,watcher:u},Ro.set(e,c)}return()=>{Jn(c,Oi,n),Jn(c,Oo,s),Jn(c,ln,a),rp(c.listeners)&&(c.watcher.close(),Ro.delete(e),vE.forEach(TE(c)),c.watcher=void 0,Object.freeze(c))}},wf=new Map,kE=(r,e,t,i)=>{let{listener:n,rawEmitter:s}=i,a=wf.get(e),c=a&&a.options;return c&&(c.persistent<t.persistent||c.interval>t.interval)&&((0,Ri.unwatchFile)(e),a=void 0),a?(Xn(a,Oi,n),Xn(a,ln,s)):(a={listeners:n,rawEmitters:s,options:t,watcher:(0,Ri.watchFile)(e,t,(u,h)=>{vf(a.rawEmitters,m=>{m(er.CHANGE,e,{curr:u,prev:h})});let p=u.mtimeMs;(u.size!==h.size||p>h.mtimeMs||p===0)&&vf(a.listeners,m=>m(r,u))})},wf.set(e,a)),()=>{Jn(a,Oi,n),Jn(a,ln,s),rp(a.listeners)&&(wf.delete(e),(0,Ri.unwatchFile)(e),a.options=a.watcher=void 0,Object.freeze(a))}},Io=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let i=this.fsw.options,n=Ge.dirname(e),s=Ge.basename(e);this.fsw._getWatchedDir(n).add(s);let c=Ge.resolve(e),u={persistent:i.persistent};t||(t=Lo);let h;if(i.usePolling){let p=i.interval!==i.binaryInterval;u.interval=p&&SE(s)?i.binaryInterval:i.interval,h=kE(e,c,u,{listener:t,rawEmitter:this.fsw._emitRaw})}else h=CE(e,c,u,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return h}_handleFile(e,t,i){if(this.fsw.closed)return;let n=Ge.dirname(e),s=Ge.basename(e),a=this.fsw._getWatchedDir(n),c=t;if(a.has(s))return;let u=async(p,m)=>{if(this.fsw._throttle(EE,e,5)){if(!m||m.mtimeMs===0)try{let _=await(0,tr.stat)(e);if(this.fsw.closed)return;let E=_.atimeMs,S=_.mtimeMs;if((!E||E<=S||S!==c.mtimeMs)&&this.fsw._emit(er.CHANGE,e,_),(yE||_E||bE)&&c.ino!==_.ino){this.fsw._closeFile(p),c=_;let C=this._watchWithNodeFs(e,u);C&&this.fsw._addPathCloser(p,C)}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(er.CHANGE,e,m),c=m}}},h=this._watchWithNodeFs(e,u);if(!(i&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(er.ADD,e,0))return;this.fsw._emit(er.ADD,e,t)}return h}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,tr.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(er.CHANGE,i,e.stats)):(a.add(n),this.fsw._symlinkPaths.set(s,c),this.fsw._emit(er.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=Ge.join(e,"");let u=n?`${e}:${n}`:e;if(c=this.fsw._throttle("readdir",u,1e3),!c)return;let h=this.fsw._getWatchedDir(i.path),p=new Set,m=this.fsw._readdirp(e,{fileFilter:_=>i.filterPath(_),directoryFilter:_=>i.filterDir(_)});if(m)return m.on(mE,async _=>{if(this.fsw.closed){m=void 0;return}let E=_.path,S=Ge.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&&!h.has(E))&&(this.fsw._incrReadyCount(),S=Ge.join(s,Ge.relative(s,S)),this._addToNodeFs(S,t,i,a+1))}}).on(er.ERROR,this._boundHandleError),new Promise((_,E)=>{if(!m)return E();m.once(xf,()=>{if(this.fsw.closed){m=void 0;return}let S=c?c.clear():!1;_(void 0),h.getChildren().filter(C=>C!==e&&!p.has(C)).forEach(C=>{this.fsw._remove(e,C)}),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(Ge.dirname(e)),h=u.has(Ge.basename(e));!(i&&this.fsw.options.ignoreInitial)&&!s&&!h&&this.fsw._emit(er.ADD_DIR,e,t),u.add(Ge.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 wE[c.statMethod](c.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(c.watchPath,u))return a(),!1;let h=this.fsw.options.followSymlinks,p;if(u.isDirectory()){let m=Ge.resolve(e),_=h?await(0,tr.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=h?await(0,tr.realpath)(e):e;if(this.fsw.closed)return;let _=Ge.dirname(c.watchPath);if(this.fsw._getWatchedDir(_).add(c.watchPath),this.fsw._emit(er.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(Ge.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 Tf="/",PE="//",fp=".",OE="..",RE="string",AE=/\\/g,up=/\/\//g,IE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,LE=/^\.[/\\]/;function Mo(r){return Array.isArray(r)?r:[r]}var Cf=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function NE(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(up,"/"),e&&(r="/"+r),r}function ip(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 FE(r,e){if(r==null)throw new TypeError("anymatch: specify first argument");let i=Mo(r).map(n=>NE(n));return e==null?(n,s)=>ip(i,n,s):ip(i,e)}var np=r=>{let e=Mo(r).flat();if(!e.every(t=>typeof t===RE))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(lp)},sp=r=>{let e=r.replace(AE,Tf),t=!1;return e.startsWith(PE)&&(t=!0),e=e.replace(up,Tf),t&&(e=Tf+e),e},lp=r=>sp(xe.normalize(sp(r))),op=(r="")=>e=>typeof e=="string"?lp(xe.isAbsolute(e)?e:xe.join(r,e)):e,DE=(r,e)=>xe.isAbsolute(r)?r:xe.join(e,r),BE=Object.freeze(new Set),kf=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!==fp&&e!==OE&&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,Fo.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=Lo,this.items=BE,Object.freeze(this)}},jE="stat",UE="lstat",Pf=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,i){this.fsw=i;let n=e;this.path=e=e.replace(LE,""),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?jE:UE}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)}},Of=class extends ap.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?Mo(e.ignored):Mo([]),awaitWriteFinish:t===!0?i:typeof t=="object"?{...i,...t}:!1};tp&&(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=Lo,this._readyEmitted=!0,process.nextTick(()=>this.emit(Xe.READY)))},this._emitRaw=(...u)=>this.emit(Xe.RAW,...u),this._boundRemove=this._remove.bind(this),this.options=n,this._nodeFsHandler=new Io(this),Object.freeze(n)}_addIgnoredPath(e){if(Cf(e)){for(let t of this._ignoredPaths)if(Cf(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)Cf(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=np(e);return n&&(s=s.map(a=>DE(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=np(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)||fp;e[s]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==Xe.ERROR&&this.emit(Xe.ALL,e,...t)}async _emit(e,t,i){if(this.closed)return;let n=this.options;Sf&&(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===Xe.UNLINK)return this._pendingUnlinks.set(t,[e,...s]),setTimeout(()=>{this._pendingUnlinks.forEach((u,h)=>{this.emit(...u),this.emit(Xe.ALL,...u),this._pendingUnlinks.delete(h)})},typeof n.atomic=="number"?n.atomic:100),this;e===Xe.ADD&&this._pendingUnlinks.has(t)&&(e=Xe.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===Xe.ADD||e===Xe.CHANGE)&&this._readyEmitted){let u=(h,p)=>{h?(e=Xe.ERROR,s[0]=h,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===Xe.CHANGE&&!this._throttle(Xe.CHANGE,t,50))return this;if(n.alwaysStat&&i===void 0&&(e===Xe.ADD||e===Xe.ADD_DIR||e===Xe.CHANGE)){let u=n.cwd?xe.join(n.cwd,t):t,h;try{h=await(0,Fo.stat)(u)}catch{}if(!h||this.closed)return;s.push(h)}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(Xe.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 h=n.get(t),p=h?h.count:0;return n.delete(t),clearTimeout(a),h&&clearTimeout(h.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 h=new Date,p=this._pendingWrites;function m(_){(0,cp.stat)(u,(E,S)=>{if(E||!p.has(e)){E&&E.code!=="ENOENT"&&n(E);return}let C=Number(new Date);_&&S.size!==_.size&&(p.get(e).lastChange=C);let H=p.get(e);C-H.lastChange>=t?(p.delete(e),n(void 0,S)):c=setTimeout(m,a,S)})}p.has(e)||(p.set(e,{lastChange:h,cancelWait:()=>(p.delete(e),clearTimeout(c),i)}),c=setTimeout(m,a))}_isIgnored(e,t){if(this.options.atomic&&IE.test(e))return!0;if(!this._userIgnored){let{cwd:i}=this.options,s=(this.options.ignored||[]).map(op(i)),c=[...[...this._ignoredPaths].map(op(i)),...s];this._userIgnored=FE(c,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Pf(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=xe.resolve(e);return this._watched.has(t)||this._watched.set(t,new kf(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),h=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()===Xe.ADD)return;this._watched.delete(n),this._watched.delete(s);let m=i?Xe.UNLINK_DIR:Xe.UNLINK;h&&!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:Xe.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},n=Jd(e,i);return this._streams.add(n),n.once(ep,()=>{n=void 0}),n.once(xf,()=>{n&&(this._streams.delete(n),n=void 0)}),n}};function hp(r,e={}){let t=new Of(e);return t.add(r),t}var dp=he(Fc()),_r=he(kr()),KE=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/*.log"],qE=300,Do=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,dp.default)(),this.initializeIgnoreFilter()}initializeIgnoreFilter(){this.ignoreFilter.add(KE);let e=ri.join(this.workspaceRoot,".gitignore");try{if(hn.existsSync(e)){let t=hn.readFileSync(e,"utf-8");this.ignoreFilter.add(t)}}catch{}}onFileChanged(e){this.onFileChangedCallback=e}start(){this.watcher||(this.watcher=hp(this.workspaceRoot,{ignored:e=>{let t=ri.relative(this.workspaceRoot,e);if(!t||t===".")return!1;let i=t.split(ri.sep).join("/");return this.ignoreFilter.ignores(i)},persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50}}),this.watcher.on("add",e=>this.handleEvent(e,_r.FileChangeType.CREATE)),this.watcher.on("change",e=>this.handleEvent(e,_r.FileChangeType.MODIFY)),this.watcher.on("unlink",e=>this.handleEvent(e,_r.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=ri.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)},qE);this.pendingEvents.set(i,a)}mergeTypes(e,t){return e?t===_r.FileChangeType.DELETE||e===_r.FileChangeType.DELETE?_r.FileChangeType.DELETE:e===_r.FileChangeType.CREATE?_r.FileChangeType.CREATE:t:t}emit(e,t){let i={path:e,changeType:t,timestamp:new Date().toISOString(),source:"watcher"};if(t!==_r.FileChangeType.DELETE)try{let n=ri.join(this.workspaceRoot,e),s=hn.statSync(n);i.size=s.size}catch{}this.onFileChangedCallback?.(i)}dispose(){this.stop(),this.onFileChangedCallback=null}};var WE={online:!1,viewerCount:0},Bo=class r{enabled=!1;state={...WE};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 jo(r,e,t,i){if(i)return process.stderr.write(`Logging in with API key...
36
+ `),await r.loginWithApiKey(i)?(process.stderr.write(`Login successful.
37
37
  `),!0):(process.stderr.write(`Login failed. Check your API key.
38
- `),!1);try{let i=await r.startDeviceCodeFlow();process.stderr.write(`
39
- `),process.stderr.write(` Open this URL: ${i.verificationUri}
40
- `),process.stderr.write(` Enter code: ${i.userCode}
38
+ `),!1);try{let n=await r.startDeviceCodeFlow();process.stderr.write(`
39
+ `),process.stderr.write(` Open this URL: ${n.verificationUri}
40
+ `),process.stderr.write(` Enter code: ${n.userCode}
41
41
  `),process.stderr.write(`
42
42
  `),process.stderr.write(` Waiting for authorization...
43
- `);try{await e.openUrl(i.verificationUri)}catch{}let s=await r.pollForToken(i.deviceCode);return s&&s.status==="success"?(process.stderr.write(` Login successful!
43
+ `);try{await e.openUrl(n.verificationUri)}catch{}let s=await r.pollForToken(n.deviceCode);return s&&s.status==="success"?(process.stderr.write(` Login successful!
44
44
 
45
45
  `),!0):(process.stderr.write(` Login failed or expired.
46
46
 
47
- `),!1)}catch(i){return t.error("Login error",i),process.stderr.write(`Login error: ${i instanceof Error?i.message:String(i)}
48
- `),!1}}var li=ue(Tr());function Nb(r){switch(r){case"numbered-choice":return"select";case"free-input":return"input";default:return"confirmation"}}function up(r,e,t){let n=new Date().toISOString();switch(r){case"working":return e==="idle"?{type:li.TerminalEventType.SESSION_START,timestamp:n}:null;case"waiting":return{type:li.TerminalEventType.WAITING_INPUT,timestamp:n,promptType:Nb(t?.type),question:t?.question||"Confirm action?",options:t?.choices?.map(i=>i.label)};case"completed":return{type:li.TerminalEventType.SESSION_END,timestamp:n,status:"success"};case"error":return e==="working"?{type:li.TerminalEventType.SESSION_END,timestamp:n,status:"error"}:{type:li.TerminalEventType.ERROR,timestamp:n,severity:"error",message:"Command failed"};default:return null}}async function dp(r){let{storage:e,config:t,logger:n,machineId:i,notification:s,browser:a,cwd:c,watch:u,statusLine:d,multiViewer:p}=r,m=new Fo(n);d&&m.enable();let _=t.getServerUrl(),v=new URL(_).host,S=await i.getMachineId(),T=new ht.CryptoService(e,n,v,S);await T.initialize();let H=await T.getShortFingerprint();process.stderr.write(`Agent fingerprint: ${H} (verify in the web app; run 'termiq fingerprint' for the full safety number)
49
- `);let de=new ht.AuthService(e,T,i,t,n,s,a,v,S),z=await de.hasValidToken();z||await de.refreshAccessToken()||(process.stderr.write(`Not logged in. Starting login flow...
50
- `),await Do(de,a,n)||process.exit(1),z=!0);let C;try{let{machineIdSync:A}=await Promise.resolve().then(()=>ue(Vc()));C=A()}catch{C=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}let D,Q=new ht.StatusDetector((A,ee,Ne)=>{if(!U.getStatus().connected)return;let Xe=D;D=ee,U.updateStatus({instanceId:se,terminalId:A,status:ee,encryptedPrompt:Ne&&T.encryptPromptInfo(Ne)||void 0}).catch(()=>{});let st=up(ee,Xe,Ne);st&&U.sendTerminalEvent(se,A,st)}),K=p?[hp.Capability.MULTI_VIEWER_RENDER]:[],U=new ht.WebSocketService(de,T,t,n,s,C,"cli",K);p&&n.info("Multi-viewer rendering capability advertised");let le=!1;U.onStatusChange(A=>{if(A==="connected"){if(le)n.info("Reconnected to termiq.io");else{let ee=p?" (multi-viewer mode)":"";process.stderr.write(`Connected to termiq.io${ee}
51
- `),le=!0}m.update({online:!0})}else A==="disconnected"?(n.info("Disconnected from termiq.io (will retry)"),m.update({online:!1})):A==="error"&&(n.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
- `),R(),process.exit(1)});try{await U.connect()}catch(A){process.stderr.write(`Connection failed: ${A instanceof Error?A.message:String(A)}
53
- `),process.exit(1)}let pe=lp.basename(c),se=`cli_${Date.now()}`,nt=T.encryptWorkspaceInfo({name:pe,path:c});await U.registerWorkspace({instanceId:se,encryptedInfo:nt||void 0});let we=new Co(n);p&&we.setMultiViewerMode(!0),we.setPreWriteHook(A=>m.inspectPtyOutput(A));let Se=null;we.setOnResize((A,ee)=>{m.update({ptyCols:A,ptyRows:ee}),p&&Se&&U.sendPtyResized(se,Se,A,ee)}),we.setOnLocalClaim((A,ee)=>{p&&Se&&U.sendClaimControl(se,Se,A,ee)});let _e=we.spawn(c,m.reservedRows()),We=`CLI: ${pe}`,at=process.env.SHELL||"/bin/bash",Qe=T.encryptTerminalInfo({name:We,command:at,cwd:c});await U.terminalCreated({instanceId:se,terminalId:_e,encryptedInfo:Qe||void 0,streamId:we.getStreamId()??void 0}),Se=_e,p&&U.sendPtyResized(se,_e,we.getPtyCols(),we.getPtyRows());let Te=new ht.FileTransferService(n,"/tmp",c);Te.setCrypto(T);let it=new ht.FileTrackerService(n,c),ze=new ht.FileListService(n,c),yt=u?new Mo(n,c):null,L=U.getSocket();L&&Te.attach(L,se),it.onFileChanged((A,ee)=>{U.sendFileChangedEvent(se,A,ee)}),it.onFileViewTransfer(async(A,ee,Ne)=>{try{await Te.sendBuffer(A,ee,Ne.path.split("/").pop()||"view",Ne.mimeType||"text/plain",{purpose:"view",viewMetadata:Ne})}catch(Xe){n.error("File view transfer failed",Xe)}}),U.onFileViewRequest((A,ee)=>{it.handleViewRequest(A,ee)}),U.onFileListRequest((A,ee)=>{ze.handleListRequest(ee)}),ze.onResponse(A=>{U.sendFileListResponse(se,A)}),U.onFileDownloadRequest(async(A,ee,Ne)=>{try{await Te.sendFile(A,ee,void 0,void 0,Ne)}catch(Xe){n.error("File download failed",Xe)}}),yt&&(yt.onFileChanged(A=>{U.sendFileChangedEvent(se,_e,A)}),yt.start()),Q.startTracking(_e),we.setOnOutput(A=>{U.sendOutput(se,_e,A),Q.processOutput(_e,A),it.processOutput(_e,A)}),we.setOnLocalInput(A=>{(0,ht.isAnswerKeystroke)(A)&&Q.resolvePrompt(_e)}),U.onInput((A,ee,Ne,Xe,st)=>{if(A===_e){if(st){let dt=Q.getEmittedPromptKey(_e);if(dt&&dt!==st){n.warn("Stale answer rejected \u2014 prompt changed",{terminalId:_e}),Q.reEmitPrompt(_e);return}}(0,ht.isAnswerKeystroke)(ee)&&Q.resolvePrompt(_e),we.write(ee,Xe)}}),U.setTerminalActiveCheck(A=>A===_e&&we.isAlive()),U.onResizeRequest((A,ee,Ne)=>{A===_e&&(n.info("Remote resize received",{terminalId:A,cols:ee,rows:Ne}),we.resize(ee,Ne))}),U.onClientAttached(({clientCount:A})=>{we.setSigwinchEnabled(!1),m.update({viewerCount:A}),U.sendInputResume(_e)}),U.onClientDetached(({clientCount:A})=>{A===0&&we.setSigwinchEnabled(!0),m.update({viewerCount:A})}),U.onGetBufferRequest(A=>A===_e?we.getBuffer():null),U.onRedrawRequest(A=>{A===_e&&we.redrawNoResize()});async function j(){let A=T.encryptWorkspaceInfo({name:pe,path:c});await U.registerWorkspace({instanceId:se,encryptedInfo:A||void 0});let ee=T.encryptTerminalInfo({name:We,command:at,cwd:c});await U.terminalCreated({instanceId:se,terminalId:_e,encryptedInfo:ee||void 0,streamId:we.getStreamId()??void 0})}U.onMetaSessionEstablished(A=>{A&&j().catch(ee=>{n.error("Failed to re-register metadata after meta session",ee)}),Q.resendWaitingPrompts()}),U.onReconnect(async()=>{try{await j();let A=U.getSocket();A&&Te.attach(A,se)}catch(A){n.error("Failed to re-register on reconnect",A)}});function R(){yt?.dispose(),Te.detach(),it.dispose(),ze.dispose(),Q.stopTracking(_e),Q.dispose(),U.disposeInputStream(_e),U.terminalClosed({instanceId:se,terminalId:_e}).catch(()=>{}),U.unregisterWorkspace(se).catch(()=>{}),U.disconnect(),we.dispose()}we.setOnExit(()=>{m.disable(),process.stderr.write(`Session ended.
54
- `),R(),process.exit(0)}),process.on("SIGINT",()=>{m.disable(),process.stderr.write(`Session ended.
55
- `),R(),process.exit(0)}),process.on("SIGTERM",()=>{m.disable(),process.stderr.write(`Session ended.
56
- `),R(),process.exit(0)})}async function pp(r){await r.logout(),process.stderr.write(`Logged out.
57
- `)}async function gp(r,e){let t=await r.hasValidToken(),n=await r.getAgentId();if(t?(process.stderr.write(`Status: logged in
58
- `),n&&process.stderr.write(`Agent ID: ${n}
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 dn=he(kr());function HE(r){switch(r){case"numbered-choice":return"select";case"free-input":return"input";default:return"confirmation"}}function pp(r,e,t,i=!1,n){let s=new Date().toISOString();switch(r){case"working":return e==="idle"?{type:dn.TerminalEventType.SESSION_START,timestamp:s}:null;case"waiting":return{type:dn.TerminalEventType.WAITING_INPUT,timestamp:s,promptType:HE(t?.type),...i&&{question:t?.question||"Confirm action?",options:t?.choices?.map(a=>a.label)},...n&&{source:n}};case"completed":return{type:dn.TerminalEventType.SESSION_END,timestamp:s,status:"success"};case"error":return e==="working"?{type:dn.TerminalEventType.SESSION_END,timestamp:s,status:"error"}:{type:dn.TerminalEventType.ERROR,timestamp:s,severity:"error",message:"Command failed"};default:return null}}async function yp(r){let{storage:e,config:t,logger:i,machineId:n,notification:s,browser:a,cwd:c,watch:u,statusLine:h,multiViewer:p,pushPromptText:m=!1,signalWaiting:_=!0}=r,E=new Bo(i);h&&E.enable();let S=t.getServerUrl(),C=new URL(S).host,H=await n.getMachineId(),ne=new ht.CryptoService(e,i,C,H);await ne.initialize();let z=await ne.getShortFingerprint();process.stderr.write(`Agent fingerprint: ${z} (verify in the web app; run 'termiq fingerprint' for the full safety number)
49
+ `);let T=new ht.AuthService(e,ne,n,t,i,s,a,C,H),F=await T.hasValidToken();F||await T.refreshAccessToken()||(process.stderr.write(`Not logged in. Starting login flow...
50
+ `),await jo(T,a,i)||process.exit(1),F=!0);let te;try{let{machineIdSync:j}=await Promise.resolve().then(()=>he(Yc()));te=j()}catch{te=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}let U,ee=new ht.StatusDetector((j,ue,je)=>{if(!K.getStatus().connected)return;let it=U;U=ue,K.updateStatus({instanceId:Se,terminalId:j,status:ue,encryptedPrompt:je&&ne.encryptPromptInfo(je)||void 0}).catch(()=>{});let _t=pp(ue,it,je,m,ee.getWaitingSource(j)??void 0);_t&&K.sendTerminalEvent(Se,j,_t)},j=>{i.warn("Detector drift: agent announced waiting, parser did not see it",{terminalId:j})},{signalWaiting:_}),pe=p?[mp.Capability.MULTI_VIEWER_RENDER]:[],K=new ht.WebSocketService(T,ne,t,i,s,te,"cli",pe);p&&i.info("Multi-viewer rendering capability advertised");let Ne=!1;K.onStatusChange(j=>{if(j==="connected"){if(Ne)i.info("Reconnected to termiq.io");else{let ue=p?" (multi-viewer mode)":"";process.stderr.write(`Connected to termiq.io${ue}
51
+ `),Ne=!0}E.update({online:!0})}else j==="disconnected"?(i.info("Disconnected from termiq.io (will retry)"),E.update({online:!1})):j==="error"&&(i.warn("Connection degraded (no server response) \u2014 reconnecting"),E.update({online:!1}))}),K.onAuthFailure(()=>{process.stderr.write(`Session expired. Please run "termiq login" again.
52
+ `),Pe(),process.exit(1)});try{await K.connect()}catch(j){process.stderr.write(`Connection failed: ${j instanceof Error?j.message:String(j)}
53
+ `),process.exit(1)}let tt=gp.basename(c),Se=`cli_${Date.now()}`,Me=ne.encryptWorkspaceInfo({name:tt,path:c});await K.registerWorkspace({instanceId:Se,encryptedInfo:Me||void 0});let ve=new ko(i);p&&ve.setMultiViewerMode(!0),ve.setPreWriteHook(j=>E.inspectPtyOutput(j));let Ke=null;ve.setOnResize((j,ue)=>{E.update({ptyCols:j,ptyRows:ue}),p&&Ke&&K.sendPtyResized(Se,Ke,j,ue)}),ve.setOnLocalClaim((j,ue)=>{p&&Ke&&K.sendClaimControl(Se,Ke,j,ue)});let Ee=ve.spawn(c,E.reservedRows()),rt=`CLI: ${tt}`,Fe=process.env.SHELL||"/bin/bash",yt=ne.encryptTerminalInfo({name:rt,command:Fe,cwd:c});await K.terminalCreated({instanceId:Se,terminalId:Ee,encryptedInfo:yt||void 0,streamId:ve.getStreamId()??void 0}),Ke=Ee,p&&K.sendPtyResized(Se,Ee,ve.getPtyCols(),ve.getPtyRows());let qe=new ht.FileTransferService(i,"/tmp",c);qe.setCrypto(ne);let dt=new ht.FileTrackerService(i,c),I=new ht.FileListService(i,c),B=u?new Do(i,c):null,A=K.getSocket();A&&qe.attach(A,Se),dt.onFileChanged((j,ue)=>{K.sendFileChangedEvent(Se,j,ue)}),dt.onFileViewTransfer(async(j,ue,je)=>{try{await qe.sendBuffer(j,ue,je.path.split("/").pop()||"view",je.mimeType||"text/plain",{purpose:"view",viewMetadata:je})}catch(it){i.error("File view transfer failed",it)}}),K.onFileViewRequest((j,ue)=>{dt.handleViewRequest(j,ue)}),K.onFileListRequest((j,ue)=>{I.handleListRequest(ue)}),I.onResponse(j=>{K.sendFileListResponse(Se,j)}),K.onFileDownloadRequest(async(j,ue,je)=>{try{await qe.sendFile(j,ue,void 0,void 0,je)}catch(it){i.error("File download failed",it)}}),B&&(B.onFileChanged(j=>{K.sendFileChangedEvent(Se,Ee,j)}),B.start()),ee.startTracking(Ee),ve.setOnOutput(j=>{K.sendOutput(Se,Ee,j),ee.processOutput(Ee,j),dt.processOutput(Ee,j)}),ve.setOnLocalInput(j=>{(0,ht.isAnswerKeystroke)(j)&&ee.resolvePrompt(Ee)}),K.onInput((j,ue,je,it,_t)=>{if(j===Ee){if(_t){let Vt=ee.getEmittedPromptKey(Ee);if(Vt&&Vt!==_t){i.warn("Stale answer rejected \u2014 prompt changed",{terminalId:Ee}),ee.reEmitPrompt(Ee);return}}(0,ht.isAnswerKeystroke)(ue)&&ee.resolvePrompt(Ee),ve.write(ue,it)}}),K.setTerminalActiveCheck(j=>j===Ee&&ve.isAlive()),K.onResizeRequest((j,ue,je)=>{j===Ee&&(i.info("Remote resize received",{terminalId:j,cols:ue,rows:je}),ve.resize(ue,je))}),K.onClientAttached(({clientCount:j})=>{ve.setSigwinchEnabled(!1),E.update({viewerCount:j}),K.sendInputResume(Ee)}),K.onClientDetached(({clientCount:j})=>{j===0&&ve.setSigwinchEnabled(!0),E.update({viewerCount:j})}),K.onGetBufferRequest(j=>j===Ee?ve.getBuffer():null),K.onRedrawRequest(j=>{j===Ee&&ve.redrawNoResize()});async function se(){let j=ne.encryptWorkspaceInfo({name:tt,path:c});await K.registerWorkspace({instanceId:Se,encryptedInfo:j||void 0});let ue=ne.encryptTerminalInfo({name:rt,command:Fe,cwd:c});await K.terminalCreated({instanceId:Se,terminalId:Ee,encryptedInfo:ue||void 0,streamId:ve.getStreamId()??void 0})}K.onMetaSessionEstablished(j=>{j&&se().catch(ue=>{i.error("Failed to re-register metadata after meta session",ue)}),ee.resendWaitingPrompts()}),K.onReconnect(async()=>{try{await se();let j=K.getSocket();j&&qe.attach(j,Se)}catch(j){i.error("Failed to re-register on reconnect",j)}});function Pe(){B?.dispose(),qe.detach(),dt.dispose(),I.dispose(),ee.stopTracking(Ee),ee.dispose(),K.disposeInputStream(Ee),K.terminalClosed({instanceId:Se,terminalId:Ee}).catch(()=>{}),K.unregisterWorkspace(Se).catch(()=>{}),K.disconnect(),ve.dispose()}ve.setOnExit(()=>{E.disable(),process.stderr.write(`Session ended.
54
+ `),Pe(),process.exit(0)}),process.on("SIGINT",()=>{E.disable(),process.stderr.write(`Session ended.
55
+ `),Pe(),process.exit(0)}),process.on("SIGTERM",()=>{E.disable(),process.stderr.write(`Session ended.
56
+ `),Pe(),process.exit(0)})}async function _p(r){await r.logout(),process.stderr.write(`Logged out.
57
+ `)}async function bp(r,e){let t=await r.hasValidToken(),i=await r.getAgentId();if(t?(process.stderr.write(`Status: logged in
58
+ `),i&&process.stderr.write(`Agent ID: ${i}
59
59
  `)):(process.stderr.write(`Status: not logged in
60
60
  `),process.stderr.write(`Run 'termiq login' to authenticate.
61
- `)),e){let i=await e.getShortFingerprint();process.stderr.write(`Fingerprint: ${i}
61
+ `)),e){let n=await e.getShortFingerprint();process.stderr.write(`Fingerprint: ${n}
62
62
  `),process.stderr.write(`Run 'termiq fingerprint' for the full safety number.
63
- `)}}async function mp(r){let e=await r.getSafetyNumber(),t=await r.getShortFingerprint();process.stdout.write(`
63
+ `)}}async function Ep(r){let e=await r.getSafetyNumber(),t=await r.getShortFingerprint();process.stdout.write(`
64
64
  TermIQ agent safety number
65
65
  ${e}
66
66
 
@@ -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 It=ue(qi()),Le=process.argv.slice(2);(Le.includes("--help")||Le.includes("-h"))&&(process.stderr.write(`
73
- termiq v${To()} \u2014 Access terminals from anywhere
72
+ `)}var Nt=he(qn()),Le=process.argv.slice(2);(Le.includes("--help")||Le.includes("-h"))&&(process.stderr.write(`
73
+ termiq v${Co()} \u2014 Access terminals from anywhere
74
74
 
75
75
  Usage:
76
76
  termiq Start a shell with cloud access (default)
@@ -94,21 +94,33 @@ you are connected to THIS agent (no server-in-the-middle).
94
94
  --multi-viewer Latest-wins geometry (opt-in, persists in config): pty
95
95
  follows whoever typed or resized last; other viewers
96
96
  mirror it. Default \u2014 LCD policy (min size over viewers).
97
+ --push-prompt-text
98
+ Put the prompt's text in push notifications (opt-in,
99
+ persists in config). Off by default: the server is told
100
+ only that a terminal is waiting, never what it asked.
101
+ Turning this on sends the question and button labels in
102
+ the clear, so the server can show them in the shade.
103
+ The prompt itself always reaches your devices encrypted.
104
+ --no-signal-waiting
105
+ Ignore the agent's own "waiting" signal (codex and gemini
106
+ put it in the window title). On by default: when our
107
+ parsing misses a prompt, that signal still notifies you,
108
+ with a plain input box instead of buttons. Persists.
97
109
  --help, -h Show this help
98
110
 
99
111
  Environment:
100
112
  TERMIQ_TOKEN API key (equivalent to --token)
101
113
 
102
- `),process.exit(0));(Le.includes("--version")||Le.includes("-V"))&&(process.stdout.write(`${To()}
103
- `),process.exit(0));var yp=Dd(Le,pf,Fd);yp&&(process.stderr.write(`Unknown flag: ${yp}
114
+ `),process.exit(0));(Le.includes("--version")||Le.includes("-V"))&&(process.stdout.write(`${Co()}
115
+ `),process.exit(0));var wp=qd(Le,_f,Kd);wp&&(process.stderr.write(`Unknown flag: ${wp}
104
116
  Run 'termiq --help' for usage.
105
- `),process.exit(1));var _p=Md(Le,pf)??"start",Mb=Le.includes("--verbose")||Le.includes("-v"),Fb=Le.includes("--watch")||Le.includes("-w"),Db=Le.includes("--log-to-file"),Bb=Le.includes("--statusline"),jb=Le.includes("--multi-viewer"),Ub=Le.includes("--force"),Kb=Le.find(r=>r.startsWith("--token="))?.split("=")[1]||(Le.includes("--token")?Le[Le.indexOf("--token")+1]:void 0),Ep=Le.find(r=>r.startsWith("--server="))?.split("=")[1]||(Le.includes("--server")?Le[Le.indexOf("--server")+1]:void 0),Cf=Le.find(r=>r.startsWith("--log-level="))?.split("=")[1]||(Le.includes("--log-level")?Le[Le.indexOf("--log-level")+1]:void 0),qb=["silent","error","warn","info","debug"],Wb=Cf&&qb.includes(Cf)?Cf:Mb?"info":"silent",Hb=Le.find(r=>r.startsWith("--cid="))?.split("=")[1]||(Le.includes("--cid")?Le[Le.indexOf("--cid")+1]:void 0),Vb=Hb||(0,It.generateCorrelationId)(),zb=process.env.TERMIQ_TOKEN,mr=new Wi(Wb,Db),rn=new mi,gr=new yi(Ep?{serverUrl:Ep}:void 0),nn=new Vi,Bo=new zi(mr),Zi=new Yi;async function $b(){switch(_p){case"start":case void 0:{process.env.TERMIQ_SESSION_ACTIVE==="1"&&!Ub&&(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).
117
+ `),process.exit(1));var vp=Ud(Le,_f)??"start",VE=Le.includes("--verbose")||Le.includes("-v"),$E=Le.includes("--watch")||Le.includes("-w"),zE=Le.includes("--log-to-file"),GE=Le.includes("--statusline"),YE=Le.includes("--multi-viewer"),XE=Le.includes("--push-prompt-text"),JE=Le.includes("--no-signal-waiting"),ZE=Le.includes("--force"),QE=Le.find(r=>r.startsWith("--token="))?.split("=")[1]||(Le.includes("--token")?Le[Le.indexOf("--token")+1]:void 0),xp=Le.find(r=>r.startsWith("--server="))?.split("=")[1]||(Le.includes("--server")?Le[Le.indexOf("--server")+1]:void 0),Rf=Le.find(r=>r.startsWith("--log-level="))?.split("=")[1]||(Le.includes("--log-level")?Le[Le.indexOf("--log-level")+1]:void 0),ew=["silent","error","warn","info","debug"],tw=Rf&&ew.includes(Rf)?Rf:VE?"info":"silent",rw=Le.find(r=>r.startsWith("--cid="))?.split("=")[1]||(Le.includes("--cid")?Le[Le.indexOf("--cid")+1]:void 0),iw=rw||(0,Nt.generateCorrelationId)(),nw=process.env.TERMIQ_TOKEN,br=new Wn(tw,zE),ii=new _n,Tt=new bn(xp?{serverUrl:xp}:void 0),ni=new Vn,Uo=new $n(br),Zn=new Yn;async function sw(){switch(vp){case"start":case void 0:{process.env.TERMIQ_SESSION_ACTIVE==="1"&&!ZE&&(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
118
  \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)),jb&&await gr.setMultiViewer(!0);let r=gr.getMultiViewer();await dp({storage:rn,config:gr,logger:mr,machineId:nn,notification:Bo,browser:Zi,cwd:process.cwd(),watch:Fb,statusLine:Bb,multiViewer:r});break}case"login":{let r=new URL(gr.getServerUrl()).host,e=await nn.getMachineId(),t=new It.CryptoService(rn,mr,r,e);await t.initialize();let n=new It.AuthService(rn,t,nn,gr,mr,Bo,Zi,r,e),i=await Do(n,Zi,mr,Kb||zb);process.exit(i?0:1);break}case"logout":{let r=new URL(gr.getServerUrl()).host,e=await nn.getMachineId(),t=new It.CryptoService(rn,mr,r,e);await t.initialize();let n=new It.AuthService(rn,t,nn,gr,mr,Bo,Zi,r,e);await pp(n),process.exit(0);break}case"status":{let r=new URL(gr.getServerUrl()).host,e=await nn.getMachineId(),t=new It.CryptoService(rn,mr,r,e);await t.initialize();let n=new It.AuthService(rn,t,nn,gr,mr,Bo,Zi,r,e);await gp(n,t),process.exit(0);break}case"fingerprint":{let r=new URL(gr.getServerUrl()).host,e=await nn.getMachineId(),t=new It.CryptoService(rn,mr,r,e);await t.initialize(),await mp(t),process.exit(0);break}case"version":{process.stdout.write(`${To()}
119
+ `),process.exit(1)),YE&&await Tt.setMultiViewer(!0);let r=Tt.getMultiViewer();XE&&await Tt.setPushPromptText(!0);let e=Tt.getPushPromptText();JE&&await Tt.setSignalWaiting(!1);let t=Tt.getSignalWaiting();await yp({storage:ii,config:Tt,logger:br,machineId:ni,notification:Uo,browser:Zn,cwd:process.cwd(),watch:$E,statusLine:GE,multiViewer:r,pushPromptText:e,signalWaiting:t});break}case"login":{let r=new URL(Tt.getServerUrl()).host,e=await ni.getMachineId(),t=new Nt.CryptoService(ii,br,r,e);await t.initialize();let i=new Nt.AuthService(ii,t,ni,Tt,br,Uo,Zn,r,e),n=await jo(i,Zn,br,QE||nw);process.exit(n?0:1);break}case"logout":{let r=new URL(Tt.getServerUrl()).host,e=await ni.getMachineId(),t=new Nt.CryptoService(ii,br,r,e);await t.initialize();let i=new Nt.AuthService(ii,t,ni,Tt,br,Uo,Zn,r,e);await _p(i),process.exit(0);break}case"status":{let r=new URL(Tt.getServerUrl()).host,e=await ni.getMachineId(),t=new Nt.CryptoService(ii,br,r,e);await t.initialize();let i=new Nt.AuthService(ii,t,ni,Tt,br,Uo,Zn,r,e);await bp(i,t),process.exit(0);break}case"fingerprint":{let r=new URL(Tt.getServerUrl()).host,e=await ni.getMachineId(),t=new Nt.CryptoService(ii,br,r,e);await t.initialize(),await Ep(t),process.exit(0);break}case"version":{process.stdout.write(`${Co()}
108
120
  `),process.exit(0);break}case"help":{process.stderr.write(`Run 'termiq --help' for full usage.
109
- `),process.exit(0);break}default:process.stderr.write(`Unknown command: ${_p}
121
+ `),process.exit(0);break}default:process.stderr.write(`Unknown command: ${vp}
110
122
  Run 'termiq --help' for usage.
111
- `),process.exit(1)}}(0,It.runWithCorrelation)(Vb,()=>$b().catch(r=>{process.stderr.write(`Fatal error: ${r instanceof Error?r.message:String(r)}
123
+ `),process.exit(1)}}(0,Nt.runWithCorrelation)(iw,()=>sw().catch(r=>{process.stderr.write(`Fatal error: ${r instanceof Error?r.message:String(r)}
112
124
  `),process.exit(1)}));
113
125
  /*! Bundled license information:
114
126