@termiq/cli 3.14.0 → 3.14.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +41 -39
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -1,53 +1,55 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Yd=Object.create;var ko=Object.defineProperty;var Xd=Object.getOwnPropertyDescriptor;var Jd=Object.getOwnPropertyNames;var Zd=Object.getPrototypeOf,Qd=Object.prototype.hasOwnProperty;var Ft=(r,e)=>()=>(r&&(e=r(r=0)),e);var M=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ep=(r,e)=>{for(var t in e)ko(r,t,{get:e[t],enumerable:!0})},tp=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Jd(e))!Qd.call(r,s)&&s!==t&&ko(r,s,{get:()=>e[s],enumerable:!(i=Xd(e,s))||i.enumerable});return r};var ce=(r,e,t)=>(t=r!=null?Yd(Zd(r)):{},tp(e||!r||!r.__esModule?ko(t,"default",{value:r,enumerable:!0}):t,r));var Ws=M(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.generateCorrelationId=sp;ts.runWithCorrelation=np;ts.getCurrentCorrelationId=op;var ip=require("async_hooks");function sp(){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 hf=new ip.AsyncLocalStorage;function np(r,e){return hf.run(r,e)}function op(){return hf.getStore()}});var pf=M(yi=>{"use strict";Object.defineProperty(yi,"__esModule",{value:!0});yi.LOG_LEVELS=void 0;yi.shouldLog=cp;yi.formatLogLine=fp;var ap=Ws();yi.LOG_LEVELS=["silent","error","warn","info","debug"];var df={silent:0,error:1,warn:2,info:3,debug:4};function cp(r,e){return df[r]<=df[e]}function fp(r,e,t,i){let s={ts:new Date().toISOString(),level:r,src:e,msg:t},n=(0,ap.getCurrentCorrelationId)();n&&(s.cid=n);let a=i;a.length>0&&typeof a[0]=="object"&&a[0]!==null&&!(a[0]instanceof Error)&&!Array.isArray(a[0])&&(s.ctx=a[0],a=a.slice(1));let c=[...a].reverse().find(u=>u instanceof Error);c&&(s.err={message:c.message,stack:c.stack,name:c.name},a=a.filter(u=>u!==c)),a.length>0&&(s.args=a);try{return JSON.stringify(s)}catch{return JSON.stringify({ts:s.ts,level:r,src:e,msg:t,_unserializable:!0})}}});var gf=M(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.formatLogLine=Or.shouldLog=Or.LOG_LEVELS=void 0;var Ro=pf();Object.defineProperty(Or,"LOG_LEVELS",{enumerable:!0,get:function(){return Ro.LOG_LEVELS}});Object.defineProperty(Or,"shouldLog",{enumerable:!0,get:function(){return Ro.shouldLog}});Object.defineProperty(Or,"formatLogLine",{enumerable:!0,get:function(){return Ro.formatLogLine}})});var mf=M(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.CircularBuffer=void 0;var Ao=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}};Hs.CircularBuffer=Ao});var Ks=M(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.getApiUrl=up;Vs.getWsUrl=lp;function up(r){return`${r.getServerUrl()}/api`}function lp(r){let e=r.getServerUrl();return e.startsWith("https://")?e.replace(/^https:\/\//,"wss://"):e.replace(/^http:\/\//,"ws://")}});var yf=M(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.getCurrentCorrelationId=gt.runWithCorrelation=gt.generateCorrelationId=gt.getWsUrl=gt.getApiUrl=gt.CircularBuffer=void 0;var hp=mf();Object.defineProperty(gt,"CircularBuffer",{enumerable:!0,get:function(){return hp.CircularBuffer}});var _f=Ks();Object.defineProperty(gt,"getApiUrl",{enumerable:!0,get:function(){return _f.getApiUrl}});Object.defineProperty(gt,"getWsUrl",{enumerable:!0,get:function(){return _f.getWsUrl}});var Po=Ws();Object.defineProperty(gt,"generateCorrelationId",{enumerable:!0,get:function(){return Po.generateCorrelationId}});Object.defineProperty(gt,"runWithCorrelation",{enumerable:!0,get:function(){return Po.runWithCorrelation}});Object.defineProperty(gt,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Po.getCurrentCorrelationId}})});var Ef=M(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0})});var bf=M(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0})});var xf=M(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.PLAN_LIMITS=void 0;zs.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 Tf=M(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0})});var Cf=M(zt=>{"use strict";var dp=zt&&zt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),$s=zt&&zt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&dp(e,r,t)};Object.defineProperty(zt,"__esModule",{value:!0});$s(Ef(),zt);$s(bf(),zt);$s(xf(),zt);$s(Tf(),zt)});var Of=M(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.API_VERSION=Ot.WS_NAMESPACES=Ot.TIMEOUTS=Ot.STATUS_PATTERNS=Ot.TERMINAL_STATUSES=void 0;Ot.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"}};Ot.STATUS_PATTERNS={idle:[/[❯$]\s*$/,/>\s*$/],waiting:[/\[Y\/n\]/i,/\(y\/N\)/i,/Continue\?/i,/proceed\?/i],completed:[/✓/,/Done/,/Completed/,/Success/],error:[/Error/,/Failed/,/✕/,/Exception/]};Ot.TIMEOUTS={HEARTBEAT_INTERVAL:3e4,OFFLINE_THRESHOLD:6e4,DEVICE_CODE_EXPIRY:9e5,DEVICE_CODE_POLL_INTERVAL:5e3};Ot.WS_NAMESPACES={AGENT:"/agent",CLIENT:"/client"};Ot.API_VERSION="v1"});var kf=M(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.isMultiRecipientPayload=pp;Gs.isEncryptedPayload=gp;function pp(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 Io=M((yE,Ys)=>{(function(r){"use strict";var e=function(f){var h,l=new Float64Array(16);if(f)for(h=0;h<f.length;h++)l[h]=f[h];return l},t=function(){throw new Error("no PRNG")},i=new Uint8Array(16),s=new Uint8Array(32);s[0]=9;var n=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]),y=e([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function b(f,h,l,o){f[h]=l>>24&255,f[h+1]=l>>16&255,f[h+2]=l>>8&255,f[h+3]=l&255,f[h+4]=o>>24&255,f[h+5]=o>>16&255,f[h+6]=o>>8&255,f[h+7]=o&255}function T(f,h,l,o,g){var v,w=0;for(v=0;v<g;v++)w|=f[h+v]^l[o+v];return(1&w-1>>>8)-1}function C(f,h,l,o){return T(f,h,l,o,16)}function V(f,h,l,o){return T(f,h,l,o,32)}function _e(f,h,l,o){for(var g=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,v=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,w=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,k=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,F=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,Y=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,Ce=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,K=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,re=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,ie=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,le=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,fe=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,se=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,oe=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ne=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,z=g,J=v,H=w,$=k,G=F,q=Y,x=W,S=Ce,I=K,O=re,R=ie,D=le,Z=fe,he=se,ge=oe,de=ne,_,ye=0;ye<20;ye+=2)_=z+Z|0,G^=_<<7|_>>>25,_=G+z|0,I^=_<<9|_>>>23,_=I+G|0,Z^=_<<13|_>>>19,_=Z+I|0,z^=_<<18|_>>>14,_=q+J|0,O^=_<<7|_>>>25,_=O+q|0,he^=_<<9|_>>>23,_=he+O|0,J^=_<<13|_>>>19,_=J+he|0,q^=_<<18|_>>>14,_=R+x|0,ge^=_<<7|_>>>25,_=ge+R|0,H^=_<<9|_>>>23,_=H+ge|0,x^=_<<13|_>>>19,_=x+H|0,R^=_<<18|_>>>14,_=de+D|0,$^=_<<7|_>>>25,_=$+de|0,S^=_<<9|_>>>23,_=S+$|0,D^=_<<13|_>>>19,_=D+S|0,de^=_<<18|_>>>14,_=z+$|0,J^=_<<7|_>>>25,_=J+z|0,H^=_<<9|_>>>23,_=H+J|0,$^=_<<13|_>>>19,_=$+H|0,z^=_<<18|_>>>14,_=q+G|0,x^=_<<7|_>>>25,_=x+q|0,S^=_<<9|_>>>23,_=S+x|0,G^=_<<13|_>>>19,_=G+S|0,q^=_<<18|_>>>14,_=R+O|0,D^=_<<7|_>>>25,_=D+R|0,I^=_<<9|_>>>23,_=I+D|0,O^=_<<13|_>>>19,_=O+I|0,R^=_<<18|_>>>14,_=de+ge|0,Z^=_<<7|_>>>25,_=Z+de|0,he^=_<<9|_>>>23,_=he+Z|0,ge^=_<<13|_>>>19,_=ge+he|0,de^=_<<18|_>>>14;z=z+g|0,J=J+v|0,H=H+w|0,$=$+k|0,G=G+F|0,q=q+Y|0,x=x+W|0,S=S+Ce|0,I=I+K|0,O=O+re|0,R=R+ie|0,D=D+le|0,Z=Z+fe|0,he=he+se|0,ge=ge+oe|0,de=de+ne|0,f[0]=z>>>0&255,f[1]=z>>>8&255,f[2]=z>>>16&255,f[3]=z>>>24&255,f[4]=J>>>0&255,f[5]=J>>>8&255,f[6]=J>>>16&255,f[7]=J>>>24&255,f[8]=H>>>0&255,f[9]=H>>>8&255,f[10]=H>>>16&255,f[11]=H>>>24&255,f[12]=$>>>0&255,f[13]=$>>>8&255,f[14]=$>>>16&255,f[15]=$>>>24&255,f[16]=G>>>0&255,f[17]=G>>>8&255,f[18]=G>>>16&255,f[19]=G>>>24&255,f[20]=q>>>0&255,f[21]=q>>>8&255,f[22]=q>>>16&255,f[23]=q>>>24&255,f[24]=x>>>0&255,f[25]=x>>>8&255,f[26]=x>>>16&255,f[27]=x>>>24&255,f[28]=S>>>0&255,f[29]=S>>>8&255,f[30]=S>>>16&255,f[31]=S>>>24&255,f[32]=I>>>0&255,f[33]=I>>>8&255,f[34]=I>>>16&255,f[35]=I>>>24&255,f[36]=O>>>0&255,f[37]=O>>>8&255,f[38]=O>>>16&255,f[39]=O>>>24&255,f[40]=R>>>0&255,f[41]=R>>>8&255,f[42]=R>>>16&255,f[43]=R>>>24&255,f[44]=D>>>0&255,f[45]=D>>>8&255,f[46]=D>>>16&255,f[47]=D>>>24&255,f[48]=Z>>>0&255,f[49]=Z>>>8&255,f[50]=Z>>>16&255,f[51]=Z>>>24&255,f[52]=he>>>0&255,f[53]=he>>>8&255,f[54]=he>>>16&255,f[55]=he>>>24&255,f[56]=ge>>>0&255,f[57]=ge>>>8&255,f[58]=ge>>>16&255,f[59]=ge>>>24&255,f[60]=de>>>0&255,f[61]=de>>>8&255,f[62]=de>>>16&255,f[63]=de>>>24&255}function X(f,h,l,o){for(var g=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,v=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,w=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,k=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,F=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,Y=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,Ce=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,K=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,re=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,ie=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,le=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,fe=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,se=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,oe=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ne=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,z=g,J=v,H=w,$=k,G=F,q=Y,x=W,S=Ce,I=K,O=re,R=ie,D=le,Z=fe,he=se,ge=oe,de=ne,_,ye=0;ye<20;ye+=2)_=z+Z|0,G^=_<<7|_>>>25,_=G+z|0,I^=_<<9|_>>>23,_=I+G|0,Z^=_<<13|_>>>19,_=Z+I|0,z^=_<<18|_>>>14,_=q+J|0,O^=_<<7|_>>>25,_=O+q|0,he^=_<<9|_>>>23,_=he+O|0,J^=_<<13|_>>>19,_=J+he|0,q^=_<<18|_>>>14,_=R+x|0,ge^=_<<7|_>>>25,_=ge+R|0,H^=_<<9|_>>>23,_=H+ge|0,x^=_<<13|_>>>19,_=x+H|0,R^=_<<18|_>>>14,_=de+D|0,$^=_<<7|_>>>25,_=$+de|0,S^=_<<9|_>>>23,_=S+$|0,D^=_<<13|_>>>19,_=D+S|0,de^=_<<18|_>>>14,_=z+$|0,J^=_<<7|_>>>25,_=J+z|0,H^=_<<9|_>>>23,_=H+J|0,$^=_<<13|_>>>19,_=$+H|0,z^=_<<18|_>>>14,_=q+G|0,x^=_<<7|_>>>25,_=x+q|0,S^=_<<9|_>>>23,_=S+x|0,G^=_<<13|_>>>19,_=G+S|0,q^=_<<18|_>>>14,_=R+O|0,D^=_<<7|_>>>25,_=D+R|0,I^=_<<9|_>>>23,_=I+D|0,O^=_<<13|_>>>19,_=O+I|0,R^=_<<18|_>>>14,_=de+ge|0,Z^=_<<7|_>>>25,_=Z+de|0,he^=_<<9|_>>>23,_=he+Z|0,ge^=_<<13|_>>>19,_=ge+he|0,de^=_<<18|_>>>14;f[0]=z>>>0&255,f[1]=z>>>8&255,f[2]=z>>>16&255,f[3]=z>>>24&255,f[4]=q>>>0&255,f[5]=q>>>8&255,f[6]=q>>>16&255,f[7]=q>>>24&255,f[8]=R>>>0&255,f[9]=R>>>8&255,f[10]=R>>>16&255,f[11]=R>>>24&255,f[12]=de>>>0&255,f[13]=de>>>8&255,f[14]=de>>>16&255,f[15]=de>>>24&255,f[16]=x>>>0&255,f[17]=x>>>8&255,f[18]=x>>>16&255,f[19]=x>>>24&255,f[20]=S>>>0&255,f[21]=S>>>8&255,f[22]=S>>>16&255,f[23]=S>>>24&255,f[24]=I>>>0&255,f[25]=I>>>8&255,f[26]=I>>>16&255,f[27]=I>>>24&255,f[28]=O>>>0&255,f[29]=O>>>8&255,f[30]=O>>>16&255,f[31]=O>>>24&255}function P(f,h,l,o){_e(f,h,l,o)}function B(f,h,l,o){X(f,h,l,o)}var te=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function A(f,h,l,o,g,v,w){var k=new Uint8Array(16),F=new Uint8Array(64),Y,W;for(W=0;W<16;W++)k[W]=0;for(W=0;W<8;W++)k[W]=v[W];for(;g>=64;){for(P(F,k,w,te),W=0;W<64;W++)f[h+W]=l[o+W]^F[W];for(Y=1,W=8;W<16;W++)Y=Y+(k[W]&255)|0,k[W]=Y&255,Y>>>=8;g-=64,h+=64,o+=64}if(g>0)for(P(F,k,w,te),W=0;W<g;W++)f[h+W]=l[o+W]^F[W];return 0}function ae(f,h,l,o,g){var v=new Uint8Array(16),w=new Uint8Array(64),k,F;for(F=0;F<16;F++)v[F]=0;for(F=0;F<8;F++)v[F]=o[F];for(;l>=64;){for(P(w,v,g,te),F=0;F<64;F++)f[h+F]=w[F];for(k=1,F=8;F<16;F++)k=k+(v[F]&255)|0,v[F]=k&255,k>>>=8;l-=64,h+=64}if(l>0)for(P(w,v,g,te),F=0;F<l;F++)f[h+F]=w[F];return 0}function pe(f,h,l,o,g){var v=new Uint8Array(32);B(v,o,g,te);for(var w=new Uint8Array(8),k=0;k<8;k++)w[k]=o[k+16];return ae(f,h,l,w,v)}function Q(f,h,l,o,g,v,w){var k=new Uint8Array(32);B(k,v,w,te);for(var F=new Uint8Array(8),Y=0;Y<8;Y++)F[Y]=v[Y+16];return A(f,h,l,o,g,F,k)}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 h,l,o,g,v,w,k,F;h=f[0]&255|(f[1]&255)<<8,this.r[0]=h&8191,l=f[2]&255|(f[3]&255)<<8,this.r[1]=(h>>>13|l<<3)&8191,o=f[4]&255|(f[5]&255)<<8,this.r[2]=(l>>>10|o<<6)&7939,g=f[6]&255|(f[7]&255)<<8,this.r[3]=(o>>>7|g<<9)&8191,v=f[8]&255|(f[9]&255)<<8,this.r[4]=(g>>>4|v<<12)&255,this.r[5]=v>>>1&8190,w=f[10]&255|(f[11]&255)<<8,this.r[6]=(v>>>14|w<<2)&8191,k=f[12]&255|(f[13]&255)<<8,this.r[7]=(w>>>11|k<<5)&8065,F=f[14]&255|(f[15]&255)<<8,this.r[8]=(k>>>8|F<<8)&8191,this.r[9]=F>>>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,h,l){for(var o=this.fin?0:2048,g,v,w,k,F,Y,W,Ce,K,re,ie,le,fe,se,oe,ne,z,J,H,$=this.h[0],G=this.h[1],q=this.h[2],x=this.h[3],S=this.h[4],I=this.h[5],O=this.h[6],R=this.h[7],D=this.h[8],Z=this.h[9],he=this.r[0],ge=this.r[1],de=this.r[2],_=this.r[3],ye=this.r[4],Oe=this.r[5],ke=this.r[6],me=this.r[7],be=this.r[8],xe=this.r[9];l>=16;)g=f[h+0]&255|(f[h+1]&255)<<8,$+=g&8191,v=f[h+2]&255|(f[h+3]&255)<<8,G+=(g>>>13|v<<3)&8191,w=f[h+4]&255|(f[h+5]&255)<<8,q+=(v>>>10|w<<6)&8191,k=f[h+6]&255|(f[h+7]&255)<<8,x+=(w>>>7|k<<9)&8191,F=f[h+8]&255|(f[h+9]&255)<<8,S+=(k>>>4|F<<12)&8191,I+=F>>>1&8191,Y=f[h+10]&255|(f[h+11]&255)<<8,O+=(F>>>14|Y<<2)&8191,W=f[h+12]&255|(f[h+13]&255)<<8,R+=(Y>>>11|W<<5)&8191,Ce=f[h+14]&255|(f[h+15]&255)<<8,D+=(W>>>8|Ce<<8)&8191,Z+=Ce>>>5|o,K=0,re=K,re+=$*he,re+=G*(5*xe),re+=q*(5*be),re+=x*(5*me),re+=S*(5*ke),K=re>>>13,re&=8191,re+=I*(5*Oe),re+=O*(5*ye),re+=R*(5*_),re+=D*(5*de),re+=Z*(5*ge),K+=re>>>13,re&=8191,ie=K,ie+=$*ge,ie+=G*he,ie+=q*(5*xe),ie+=x*(5*be),ie+=S*(5*me),K=ie>>>13,ie&=8191,ie+=I*(5*ke),ie+=O*(5*Oe),ie+=R*(5*ye),ie+=D*(5*_),ie+=Z*(5*de),K+=ie>>>13,ie&=8191,le=K,le+=$*de,le+=G*ge,le+=q*he,le+=x*(5*xe),le+=S*(5*be),K=le>>>13,le&=8191,le+=I*(5*me),le+=O*(5*ke),le+=R*(5*Oe),le+=D*(5*ye),le+=Z*(5*_),K+=le>>>13,le&=8191,fe=K,fe+=$*_,fe+=G*de,fe+=q*ge,fe+=x*he,fe+=S*(5*xe),K=fe>>>13,fe&=8191,fe+=I*(5*be),fe+=O*(5*me),fe+=R*(5*ke),fe+=D*(5*Oe),fe+=Z*(5*ye),K+=fe>>>13,fe&=8191,se=K,se+=$*ye,se+=G*_,se+=q*de,se+=x*ge,se+=S*he,K=se>>>13,se&=8191,se+=I*(5*xe),se+=O*(5*be),se+=R*(5*me),se+=D*(5*ke),se+=Z*(5*Oe),K+=se>>>13,se&=8191,oe=K,oe+=$*Oe,oe+=G*ye,oe+=q*_,oe+=x*de,oe+=S*ge,K=oe>>>13,oe&=8191,oe+=I*he,oe+=O*(5*xe),oe+=R*(5*be),oe+=D*(5*me),oe+=Z*(5*ke),K+=oe>>>13,oe&=8191,ne=K,ne+=$*ke,ne+=G*Oe,ne+=q*ye,ne+=x*_,ne+=S*de,K=ne>>>13,ne&=8191,ne+=I*ge,ne+=O*he,ne+=R*(5*xe),ne+=D*(5*be),ne+=Z*(5*me),K+=ne>>>13,ne&=8191,z=K,z+=$*me,z+=G*ke,z+=q*Oe,z+=x*ye,z+=S*_,K=z>>>13,z&=8191,z+=I*de,z+=O*ge,z+=R*he,z+=D*(5*xe),z+=Z*(5*be),K+=z>>>13,z&=8191,J=K,J+=$*be,J+=G*me,J+=q*ke,J+=x*Oe,J+=S*ye,K=J>>>13,J&=8191,J+=I*_,J+=O*de,J+=R*ge,J+=D*he,J+=Z*(5*xe),K+=J>>>13,J&=8191,H=K,H+=$*xe,H+=G*be,H+=q*me,H+=x*ke,H+=S*Oe,K=H>>>13,H&=8191,H+=I*ye,H+=O*_,H+=R*de,H+=D*ge,H+=Z*he,K+=H>>>13,H&=8191,K=(K<<2)+K|0,K=K+re|0,re=K&8191,K=K>>>13,ie+=K,$=re,G=ie,q=le,x=fe,S=se,I=oe,O=ne,R=z,D=J,Z=H,h+=16,l-=16;this.h[0]=$,this.h[1]=G,this.h[2]=q,this.h[3]=x,this.h[4]=S,this.h[5]=I,this.h[6]=O,this.h[7]=R,this.h[8]=D,this.h[9]=Z},Ne.prototype.finish=function(f,h){var l=new Uint16Array(10),o,g,v,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,v=this.h[0]+this.pad[0],this.h[0]=v&65535,w=1;w<8;w++)v=(this.h[w]+this.pad[w]|0)+(v>>>16)|0,this.h[w]=v&65535;f[h+0]=this.h[0]>>>0&255,f[h+1]=this.h[0]>>>8&255,f[h+2]=this.h[1]>>>0&255,f[h+3]=this.h[1]>>>8&255,f[h+4]=this.h[2]>>>0&255,f[h+5]=this.h[2]>>>8&255,f[h+6]=this.h[3]>>>0&255,f[h+7]=this.h[3]>>>8&255,f[h+8]=this.h[4]>>>0&255,f[h+9]=this.h[4]>>>8&255,f[h+10]=this.h[5]>>>0&255,f[h+11]=this.h[5]>>>8&255,f[h+12]=this.h[6]>>>0&255,f[h+13]=this.h[6]>>>8&255,f[h+14]=this.h[7]>>>0&255,f[h+15]=this.h[7]>>>8&255},Ne.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 ve(f,h,l,o,g,v){var w=new Ne(v);return w.update(l,o,g),w.finish(f,h),0}function ze(f,h,l,o,g,v){var w=new Uint8Array(16);return ve(w,0,l,o,g,v),C(f,h,w,0)}function ee(f,h,l,o,g){var v;if(l<32)return-1;for(Q(f,0,h,0,l,o,g),ve(f,16,f,32,l-32,f),v=0;v<16;v++)f[v]=0;return 0}function Je(f,h,l,o,g){var v,w=new Uint8Array(32);if(l<32||(pe(w,0,32,o,g),ze(h,16,h,32,l-32,w)!==0))return-1;for(Q(f,0,h,0,l,o,g),v=0;v<32;v++)f[v]=0;return 0}function We(f,h){var l;for(l=0;l<16;l++)f[l]=h[l]|0}function nt(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 Me(f,h,l){for(var o,g=~(l-1),v=0;v<16;v++)o=g&(f[v]^h[v]),f[v]^=o,h[v]^=o}function Te(f,h){var l,o,g,v=e(),w=e();for(l=0;l<16;l++)w[l]=h[l];for(nt(w),nt(w),nt(w),o=0;o<2;o++){for(v[0]=w[0]-65517,l=1;l<15;l++)v[l]=w[l]-65535-(v[l-1]>>16&1),v[l-1]&=65535;v[15]=w[15]-32767-(v[14]>>16&1),g=v[15]>>16&1,v[14]&=65535,Me(w,v,1-g)}for(l=0;l<16;l++)f[2*l]=w[l]&255,f[2*l+1]=w[l]>>8}function ot(f,h){var l=new Uint8Array(32),o=new Uint8Array(32);return Te(l,f),Te(o,h),V(l,0,o,0)}function He(f){var h=new Uint8Array(32);return Te(h,f),h[0]&1}function vt(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 E(f,h,l){var o,g,v=0,w=0,k=0,F=0,Y=0,W=0,Ce=0,K=0,re=0,ie=0,le=0,fe=0,se=0,oe=0,ne=0,z=0,J=0,H=0,$=0,G=0,q=0,x=0,S=0,I=0,O=0,R=0,D=0,Z=0,he=0,ge=0,de=0,_=l[0],ye=l[1],Oe=l[2],ke=l[3],me=l[4],be=l[5],xe=l[6],Xe=l[7],Pe=l[8],$e=l[9],Ge=l[10],Ye=l[11],et=l[12],ft=l[13],ut=l[14],lt=l[15];o=h[0],v+=o*_,w+=o*ye,k+=o*Oe,F+=o*ke,Y+=o*me,W+=o*be,Ce+=o*xe,K+=o*Xe,re+=o*Pe,ie+=o*$e,le+=o*Ge,fe+=o*Ye,se+=o*et,oe+=o*ft,ne+=o*ut,z+=o*lt,o=h[1],w+=o*_,k+=o*ye,F+=o*Oe,Y+=o*ke,W+=o*me,Ce+=o*be,K+=o*xe,re+=o*Xe,ie+=o*Pe,le+=o*$e,fe+=o*Ge,se+=o*Ye,oe+=o*et,ne+=o*ft,z+=o*ut,J+=o*lt,o=h[2],k+=o*_,F+=o*ye,Y+=o*Oe,W+=o*ke,Ce+=o*me,K+=o*be,re+=o*xe,ie+=o*Xe,le+=o*Pe,fe+=o*$e,se+=o*Ge,oe+=o*Ye,ne+=o*et,z+=o*ft,J+=o*ut,H+=o*lt,o=h[3],F+=o*_,Y+=o*ye,W+=o*Oe,Ce+=o*ke,K+=o*me,re+=o*be,ie+=o*xe,le+=o*Xe,fe+=o*Pe,se+=o*$e,oe+=o*Ge,ne+=o*Ye,z+=o*et,J+=o*ft,H+=o*ut,$+=o*lt,o=h[4],Y+=o*_,W+=o*ye,Ce+=o*Oe,K+=o*ke,re+=o*me,ie+=o*be,le+=o*xe,fe+=o*Xe,se+=o*Pe,oe+=o*$e,ne+=o*Ge,z+=o*Ye,J+=o*et,H+=o*ft,$+=o*ut,G+=o*lt,o=h[5],W+=o*_,Ce+=o*ye,K+=o*Oe,re+=o*ke,ie+=o*me,le+=o*be,fe+=o*xe,se+=o*Xe,oe+=o*Pe,ne+=o*$e,z+=o*Ge,J+=o*Ye,H+=o*et,$+=o*ft,G+=o*ut,q+=o*lt,o=h[6],Ce+=o*_,K+=o*ye,re+=o*Oe,ie+=o*ke,le+=o*me,fe+=o*be,se+=o*xe,oe+=o*Xe,ne+=o*Pe,z+=o*$e,J+=o*Ge,H+=o*Ye,$+=o*et,G+=o*ft,q+=o*ut,x+=o*lt,o=h[7],K+=o*_,re+=o*ye,ie+=o*Oe,le+=o*ke,fe+=o*me,se+=o*be,oe+=o*xe,ne+=o*Xe,z+=o*Pe,J+=o*$e,H+=o*Ge,$+=o*Ye,G+=o*et,q+=o*ft,x+=o*ut,S+=o*lt,o=h[8],re+=o*_,ie+=o*ye,le+=o*Oe,fe+=o*ke,se+=o*me,oe+=o*be,ne+=o*xe,z+=o*Xe,J+=o*Pe,H+=o*$e,$+=o*Ge,G+=o*Ye,q+=o*et,x+=o*ft,S+=o*ut,I+=o*lt,o=h[9],ie+=o*_,le+=o*ye,fe+=o*Oe,se+=o*ke,oe+=o*me,ne+=o*be,z+=o*xe,J+=o*Xe,H+=o*Pe,$+=o*$e,G+=o*Ge,q+=o*Ye,x+=o*et,S+=o*ft,I+=o*ut,O+=o*lt,o=h[10],le+=o*_,fe+=o*ye,se+=o*Oe,oe+=o*ke,ne+=o*me,z+=o*be,J+=o*xe,H+=o*Xe,$+=o*Pe,G+=o*$e,q+=o*Ge,x+=o*Ye,S+=o*et,I+=o*ft,O+=o*ut,R+=o*lt,o=h[11],fe+=o*_,se+=o*ye,oe+=o*Oe,ne+=o*ke,z+=o*me,J+=o*be,H+=o*xe,$+=o*Xe,G+=o*Pe,q+=o*$e,x+=o*Ge,S+=o*Ye,I+=o*et,O+=o*ft,R+=o*ut,D+=o*lt,o=h[12],se+=o*_,oe+=o*ye,ne+=o*Oe,z+=o*ke,J+=o*me,H+=o*be,$+=o*xe,G+=o*Xe,q+=o*Pe,x+=o*$e,S+=o*Ge,I+=o*Ye,O+=o*et,R+=o*ft,D+=o*ut,Z+=o*lt,o=h[13],oe+=o*_,ne+=o*ye,z+=o*Oe,J+=o*ke,H+=o*me,$+=o*be,G+=o*xe,q+=o*Xe,x+=o*Pe,S+=o*$e,I+=o*Ge,O+=o*Ye,R+=o*et,D+=o*ft,Z+=o*ut,he+=o*lt,o=h[14],ne+=o*_,z+=o*ye,J+=o*Oe,H+=o*ke,$+=o*me,G+=o*be,q+=o*xe,x+=o*Xe,S+=o*Pe,I+=o*$e,O+=o*Ge,R+=o*Ye,D+=o*et,Z+=o*ft,he+=o*ut,ge+=o*lt,o=h[15],z+=o*_,J+=o*ye,H+=o*Oe,$+=o*ke,G+=o*me,q+=o*be,x+=o*xe,S+=o*Xe,I+=o*Pe,O+=o*$e,R+=o*Ge,D+=o*Ye,Z+=o*et,he+=o*ft,ge+=o*ut,de+=o*lt,v+=38*J,w+=38*H,k+=38*$,F+=38*G,Y+=38*q,W+=38*x,Ce+=38*S,K+=38*I,re+=38*O,ie+=38*R,le+=38*D,fe+=38*Z,se+=38*he,oe+=38*ge,ne+=38*de,g=1,o=v+g+65535,g=Math.floor(o/65536),v=o-g*65536,o=w+g+65535,g=Math.floor(o/65536),w=o-g*65536,o=k+g+65535,g=Math.floor(o/65536),k=o-g*65536,o=F+g+65535,g=Math.floor(o/65536),F=o-g*65536,o=Y+g+65535,g=Math.floor(o/65536),Y=o-g*65536,o=W+g+65535,g=Math.floor(o/65536),W=o-g*65536,o=Ce+g+65535,g=Math.floor(o/65536),Ce=o-g*65536,o=K+g+65535,g=Math.floor(o/65536),K=o-g*65536,o=re+g+65535,g=Math.floor(o/65536),re=o-g*65536,o=ie+g+65535,g=Math.floor(o/65536),ie=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=se+g+65535,g=Math.floor(o/65536),se=o-g*65536,o=oe+g+65535,g=Math.floor(o/65536),oe=o-g*65536,o=ne+g+65535,g=Math.floor(o/65536),ne=o-g*65536,o=z+g+65535,g=Math.floor(o/65536),z=o-g*65536,v+=g-1+37*(g-1),g=1,o=v+g+65535,g=Math.floor(o/65536),v=o-g*65536,o=w+g+65535,g=Math.floor(o/65536),w=o-g*65536,o=k+g+65535,g=Math.floor(o/65536),k=o-g*65536,o=F+g+65535,g=Math.floor(o/65536),F=o-g*65536,o=Y+g+65535,g=Math.floor(o/65536),Y=o-g*65536,o=W+g+65535,g=Math.floor(o/65536),W=o-g*65536,o=Ce+g+65535,g=Math.floor(o/65536),Ce=o-g*65536,o=K+g+65535,g=Math.floor(o/65536),K=o-g*65536,o=re+g+65535,g=Math.floor(o/65536),re=o-g*65536,o=ie+g+65535,g=Math.floor(o/65536),ie=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=se+g+65535,g=Math.floor(o/65536),se=o-g*65536,o=oe+g+65535,g=Math.floor(o/65536),oe=o-g*65536,o=ne+g+65535,g=Math.floor(o/65536),ne=o-g*65536,o=z+g+65535,g=Math.floor(o/65536),z=o-g*65536,v+=g-1+37*(g-1),f[0]=v,f[1]=w,f[2]=k,f[3]=F,f[4]=Y,f[5]=W,f[6]=Ce,f[7]=K,f[8]=re,f[9]=ie,f[10]=le,f[11]=fe,f[12]=se,f[13]=oe,f[14]=ne,f[15]=z}function U(f,h){E(f,h,h)}function ue(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=253;o>=0;o--)U(l,l),o!==2&&o!==4&&E(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function Ve(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=250;o>=0;o--)U(l,l),o!==1&&E(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function ct(f,h,l){var o=new Uint8Array(32),g=new Float64Array(80),v,w,k=e(),F=e(),Y=e(),W=e(),Ce=e(),K=e();for(w=0;w<31;w++)o[w]=h[w];for(o[31]=h[31]&127|64,o[0]&=248,vt(g,l),w=0;w<16;w++)F[w]=g[w],W[w]=k[w]=Y[w]=0;for(k[0]=W[0]=1,w=254;w>=0;--w)v=o[w>>>3]>>>(w&7)&1,Me(k,F,v),Me(Y,W,v),L(Ce,k,Y),j(k,k,Y),L(Y,F,W),j(F,F,W),U(W,Ce),U(K,k),E(k,Y,k),E(Y,F,Ce),L(Ce,k,Y),j(k,k,Y),U(F,k),j(Y,W,K),E(k,Y,c),L(k,k,W),E(Y,Y,k),E(k,W,K),E(W,F,g),U(F,Ce),Me(k,F,v),Me(Y,W,v);for(w=0;w<16;w++)g[w+16]=k[w],g[w+32]=Y[w],g[w+48]=F[w],g[w+64]=W[w];var re=g.subarray(32),ie=g.subarray(16);return ue(re,re),E(ie,ie,re),Te(f,ie),0}function Et(f,h){return ct(f,h,s)}function wt(f,h){return t(h,32),Et(f,h)}function or(f,h,l){var o=new Uint8Array(32);return ct(o,l,h),B(f,i,o,te)}var Tr=ee,Kr=Je;function Cr(f,h,l,o,g,v){var w=new Uint8Array(32);return or(w,g,v),Tr(f,h,l,o,w)}function gi(f,h,l,o,g,v){var w=new Uint8Array(32);return or(w,g,v),Kr(f,h,l,o,w)}var Is=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function sf(f,h,l,o){for(var g=new Int32Array(16),v=new Int32Array(16),w,k,F,Y,W,Ce,K,re,ie,le,fe,se,oe,ne,z,J,H,$,G,q,x,S,I,O,R,D,Z=f[0],he=f[1],ge=f[2],de=f[3],_=f[4],ye=f[5],Oe=f[6],ke=f[7],me=h[0],be=h[1],xe=h[2],Xe=h[3],Pe=h[4],$e=h[5],Ge=h[6],Ye=h[7],et=0;o>=128;){for(G=0;G<16;G++)q=8*G+et,g[G]=l[q+0]<<24|l[q+1]<<16|l[q+2]<<8|l[q+3],v[G]=l[q+4]<<24|l[q+5]<<16|l[q+6]<<8|l[q+7];for(G=0;G<80;G++)if(w=Z,k=he,F=ge,Y=de,W=_,Ce=ye,K=Oe,re=ke,ie=me,le=be,fe=xe,se=Xe,oe=Pe,ne=$e,z=Ge,J=Ye,x=ke,S=Ye,I=S&65535,O=S>>>16,R=x&65535,D=x>>>16,x=(_>>>14|Pe<<18)^(_>>>18|Pe<<14)^(Pe>>>9|_<<23),S=(Pe>>>14|_<<18)^(Pe>>>18|_<<14)^(_>>>9|Pe<<23),I+=S&65535,O+=S>>>16,R+=x&65535,D+=x>>>16,x=_&ye^~_&Oe,S=Pe&$e^~Pe&Ge,I+=S&65535,O+=S>>>16,R+=x&65535,D+=x>>>16,x=Is[G*2],S=Is[G*2+1],I+=S&65535,O+=S>>>16,R+=x&65535,D+=x>>>16,x=g[G%16],S=v[G%16],I+=S&65535,O+=S>>>16,R+=x&65535,D+=x>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,H=R&65535|D<<16,$=I&65535|O<<16,x=H,S=$,I=S&65535,O=S>>>16,R=x&65535,D=x>>>16,x=(Z>>>28|me<<4)^(me>>>2|Z<<30)^(me>>>7|Z<<25),S=(me>>>28|Z<<4)^(Z>>>2|me<<30)^(Z>>>7|me<<25),I+=S&65535,O+=S>>>16,R+=x&65535,D+=x>>>16,x=Z&he^Z&ge^he&ge,S=me&be^me&xe^be&xe,I+=S&65535,O+=S>>>16,R+=x&65535,D+=x>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,re=R&65535|D<<16,J=I&65535|O<<16,x=Y,S=se,I=S&65535,O=S>>>16,R=x&65535,D=x>>>16,x=H,S=$,I+=S&65535,O+=S>>>16,R+=x&65535,D+=x>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,Y=R&65535|D<<16,se=I&65535|O<<16,he=w,ge=k,de=F,_=Y,ye=W,Oe=Ce,ke=K,Z=re,be=ie,xe=le,Xe=fe,Pe=se,$e=oe,Ge=ne,Ye=z,me=J,G%16===15)for(q=0;q<16;q++)x=g[q],S=v[q],I=S&65535,O=S>>>16,R=x&65535,D=x>>>16,x=g[(q+9)%16],S=v[(q+9)%16],I+=S&65535,O+=S>>>16,R+=x&65535,D+=x>>>16,H=g[(q+1)%16],$=v[(q+1)%16],x=(H>>>1|$<<31)^(H>>>8|$<<24)^H>>>7,S=($>>>1|H<<31)^($>>>8|H<<24)^($>>>7|H<<25),I+=S&65535,O+=S>>>16,R+=x&65535,D+=x>>>16,H=g[(q+14)%16],$=v[(q+14)%16],x=(H>>>19|$<<13)^($>>>29|H<<3)^H>>>6,S=($>>>19|H<<13)^(H>>>29|$<<3)^($>>>6|H<<26),I+=S&65535,O+=S>>>16,R+=x&65535,D+=x>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,g[q]=R&65535|D<<16,v[q]=I&65535|O<<16;x=Z,S=me,I=S&65535,O=S>>>16,R=x&65535,D=x>>>16,x=f[0],S=h[0],I+=S&65535,O+=S>>>16,R+=x&65535,D+=x>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,f[0]=Z=R&65535|D<<16,h[0]=me=I&65535|O<<16,x=he,S=be,I=S&65535,O=S>>>16,R=x&65535,D=x>>>16,x=f[1],S=h[1],I+=S&65535,O+=S>>>16,R+=x&65535,D+=x>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,f[1]=he=R&65535|D<<16,h[1]=be=I&65535|O<<16,x=ge,S=xe,I=S&65535,O=S>>>16,R=x&65535,D=x>>>16,x=f[2],S=h[2],I+=S&65535,O+=S>>>16,R+=x&65535,D+=x>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,f[2]=ge=R&65535|D<<16,h[2]=xe=I&65535|O<<16,x=de,S=Xe,I=S&65535,O=S>>>16,R=x&65535,D=x>>>16,x=f[3],S=h[3],I+=S&65535,O+=S>>>16,R+=x&65535,D+=x>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,f[3]=de=R&65535|D<<16,h[3]=Xe=I&65535|O<<16,x=_,S=Pe,I=S&65535,O=S>>>16,R=x&65535,D=x>>>16,x=f[4],S=h[4],I+=S&65535,O+=S>>>16,R+=x&65535,D+=x>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,f[4]=_=R&65535|D<<16,h[4]=Pe=I&65535|O<<16,x=ye,S=$e,I=S&65535,O=S>>>16,R=x&65535,D=x>>>16,x=f[5],S=h[5],I+=S&65535,O+=S>>>16,R+=x&65535,D+=x>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,f[5]=ye=R&65535|D<<16,h[5]=$e=I&65535|O<<16,x=Oe,S=Ge,I=S&65535,O=S>>>16,R=x&65535,D=x>>>16,x=f[6],S=h[6],I+=S&65535,O+=S>>>16,R+=x&65535,D+=x>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,f[6]=Oe=R&65535|D<<16,h[6]=Ge=I&65535|O<<16,x=ke,S=Ye,I=S&65535,O=S>>>16,R=x&65535,D=x>>>16,x=f[7],S=h[7],I+=S&65535,O+=S>>>16,R+=x&65535,D+=x>>>16,O+=I>>>16,R+=O>>>16,D+=R>>>16,f[7]=ke=R&65535|D<<16,h[7]=Ye=I&65535|O<<16,et+=128,o-=128}return o}function zr(f,h,l){var o=new Int32Array(8),g=new Int32Array(8),v=new Uint8Array(256),w,k=l;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,g[0]=4089235720,g[1]=2227873595,g[2]=4271175723,g[3]=1595750129,g[4]=2917565137,g[5]=725511199,g[6]=4215389547,g[7]=327033209,sf(o,g,h,l),l%=128,w=0;w<l;w++)v[w]=h[k-l+w];for(v[l]=128,l=256-128*(l<112?1:0),v[l-9]=0,b(v,l-8,k/536870912|0,k<<3),sf(o,g,v,l),w=0;w<8;w++)b(f,8*w,o[w],g[w]);return 0}function Ls(f,h){var l=e(),o=e(),g=e(),v=e(),w=e(),k=e(),F=e(),Y=e(),W=e();j(l,f[1],f[0]),j(W,h[1],h[0]),E(l,l,W),L(o,f[0],f[1]),L(W,h[0],h[1]),E(o,o,W),E(g,f[3],h[3]),E(g,g,d),E(v,f[2],h[2]),L(v,v,v),j(w,o,l),j(k,v,g),L(F,v,g),L(Y,o,l),E(f[0],w,k),E(f[1],Y,F),E(f[2],F,k),E(f[3],w,Y)}function nf(f,h,l){var o;for(o=0;o<4;o++)Me(f[o],h[o],l)}function yo(f,h){var l=e(),o=e(),g=e();ue(g,h[2]),E(l,h[0],g),E(o,h[1],g),Te(f,o),f[31]^=He(l)<<7}function vo(f,h,l){var o,g;for(We(f[0],n),We(f[1],a),We(f[2],a),We(f[3],n),g=255;g>=0;--g)o=l[g/8|0]>>(g&7)&1,nf(f,h,o),Ls(h,f),Ls(f,f),nf(f,h,o)}function Ns(f,h){var l=[e(),e(),e(),e()];We(l[0],p),We(l[1],m),We(l[2],a),E(l[3],p,m),vo(f,l,h)}function Eo(f,h,l){var o=new Uint8Array(64),g=[e(),e(),e(),e()],v;for(l||t(h,32),zr(o,h,32),o[0]&=248,o[31]&=127,o[31]|=64,Ns(g,o),yo(f,g),v=0;v<32;v++)h[v+32]=f[v];return 0}var Ds=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 wo(f,h){var l,o,g,v;for(o=63;o>=32;--o){for(l=0,g=o-32,v=o-12;g<v;++g)h[g]+=l-16*h[o]*Ds[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)*Ds[g],l=h[g]>>8,h[g]&=255;for(g=0;g<32;g++)h[g]-=l*Ds[g];for(o=0;o<32;o++)h[o+1]+=h[o]>>8,f[o]=h[o]&255}function bo(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;wo(f,h)}function of(f,h,l,o){var g=new Uint8Array(64),v=new Uint8Array(64),w=new Uint8Array(64),k,F,Y=new Float64Array(64),W=[e(),e(),e(),e()];zr(g,o,32),g[0]&=248,g[31]&=127,g[31]|=64;var Ce=l+64;for(k=0;k<l;k++)f[64+k]=h[k];for(k=0;k<32;k++)f[32+k]=g[32+k];for(zr(w,f.subarray(32),l+32),bo(w),Ns(W,w),yo(f,W),k=32;k<64;k++)f[k]=o[k];for(zr(v,f,l+64),bo(v),k=0;k<64;k++)Y[k]=0;for(k=0;k<32;k++)Y[k]=w[k];for(k=0;k<32;k++)for(F=0;F<32;F++)Y[k+F]+=v[k]*g[F];return wo(f.subarray(32),Y),Ce}function Kd(f,h){var l=e(),o=e(),g=e(),v=e(),w=e(),k=e(),F=e();return We(f[2],a),vt(f[1],h),U(g,f[1]),E(v,g,u),j(g,g,f[2]),L(v,f[2],v),U(w,v),U(k,w),E(F,k,w),E(l,F,g),E(l,l,v),Ve(l,l),E(l,l,g),E(l,l,v),E(l,l,v),E(f[0],l,v),U(o,f[0]),E(o,o,v),ot(o,g)&&E(f[0],f[0],y),U(o,f[0]),E(o,o,v),ot(o,g)?-1:(He(f[0])===h[31]>>7&&j(f[0],n,f[0]),E(f[3],f[0],f[1]),0)}function xo(f,h,l,o){var g,v=new Uint8Array(32),w=new Uint8Array(64),k=[e(),e(),e(),e()],F=[e(),e(),e(),e()];if(l<64||Kd(F,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(zr(w,f,l),bo(w),vo(k,F,w),Ns(F,h.subarray(32)),Ls(k,F),yo(v,k),l-=64,V(h,0,v,0)){for(g=0;g<l;g++)f[g]=0;return-1}for(g=0;g<l;g++)f[g]=h[g+64];return l}var So=32,Ms=24,Yi=32,mi=16,Xi=32,Fs=32,Ji=32,Zi=32,To=32,af=Ms,zd=Yi,$d=mi,ar=64,$r=32,_i=64,Co=32,Oo=64;r.lowlevel={crypto_core_hsalsa20:B,crypto_stream_xor:Q,crypto_stream:pe,crypto_stream_salsa20_xor:A,crypto_stream_salsa20:ae,crypto_onetimeauth:ve,crypto_onetimeauth_verify:ze,crypto_verify_16:C,crypto_verify_32:V,crypto_secretbox:ee,crypto_secretbox_open:Je,crypto_scalarmult:ct,crypto_scalarmult_base:Et,crypto_box_beforenm:or,crypto_box_afternm:Tr,crypto_box:Cr,crypto_box_open:gi,crypto_box_keypair:wt,crypto_hash:zr,crypto_sign:of,crypto_sign_keypair:Eo,crypto_sign_open:xo,crypto_secretbox_KEYBYTES:So,crypto_secretbox_NONCEBYTES:Ms,crypto_secretbox_ZEROBYTES:Yi,crypto_secretbox_BOXZEROBYTES:mi,crypto_scalarmult_BYTES:Xi,crypto_scalarmult_SCALARBYTES:Fs,crypto_box_PUBLICKEYBYTES:Ji,crypto_box_SECRETKEYBYTES:Zi,crypto_box_BEFORENMBYTES:To,crypto_box_NONCEBYTES:af,crypto_box_ZEROBYTES:zd,crypto_box_BOXZEROBYTES:$d,crypto_sign_BYTES:ar,crypto_sign_PUBLICKEYBYTES:$r,crypto_sign_SECRETKEYBYTES:_i,crypto_sign_SEEDBYTES:Co,crypto_hash_BYTES:Oo,gf:e,D:u,L:Ds,pack25519:Te,unpack25519:vt,M:E,A:L,S:U,Z:j,pow2523:Ve,add:Ls,set25519:We,modL:wo,scalarmult:vo,scalarbase:Ns};function cf(f,h){if(f.length!==So)throw new Error("bad key size");if(h.length!==Ms)throw new Error("bad nonce size")}function Gd(f,h){if(f.length!==Ji)throw new Error("bad public key size");if(h.length!==Zi)throw new Error("bad secret key size")}function bt(){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 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){bt(f,h,l),cf(l,h);for(var o=new Uint8Array(Yi+f.length),g=new Uint8Array(o.length),v=0;v<f.length;v++)o[v+Yi]=f[v];return ee(g,o,o.length,h,l),g.subarray(mi)},r.secretbox.open=function(f,h,l){bt(f,h,l),cf(l,h);for(var o=new Uint8Array(mi+f.length),g=new Uint8Array(o.length),v=0;v<f.length;v++)o[v+mi]=f[v];return o.length<32||Je(g,o,o.length,h,l)!==0?null:g.subarray(Yi)},r.secretbox.keyLength=So,r.secretbox.nonceLength=Ms,r.secretbox.overheadLength=mi,r.scalarMult=function(f,h){if(bt(f,h),f.length!==Fs)throw new Error("bad n size");if(h.length!==Xi)throw new Error("bad p size");var l=new Uint8Array(Xi);return ct(l,f,h),l},r.scalarMult.base=function(f){if(bt(f),f.length!==Fs)throw new Error("bad n size");var h=new Uint8Array(Xi);return Et(h,f),h},r.scalarMult.scalarLength=Fs,r.scalarMult.groupElementLength=Xi,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){bt(f,h),Gd(f,h);var l=new Uint8Array(To);return or(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(Ji),h=new Uint8Array(Zi);return wt(f,h),{publicKey:f,secretKey:h}},r.box.keyPair.fromSecretKey=function(f){if(bt(f),f.length!==Zi)throw new Error("bad secret key size");var h=new Uint8Array(Ji);return Et(h,f),{publicKey:h,secretKey:new Uint8Array(f)}},r.box.publicKeyLength=Ji,r.box.secretKeyLength=Zi,r.box.sharedKeyLength=To,r.box.nonceLength=af,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(f,h){if(bt(f,h),h.length!==_i)throw new Error("bad secret key size");var l=new Uint8Array(ar+f.length);return of(l,f,f.length,h),l},r.sign.open=function(f,h){if(bt(f,h),h.length!==$r)throw new Error("bad public key size");var l=new Uint8Array(f.length),o=xo(l,f,f.length,h);if(o<0)return null;for(var g=new Uint8Array(o),v=0;v<g.length;v++)g[v]=l[v];return g},r.sign.detached=function(f,h){for(var l=r.sign(f,h),o=new Uint8Array(ar),g=0;g<o.length;g++)o[g]=l[g];return o},r.sign.detached.verify=function(f,h,l){if(bt(f,h,l),h.length!==ar)throw new Error("bad signature size");if(l.length!==$r)throw new Error("bad public key size");var o=new Uint8Array(ar+f.length),g=new Uint8Array(ar+f.length),v;for(v=0;v<ar;v++)o[v]=h[v];for(v=0;v<f.length;v++)o[v+ar]=f[v];return xo(g,o,o.length,l)>=0},r.sign.keyPair=function(){var f=new Uint8Array($r),h=new Uint8Array(_i);return Eo(f,h),{publicKey:f,secretKey:h}},r.sign.keyPair.fromSecretKey=function(f){if(bt(f),f.length!==_i)throw new Error("bad secret key size");for(var h=new Uint8Array($r),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(bt(f),f.length!==Co)throw new Error("bad seed size");for(var h=new Uint8Array($r),l=new Uint8Array(_i),o=0;o<32;o++)l[o]=f[o];return Eo(h,l,!0),{publicKey:h,secretKey:l}},r.sign.publicKeyLength=$r,r.sign.secretKeyLength=_i,r.sign.seedLength=Co,r.sign.signatureLength=ar,r.hash=function(f){bt(f);var h=new Uint8Array(Oo);return zr(h,f,f.length),h},r.hash.hashLength=Oo,r.verify=function(f,h){return bt(f,h),f.length===0||h.length===0||f.length!==h.length?!1:T(f,0,h,0,f.length)===0},r.setPRNG=function(f){t=f},(function(){var f=typeof self<"u"?self.crypto||self.msCrypto:null;if(f&&f.getRandomValues){var h=65536;r.setPRNG(function(l,o){var g,v=new Uint8Array(o);for(g=0;g<o;g+=h)f.getRandomValues(v.subarray(g,g+Math.min(o-g,h)));for(g=0;g<o;g++)l[g]=v[g];ff(v)})}else typeof require<"u"&&(f=require("crypto"),f&&f.randomBytes&&r.setPRNG(function(l,o){var g,v=f.randomBytes(o);for(g=0;g<o;g++)l[g]=v[g];ff(v)}))})()})(typeof Ys<"u"&&Ys.exports?Ys.exports:self.nacl=self.nacl||{})});var Lo=M((Rf,Xs)=>{(function(r,e){"use strict";typeof Xs<"u"&&Xs.exports?Xs.exports=e():(r.nacl||(r.nacl={}),r.nacl.util=e())})(Rf,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,s=unescape(encodeURIComponent(t)),n=new Uint8Array(s.length);for(i=0;i<s.length;i++)n[i]=s.charCodeAt(i);return n},r.encodeUTF8=function(t){var i,s=[];for(i=0;i<t.length;i++)s.push(String.fromCharCode(t[i]));return decodeURIComponent(escape(s.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,s=[],n=t.length;for(i=0;i<n;i++)s.push(String.fromCharCode(t[i]));return btoa(s.join(""))},r.decodeBase64=function(t){e(t);var i,s=atob(t),n=new Uint8Array(s.length);for(i=0;i<s.length;i++)n[i]=s.charCodeAt(i);return n}),r})});var Af=M(Rr=>{"use strict";var mp=Rr&&Rr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Rr,"__esModule",{value:!0});Rr.encrypt=_p;Rr.decrypt=yp;Rr.encryptBinary=vp;Rr.decryptBinary=Ep;var ur=mp(Io()),kr=Lo();function _p(r,e,t){let i=ur.default.randomBytes(ur.default.secretbox.nonceLength),s=new TextEncoder().encode(r),n=ur.default.secretbox(s,i,e);return{v:1,sid:t,n:(0,kr.encodeBase64)(i),c:(0,kr.encodeBase64)(n)}}function yp(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,kr.decodeBase64)(r.n),i=(0,kr.decodeBase64)(r.c);if(t.length!==ur.default.secretbox.nonceLength)throw new Error(`Invalid nonce length: ${t.length}`);let s=ur.default.secretbox.open(i,t,e);if(!s)throw new Error("Decryption failed: invalid ciphertext or wrong key");return new TextDecoder().decode(s)}function vp(r,e,t){let i=ur.default.randomBytes(ur.default.secretbox.nonceLength),s=ur.default.secretbox(r,i,e);return{v:1,sid:t,n:(0,kr.encodeBase64)(i),c:(0,kr.encodeBase64)(s)}}function Ep(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,kr.decodeBase64)(r.n),i=(0,kr.decodeBase64)(r.c),s=ur.default.secretbox.open(i,t,e);if(!s)throw new Error("Decryption failed: invalid ciphertext or wrong key");return s}});var Pf=M(Bt=>{"use strict";var wp=Bt&&Bt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Bt,"__esModule",{value:!0});Bt.generateKeyPair=bp;Bt.deriveSharedSecret=xp;Bt.deriveMetaSid=Sp;Bt.isValidPublicKey=Tp;Bt.clearKey=Cp;Bt.keyToBase64=Op;Bt.base64ToKey=kp;var vi=wp(Io()),$t=Lo();function bp(){let r=vi.default.box.keyPair();return{publicKey:(0,$t.encodeBase64)(r.publicKey),secretKey:(0,$t.encodeBase64)(r.secretKey)}}function xp(r,e){let t=(0,$t.decodeBase64)(r),i=(0,$t.decodeBase64)(e);if(t.length!==vi.default.box.publicKeyLength)throw new Error(`Invalid public key length: ${t.length}`);if(i.length!==vi.default.box.secretKeyLength)throw new Error(`Invalid secret key length: ${i.length}`);return vi.default.box.before(t,i)}function Sp(r,e){let t=new TextEncoder().encode("termiq-meta-v1"),i=(0,$t.decodeBase64)(r),s=(0,$t.decodeBase64)(e),n=new Uint8Array(t.length+i.length+s.length);return n.set(t,0),n.set(i,t.length),n.set(s,t.length+i.length),(0,$t.encodeBase64)(vi.default.hash(n).slice(0,32))}function Tp(r){try{return(0,$t.decodeBase64)(r).length===vi.default.box.publicKeyLength}catch{return!1}}function Cp(r){r.fill(0)}function Op(r){return(0,$t.encodeBase64)(r)}function kp(r){return(0,$t.decodeBase64)(r)}});var Lf=M(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.base64ToKey=Ie.keyToBase64=Ie.clearKey=Ie.isValidPublicKey=Ie.deriveMetaSid=Ie.deriveSharedSecret=Ie.generateKeyPair=Ie.decryptBinary=Ie.encryptBinary=Ie.decrypt=Ie.encrypt=Ie.isMultiRecipientPayload=Ie.isEncryptedPayload=void 0;var If=kf();Object.defineProperty(Ie,"isEncryptedPayload",{enumerable:!0,get:function(){return If.isEncryptedPayload}});Object.defineProperty(Ie,"isMultiRecipientPayload",{enumerable:!0,get:function(){return If.isMultiRecipientPayload}});var Js=Af();Object.defineProperty(Ie,"encrypt",{enumerable:!0,get:function(){return Js.encrypt}});Object.defineProperty(Ie,"decrypt",{enumerable:!0,get:function(){return Js.decrypt}});Object.defineProperty(Ie,"encryptBinary",{enumerable:!0,get:function(){return Js.encryptBinary}});Object.defineProperty(Ie,"decryptBinary",{enumerable:!0,get:function(){return Js.decryptBinary}});var Gr=Pf();Object.defineProperty(Ie,"generateKeyPair",{enumerable:!0,get:function(){return Gr.generateKeyPair}});Object.defineProperty(Ie,"deriveSharedSecret",{enumerable:!0,get:function(){return Gr.deriveSharedSecret}});Object.defineProperty(Ie,"deriveMetaSid",{enumerable:!0,get:function(){return Gr.deriveMetaSid}});Object.defineProperty(Ie,"isValidPublicKey",{enumerable:!0,get:function(){return Gr.isValidPublicKey}});Object.defineProperty(Ie,"clearKey",{enumerable:!0,get:function(){return Gr.clearKey}});Object.defineProperty(Ie,"keyToBase64",{enumerable:!0,get:function(){return Gr.keyToBase64}});Object.defineProperty(Ie,"base64ToKey",{enumerable:!0,get:function(){return Gr.base64ToKey}})});var Nf=M(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.MIN_CLIENT_VERSION=xt.PROTOCOL_VERSION_MINOR=xt.PROTOCOL_VERSION_MAJOR=xt.PROTOCOL_VERSION=void 0;xt.isCompatibleVersion=Rp;xt.compareVersions=Ap;xt.PROTOCOL_VERSION="2.1";xt.PROTOCOL_VERSION_MAJOR=2;xt.PROTOCOL_VERSION_MINOR=1;xt.MIN_CLIENT_VERSION="2.0";function Rp(r){let[e]=r.split(".").map(Number);return e===xt.PROTOCOL_VERSION_MAJOR}function Ap(r,e){let[t,i]=r.split(".").map(Number),[s,n]=e.split(".").map(Number);return t!==s?t<s?-1:1:i!==n?i<n?-1:1:0}});var Df=M(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.SERVER_CAPABILITIES=Gt.DEFAULT_CLIENT_CAPABILITIES=Gt.Capability=void 0;Gt.hasCapability=Pp;Gt.negotiateCapabilities=Ip;var Ei;(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"})(Ei||(Gt.Capability=Ei={}));Gt.DEFAULT_CLIENT_CAPABILITIES=[Ei.E2E_ENCRYPTION,Ei.TERMINAL_EVENTS,Ei.RELIABLE_INPUT];Gt.SERVER_CAPABILITIES=Object.values(Ei);function Pp(r,e){return r.includes(e)}function Ip(r,e){return r.filter(t=>e.includes(t))}});var Mf=M(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.DEFAULT_PRIORITY=lr.PRIORITY_NAMES=lr.Priority=void 0;lr.comparePriority=Lp;var Yr;(function(r){r[r.CRITICAL=0]="CRITICAL",r[r.HIGH=1]="HIGH",r[r.NORMAL=2]="NORMAL",r[r.LOW=3]="LOW"})(Yr||(lr.Priority=Yr={}));lr.PRIORITY_NAMES={[Yr.CRITICAL]:"CRITICAL",[Yr.HIGH]:"HIGH",[Yr.NORMAL]:"NORMAL",[Yr.LOW]:"LOW"};lr.DEFAULT_PRIORITY=Yr.NORMAL;function Lp(r,e){return r-e}});var Ff=M(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.DEFAULT_RELIABILITY=Yt.RELIABILITY_NAMES=Yt.Reliability=void 0;Yt.requiresAck=Np;Yt.requiresBuffer=Dp;var Ar;(function(r){r[r.FIRE_FORGET=0]="FIRE_FORGET",r[r.BUFFERED=1]="BUFFERED",r[r.GUARANTEED=2]="GUARANTEED"})(Ar||(Yt.Reliability=Ar={}));Yt.RELIABILITY_NAMES={[Ar.FIRE_FORGET]:"FIRE_FORGET",[Ar.BUFFERED]:"BUFFERED",[Ar.GUARANTEED]:"GUARANTEED"};Yt.DEFAULT_RELIABILITY=Ar.FIRE_FORGET;function Np(r){return r===Ar.GUARANTEED}function Dp(r){return r>=Ar.BUFFERED}});var Bf=M(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.createMessage=Mp;function Mp(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 jf=M(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.TerminalEventType=void 0;Xr.deriveStatusFromEvent=Fp;Xr.shouldTriggerPushNotification=Bp;Xr.getPushNotificationMessage=jp;var ht;(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"})(ht||(Xr.TerminalEventType=ht={}));function Fp(r){switch(r.type){case ht.SESSION_START:case ht.TOOL_START:case ht.MESSAGE:return"working";case ht.WAITING_INPUT:return"waiting";case ht.SESSION_END:return r.status==="success"?"completed":"error";case ht.ERROR:return r.severity==="fatal"?"error":"working";case ht.TOOL_END:return r.status==="error"?"error":"working";default:return"idle"}}function Bp(r){switch(r.type){case ht.WAITING_INPUT:return!0;case ht.SESSION_END:return!0;case ht.ERROR:return r.severity!=="warning";default:return!1}}function jp(r,e){switch(r.type){case ht.WAITING_INPUT:return{title:`${e}: Input Required`,body:r.question.slice(0,100)};case ht.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 ht.ERROR:{let t=r;return t.severity==="warning"?null:{title:`${e}: Error`,body:t.message.slice(0,100)}}default:return null}}});var Wf=M(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.TransferDirection=je.TransferStatus=je.CHUNK_TTL_SECONDS=je.TRANSFER_TTL_SECONDS=je.MAX_RETRIES=je.ACK_TIMEOUT_MS=je.WINDOW_SIZE=je.DEFAULT_MAX_FILE_SIZE=je.CHUNK_SIZE=void 0;je.calculateTotalChunks=Up;je.getMissingChunks=qp;je.isTransferComplete=Wp;je.CHUNK_SIZE=64*1024;je.DEFAULT_MAX_FILE_SIZE=100*1024*1024;je.WINDOW_SIZE=10;je.ACK_TIMEOUT_MS=3e4;je.MAX_RETRIES=3;je.TRANSFER_TTL_SECONDS=1440*60;je.CHUNK_TTL_SECONDS=1440*60;var Uf;(function(r){r.PENDING="pending",r.ACTIVE="active",r.PAUSED="paused",r.COMPLETED="completed",r.FAILED="failed",r.CANCELLED="cancelled",r.EXPIRED="expired"})(Uf||(je.TransferStatus=Uf={}));var qf;(function(r){r.DOWNLOAD="download",r.UPLOAD="upload"})(qf||(je.TransferDirection=qf={}));function Up(r,e=je.CHUNK_SIZE){return Math.ceil(r/e)}function qp(r,e){let t=new Set(e),i=[];for(let s=0;s<r;s++)t.has(s)||i.push(s);return i}function Wp(r,e){return e.length===r}});var Hf=M(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.ERROR_MESSAGES=hr.ErrorCode=void 0;hr.createError=Hp;hr.isRetryableError=Vp;var Re;(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"})(Re||(hr.ErrorCode=Re={}));hr.ERROR_MESSAGES={[Re.AUTH_FAILED]:"Authentication failed",[Re.TOKEN_EXPIRED]:"Token expired",[Re.TOKEN_INVALID]:"Invalid token",[Re.NOT_FOUND]:"Resource not found",[Re.ALREADY_EXISTS]:"Resource already exists",[Re.ACCESS_DENIED]:"Access denied",[Re.FORBIDDEN]:"Operation forbidden",[Re.RATE_LIMITED]:"Rate limit exceeded",[Re.TOO_MANY_CONNECTIONS]:"Too many connections",[Re.QUOTA_EXCEEDED]:"Plan quota exceeded",[Re.FILE_TOO_LARGE]:"File size exceeds limit",[Re.QUEUE_FULL]:"Message queue is full",[Re.TRANSFERS_LIMIT]:"Daily transfers limit reached",[Re.TRANSFER_FAILED]:"File transfer failed",[Re.TRANSFER_EXPIRED]:"Transfer expired",[Re.TRANSFER_CANCELLED]:"Transfer cancelled",[Re.CHECKSUM_MISMATCH]:"File checksum mismatch",[Re.CHUNK_MISSING]:"Chunk missing or corrupted",[Re.INVALID_MESSAGE]:"Invalid message format",[Re.UNSUPPORTED_VERSION]:"Unsupported protocol version",[Re.CAPABILITY_REQUIRED]:"Required capability not supported",[Re.INVALID_STATE]:"Invalid state for this operation",[Re.TIMEOUT]:"Operation timed out",[Re.CONNECTION_LOST]:"Connection lost",[Re.INTERNAL_ERROR]:"Internal server error",[Re.SERVICE_UNAVAILABLE]:"Service temporarily unavailable"};function Hp(r,e={}){return{code:r,message:e.message||hr.ERROR_MESSAGES[r],details:e.details,retryable:e.retryable??!1,retryAfter:e.retryAfter}}function Vp(r){return[Re.RATE_LIMITED,Re.TIMEOUT,Re.CONNECTION_LOST,Re.SERVICE_UNAVAILABLE].includes(r)}});var $f=M(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.FileEntryType=St.DiffBase=St.FileViewType=St.FileChangeType=void 0;St.getLanguageFromPath=Kp;St.parseUnifiedDiff=zp;St.createSimpleDiff=$p;var Pr;(function(r){r.CREATE="create",r.MODIFY="modify",r.DELETE="delete"})(Pr||(St.FileChangeType=Pr={}));var Vf;(function(r){r.CONTENT="content",r.DIFF="diff"})(Vf||(St.FileViewType=Vf={}));var Kf;(function(r){r.GIT="git",r.PREVIOUS="previous"})(Kf||(St.DiffBase=Kf={}));function Kp(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 zp(r,e){let t=r.split(`
|
|
3
|
-
`),
|
|
4
|
-
`),
|
|
5
|
-
`),n=[],a=0,c=0,u=Math.max(i.length,s.length);for(let p=0;p<u;p++){let m=i[p],y=s[p];m===y?m!==void 0&&n.push({type:"context",content:m,oldLineNumber:p+1,newLineNumber:p+1}):(m!==void 0&&(n.push({type:"remove",content:m,oldLineNumber:p+1,newLineNumber:null}),c++),y!==void 0&&(n.push({type:"add",content:y,oldLineNumber:null,newLineNumber:p+1}),a++))}let d;return r===""?d=Pr.CREATE:e===""?d=Pr.DELETE:d=Pr.MODIFY,{path:t,changeType:d,hunks:[{oldStart:1,oldLines:i.length,newStart:1,newLines:s.length,lines:n}],additions:a,deletions:c,isBinary:!1}}var zf;(function(r){r.FILE="file",r.DIRECTORY="directory"})(zf||(St.FileEntryType=zf={}))});var Gf=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 wi=Nf();Object.defineProperty(N,"PROTOCOL_VERSION",{enumerable:!0,get:function(){return wi.PROTOCOL_VERSION}});Object.defineProperty(N,"PROTOCOL_VERSION_MAJOR",{enumerable:!0,get:function(){return wi.PROTOCOL_VERSION_MAJOR}});Object.defineProperty(N,"PROTOCOL_VERSION_MINOR",{enumerable:!0,get:function(){return wi.PROTOCOL_VERSION_MINOR}});Object.defineProperty(N,"MIN_CLIENT_VERSION",{enumerable:!0,get:function(){return wi.MIN_CLIENT_VERSION}});Object.defineProperty(N,"isCompatibleVersion",{enumerable:!0,get:function(){return wi.isCompatibleVersion}});Object.defineProperty(N,"compareVersions",{enumerable:!0,get:function(){return wi.compareVersions}});var rs=Df();Object.defineProperty(N,"Capability",{enumerable:!0,get:function(){return rs.Capability}});Object.defineProperty(N,"DEFAULT_CLIENT_CAPABILITIES",{enumerable:!0,get:function(){return rs.DEFAULT_CLIENT_CAPABILITIES}});Object.defineProperty(N,"SERVER_CAPABILITIES",{enumerable:!0,get:function(){return rs.SERVER_CAPABILITIES}});Object.defineProperty(N,"hasCapability",{enumerable:!0,get:function(){return rs.hasCapability}});Object.defineProperty(N,"negotiateCapabilities",{enumerable:!0,get:function(){return rs.negotiateCapabilities}});var Zs=Mf();Object.defineProperty(N,"Priority",{enumerable:!0,get:function(){return Zs.Priority}});Object.defineProperty(N,"PRIORITY_NAMES",{enumerable:!0,get:function(){return Zs.PRIORITY_NAMES}});Object.defineProperty(N,"DEFAULT_PRIORITY",{enumerable:!0,get:function(){return Zs.DEFAULT_PRIORITY}});Object.defineProperty(N,"comparePriority",{enumerable:!0,get:function(){return Zs.comparePriority}});var is=Ff();Object.defineProperty(N,"Reliability",{enumerable:!0,get:function(){return is.Reliability}});Object.defineProperty(N,"RELIABILITY_NAMES",{enumerable:!0,get:function(){return is.RELIABILITY_NAMES}});Object.defineProperty(N,"DEFAULT_RELIABILITY",{enumerable:!0,get:function(){return is.DEFAULT_RELIABILITY}});Object.defineProperty(N,"requiresAck",{enumerable:!0,get:function(){return is.requiresAck}});Object.defineProperty(N,"requiresBuffer",{enumerable:!0,get:function(){return is.requiresBuffer}});var Gp=Bf();Object.defineProperty(N,"createMessage",{enumerable:!0,get:function(){return Gp.createMessage}});var Qs=jf();Object.defineProperty(N,"TerminalEventType",{enumerable:!0,get:function(){return Qs.TerminalEventType}});Object.defineProperty(N,"deriveStatusFromEvent",{enumerable:!0,get:function(){return Qs.deriveStatusFromEvent}});Object.defineProperty(N,"shouldTriggerPushNotification",{enumerable:!0,get:function(){return Qs.shouldTriggerPushNotification}});Object.defineProperty(N,"getPushNotificationMessage",{enumerable:!0,get:function(){return Qs.getPushNotificationMessage}});var kt=Wf();Object.defineProperty(N,"CHUNK_SIZE",{enumerable:!0,get:function(){return kt.CHUNK_SIZE}});Object.defineProperty(N,"DEFAULT_MAX_FILE_SIZE",{enumerable:!0,get:function(){return kt.DEFAULT_MAX_FILE_SIZE}});Object.defineProperty(N,"WINDOW_SIZE",{enumerable:!0,get:function(){return kt.WINDOW_SIZE}});Object.defineProperty(N,"ACK_TIMEOUT_MS",{enumerable:!0,get:function(){return kt.ACK_TIMEOUT_MS}});Object.defineProperty(N,"MAX_RETRIES",{enumerable:!0,get:function(){return kt.MAX_RETRIES}});Object.defineProperty(N,"TRANSFER_TTL_SECONDS",{enumerable:!0,get:function(){return kt.TRANSFER_TTL_SECONDS}});Object.defineProperty(N,"CHUNK_TTL_SECONDS",{enumerable:!0,get:function(){return kt.CHUNK_TTL_SECONDS}});Object.defineProperty(N,"TransferStatus",{enumerable:!0,get:function(){return kt.TransferStatus}});Object.defineProperty(N,"TransferDirection",{enumerable:!0,get:function(){return kt.TransferDirection}});Object.defineProperty(N,"calculateTotalChunks",{enumerable:!0,get:function(){return kt.calculateTotalChunks}});Object.defineProperty(N,"getMissingChunks",{enumerable:!0,get:function(){return kt.getMissingChunks}});Object.defineProperty(N,"isTransferComplete",{enumerable:!0,get:function(){return kt.isTransferComplete}});var en=Hf();Object.defineProperty(N,"ErrorCode",{enumerable:!0,get:function(){return en.ErrorCode}});Object.defineProperty(N,"ERROR_MESSAGES",{enumerable:!0,get:function(){return en.ERROR_MESSAGES}});Object.defineProperty(N,"createError",{enumerable:!0,get:function(){return en.createError}});Object.defineProperty(N,"isRetryableError",{enumerable:!0,get:function(){return en.isRetryableError}});var Jr=$f();Object.defineProperty(N,"FileChangeType",{enumerable:!0,get:function(){return Jr.FileChangeType}});Object.defineProperty(N,"FileViewType",{enumerable:!0,get:function(){return Jr.FileViewType}});Object.defineProperty(N,"DiffBase",{enumerable:!0,get:function(){return Jr.DiffBase}});Object.defineProperty(N,"FileEntryType",{enumerable:!0,get:function(){return Jr.FileEntryType}});Object.defineProperty(N,"getLanguageFromPath",{enumerable:!0,get:function(){return Jr.getLanguageFromPath}});Object.defineProperty(N,"parseUnifiedDiff",{enumerable:!0,get:function(){return Jr.parseUnifiedDiff}});Object.defineProperty(N,"createSimpleDiff",{enumerable:!0,get:function(){return Jr.createSimpleDiff}})});var dr=M(Xt=>{"use strict";var Yp=Xt&&Xt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),tn=Xt&&Xt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Yp(e,r,t)};Object.defineProperty(Xt,"__esModule",{value:!0});tn(Cf(),Xt);tn(Of(),Xt);tn(Lf(),Xt);tn(Gf(),Xt)});var Xf=M(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.CryptoService=void 0;var Ze=dr(),Xp=3600*1e3,Yf=10,Do=class{storage;logger;sessions=new Map;agentSessions=new Map;metaSessions=new Map;keyPair=null;publicKeyKey;secretKeyKey;keyVersionKey;constructor(e,t,i,s){this.storage=e,this.logger=t;let n=`termiq.${i}.${s}`;this.publicKeyKey=`${n}.crypto.publicKey`,this.secretKeyKey=`${n}.crypto.secretKey`,this.keyVersionKey=`${n}.crypto.keyVersion`,this.logger.info("CryptoService namespace",i,s)}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 identity key pair")):await this.generateIdentityKeyPair()}async generateIdentityKeyPair(){this.logger.info("Generating new identity key pair"),this.keyPair=(0,Ze.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("Identity key pair generated and stored"),this.keyPair}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 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 s=this.sessions.get(e);s||(s=new Map,this.sessions.set(e,s));let n=(0,Ze.deriveSharedSecret)(t,this.keyPair.secretKey),a={terminalId:e,clientPublicKey:t,sharedSecret:n,createdAt:Date.now(),sessionId:i};return s.set(i,a),this.logger.info("Key exchange completed",e,i,"total:",s.size),!0}catch(s){return this.logger.error("Key exchange failed",s),!1}}encryptOutput(e,t){let i=this.sessions.get(e);if(!i||i.size===0)return null;try{if(i.size===1){let n=i.values().next().value;return n?(0,Ze.encrypt)(t,n.sharedSecret,n.sessionId):null}let s=[];for(let n of i.values()){let a=(0,Ze.encrypt)(t,n.sharedSecret,n.sessionId);s.push({sid:a.sid,n:a.n,c:a.c})}return{v:2,recipients:s}}catch(s){return this.logger.error("Encryption failed",s),null}}decryptInput(e,t){let i=this.sessions.get(e);if(!i)return this.logger.error("No sessions for terminal",e),null;let s=i.get(t.sid);if(!s)return this.logger.error("No session for sessionId",t.sid),null;try{return(0,Ze.decrypt)(t,s.sharedSecret)}catch(n){return this.logger.error("Decryption failed",n),null}}encryptFileChunk(e,t){let i=this.sessions.get(e);if(!i||i.size===0)return null;let s=null;for(let n of i.values())(!s||n.createdAt>s.createdAt)&&(s=n);if(!s)return null;try{return(0,Ze.encryptBinary)(t,s.sharedSecret,s.sessionId)}catch(n){return this.logger.error("File chunk encryption failed",n),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,Ze.decryptBinary)(t,i.sharedSecret)}catch(s){return this.logger.error("File chunk decryption failed",s),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 s=i.get(t);s&&((0,Ze.clearKey)(s.sharedSecret),i.delete(t),this.logger.info("Session removed",e,t)),i.size===0&&this.sessions.delete(e)}else{for(let s of i.values())(0,Ze.clearKey)(s.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,Ze.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(),s=[];for(let[n,a]of t)i-a.createdAt>Xp&&s.push(n);for(let n of s){let a=t.get(n);a&&((0,Ze.clearKey)(a.sharedSecret),t.delete(n),this.logger.info("Session expired (TTL)",e,n,`age:${Math.round((i-a.createdAt)/1e3)}s`))}if(t.size>Yf){let a=Array.from(t.entries()).sort((c,u)=>c[1].createdAt-u[1].createdAt).slice(0,t.size-Yf);for(let[,c]of a)(0,Ze.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 s of i.values())e.push({terminalId:t,createdAt:s.createdAt,sessionId:s.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,Ze.clearKey)(i.sharedSecret));let s=(0,Ze.deriveSharedSecret)(e,this.keyPair.secretKey),n={sessionId:t,clientPublicKey:e,sharedSecret:s,createdAt:Date.now()};return this.agentSessions.set(t,n),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,Ze.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,Ze.deriveSharedSecret)(e,this.keyPair.secretKey),s=(0,Ze.deriveMetaSid)(this.keyPair.publicKey,e);return this.metaSessions.set(e,{clientIdentityPub:e,sharedSecret:i,sidMeta:s}),this.logger.info("Meta key exchange completed",s,"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,Ze.encrypt)(e,i.sharedSecret,i.sidMeta):null}let t=[];for(let i of this.metaSessions.values()){let s=(0,Ze.encrypt)(e,i.sharedSecret,i.sidMeta);t.push({sid:s.sid,n:s.n,c:s.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,Ze.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),this.keyPair=null,this.clearAllSessions(),this.clearAllAgentSessions(),this.logger.info("All crypto keys deleted")}};rn.CryptoService=Do});var Jf=M(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.AuthService=void 0;var ss=Ks(),Mo=class{storage;cryptoService;machineId;config;logger;notification;browser;pollingAbortController=null;tokenKey;refreshTokenKey;agentIdKey;constructor(e,t,i,s,n,a,c,u,d){this.storage=e,this.cryptoService=t,this.machineId=i,this.config=s,this.logger=n,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,ss.getApiUrl)(this.config),t=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("Starting device code flow",t,i);let n=await fetch(`${e}/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machineId:t,machineName:i,publicKey:s})});if(!n.ok){let a=await n.text();throw new Error(`Failed to get device code: ${a}`)}return n.json()}async pollForToken(e){this.cancelPolling();let t=(0,ss.getApiUrl)(this.config),i=5e3,s=60;this.pollingAbortController=new AbortController;let n=this.pollingAbortController.signal;this.logger.info("Starting token polling");for(let a=0;a<s;a++){if(n.aborted)return this.logger.info("Polling was cancelled"),null;if(await this.sleep(i),n.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:n});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(n.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,ss.getApiUrl)(this.config),i=await this.machineId.getMachineId(),s=this.machineId.getMachineName(),n=await this.cryptoService.getPublicKey();n||(await this.cryptoService.generateIdentityKeyPair(),n=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:s,publicKey:n})});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,ss.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 s=await i.json();return await this.storage.set(this.tokenKey,s.accessToken),await this.storage.set(this.refreshTokenKey,s.refreshToken),this.logger.info("Access token refreshed successfully"),s.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,ss.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 s=i instanceof Error?i.message:String(i);return this.logger.error(`Error fetching limits: ${s}`),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))}};sn.AuthService=Mo});var Zf=M(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.StatusDetector=void 0;var nn={working:[/✶/,/⠋|⠙|⠹|⠸|⠼|⠴|⠦|⠧|⠇|⠏/],idle:[/[❯$#>]\s*$/,/^\s*\d+\s*[❯$#>]\s*$/,/\(base\)\s*[❯$#>]\s*$/,/\)\s*[❯$#>]\s*$/],waiting:[/\[Y\/n\]/i,/\[y\/N\]/i,/\(y\/n\)/i,/\(yes\/no\)/i,/Continue\?/i,/Proceed\?/i,/Are you sure\?/i,/Confirm\?/i,/Press Enter to continue/i,/Press any key/i,/\[Enter\]/i,/Do you want to/i,/Would you like to/i,/Shall I/i,/^\s*\d+[.)]\s+.+$/m,/Select.*:/i,/Choose.*:/i,/Which.*\?/i,/Какой вариант/i,/Выберите/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]},ns={IDLE_TIMEOUT_MS:5e3,DEBOUNCE_MS:500,BUFFER_SIZE:2e3,WORKING_TIMEOUT_MS:3e4},Fo=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,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)),this.states.delete(e)}processOutput(e,t){let i=this.states.get(e);if(!i)return;i.lastOutput=Date.now(),i.outputBuffer+=t,i.outputBuffer.length>ns.BUFFER_SIZE&&(i.outputBuffer=i.outputBuffer.slice(-ns.BUFFER_SIZE));let s=this.analyzeOutput(i.outputBuffer);s&&this.scheduleStatusUpdate(e,s),this.resetWorkingTimeout(e,i)}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 s;if(t!==void 0&&t!==0)s="error";else{let n=this.analyzeOutput(i.outputBuffer);n==="waiting"?s="waiting":n==="error"?s="error":n==="completed"?s="completed":s="idle"}this.scheduleStatusUpdate(e,s),(s==="completed"||s==="error")&&setTimeout(()=>{let n=this.states.get(e);n&&(n.status==="completed"||n.status==="error")&&this.scheduleStatusUpdate(e,"idle")},ns.IDLE_TIMEOUT_MS)}analyzeOutput(e){let t=e.split(`
|
|
6
|
-
`).
|
|
7
|
-
`)
|
|
8
|
-
`).slice(-
|
|
9
|
-
`),
|
|
10
|
-
`)
|
|
11
|
-
`)
|
|
2
|
+
"use strict";var Yd=Object.create;var ko=Object.defineProperty;var Xd=Object.getOwnPropertyDescriptor;var Jd=Object.getOwnPropertyNames;var Zd=Object.getPrototypeOf,Qd=Object.prototype.hasOwnProperty;var Ft=(r,e)=>()=>(r&&(e=r(r=0)),e);var D=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ep=(r,e)=>{for(var t in e)ko(r,t,{get:e[t],enumerable:!0})},tp=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Jd(e))!Qd.call(r,i)&&i!==t&&ko(r,i,{get:()=>e[i],enumerable:!(s=Xd(e,i))||s.enumerable});return r};var ce=(r,e,t)=>(t=r!=null?Yd(Zd(r)):{},tp(e||!r||!r.__esModule?ko(t,"default",{value:r,enumerable:!0}):t,r));var Wi=D(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.generateCorrelationId=ip;ri.runWithCorrelation=np;ri.getCurrentCorrelationId=op;var sp=require("async_hooks");function ip(){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 hf=new sp.AsyncLocalStorage;function np(r,e){return hf.run(r,e)}function op(){return hf.getStore()}});var pf=D(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});ys.LOG_LEVELS=void 0;ys.shouldLog=cp;ys.formatLogLine=fp;var ap=Wi();ys.LOG_LEVELS=["silent","error","warn","info","debug"];var df={silent:0,error:1,warn:2,info:3,debug:4};function cp(r,e){return df[r]<=df[e]}function fp(r,e,t,s){let i={ts:new Date().toISOString(),level:r,src:e,msg:t},n=(0,ap.getCurrentCorrelationId)();n&&(i.cid=n);let a=s;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 gf=D(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.formatLogLine=Or.shouldLog=Or.LOG_LEVELS=void 0;var Ro=pf();Object.defineProperty(Or,"LOG_LEVELS",{enumerable:!0,get:function(){return Ro.LOG_LEVELS}});Object.defineProperty(Or,"shouldLog",{enumerable:!0,get:function(){return Ro.shouldLog}});Object.defineProperty(Or,"formatLogLine",{enumerable:!0,get:function(){return Ro.formatLogLine}})});var mf=D(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});Hi.CircularBuffer=void 0;var Ao=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}};Hi.CircularBuffer=Ao});var zi=D(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.getApiUrl=up;Vi.getWsUrl=lp;function up(r){return`${r.getServerUrl()}/api`}function lp(r){let e=r.getServerUrl();return e.startsWith("https://")?e.replace(/^https:\/\//,"wss://"):e.replace(/^http:\/\//,"ws://")}});var yf=D(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.getCurrentCorrelationId=gt.runWithCorrelation=gt.generateCorrelationId=gt.getWsUrl=gt.getApiUrl=gt.CircularBuffer=void 0;var hp=mf();Object.defineProperty(gt,"CircularBuffer",{enumerable:!0,get:function(){return hp.CircularBuffer}});var _f=zi();Object.defineProperty(gt,"getApiUrl",{enumerable:!0,get:function(){return _f.getApiUrl}});Object.defineProperty(gt,"getWsUrl",{enumerable:!0,get:function(){return _f.getWsUrl}});var Po=Wi();Object.defineProperty(gt,"generateCorrelationId",{enumerable:!0,get:function(){return Po.generateCorrelationId}});Object.defineProperty(gt,"runWithCorrelation",{enumerable:!0,get:function(){return Po.runWithCorrelation}});Object.defineProperty(gt,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Po.getCurrentCorrelationId}})});var Ef=D(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0})});var bf=D(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0})});var xf=D(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});Ki.PLAN_LIMITS=void 0;Ki.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 Tf=D(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0})});var Cf=D(Kt=>{"use strict";var dp=Kt&&Kt.__createBinding||(Object.create?(function(r,e,t,s){s===void 0&&(s=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,s,i)}):(function(r,e,t,s){s===void 0&&(s=t),r[s]=e[t]})),$i=Kt&&Kt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&dp(e,r,t)};Object.defineProperty(Kt,"__esModule",{value:!0});$i(Ef(),Kt);$i(bf(),Kt);$i(xf(),Kt);$i(Tf(),Kt)});var Of=D(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.API_VERSION=Ot.WS_NAMESPACES=Ot.TIMEOUTS=Ot.STATUS_PATTERNS=Ot.TERMINAL_STATUSES=void 0;Ot.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"}};Ot.STATUS_PATTERNS={idle:[/[❯$]\s*$/,/>\s*$/],waiting:[/\[Y\/n\]/i,/\(y\/N\)/i,/Continue\?/i,/proceed\?/i],completed:[/✓/,/Done/,/Completed/,/Success/],error:[/Error/,/Failed/,/✕/,/Exception/]};Ot.TIMEOUTS={HEARTBEAT_INTERVAL:3e4,OFFLINE_THRESHOLD:6e4,DEVICE_CODE_EXPIRY:9e5,DEVICE_CODE_POLL_INTERVAL:5e3};Ot.WS_NAMESPACES={AGENT:"/agent",CLIENT:"/client"};Ot.API_VERSION="v1"});var kf=D(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});Gi.isMultiRecipientPayload=pp;Gi.isEncryptedPayload=gp;function pp(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 Io=D((yE,Yi)=>{(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")},s=new Uint8Array(16),i=new Uint8Array(32);i[0]=9;var n=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]),y=e([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function b(f,h,l,o){f[h]=l>>24&255,f[h+1]=l>>16&255,f[h+2]=l>>8&255,f[h+3]=l&255,f[h+4]=o>>24&255,f[h+5]=o>>16&255,f[h+6]=o>>8&255,f[h+7]=o&255}function T(f,h,l,o,g){var v,w=0;for(v=0;v<g;v++)w|=f[h+v]^l[o+v];return(1&w-1>>>8)-1}function C(f,h,l,o){return T(f,h,l,o,16)}function V(f,h,l,o){return T(f,h,l,o,32)}function _e(f,h,l,o){for(var g=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,v=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,w=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,k=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,F=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,Y=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,Ce=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,z=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,re=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,se=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,le=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,fe=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,ie=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,oe=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ne=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,K=g,J=v,H=w,$=k,G=F,q=Y,x=W,S=Ce,I=z,O=re,R=se,M=le,Z=fe,he=ie,ge=oe,de=ne,_,ye=0;ye<20;ye+=2)_=K+Z|0,G^=_<<7|_>>>25,_=G+K|0,I^=_<<9|_>>>23,_=I+G|0,Z^=_<<13|_>>>19,_=Z+I|0,K^=_<<18|_>>>14,_=q+J|0,O^=_<<7|_>>>25,_=O+q|0,he^=_<<9|_>>>23,_=he+O|0,J^=_<<13|_>>>19,_=J+he|0,q^=_<<18|_>>>14,_=R+x|0,ge^=_<<7|_>>>25,_=ge+R|0,H^=_<<9|_>>>23,_=H+ge|0,x^=_<<13|_>>>19,_=x+H|0,R^=_<<18|_>>>14,_=de+M|0,$^=_<<7|_>>>25,_=$+de|0,S^=_<<9|_>>>23,_=S+$|0,M^=_<<13|_>>>19,_=M+S|0,de^=_<<18|_>>>14,_=K+$|0,J^=_<<7|_>>>25,_=J+K|0,H^=_<<9|_>>>23,_=H+J|0,$^=_<<13|_>>>19,_=$+H|0,K^=_<<18|_>>>14,_=q+G|0,x^=_<<7|_>>>25,_=x+q|0,S^=_<<9|_>>>23,_=S+x|0,G^=_<<13|_>>>19,_=G+S|0,q^=_<<18|_>>>14,_=R+O|0,M^=_<<7|_>>>25,_=M+R|0,I^=_<<9|_>>>23,_=I+M|0,O^=_<<13|_>>>19,_=O+I|0,R^=_<<18|_>>>14,_=de+ge|0,Z^=_<<7|_>>>25,_=Z+de|0,he^=_<<9|_>>>23,_=he+Z|0,ge^=_<<13|_>>>19,_=ge+he|0,de^=_<<18|_>>>14;K=K+g|0,J=J+v|0,H=H+w|0,$=$+k|0,G=G+F|0,q=q+Y|0,x=x+W|0,S=S+Ce|0,I=I+z|0,O=O+re|0,R=R+se|0,M=M+le|0,Z=Z+fe|0,he=he+ie|0,ge=ge+oe|0,de=de+ne|0,f[0]=K>>>0&255,f[1]=K>>>8&255,f[2]=K>>>16&255,f[3]=K>>>24&255,f[4]=J>>>0&255,f[5]=J>>>8&255,f[6]=J>>>16&255,f[7]=J>>>24&255,f[8]=H>>>0&255,f[9]=H>>>8&255,f[10]=H>>>16&255,f[11]=H>>>24&255,f[12]=$>>>0&255,f[13]=$>>>8&255,f[14]=$>>>16&255,f[15]=$>>>24&255,f[16]=G>>>0&255,f[17]=G>>>8&255,f[18]=G>>>16&255,f[19]=G>>>24&255,f[20]=q>>>0&255,f[21]=q>>>8&255,f[22]=q>>>16&255,f[23]=q>>>24&255,f[24]=x>>>0&255,f[25]=x>>>8&255,f[26]=x>>>16&255,f[27]=x>>>24&255,f[28]=S>>>0&255,f[29]=S>>>8&255,f[30]=S>>>16&255,f[31]=S>>>24&255,f[32]=I>>>0&255,f[33]=I>>>8&255,f[34]=I>>>16&255,f[35]=I>>>24&255,f[36]=O>>>0&255,f[37]=O>>>8&255,f[38]=O>>>16&255,f[39]=O>>>24&255,f[40]=R>>>0&255,f[41]=R>>>8&255,f[42]=R>>>16&255,f[43]=R>>>24&255,f[44]=M>>>0&255,f[45]=M>>>8&255,f[46]=M>>>16&255,f[47]=M>>>24&255,f[48]=Z>>>0&255,f[49]=Z>>>8&255,f[50]=Z>>>16&255,f[51]=Z>>>24&255,f[52]=he>>>0&255,f[53]=he>>>8&255,f[54]=he>>>16&255,f[55]=he>>>24&255,f[56]=ge>>>0&255,f[57]=ge>>>8&255,f[58]=ge>>>16&255,f[59]=ge>>>24&255,f[60]=de>>>0&255,f[61]=de>>>8&255,f[62]=de>>>16&255,f[63]=de>>>24&255}function X(f,h,l,o){for(var g=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,v=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,w=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,k=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,F=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,Y=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,Ce=h[4]&255|(h[5]&255)<<8|(h[6]&255)<<16|(h[7]&255)<<24,z=h[8]&255|(h[9]&255)<<8|(h[10]&255)<<16|(h[11]&255)<<24,re=h[12]&255|(h[13]&255)<<8|(h[14]&255)<<16|(h[15]&255)<<24,se=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,le=l[16]&255|(l[17]&255)<<8|(l[18]&255)<<16|(l[19]&255)<<24,fe=l[20]&255|(l[21]&255)<<8|(l[22]&255)<<16|(l[23]&255)<<24,ie=l[24]&255|(l[25]&255)<<8|(l[26]&255)<<16|(l[27]&255)<<24,oe=l[28]&255|(l[29]&255)<<8|(l[30]&255)<<16|(l[31]&255)<<24,ne=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,K=g,J=v,H=w,$=k,G=F,q=Y,x=W,S=Ce,I=z,O=re,R=se,M=le,Z=fe,he=ie,ge=oe,de=ne,_,ye=0;ye<20;ye+=2)_=K+Z|0,G^=_<<7|_>>>25,_=G+K|0,I^=_<<9|_>>>23,_=I+G|0,Z^=_<<13|_>>>19,_=Z+I|0,K^=_<<18|_>>>14,_=q+J|0,O^=_<<7|_>>>25,_=O+q|0,he^=_<<9|_>>>23,_=he+O|0,J^=_<<13|_>>>19,_=J+he|0,q^=_<<18|_>>>14,_=R+x|0,ge^=_<<7|_>>>25,_=ge+R|0,H^=_<<9|_>>>23,_=H+ge|0,x^=_<<13|_>>>19,_=x+H|0,R^=_<<18|_>>>14,_=de+M|0,$^=_<<7|_>>>25,_=$+de|0,S^=_<<9|_>>>23,_=S+$|0,M^=_<<13|_>>>19,_=M+S|0,de^=_<<18|_>>>14,_=K+$|0,J^=_<<7|_>>>25,_=J+K|0,H^=_<<9|_>>>23,_=H+J|0,$^=_<<13|_>>>19,_=$+H|0,K^=_<<18|_>>>14,_=q+G|0,x^=_<<7|_>>>25,_=x+q|0,S^=_<<9|_>>>23,_=S+x|0,G^=_<<13|_>>>19,_=G+S|0,q^=_<<18|_>>>14,_=R+O|0,M^=_<<7|_>>>25,_=M+R|0,I^=_<<9|_>>>23,_=I+M|0,O^=_<<13|_>>>19,_=O+I|0,R^=_<<18|_>>>14,_=de+ge|0,Z^=_<<7|_>>>25,_=Z+de|0,he^=_<<9|_>>>23,_=he+Z|0,ge^=_<<13|_>>>19,_=ge+he|0,de^=_<<18|_>>>14;f[0]=K>>>0&255,f[1]=K>>>8&255,f[2]=K>>>16&255,f[3]=K>>>24&255,f[4]=q>>>0&255,f[5]=q>>>8&255,f[6]=q>>>16&255,f[7]=q>>>24&255,f[8]=R>>>0&255,f[9]=R>>>8&255,f[10]=R>>>16&255,f[11]=R>>>24&255,f[12]=de>>>0&255,f[13]=de>>>8&255,f[14]=de>>>16&255,f[15]=de>>>24&255,f[16]=x>>>0&255,f[17]=x>>>8&255,f[18]=x>>>16&255,f[19]=x>>>24&255,f[20]=S>>>0&255,f[21]=S>>>8&255,f[22]=S>>>16&255,f[23]=S>>>24&255,f[24]=I>>>0&255,f[25]=I>>>8&255,f[26]=I>>>16&255,f[27]=I>>>24&255,f[28]=O>>>0&255,f[29]=O>>>8&255,f[30]=O>>>16&255,f[31]=O>>>24&255}function P(f,h,l,o){_e(f,h,l,o)}function B(f,h,l,o){X(f,h,l,o)}var te=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function A(f,h,l,o,g,v,w){var k=new Uint8Array(16),F=new Uint8Array(64),Y,W;for(W=0;W<16;W++)k[W]=0;for(W=0;W<8;W++)k[W]=v[W];for(;g>=64;){for(P(F,k,w,te),W=0;W<64;W++)f[h+W]=l[o+W]^F[W];for(Y=1,W=8;W<16;W++)Y=Y+(k[W]&255)|0,k[W]=Y&255,Y>>>=8;g-=64,h+=64,o+=64}if(g>0)for(P(F,k,w,te),W=0;W<g;W++)f[h+W]=l[o+W]^F[W];return 0}function ae(f,h,l,o,g){var v=new Uint8Array(16),w=new Uint8Array(64),k,F;for(F=0;F<16;F++)v[F]=0;for(F=0;F<8;F++)v[F]=o[F];for(;l>=64;){for(P(w,v,g,te),F=0;F<64;F++)f[h+F]=w[F];for(k=1,F=8;F<16;F++)k=k+(v[F]&255)|0,v[F]=k&255,k>>>=8;l-=64,h+=64}if(l>0)for(P(w,v,g,te),F=0;F<l;F++)f[h+F]=w[F];return 0}function pe(f,h,l,o,g){var v=new Uint8Array(32);B(v,o,g,te);for(var w=new Uint8Array(8),k=0;k<8;k++)w[k]=o[k+16];return ae(f,h,l,w,v)}function Q(f,h,l,o,g,v,w){var k=new Uint8Array(32);B(k,v,w,te);for(var F=new Uint8Array(8),Y=0;Y<8;Y++)F[Y]=v[Y+16];return A(f,h,l,o,g,F,k)}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 h,l,o,g,v,w,k,F;h=f[0]&255|(f[1]&255)<<8,this.r[0]=h&8191,l=f[2]&255|(f[3]&255)<<8,this.r[1]=(h>>>13|l<<3)&8191,o=f[4]&255|(f[5]&255)<<8,this.r[2]=(l>>>10|o<<6)&7939,g=f[6]&255|(f[7]&255)<<8,this.r[3]=(o>>>7|g<<9)&8191,v=f[8]&255|(f[9]&255)<<8,this.r[4]=(g>>>4|v<<12)&255,this.r[5]=v>>>1&8190,w=f[10]&255|(f[11]&255)<<8,this.r[6]=(v>>>14|w<<2)&8191,k=f[12]&255|(f[13]&255)<<8,this.r[7]=(w>>>11|k<<5)&8065,F=f[14]&255|(f[15]&255)<<8,this.r[8]=(k>>>8|F<<8)&8191,this.r[9]=F>>>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,h,l){for(var o=this.fin?0:2048,g,v,w,k,F,Y,W,Ce,z,re,se,le,fe,ie,oe,ne,K,J,H,$=this.h[0],G=this.h[1],q=this.h[2],x=this.h[3],S=this.h[4],I=this.h[5],O=this.h[6],R=this.h[7],M=this.h[8],Z=this.h[9],he=this.r[0],ge=this.r[1],de=this.r[2],_=this.r[3],ye=this.r[4],Oe=this.r[5],ke=this.r[6],me=this.r[7],be=this.r[8],xe=this.r[9];l>=16;)g=f[h+0]&255|(f[h+1]&255)<<8,$+=g&8191,v=f[h+2]&255|(f[h+3]&255)<<8,G+=(g>>>13|v<<3)&8191,w=f[h+4]&255|(f[h+5]&255)<<8,q+=(v>>>10|w<<6)&8191,k=f[h+6]&255|(f[h+7]&255)<<8,x+=(w>>>7|k<<9)&8191,F=f[h+8]&255|(f[h+9]&255)<<8,S+=(k>>>4|F<<12)&8191,I+=F>>>1&8191,Y=f[h+10]&255|(f[h+11]&255)<<8,O+=(F>>>14|Y<<2)&8191,W=f[h+12]&255|(f[h+13]&255)<<8,R+=(Y>>>11|W<<5)&8191,Ce=f[h+14]&255|(f[h+15]&255)<<8,M+=(W>>>8|Ce<<8)&8191,Z+=Ce>>>5|o,z=0,re=z,re+=$*he,re+=G*(5*xe),re+=q*(5*be),re+=x*(5*me),re+=S*(5*ke),z=re>>>13,re&=8191,re+=I*(5*Oe),re+=O*(5*ye),re+=R*(5*_),re+=M*(5*de),re+=Z*(5*ge),z+=re>>>13,re&=8191,se=z,se+=$*ge,se+=G*he,se+=q*(5*xe),se+=x*(5*be),se+=S*(5*me),z=se>>>13,se&=8191,se+=I*(5*ke),se+=O*(5*Oe),se+=R*(5*ye),se+=M*(5*_),se+=Z*(5*de),z+=se>>>13,se&=8191,le=z,le+=$*de,le+=G*ge,le+=q*he,le+=x*(5*xe),le+=S*(5*be),z=le>>>13,le&=8191,le+=I*(5*me),le+=O*(5*ke),le+=R*(5*Oe),le+=M*(5*ye),le+=Z*(5*_),z+=le>>>13,le&=8191,fe=z,fe+=$*_,fe+=G*de,fe+=q*ge,fe+=x*he,fe+=S*(5*xe),z=fe>>>13,fe&=8191,fe+=I*(5*be),fe+=O*(5*me),fe+=R*(5*ke),fe+=M*(5*Oe),fe+=Z*(5*ye),z+=fe>>>13,fe&=8191,ie=z,ie+=$*ye,ie+=G*_,ie+=q*de,ie+=x*ge,ie+=S*he,z=ie>>>13,ie&=8191,ie+=I*(5*xe),ie+=O*(5*be),ie+=R*(5*me),ie+=M*(5*ke),ie+=Z*(5*Oe),z+=ie>>>13,ie&=8191,oe=z,oe+=$*Oe,oe+=G*ye,oe+=q*_,oe+=x*de,oe+=S*ge,z=oe>>>13,oe&=8191,oe+=I*he,oe+=O*(5*xe),oe+=R*(5*be),oe+=M*(5*me),oe+=Z*(5*ke),z+=oe>>>13,oe&=8191,ne=z,ne+=$*ke,ne+=G*Oe,ne+=q*ye,ne+=x*_,ne+=S*de,z=ne>>>13,ne&=8191,ne+=I*ge,ne+=O*he,ne+=R*(5*xe),ne+=M*(5*be),ne+=Z*(5*me),z+=ne>>>13,ne&=8191,K=z,K+=$*me,K+=G*ke,K+=q*Oe,K+=x*ye,K+=S*_,z=K>>>13,K&=8191,K+=I*de,K+=O*ge,K+=R*he,K+=M*(5*xe),K+=Z*(5*be),z+=K>>>13,K&=8191,J=z,J+=$*be,J+=G*me,J+=q*ke,J+=x*Oe,J+=S*ye,z=J>>>13,J&=8191,J+=I*_,J+=O*de,J+=R*ge,J+=M*he,J+=Z*(5*xe),z+=J>>>13,J&=8191,H=z,H+=$*xe,H+=G*be,H+=q*me,H+=x*ke,H+=S*Oe,z=H>>>13,H&=8191,H+=I*ye,H+=O*_,H+=R*de,H+=M*ge,H+=Z*he,z+=H>>>13,H&=8191,z=(z<<2)+z|0,z=z+re|0,re=z&8191,z=z>>>13,se+=z,$=re,G=se,q=le,x=fe,S=ie,I=oe,O=ne,R=K,M=J,Z=H,h+=16,l-=16;this.h[0]=$,this.h[1]=G,this.h[2]=q,this.h[3]=x,this.h[4]=S,this.h[5]=I,this.h[6]=O,this.h[7]=R,this.h[8]=M,this.h[9]=Z},Ne.prototype.finish=function(f,h){var l=new Uint16Array(10),o,g,v,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,v=this.h[0]+this.pad[0],this.h[0]=v&65535,w=1;w<8;w++)v=(this.h[w]+this.pad[w]|0)+(v>>>16)|0,this.h[w]=v&65535;f[h+0]=this.h[0]>>>0&255,f[h+1]=this.h[0]>>>8&255,f[h+2]=this.h[1]>>>0&255,f[h+3]=this.h[1]>>>8&255,f[h+4]=this.h[2]>>>0&255,f[h+5]=this.h[2]>>>8&255,f[h+6]=this.h[3]>>>0&255,f[h+7]=this.h[3]>>>8&255,f[h+8]=this.h[4]>>>0&255,f[h+9]=this.h[4]>>>8&255,f[h+10]=this.h[5]>>>0&255,f[h+11]=this.h[5]>>>8&255,f[h+12]=this.h[6]>>>0&255,f[h+13]=this.h[6]>>>8&255,f[h+14]=this.h[7]>>>0&255,f[h+15]=this.h[7]>>>8&255},Ne.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 ve(f,h,l,o,g,v){var w=new Ne(v);return w.update(l,o,g),w.finish(f,h),0}function Ke(f,h,l,o,g,v){var w=new Uint8Array(16);return ve(w,0,l,o,g,v),C(f,h,w,0)}function ee(f,h,l,o,g){var v;if(l<32)return-1;for(Q(f,0,h,0,l,o,g),ve(f,16,f,32,l-32,f),v=0;v<16;v++)f[v]=0;return 0}function Je(f,h,l,o,g){var v,w=new Uint8Array(32);if(l<32||(pe(w,0,32,o,g),Ke(h,16,h,32,l-32,w)!==0))return-1;for(Q(f,0,h,0,l,o,g),v=0;v<32;v++)f[v]=0;return 0}function We(f,h){var l;for(l=0;l<16;l++)f[l]=h[l]|0}function nt(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 De(f,h,l){for(var o,g=~(l-1),v=0;v<16;v++)o=g&(f[v]^h[v]),f[v]^=o,h[v]^=o}function Te(f,h){var l,o,g,v=e(),w=e();for(l=0;l<16;l++)w[l]=h[l];for(nt(w),nt(w),nt(w),o=0;o<2;o++){for(v[0]=w[0]-65517,l=1;l<15;l++)v[l]=w[l]-65535-(v[l-1]>>16&1),v[l-1]&=65535;v[15]=w[15]-32767-(v[14]>>16&1),g=v[15]>>16&1,v[14]&=65535,De(w,v,1-g)}for(l=0;l<16;l++)f[2*l]=w[l]&255,f[2*l+1]=w[l]>>8}function ot(f,h){var l=new Uint8Array(32),o=new Uint8Array(32);return Te(l,f),Te(o,h),V(l,0,o,0)}function He(f){var h=new Uint8Array(32);return Te(h,f),h[0]&1}function vt(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 E(f,h,l){var o,g,v=0,w=0,k=0,F=0,Y=0,W=0,Ce=0,z=0,re=0,se=0,le=0,fe=0,ie=0,oe=0,ne=0,K=0,J=0,H=0,$=0,G=0,q=0,x=0,S=0,I=0,O=0,R=0,M=0,Z=0,he=0,ge=0,de=0,_=l[0],ye=l[1],Oe=l[2],ke=l[3],me=l[4],be=l[5],xe=l[6],Xe=l[7],Pe=l[8],$e=l[9],Ge=l[10],Ye=l[11],et=l[12],ft=l[13],ut=l[14],lt=l[15];o=h[0],v+=o*_,w+=o*ye,k+=o*Oe,F+=o*ke,Y+=o*me,W+=o*be,Ce+=o*xe,z+=o*Xe,re+=o*Pe,se+=o*$e,le+=o*Ge,fe+=o*Ye,ie+=o*et,oe+=o*ft,ne+=o*ut,K+=o*lt,o=h[1],w+=o*_,k+=o*ye,F+=o*Oe,Y+=o*ke,W+=o*me,Ce+=o*be,z+=o*xe,re+=o*Xe,se+=o*Pe,le+=o*$e,fe+=o*Ge,ie+=o*Ye,oe+=o*et,ne+=o*ft,K+=o*ut,J+=o*lt,o=h[2],k+=o*_,F+=o*ye,Y+=o*Oe,W+=o*ke,Ce+=o*me,z+=o*be,re+=o*xe,se+=o*Xe,le+=o*Pe,fe+=o*$e,ie+=o*Ge,oe+=o*Ye,ne+=o*et,K+=o*ft,J+=o*ut,H+=o*lt,o=h[3],F+=o*_,Y+=o*ye,W+=o*Oe,Ce+=o*ke,z+=o*me,re+=o*be,se+=o*xe,le+=o*Xe,fe+=o*Pe,ie+=o*$e,oe+=o*Ge,ne+=o*Ye,K+=o*et,J+=o*ft,H+=o*ut,$+=o*lt,o=h[4],Y+=o*_,W+=o*ye,Ce+=o*Oe,z+=o*ke,re+=o*me,se+=o*be,le+=o*xe,fe+=o*Xe,ie+=o*Pe,oe+=o*$e,ne+=o*Ge,K+=o*Ye,J+=o*et,H+=o*ft,$+=o*ut,G+=o*lt,o=h[5],W+=o*_,Ce+=o*ye,z+=o*Oe,re+=o*ke,se+=o*me,le+=o*be,fe+=o*xe,ie+=o*Xe,oe+=o*Pe,ne+=o*$e,K+=o*Ge,J+=o*Ye,H+=o*et,$+=o*ft,G+=o*ut,q+=o*lt,o=h[6],Ce+=o*_,z+=o*ye,re+=o*Oe,se+=o*ke,le+=o*me,fe+=o*be,ie+=o*xe,oe+=o*Xe,ne+=o*Pe,K+=o*$e,J+=o*Ge,H+=o*Ye,$+=o*et,G+=o*ft,q+=o*ut,x+=o*lt,o=h[7],z+=o*_,re+=o*ye,se+=o*Oe,le+=o*ke,fe+=o*me,ie+=o*be,oe+=o*xe,ne+=o*Xe,K+=o*Pe,J+=o*$e,H+=o*Ge,$+=o*Ye,G+=o*et,q+=o*ft,x+=o*ut,S+=o*lt,o=h[8],re+=o*_,se+=o*ye,le+=o*Oe,fe+=o*ke,ie+=o*me,oe+=o*be,ne+=o*xe,K+=o*Xe,J+=o*Pe,H+=o*$e,$+=o*Ge,G+=o*Ye,q+=o*et,x+=o*ft,S+=o*ut,I+=o*lt,o=h[9],se+=o*_,le+=o*ye,fe+=o*Oe,ie+=o*ke,oe+=o*me,ne+=o*be,K+=o*xe,J+=o*Xe,H+=o*Pe,$+=o*$e,G+=o*Ge,q+=o*Ye,x+=o*et,S+=o*ft,I+=o*ut,O+=o*lt,o=h[10],le+=o*_,fe+=o*ye,ie+=o*Oe,oe+=o*ke,ne+=o*me,K+=o*be,J+=o*xe,H+=o*Xe,$+=o*Pe,G+=o*$e,q+=o*Ge,x+=o*Ye,S+=o*et,I+=o*ft,O+=o*ut,R+=o*lt,o=h[11],fe+=o*_,ie+=o*ye,oe+=o*Oe,ne+=o*ke,K+=o*me,J+=o*be,H+=o*xe,$+=o*Xe,G+=o*Pe,q+=o*$e,x+=o*Ge,S+=o*Ye,I+=o*et,O+=o*ft,R+=o*ut,M+=o*lt,o=h[12],ie+=o*_,oe+=o*ye,ne+=o*Oe,K+=o*ke,J+=o*me,H+=o*be,$+=o*xe,G+=o*Xe,q+=o*Pe,x+=o*$e,S+=o*Ge,I+=o*Ye,O+=o*et,R+=o*ft,M+=o*ut,Z+=o*lt,o=h[13],oe+=o*_,ne+=o*ye,K+=o*Oe,J+=o*ke,H+=o*me,$+=o*be,G+=o*xe,q+=o*Xe,x+=o*Pe,S+=o*$e,I+=o*Ge,O+=o*Ye,R+=o*et,M+=o*ft,Z+=o*ut,he+=o*lt,o=h[14],ne+=o*_,K+=o*ye,J+=o*Oe,H+=o*ke,$+=o*me,G+=o*be,q+=o*xe,x+=o*Xe,S+=o*Pe,I+=o*$e,O+=o*Ge,R+=o*Ye,M+=o*et,Z+=o*ft,he+=o*ut,ge+=o*lt,o=h[15],K+=o*_,J+=o*ye,H+=o*Oe,$+=o*ke,G+=o*me,q+=o*be,x+=o*xe,S+=o*Xe,I+=o*Pe,O+=o*$e,R+=o*Ge,M+=o*Ye,Z+=o*et,he+=o*ft,ge+=o*ut,de+=o*lt,v+=38*J,w+=38*H,k+=38*$,F+=38*G,Y+=38*q,W+=38*x,Ce+=38*S,z+=38*I,re+=38*O,se+=38*R,le+=38*M,fe+=38*Z,ie+=38*he,oe+=38*ge,ne+=38*de,g=1,o=v+g+65535,g=Math.floor(o/65536),v=o-g*65536,o=w+g+65535,g=Math.floor(o/65536),w=o-g*65536,o=k+g+65535,g=Math.floor(o/65536),k=o-g*65536,o=F+g+65535,g=Math.floor(o/65536),F=o-g*65536,o=Y+g+65535,g=Math.floor(o/65536),Y=o-g*65536,o=W+g+65535,g=Math.floor(o/65536),W=o-g*65536,o=Ce+g+65535,g=Math.floor(o/65536),Ce=o-g*65536,o=z+g+65535,g=Math.floor(o/65536),z=o-g*65536,o=re+g+65535,g=Math.floor(o/65536),re=o-g*65536,o=se+g+65535,g=Math.floor(o/65536),se=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=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=ne+g+65535,g=Math.floor(o/65536),ne=o-g*65536,o=K+g+65535,g=Math.floor(o/65536),K=o-g*65536,v+=g-1+37*(g-1),g=1,o=v+g+65535,g=Math.floor(o/65536),v=o-g*65536,o=w+g+65535,g=Math.floor(o/65536),w=o-g*65536,o=k+g+65535,g=Math.floor(o/65536),k=o-g*65536,o=F+g+65535,g=Math.floor(o/65536),F=o-g*65536,o=Y+g+65535,g=Math.floor(o/65536),Y=o-g*65536,o=W+g+65535,g=Math.floor(o/65536),W=o-g*65536,o=Ce+g+65535,g=Math.floor(o/65536),Ce=o-g*65536,o=z+g+65535,g=Math.floor(o/65536),z=o-g*65536,o=re+g+65535,g=Math.floor(o/65536),re=o-g*65536,o=se+g+65535,g=Math.floor(o/65536),se=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=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=ne+g+65535,g=Math.floor(o/65536),ne=o-g*65536,o=K+g+65535,g=Math.floor(o/65536),K=o-g*65536,v+=g-1+37*(g-1),f[0]=v,f[1]=w,f[2]=k,f[3]=F,f[4]=Y,f[5]=W,f[6]=Ce,f[7]=z,f[8]=re,f[9]=se,f[10]=le,f[11]=fe,f[12]=ie,f[13]=oe,f[14]=ne,f[15]=K}function U(f,h){E(f,h,h)}function ue(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=253;o>=0;o--)U(l,l),o!==2&&o!==4&&E(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function Ve(f,h){var l=e(),o;for(o=0;o<16;o++)l[o]=h[o];for(o=250;o>=0;o--)U(l,l),o!==1&&E(l,l,h);for(o=0;o<16;o++)f[o]=l[o]}function ct(f,h,l){var o=new Uint8Array(32),g=new Float64Array(80),v,w,k=e(),F=e(),Y=e(),W=e(),Ce=e(),z=e();for(w=0;w<31;w++)o[w]=h[w];for(o[31]=h[31]&127|64,o[0]&=248,vt(g,l),w=0;w<16;w++)F[w]=g[w],W[w]=k[w]=Y[w]=0;for(k[0]=W[0]=1,w=254;w>=0;--w)v=o[w>>>3]>>>(w&7)&1,De(k,F,v),De(Y,W,v),L(Ce,k,Y),j(k,k,Y),L(Y,F,W),j(F,F,W),U(W,Ce),U(z,k),E(k,Y,k),E(Y,F,Ce),L(Ce,k,Y),j(k,k,Y),U(F,k),j(Y,W,z),E(k,Y,c),L(k,k,W),E(Y,Y,k),E(k,W,z),E(W,F,g),U(F,Ce),De(k,F,v),De(Y,W,v);for(w=0;w<16;w++)g[w+16]=k[w],g[w+32]=Y[w],g[w+48]=F[w],g[w+64]=W[w];var re=g.subarray(32),se=g.subarray(16);return ue(re,re),E(se,se,re),Te(f,se),0}function Et(f,h){return ct(f,h,i)}function wt(f,h){return t(h,32),Et(f,h)}function or(f,h,l){var o=new Uint8Array(32);return ct(o,l,h),B(f,s,o,te)}var Tr=ee,zr=Je;function Cr(f,h,l,o,g,v){var w=new Uint8Array(32);return or(w,g,v),Tr(f,h,l,o,w)}function gs(f,h,l,o,g,v){var w=new Uint8Array(32);return or(w,g,v),zr(f,h,l,o,w)}var Ii=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function sf(f,h,l,o){for(var g=new Int32Array(16),v=new Int32Array(16),w,k,F,Y,W,Ce,z,re,se,le,fe,ie,oe,ne,K,J,H,$,G,q,x,S,I,O,R,M,Z=f[0],he=f[1],ge=f[2],de=f[3],_=f[4],ye=f[5],Oe=f[6],ke=f[7],me=h[0],be=h[1],xe=h[2],Xe=h[3],Pe=h[4],$e=h[5],Ge=h[6],Ye=h[7],et=0;o>=128;){for(G=0;G<16;G++)q=8*G+et,g[G]=l[q+0]<<24|l[q+1]<<16|l[q+2]<<8|l[q+3],v[G]=l[q+4]<<24|l[q+5]<<16|l[q+6]<<8|l[q+7];for(G=0;G<80;G++)if(w=Z,k=he,F=ge,Y=de,W=_,Ce=ye,z=Oe,re=ke,se=me,le=be,fe=xe,ie=Xe,oe=Pe,ne=$e,K=Ge,J=Ye,x=ke,S=Ye,I=S&65535,O=S>>>16,R=x&65535,M=x>>>16,x=(_>>>14|Pe<<18)^(_>>>18|Pe<<14)^(Pe>>>9|_<<23),S=(Pe>>>14|_<<18)^(Pe>>>18|_<<14)^(_>>>9|Pe<<23),I+=S&65535,O+=S>>>16,R+=x&65535,M+=x>>>16,x=_&ye^~_&Oe,S=Pe&$e^~Pe&Ge,I+=S&65535,O+=S>>>16,R+=x&65535,M+=x>>>16,x=Ii[G*2],S=Ii[G*2+1],I+=S&65535,O+=S>>>16,R+=x&65535,M+=x>>>16,x=g[G%16],S=v[G%16],I+=S&65535,O+=S>>>16,R+=x&65535,M+=x>>>16,O+=I>>>16,R+=O>>>16,M+=R>>>16,H=R&65535|M<<16,$=I&65535|O<<16,x=H,S=$,I=S&65535,O=S>>>16,R=x&65535,M=x>>>16,x=(Z>>>28|me<<4)^(me>>>2|Z<<30)^(me>>>7|Z<<25),S=(me>>>28|Z<<4)^(Z>>>2|me<<30)^(Z>>>7|me<<25),I+=S&65535,O+=S>>>16,R+=x&65535,M+=x>>>16,x=Z&he^Z&ge^he&ge,S=me&be^me&xe^be&xe,I+=S&65535,O+=S>>>16,R+=x&65535,M+=x>>>16,O+=I>>>16,R+=O>>>16,M+=R>>>16,re=R&65535|M<<16,J=I&65535|O<<16,x=Y,S=ie,I=S&65535,O=S>>>16,R=x&65535,M=x>>>16,x=H,S=$,I+=S&65535,O+=S>>>16,R+=x&65535,M+=x>>>16,O+=I>>>16,R+=O>>>16,M+=R>>>16,Y=R&65535|M<<16,ie=I&65535|O<<16,he=w,ge=k,de=F,_=Y,ye=W,Oe=Ce,ke=z,Z=re,be=se,xe=le,Xe=fe,Pe=ie,$e=oe,Ge=ne,Ye=K,me=J,G%16===15)for(q=0;q<16;q++)x=g[q],S=v[q],I=S&65535,O=S>>>16,R=x&65535,M=x>>>16,x=g[(q+9)%16],S=v[(q+9)%16],I+=S&65535,O+=S>>>16,R+=x&65535,M+=x>>>16,H=g[(q+1)%16],$=v[(q+1)%16],x=(H>>>1|$<<31)^(H>>>8|$<<24)^H>>>7,S=($>>>1|H<<31)^($>>>8|H<<24)^($>>>7|H<<25),I+=S&65535,O+=S>>>16,R+=x&65535,M+=x>>>16,H=g[(q+14)%16],$=v[(q+14)%16],x=(H>>>19|$<<13)^($>>>29|H<<3)^H>>>6,S=($>>>19|H<<13)^(H>>>29|$<<3)^($>>>6|H<<26),I+=S&65535,O+=S>>>16,R+=x&65535,M+=x>>>16,O+=I>>>16,R+=O>>>16,M+=R>>>16,g[q]=R&65535|M<<16,v[q]=I&65535|O<<16;x=Z,S=me,I=S&65535,O=S>>>16,R=x&65535,M=x>>>16,x=f[0],S=h[0],I+=S&65535,O+=S>>>16,R+=x&65535,M+=x>>>16,O+=I>>>16,R+=O>>>16,M+=R>>>16,f[0]=Z=R&65535|M<<16,h[0]=me=I&65535|O<<16,x=he,S=be,I=S&65535,O=S>>>16,R=x&65535,M=x>>>16,x=f[1],S=h[1],I+=S&65535,O+=S>>>16,R+=x&65535,M+=x>>>16,O+=I>>>16,R+=O>>>16,M+=R>>>16,f[1]=he=R&65535|M<<16,h[1]=be=I&65535|O<<16,x=ge,S=xe,I=S&65535,O=S>>>16,R=x&65535,M=x>>>16,x=f[2],S=h[2],I+=S&65535,O+=S>>>16,R+=x&65535,M+=x>>>16,O+=I>>>16,R+=O>>>16,M+=R>>>16,f[2]=ge=R&65535|M<<16,h[2]=xe=I&65535|O<<16,x=de,S=Xe,I=S&65535,O=S>>>16,R=x&65535,M=x>>>16,x=f[3],S=h[3],I+=S&65535,O+=S>>>16,R+=x&65535,M+=x>>>16,O+=I>>>16,R+=O>>>16,M+=R>>>16,f[3]=de=R&65535|M<<16,h[3]=Xe=I&65535|O<<16,x=_,S=Pe,I=S&65535,O=S>>>16,R=x&65535,M=x>>>16,x=f[4],S=h[4],I+=S&65535,O+=S>>>16,R+=x&65535,M+=x>>>16,O+=I>>>16,R+=O>>>16,M+=R>>>16,f[4]=_=R&65535|M<<16,h[4]=Pe=I&65535|O<<16,x=ye,S=$e,I=S&65535,O=S>>>16,R=x&65535,M=x>>>16,x=f[5],S=h[5],I+=S&65535,O+=S>>>16,R+=x&65535,M+=x>>>16,O+=I>>>16,R+=O>>>16,M+=R>>>16,f[5]=ye=R&65535|M<<16,h[5]=$e=I&65535|O<<16,x=Oe,S=Ge,I=S&65535,O=S>>>16,R=x&65535,M=x>>>16,x=f[6],S=h[6],I+=S&65535,O+=S>>>16,R+=x&65535,M+=x>>>16,O+=I>>>16,R+=O>>>16,M+=R>>>16,f[6]=Oe=R&65535|M<<16,h[6]=Ge=I&65535|O<<16,x=ke,S=Ye,I=S&65535,O=S>>>16,R=x&65535,M=x>>>16,x=f[7],S=h[7],I+=S&65535,O+=S>>>16,R+=x&65535,M+=x>>>16,O+=I>>>16,R+=O>>>16,M+=R>>>16,f[7]=ke=R&65535|M<<16,h[7]=Ye=I&65535|O<<16,et+=128,o-=128}return o}function Kr(f,h,l){var o=new Int32Array(8),g=new Int32Array(8),v=new Uint8Array(256),w,k=l;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,g[0]=4089235720,g[1]=2227873595,g[2]=4271175723,g[3]=1595750129,g[4]=2917565137,g[5]=725511199,g[6]=4215389547,g[7]=327033209,sf(o,g,h,l),l%=128,w=0;w<l;w++)v[w]=h[k-l+w];for(v[l]=128,l=256-128*(l<112?1:0),v[l-9]=0,b(v,l-8,k/536870912|0,k<<3),sf(o,g,v,l),w=0;w<8;w++)b(f,8*w,o[w],g[w]);return 0}function Li(f,h){var l=e(),o=e(),g=e(),v=e(),w=e(),k=e(),F=e(),Y=e(),W=e();j(l,f[1],f[0]),j(W,h[1],h[0]),E(l,l,W),L(o,f[0],f[1]),L(W,h[0],h[1]),E(o,o,W),E(g,f[3],h[3]),E(g,g,d),E(v,f[2],h[2]),L(v,v,v),j(w,o,l),j(k,v,g),L(F,v,g),L(Y,o,l),E(f[0],w,k),E(f[1],Y,F),E(f[2],F,k),E(f[3],w,Y)}function nf(f,h,l){var o;for(o=0;o<4;o++)De(f[o],h[o],l)}function yo(f,h){var l=e(),o=e(),g=e();ue(g,h[2]),E(l,h[0],g),E(o,h[1],g),Te(f,o),f[31]^=He(l)<<7}function vo(f,h,l){var o,g;for(We(f[0],n),We(f[1],a),We(f[2],a),We(f[3],n),g=255;g>=0;--g)o=l[g/8|0]>>(g&7)&1,nf(f,h,o),Li(h,f),Li(f,f),nf(f,h,o)}function Ni(f,h){var l=[e(),e(),e(),e()];We(l[0],p),We(l[1],m),We(l[2],a),E(l[3],p,m),vo(f,l,h)}function Eo(f,h,l){var o=new Uint8Array(64),g=[e(),e(),e(),e()],v;for(l||t(h,32),Kr(o,h,32),o[0]&=248,o[31]&=127,o[31]|=64,Ni(g,o),yo(f,g),v=0;v<32;v++)h[v+32]=f[v];return 0}var Mi=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 wo(f,h){var l,o,g,v;for(o=63;o>=32;--o){for(l=0,g=o-32,v=o-12;g<v;++g)h[g]+=l-16*h[o]*Mi[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)*Mi[g],l=h[g]>>8,h[g]&=255;for(g=0;g<32;g++)h[g]-=l*Mi[g];for(o=0;o<32;o++)h[o+1]+=h[o]>>8,f[o]=h[o]&255}function bo(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;wo(f,h)}function of(f,h,l,o){var g=new Uint8Array(64),v=new Uint8Array(64),w=new Uint8Array(64),k,F,Y=new Float64Array(64),W=[e(),e(),e(),e()];Kr(g,o,32),g[0]&=248,g[31]&=127,g[31]|=64;var Ce=l+64;for(k=0;k<l;k++)f[64+k]=h[k];for(k=0;k<32;k++)f[32+k]=g[32+k];for(Kr(w,f.subarray(32),l+32),bo(w),Ni(W,w),yo(f,W),k=32;k<64;k++)f[k]=o[k];for(Kr(v,f,l+64),bo(v),k=0;k<64;k++)Y[k]=0;for(k=0;k<32;k++)Y[k]=w[k];for(k=0;k<32;k++)for(F=0;F<32;F++)Y[k+F]+=v[k]*g[F];return wo(f.subarray(32),Y),Ce}function zd(f,h){var l=e(),o=e(),g=e(),v=e(),w=e(),k=e(),F=e();return We(f[2],a),vt(f[1],h),U(g,f[1]),E(v,g,u),j(g,g,f[2]),L(v,f[2],v),U(w,v),U(k,w),E(F,k,w),E(l,F,g),E(l,l,v),Ve(l,l),E(l,l,g),E(l,l,v),E(l,l,v),E(f[0],l,v),U(o,f[0]),E(o,o,v),ot(o,g)&&E(f[0],f[0],y),U(o,f[0]),E(o,o,v),ot(o,g)?-1:(He(f[0])===h[31]>>7&&j(f[0],n,f[0]),E(f[3],f[0],f[1]),0)}function xo(f,h,l,o){var g,v=new Uint8Array(32),w=new Uint8Array(64),k=[e(),e(),e(),e()],F=[e(),e(),e(),e()];if(l<64||zd(F,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(Kr(w,f,l),bo(w),vo(k,F,w),Ni(F,h.subarray(32)),Li(k,F),yo(v,k),l-=64,V(h,0,v,0)){for(g=0;g<l;g++)f[g]=0;return-1}for(g=0;g<l;g++)f[g]=h[g+64];return l}var So=32,Di=24,Xs=32,ms=16,Js=32,Fi=32,Zs=32,Qs=32,To=32,af=Di,Kd=Xs,$d=ms,ar=64,$r=32,_s=64,Co=32,Oo=64;r.lowlevel={crypto_core_hsalsa20:B,crypto_stream_xor:Q,crypto_stream:pe,crypto_stream_salsa20_xor:A,crypto_stream_salsa20:ae,crypto_onetimeauth:ve,crypto_onetimeauth_verify:Ke,crypto_verify_16:C,crypto_verify_32:V,crypto_secretbox:ee,crypto_secretbox_open:Je,crypto_scalarmult:ct,crypto_scalarmult_base:Et,crypto_box_beforenm:or,crypto_box_afternm:Tr,crypto_box:Cr,crypto_box_open:gs,crypto_box_keypair:wt,crypto_hash:Kr,crypto_sign:of,crypto_sign_keypair:Eo,crypto_sign_open:xo,crypto_secretbox_KEYBYTES:So,crypto_secretbox_NONCEBYTES:Di,crypto_secretbox_ZEROBYTES:Xs,crypto_secretbox_BOXZEROBYTES:ms,crypto_scalarmult_BYTES:Js,crypto_scalarmult_SCALARBYTES:Fi,crypto_box_PUBLICKEYBYTES:Zs,crypto_box_SECRETKEYBYTES:Qs,crypto_box_BEFORENMBYTES:To,crypto_box_NONCEBYTES:af,crypto_box_ZEROBYTES:Kd,crypto_box_BOXZEROBYTES:$d,crypto_sign_BYTES:ar,crypto_sign_PUBLICKEYBYTES:$r,crypto_sign_SECRETKEYBYTES:_s,crypto_sign_SEEDBYTES:Co,crypto_hash_BYTES:Oo,gf:e,D:u,L:Mi,pack25519:Te,unpack25519:vt,M:E,A:L,S:U,Z:j,pow2523:Ve,add:Li,set25519:We,modL:wo,scalarmult:vo,scalarbase:Ni};function cf(f,h){if(f.length!==So)throw new Error("bad key size");if(h.length!==Di)throw new Error("bad nonce size")}function Gd(f,h){if(f.length!==Zs)throw new Error("bad public key size");if(h.length!==Qs)throw new Error("bad secret key size")}function bt(){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 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){bt(f,h,l),cf(l,h);for(var o=new Uint8Array(Xs+f.length),g=new Uint8Array(o.length),v=0;v<f.length;v++)o[v+Xs]=f[v];return ee(g,o,o.length,h,l),g.subarray(ms)},r.secretbox.open=function(f,h,l){bt(f,h,l),cf(l,h);for(var o=new Uint8Array(ms+f.length),g=new Uint8Array(o.length),v=0;v<f.length;v++)o[v+ms]=f[v];return o.length<32||Je(g,o,o.length,h,l)!==0?null:g.subarray(Xs)},r.secretbox.keyLength=So,r.secretbox.nonceLength=Di,r.secretbox.overheadLength=ms,r.scalarMult=function(f,h){if(bt(f,h),f.length!==Fi)throw new Error("bad n size");if(h.length!==Js)throw new Error("bad p size");var l=new Uint8Array(Js);return ct(l,f,h),l},r.scalarMult.base=function(f){if(bt(f),f.length!==Fi)throw new Error("bad n size");var h=new Uint8Array(Js);return Et(h,f),h},r.scalarMult.scalarLength=Fi,r.scalarMult.groupElementLength=Js,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){bt(f,h),Gd(f,h);var l=new Uint8Array(To);return or(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(Zs),h=new Uint8Array(Qs);return wt(f,h),{publicKey:f,secretKey:h}},r.box.keyPair.fromSecretKey=function(f){if(bt(f),f.length!==Qs)throw new Error("bad secret key size");var h=new Uint8Array(Zs);return Et(h,f),{publicKey:h,secretKey:new Uint8Array(f)}},r.box.publicKeyLength=Zs,r.box.secretKeyLength=Qs,r.box.sharedKeyLength=To,r.box.nonceLength=af,r.box.overheadLength=r.secretbox.overheadLength,r.sign=function(f,h){if(bt(f,h),h.length!==_s)throw new Error("bad secret key size");var l=new Uint8Array(ar+f.length);return of(l,f,f.length,h),l},r.sign.open=function(f,h){if(bt(f,h),h.length!==$r)throw new Error("bad public key size");var l=new Uint8Array(f.length),o=xo(l,f,f.length,h);if(o<0)return null;for(var g=new Uint8Array(o),v=0;v<g.length;v++)g[v]=l[v];return g},r.sign.detached=function(f,h){for(var l=r.sign(f,h),o=new Uint8Array(ar),g=0;g<o.length;g++)o[g]=l[g];return o},r.sign.detached.verify=function(f,h,l){if(bt(f,h,l),h.length!==ar)throw new Error("bad signature size");if(l.length!==$r)throw new Error("bad public key size");var o=new Uint8Array(ar+f.length),g=new Uint8Array(ar+f.length),v;for(v=0;v<ar;v++)o[v]=h[v];for(v=0;v<f.length;v++)o[v+ar]=f[v];return xo(g,o,o.length,l)>=0},r.sign.keyPair=function(){var f=new Uint8Array($r),h=new Uint8Array(_s);return Eo(f,h),{publicKey:f,secretKey:h}},r.sign.keyPair.fromSecretKey=function(f){if(bt(f),f.length!==_s)throw new Error("bad secret key size");for(var h=new Uint8Array($r),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(bt(f),f.length!==Co)throw new Error("bad seed size");for(var h=new Uint8Array($r),l=new Uint8Array(_s),o=0;o<32;o++)l[o]=f[o];return Eo(h,l,!0),{publicKey:h,secretKey:l}},r.sign.publicKeyLength=$r,r.sign.secretKeyLength=_s,r.sign.seedLength=Co,r.sign.signatureLength=ar,r.hash=function(f){bt(f);var h=new Uint8Array(Oo);return Kr(h,f,f.length),h},r.hash.hashLength=Oo,r.verify=function(f,h){return bt(f,h),f.length===0||h.length===0||f.length!==h.length?!1:T(f,0,h,0,f.length)===0},r.setPRNG=function(f){t=f},(function(){var f=typeof self<"u"?self.crypto||self.msCrypto:null;if(f&&f.getRandomValues){var h=65536;r.setPRNG(function(l,o){var g,v=new Uint8Array(o);for(g=0;g<o;g+=h)f.getRandomValues(v.subarray(g,g+Math.min(o-g,h)));for(g=0;g<o;g++)l[g]=v[g];ff(v)})}else typeof require<"u"&&(f=require("crypto"),f&&f.randomBytes&&r.setPRNG(function(l,o){var g,v=f.randomBytes(o);for(g=0;g<o;g++)l[g]=v[g];ff(v)}))})()})(typeof Yi<"u"&&Yi.exports?Yi.exports:self.nacl=self.nacl||{})});var Lo=D((Rf,Xi)=>{(function(r,e){"use strict";typeof Xi<"u"&&Xi.exports?Xi.exports=e():(r.nacl||(r.nacl={}),r.nacl.util=e())})(Rf,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 s,i=unescape(encodeURIComponent(t)),n=new Uint8Array(i.length);for(s=0;s<i.length;s++)n[s]=i.charCodeAt(s);return n},r.encodeUTF8=function(t){var s,i=[];for(s=0;s<t.length;s++)i.push(String.fromCharCode(t[s]));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 s,i=[],n=t.length;for(s=0;s<n;s++)i.push(String.fromCharCode(t[s]));return btoa(i.join(""))},r.decodeBase64=function(t){e(t);var s,i=atob(t),n=new Uint8Array(i.length);for(s=0;s<i.length;s++)n[s]=i.charCodeAt(s);return n}),r})});var Af=D(Rr=>{"use strict";var mp=Rr&&Rr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Rr,"__esModule",{value:!0});Rr.encrypt=_p;Rr.decrypt=yp;Rr.encryptBinary=vp;Rr.decryptBinary=Ep;var ur=mp(Io()),kr=Lo();function _p(r,e,t){let s=ur.default.randomBytes(ur.default.secretbox.nonceLength),i=new TextEncoder().encode(r),n=ur.default.secretbox(i,s,e);return{v:1,sid:t,n:(0,kr.encodeBase64)(s),c:(0,kr.encodeBase64)(n)}}function yp(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,kr.decodeBase64)(r.n),s=(0,kr.decodeBase64)(r.c);if(t.length!==ur.default.secretbox.nonceLength)throw new Error(`Invalid nonce length: ${t.length}`);let i=ur.default.secretbox.open(s,t,e);if(!i)throw new Error("Decryption failed: invalid ciphertext or wrong key");return new TextDecoder().decode(i)}function vp(r,e,t){let s=ur.default.randomBytes(ur.default.secretbox.nonceLength),i=ur.default.secretbox(r,s,e);return{v:1,sid:t,n:(0,kr.encodeBase64)(s),c:(0,kr.encodeBase64)(i)}}function Ep(r,e){if(r.v!==1)throw new Error(`Unsupported encryption version: ${r.v}`);let t=(0,kr.decodeBase64)(r.n),s=(0,kr.decodeBase64)(r.c),i=ur.default.secretbox.open(s,t,e);if(!i)throw new Error("Decryption failed: invalid ciphertext or wrong key");return i}});var Pf=D(Bt=>{"use strict";var wp=Bt&&Bt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Bt,"__esModule",{value:!0});Bt.generateKeyPair=bp;Bt.deriveSharedSecret=xp;Bt.deriveMetaSid=Sp;Bt.isValidPublicKey=Tp;Bt.clearKey=Cp;Bt.keyToBase64=Op;Bt.base64ToKey=kp;var vs=wp(Io()),$t=Lo();function bp(){let r=vs.default.box.keyPair();return{publicKey:(0,$t.encodeBase64)(r.publicKey),secretKey:(0,$t.encodeBase64)(r.secretKey)}}function xp(r,e){let t=(0,$t.decodeBase64)(r),s=(0,$t.decodeBase64)(e);if(t.length!==vs.default.box.publicKeyLength)throw new Error(`Invalid public key length: ${t.length}`);if(s.length!==vs.default.box.secretKeyLength)throw new Error(`Invalid secret key length: ${s.length}`);return vs.default.box.before(t,s)}function Sp(r,e){let t=new TextEncoder().encode("termiq-meta-v1"),s=(0,$t.decodeBase64)(r),i=(0,$t.decodeBase64)(e),n=new Uint8Array(t.length+s.length+i.length);return n.set(t,0),n.set(s,t.length),n.set(i,t.length+s.length),(0,$t.encodeBase64)(vs.default.hash(n).slice(0,32))}function Tp(r){try{return(0,$t.decodeBase64)(r).length===vs.default.box.publicKeyLength}catch{return!1}}function Cp(r){r.fill(0)}function Op(r){return(0,$t.encodeBase64)(r)}function kp(r){return(0,$t.decodeBase64)(r)}});var Lf=D(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.base64ToKey=Ie.keyToBase64=Ie.clearKey=Ie.isValidPublicKey=Ie.deriveMetaSid=Ie.deriveSharedSecret=Ie.generateKeyPair=Ie.decryptBinary=Ie.encryptBinary=Ie.decrypt=Ie.encrypt=Ie.isMultiRecipientPayload=Ie.isEncryptedPayload=void 0;var If=kf();Object.defineProperty(Ie,"isEncryptedPayload",{enumerable:!0,get:function(){return If.isEncryptedPayload}});Object.defineProperty(Ie,"isMultiRecipientPayload",{enumerable:!0,get:function(){return If.isMultiRecipientPayload}});var Ji=Af();Object.defineProperty(Ie,"encrypt",{enumerable:!0,get:function(){return Ji.encrypt}});Object.defineProperty(Ie,"decrypt",{enumerable:!0,get:function(){return Ji.decrypt}});Object.defineProperty(Ie,"encryptBinary",{enumerable:!0,get:function(){return Ji.encryptBinary}});Object.defineProperty(Ie,"decryptBinary",{enumerable:!0,get:function(){return Ji.decryptBinary}});var Gr=Pf();Object.defineProperty(Ie,"generateKeyPair",{enumerable:!0,get:function(){return Gr.generateKeyPair}});Object.defineProperty(Ie,"deriveSharedSecret",{enumerable:!0,get:function(){return Gr.deriveSharedSecret}});Object.defineProperty(Ie,"deriveMetaSid",{enumerable:!0,get:function(){return Gr.deriveMetaSid}});Object.defineProperty(Ie,"isValidPublicKey",{enumerable:!0,get:function(){return Gr.isValidPublicKey}});Object.defineProperty(Ie,"clearKey",{enumerable:!0,get:function(){return Gr.clearKey}});Object.defineProperty(Ie,"keyToBase64",{enumerable:!0,get:function(){return Gr.keyToBase64}});Object.defineProperty(Ie,"base64ToKey",{enumerable:!0,get:function(){return Gr.base64ToKey}})});var Nf=D(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.MIN_CLIENT_VERSION=xt.PROTOCOL_VERSION_MINOR=xt.PROTOCOL_VERSION_MAJOR=xt.PROTOCOL_VERSION=void 0;xt.isCompatibleVersion=Rp;xt.compareVersions=Ap;xt.PROTOCOL_VERSION="2.1";xt.PROTOCOL_VERSION_MAJOR=2;xt.PROTOCOL_VERSION_MINOR=1;xt.MIN_CLIENT_VERSION="2.0";function Rp(r){let[e]=r.split(".").map(Number);return e===xt.PROTOCOL_VERSION_MAJOR}function Ap(r,e){let[t,s]=r.split(".").map(Number),[i,n]=e.split(".").map(Number);return t!==i?t<i?-1:1:s!==n?s<n?-1:1:0}});var Mf=D(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.SERVER_CAPABILITIES=Gt.DEFAULT_CLIENT_CAPABILITIES=Gt.Capability=void 0;Gt.hasCapability=Pp;Gt.negotiateCapabilities=Ip;var Es;(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"})(Es||(Gt.Capability=Es={}));Gt.DEFAULT_CLIENT_CAPABILITIES=[Es.E2E_ENCRYPTION,Es.TERMINAL_EVENTS,Es.RELIABLE_INPUT];Gt.SERVER_CAPABILITIES=Object.values(Es);function Pp(r,e){return r.includes(e)}function Ip(r,e){return r.filter(t=>e.includes(t))}});var Df=D(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.DEFAULT_PRIORITY=lr.PRIORITY_NAMES=lr.Priority=void 0;lr.comparePriority=Lp;var Yr;(function(r){r[r.CRITICAL=0]="CRITICAL",r[r.HIGH=1]="HIGH",r[r.NORMAL=2]="NORMAL",r[r.LOW=3]="LOW"})(Yr||(lr.Priority=Yr={}));lr.PRIORITY_NAMES={[Yr.CRITICAL]:"CRITICAL",[Yr.HIGH]:"HIGH",[Yr.NORMAL]:"NORMAL",[Yr.LOW]:"LOW"};lr.DEFAULT_PRIORITY=Yr.NORMAL;function Lp(r,e){return r-e}});var Ff=D(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.DEFAULT_RELIABILITY=Yt.RELIABILITY_NAMES=Yt.Reliability=void 0;Yt.requiresAck=Np;Yt.requiresBuffer=Mp;var Ar;(function(r){r[r.FIRE_FORGET=0]="FIRE_FORGET",r[r.BUFFERED=1]="BUFFERED",r[r.GUARANTEED=2]="GUARANTEED"})(Ar||(Yt.Reliability=Ar={}));Yt.RELIABILITY_NAMES={[Ar.FIRE_FORGET]:"FIRE_FORGET",[Ar.BUFFERED]:"BUFFERED",[Ar.GUARANTEED]:"GUARANTEED"};Yt.DEFAULT_RELIABILITY=Ar.FIRE_FORGET;function Np(r){return r===Ar.GUARANTEED}function Mp(r){return r>=Ar.BUFFERED}});var Bf=D(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.createMessage=Dp;function Dp(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 jf=D(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.TerminalEventType=void 0;Xr.deriveStatusFromEvent=Fp;Xr.shouldTriggerPushNotification=Bp;Xr.getPushNotificationMessage=jp;var ht;(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"})(ht||(Xr.TerminalEventType=ht={}));function Fp(r){switch(r.type){case ht.SESSION_START:case ht.TOOL_START:case ht.MESSAGE:return"working";case ht.WAITING_INPUT:return"waiting";case ht.SESSION_END:return r.status==="success"?"completed":"error";case ht.ERROR:return r.severity==="fatal"?"error":"working";case ht.TOOL_END:return r.status==="error"?"error":"working";default:return"idle"}}function Bp(r){switch(r.type){case ht.WAITING_INPUT:return!0;case ht.SESSION_END:return!0;case ht.ERROR:return r.severity!=="warning";default:return!1}}function jp(r,e){switch(r.type){case ht.WAITING_INPUT:return{title:`${e}: Input Required`,body:r.question.slice(0,100)};case ht.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 ht.ERROR:{let t=r;return t.severity==="warning"?null:{title:`${e}: Error`,body:t.message.slice(0,100)}}default:return null}}});var Wf=D(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.TransferDirection=je.TransferStatus=je.CHUNK_TTL_SECONDS=je.TRANSFER_TTL_SECONDS=je.MAX_RETRIES=je.ACK_TIMEOUT_MS=je.WINDOW_SIZE=je.DEFAULT_MAX_FILE_SIZE=je.CHUNK_SIZE=void 0;je.calculateTotalChunks=Up;je.getMissingChunks=qp;je.isTransferComplete=Wp;je.CHUNK_SIZE=64*1024;je.DEFAULT_MAX_FILE_SIZE=100*1024*1024;je.WINDOW_SIZE=10;je.ACK_TIMEOUT_MS=3e4;je.MAX_RETRIES=3;je.TRANSFER_TTL_SECONDS=1440*60;je.CHUNK_TTL_SECONDS=1440*60;var Uf;(function(r){r.PENDING="pending",r.ACTIVE="active",r.PAUSED="paused",r.COMPLETED="completed",r.FAILED="failed",r.CANCELLED="cancelled",r.EXPIRED="expired"})(Uf||(je.TransferStatus=Uf={}));var qf;(function(r){r.DOWNLOAD="download",r.UPLOAD="upload"})(qf||(je.TransferDirection=qf={}));function Up(r,e=je.CHUNK_SIZE){return Math.ceil(r/e)}function qp(r,e){let t=new Set(e),s=[];for(let i=0;i<r;i++)t.has(i)||s.push(i);return s}function Wp(r,e){return e.length===r}});var Hf=D(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.ERROR_MESSAGES=hr.ErrorCode=void 0;hr.createError=Hp;hr.isRetryableError=Vp;var Re;(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"})(Re||(hr.ErrorCode=Re={}));hr.ERROR_MESSAGES={[Re.AUTH_FAILED]:"Authentication failed",[Re.TOKEN_EXPIRED]:"Token expired",[Re.TOKEN_INVALID]:"Invalid token",[Re.NOT_FOUND]:"Resource not found",[Re.ALREADY_EXISTS]:"Resource already exists",[Re.ACCESS_DENIED]:"Access denied",[Re.FORBIDDEN]:"Operation forbidden",[Re.RATE_LIMITED]:"Rate limit exceeded",[Re.TOO_MANY_CONNECTIONS]:"Too many connections",[Re.QUOTA_EXCEEDED]:"Plan quota exceeded",[Re.FILE_TOO_LARGE]:"File size exceeds limit",[Re.QUEUE_FULL]:"Message queue is full",[Re.TRANSFERS_LIMIT]:"Daily transfers limit reached",[Re.TRANSFER_FAILED]:"File transfer failed",[Re.TRANSFER_EXPIRED]:"Transfer expired",[Re.TRANSFER_CANCELLED]:"Transfer cancelled",[Re.CHECKSUM_MISMATCH]:"File checksum mismatch",[Re.CHUNK_MISSING]:"Chunk missing or corrupted",[Re.INVALID_MESSAGE]:"Invalid message format",[Re.UNSUPPORTED_VERSION]:"Unsupported protocol version",[Re.CAPABILITY_REQUIRED]:"Required capability not supported",[Re.INVALID_STATE]:"Invalid state for this operation",[Re.TIMEOUT]:"Operation timed out",[Re.CONNECTION_LOST]:"Connection lost",[Re.INTERNAL_ERROR]:"Internal server error",[Re.SERVICE_UNAVAILABLE]:"Service temporarily unavailable"};function Hp(r,e={}){return{code:r,message:e.message||hr.ERROR_MESSAGES[r],details:e.details,retryable:e.retryable??!1,retryAfter:e.retryAfter}}function Vp(r){return[Re.RATE_LIMITED,Re.TIMEOUT,Re.CONNECTION_LOST,Re.SERVICE_UNAVAILABLE].includes(r)}});var $f=D(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.FileEntryType=St.DiffBase=St.FileViewType=St.FileChangeType=void 0;St.getLanguageFromPath=zp;St.parseUnifiedDiff=Kp;St.createSimpleDiff=$p;var Pr;(function(r){r.CREATE="create",r.MODIFY="modify",r.DELETE="delete"})(Pr||(St.FileChangeType=Pr={}));var Vf;(function(r){r.CONTENT="content",r.DIFF="diff"})(Vf||(St.FileViewType=Vf={}));var zf;(function(r){r.GIT="git",r.PREVIOUS="previous"})(zf||(St.DiffBase=zf={}));function zp(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"},s=r.split("/").pop()?.toLowerCase()||"";return{dockerfile:"dockerfile",makefile:"makefile",".gitignore":"plaintext",".env":"plaintext",".env.local":"plaintext",".env.development":"plaintext",".env.production":"plaintext"}[s]||t[e||""]||"plaintext"}function Kp(r,e){let t=r.split(`
|
|
3
|
+
`),s=[],i=0,n=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&&s.push(a);let y=parseInt(m[1],10),b=parseInt(m[2]||"1",10),T=parseInt(m[3],10),C=parseInt(m[4]||"1",10);a={oldStart:y,oldLines:b,newStart:T,newLines:C,lines:[]},c=y,u=T;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}),n++):(p.startsWith(" ")||p==="")&&a.lines.push({type:"context",content:p.startsWith(" ")?p.slice(1):p,oldLineNumber:c++,newLineNumber:u++}))}a&&s.push(a);let d;return n===0&&i>0&&s.length===1&&s[0].oldLines===0?d=Pr.CREATE:i===0&&n>0&&s.length===1&&s[0].newLines===0?d=Pr.DELETE:d=Pr.MODIFY,{path:e,changeType:d,hunks:s,additions:i,deletions:n,isBinary:!1}}function $p(r,e,t){let s=r.split(`
|
|
4
|
+
`),i=e.split(`
|
|
5
|
+
`),n=[],a=0,c=0,u=Math.max(s.length,i.length);for(let p=0;p<u;p++){let m=s[p],y=i[p];m===y?m!==void 0&&n.push({type:"context",content:m,oldLineNumber:p+1,newLineNumber:p+1}):(m!==void 0&&(n.push({type:"remove",content:m,oldLineNumber:p+1,newLineNumber:null}),c++),y!==void 0&&(n.push({type:"add",content:y,oldLineNumber:null,newLineNumber:p+1}),a++))}let d;return r===""?d=Pr.CREATE:e===""?d=Pr.DELETE:d=Pr.MODIFY,{path:t,changeType:d,hunks:[{oldStart:1,oldLines:s.length,newStart:1,newLines:i.length,lines:n}],additions:a,deletions:c,isBinary:!1}}var Kf;(function(r){r.FILE="file",r.DIRECTORY="directory"})(Kf||(St.FileEntryType=Kf={}))});var Gf=D(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 ws=Nf();Object.defineProperty(N,"PROTOCOL_VERSION",{enumerable:!0,get:function(){return ws.PROTOCOL_VERSION}});Object.defineProperty(N,"PROTOCOL_VERSION_MAJOR",{enumerable:!0,get:function(){return ws.PROTOCOL_VERSION_MAJOR}});Object.defineProperty(N,"PROTOCOL_VERSION_MINOR",{enumerable:!0,get:function(){return ws.PROTOCOL_VERSION_MINOR}});Object.defineProperty(N,"MIN_CLIENT_VERSION",{enumerable:!0,get:function(){return ws.MIN_CLIENT_VERSION}});Object.defineProperty(N,"isCompatibleVersion",{enumerable:!0,get:function(){return ws.isCompatibleVersion}});Object.defineProperty(N,"compareVersions",{enumerable:!0,get:function(){return ws.compareVersions}});var si=Mf();Object.defineProperty(N,"Capability",{enumerable:!0,get:function(){return si.Capability}});Object.defineProperty(N,"DEFAULT_CLIENT_CAPABILITIES",{enumerable:!0,get:function(){return si.DEFAULT_CLIENT_CAPABILITIES}});Object.defineProperty(N,"SERVER_CAPABILITIES",{enumerable:!0,get:function(){return si.SERVER_CAPABILITIES}});Object.defineProperty(N,"hasCapability",{enumerable:!0,get:function(){return si.hasCapability}});Object.defineProperty(N,"negotiateCapabilities",{enumerable:!0,get:function(){return si.negotiateCapabilities}});var Zi=Df();Object.defineProperty(N,"Priority",{enumerable:!0,get:function(){return Zi.Priority}});Object.defineProperty(N,"PRIORITY_NAMES",{enumerable:!0,get:function(){return Zi.PRIORITY_NAMES}});Object.defineProperty(N,"DEFAULT_PRIORITY",{enumerable:!0,get:function(){return Zi.DEFAULT_PRIORITY}});Object.defineProperty(N,"comparePriority",{enumerable:!0,get:function(){return Zi.comparePriority}});var ii=Ff();Object.defineProperty(N,"Reliability",{enumerable:!0,get:function(){return ii.Reliability}});Object.defineProperty(N,"RELIABILITY_NAMES",{enumerable:!0,get:function(){return ii.RELIABILITY_NAMES}});Object.defineProperty(N,"DEFAULT_RELIABILITY",{enumerable:!0,get:function(){return ii.DEFAULT_RELIABILITY}});Object.defineProperty(N,"requiresAck",{enumerable:!0,get:function(){return ii.requiresAck}});Object.defineProperty(N,"requiresBuffer",{enumerable:!0,get:function(){return ii.requiresBuffer}});var Gp=Bf();Object.defineProperty(N,"createMessage",{enumerable:!0,get:function(){return Gp.createMessage}});var Qi=jf();Object.defineProperty(N,"TerminalEventType",{enumerable:!0,get:function(){return Qi.TerminalEventType}});Object.defineProperty(N,"deriveStatusFromEvent",{enumerable:!0,get:function(){return Qi.deriveStatusFromEvent}});Object.defineProperty(N,"shouldTriggerPushNotification",{enumerable:!0,get:function(){return Qi.shouldTriggerPushNotification}});Object.defineProperty(N,"getPushNotificationMessage",{enumerable:!0,get:function(){return Qi.getPushNotificationMessage}});var kt=Wf();Object.defineProperty(N,"CHUNK_SIZE",{enumerable:!0,get:function(){return kt.CHUNK_SIZE}});Object.defineProperty(N,"DEFAULT_MAX_FILE_SIZE",{enumerable:!0,get:function(){return kt.DEFAULT_MAX_FILE_SIZE}});Object.defineProperty(N,"WINDOW_SIZE",{enumerable:!0,get:function(){return kt.WINDOW_SIZE}});Object.defineProperty(N,"ACK_TIMEOUT_MS",{enumerable:!0,get:function(){return kt.ACK_TIMEOUT_MS}});Object.defineProperty(N,"MAX_RETRIES",{enumerable:!0,get:function(){return kt.MAX_RETRIES}});Object.defineProperty(N,"TRANSFER_TTL_SECONDS",{enumerable:!0,get:function(){return kt.TRANSFER_TTL_SECONDS}});Object.defineProperty(N,"CHUNK_TTL_SECONDS",{enumerable:!0,get:function(){return kt.CHUNK_TTL_SECONDS}});Object.defineProperty(N,"TransferStatus",{enumerable:!0,get:function(){return kt.TransferStatus}});Object.defineProperty(N,"TransferDirection",{enumerable:!0,get:function(){return kt.TransferDirection}});Object.defineProperty(N,"calculateTotalChunks",{enumerable:!0,get:function(){return kt.calculateTotalChunks}});Object.defineProperty(N,"getMissingChunks",{enumerable:!0,get:function(){return kt.getMissingChunks}});Object.defineProperty(N,"isTransferComplete",{enumerable:!0,get:function(){return kt.isTransferComplete}});var en=Hf();Object.defineProperty(N,"ErrorCode",{enumerable:!0,get:function(){return en.ErrorCode}});Object.defineProperty(N,"ERROR_MESSAGES",{enumerable:!0,get:function(){return en.ERROR_MESSAGES}});Object.defineProperty(N,"createError",{enumerable:!0,get:function(){return en.createError}});Object.defineProperty(N,"isRetryableError",{enumerable:!0,get:function(){return en.isRetryableError}});var Jr=$f();Object.defineProperty(N,"FileChangeType",{enumerable:!0,get:function(){return Jr.FileChangeType}});Object.defineProperty(N,"FileViewType",{enumerable:!0,get:function(){return Jr.FileViewType}});Object.defineProperty(N,"DiffBase",{enumerable:!0,get:function(){return Jr.DiffBase}});Object.defineProperty(N,"FileEntryType",{enumerable:!0,get:function(){return Jr.FileEntryType}});Object.defineProperty(N,"getLanguageFromPath",{enumerable:!0,get:function(){return Jr.getLanguageFromPath}});Object.defineProperty(N,"parseUnifiedDiff",{enumerable:!0,get:function(){return Jr.parseUnifiedDiff}});Object.defineProperty(N,"createSimpleDiff",{enumerable:!0,get:function(){return Jr.createSimpleDiff}})});var dr=D(Xt=>{"use strict";var Yp=Xt&&Xt.__createBinding||(Object.create?(function(r,e,t,s){s===void 0&&(s=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,s,i)}):(function(r,e,t,s){s===void 0&&(s=t),r[s]=e[t]})),tn=Xt&&Xt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Yp(e,r,t)};Object.defineProperty(Xt,"__esModule",{value:!0});tn(Cf(),Xt);tn(Of(),Xt);tn(Lf(),Xt);tn(Gf(),Xt)});var Xf=D(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.CryptoService=void 0;var Ze=dr(),Xp=3600*1e3,Yf=10,Mo=class{storage;logger;sessions=new Map;agentSessions=new Map;metaSessions=new Map;keyPair=null;publicKeyKey;secretKeyKey;keyVersionKey;constructor(e,t,s,i){this.storage=e,this.logger=t;let n=`termiq.${s}.${i}`;this.publicKeyKey=`${n}.crypto.publicKey`,this.secretKeyKey=`${n}.crypto.secretKey`,this.keyVersionKey=`${n}.crypto.keyVersion`,this.logger.info("CryptoService namespace",s,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 identity key pair")):await this.generateIdentityKeyPair()}async generateIdentityKeyPair(){this.logger.info("Generating new identity key pair"),this.keyPair=(0,Ze.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("Identity key pair generated and stored"),this.keyPair}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 handleKeyExchange(e,t,s){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,s);try{let i=this.sessions.get(e);i||(i=new Map,this.sessions.set(e,i));let n=(0,Ze.deriveSharedSecret)(t,this.keyPair.secretKey),a={terminalId:e,clientPublicKey:t,sharedSecret:n,createdAt:Date.now(),sessionId:s};return i.set(s,a),this.logger.info("Key exchange completed",e,s,"total:",i.size),!0}catch(i){return this.logger.error("Key exchange failed",i),!1}}encryptOutput(e,t){let s=this.sessions.get(e);if(!s||s.size===0)return null;try{if(s.size===1){let n=s.values().next().value;return n?(0,Ze.encrypt)(t,n.sharedSecret,n.sessionId):null}let i=[];for(let n of s.values()){let a=(0,Ze.encrypt)(t,n.sharedSecret,n.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 s=this.sessions.get(e);if(!s)return this.logger.error("No sessions for terminal",e),null;let i=s.get(t.sid);if(!i)return this.logger.error("No session for sessionId",t.sid),null;try{return(0,Ze.decrypt)(t,i.sharedSecret)}catch(n){return this.logger.error("Decryption failed",n),null}}encryptFileChunk(e,t){let s=this.sessions.get(e);if(!s||s.size===0)return null;let i=null;for(let n of s.values())(!i||n.createdAt>i.createdAt)&&(i=n);if(!i)return null;try{return(0,Ze.encryptBinary)(t,i.sharedSecret,i.sessionId)}catch(n){return this.logger.error("File chunk encryption failed",n),null}}decryptFileChunk(e,t){let s=this.sessions.get(e)?.get(t.sid);if(!s)return this.logger.error("No session for file chunk",e,t.sid),null;try{return(0,Ze.decryptBinary)(t,s.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 s=this.sessions.get(e);if(s)if(t){let i=s.get(t);i&&((0,Ze.clearKey)(i.sharedSecret),s.delete(t),this.logger.info("Session removed",e,t)),s.size===0&&this.sessions.delete(e)}else{for(let i of s.values())(0,Ze.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,Ze.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 s=Date.now(),i=[];for(let[n,a]of t)s-a.createdAt>Xp&&i.push(n);for(let n of i){let a=t.get(n);a&&((0,Ze.clearKey)(a.sharedSecret),t.delete(n),this.logger.info("Session expired (TTL)",e,n,`age:${Math.round((s-a.createdAt)/1e3)}s`))}if(t.size>Yf){let a=Array.from(t.entries()).sort((c,u)=>c[1].createdAt-u[1].createdAt).slice(0,t.size-Yf);for(let[,c]of a)(0,Ze.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,s]of this.sessions.entries())for(let i of s.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 s=this.agentSessions.get(t);s&&(this.logger.info("Rekeying existing agent session",t),(0,Ze.clearKey)(s.sharedSecret));let i=(0,Ze.deriveSharedSecret)(e,this.keyPair.secretKey),n={sessionId:t,clientPublicKey:e,sharedSecret:i,createdAt:Date.now()};return this.agentSessions.set(t,n),this.logger.info("Agent key exchange completed",t,"total:",this.agentSessions.size),!0}catch(s){return this.logger.error("Agent key exchange failed",s),!1}}removeAgentSession(e){let t=this.agentSessions.get(e);t&&((0,Ze.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),s=(0,Ze.deriveSharedSecret)(e,this.keyPair.secretKey),i=(0,Ze.deriveMetaSid)(this.keyPair.publicKey,e);return this.metaSessions.set(e,{clientIdentityPub:e,sharedSecret:s,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 s=this.metaSessions.values().next().value;return s?(0,Ze.encrypt)(e,s.sharedSecret,s.sidMeta):null}let t=[];for(let s of this.metaSessions.values()){let i=(0,Ze.encrypt)(e,s.sharedSecret,s.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,Ze.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),this.keyPair=null,this.clearAllSessions(),this.clearAllAgentSessions(),this.logger.info("All crypto keys deleted")}};rn.CryptoService=Mo});var Jf=D(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.AuthService=void 0;var ni=zi(),Do=class{storage;cryptoService;machineId;config;logger;notification;browser;pollingAbortController=null;tokenKey;refreshTokenKey;agentIdKey;constructor(e,t,s,i,n,a,c,u,d){this.storage=e,this.cryptoService=t,this.machineId=s,this.config=i,this.logger=n,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,ni.getApiUrl)(this.config),t=await this.machineId.getMachineId(),s=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,s);let n=await fetch(`${e}/auth/device/code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machineId:t,machineName:s,publicKey:i})});if(!n.ok){let a=await n.text();throw new Error(`Failed to get device code: ${a}`)}return n.json()}async pollForToken(e){this.cancelPolling();let t=(0,ni.getApiUrl)(this.config),s=5e3,i=60;this.pollingAbortController=new AbortController;let n=this.pollingAbortController.signal;this.logger.info("Starting token polling");for(let a=0;a<i;a++){if(n.aborted)return this.logger.info("Polling was cancelled"),null;if(await this.sleep(s),n.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:n});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(n.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,ni.getApiUrl)(this.config),s=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("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:s,machineName:i,publicKey:n})});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 s=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()).exp*1e3;return Date.now()<s}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,ni.getApiUrl)(this.config);try{this.logger.info("Refreshing access token");let s=await fetch(`${t}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!s.ok)return this.logger.warn("Token refresh failed",String(s.status)),s.status===401&&await this.storage.delete(this.refreshTokenKey),null;let i=await s.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(s){return this.logger.warn("Token refresh error",s),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,ni.getApiUrl)(this.config);try{let s=await fetch(`${t}/users/me/limits`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});return s.ok?await s.json():(this.logger.error("Failed to fetch limits",String(s.status)),null)}catch(s){let i=s instanceof Error?s.message:String(s);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))}};sn.AuthService=Do});var Zf=D(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.StatusDetector=void 0;var nn={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]},bs={IDLE_TIMEOUT_MS:5e3,DEBOUNCE_MS:500,BUFFER_SIZE:16e3,WORKING_TIMEOUT_MS:3e4,RESOLVE_GRACE_MS:1500},Fo=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,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)),this.states.delete(e)}processOutput(e,t){let s=this.states.get(e);if(!s)return;s.lastOutput=Date.now(),s.outputBuffer+=t,s.outputBuffer.length>bs.BUFFER_SIZE&&(s.outputBuffer=s.outputBuffer.slice(-bs.BUFFER_SIZE));let i=Date.now()<s.resolveGraceUntil,n=!1;if(!i){let a=this.detectPrompt(s.outputBuffer);a&&a.type!=="free-input"&&this.isPromptActive(s.outputBuffer)&&(n=!0)}if(n)this.scheduleStatusUpdate(e,"waiting");else if(s.status==="waiting"&&!i){let a=this.analyzeOutput(s.outputBuffer);(a==="completed"||a==="error")&&this.scheduleStatusUpdate(e,a)}else{let a=this.analyzeOutput(s.outputBuffer);a&&this.scheduleStatusUpdate(e,a)}this.resetWorkingTimeout(e,s)}isPromptActive(e){let s=this.normalizeBuffer(this.stripAnsi(e)).split(`
|
|
6
|
+
`).map(a=>a.trim()).filter(Boolean);if(s.length===0)return!1;let i=s[s.length-1],n=s.slice(-18).join(`
|
|
7
|
+
`);return/[❯›●]/.test(n)||/\[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(n)}onCommandStart(e){let t=this.states.get(e);t&&(t.outputBuffer="",this.scheduleStatusUpdate(e,"working"),this.resetWorkingTimeout(e,t))}onCommandEnd(e,t){let s=this.states.get(e);if(!s)return;s.workingTimeout&&(clearTimeout(s.workingTimeout),s.workingTimeout=null);let i;if(t!==void 0&&t!==0)i="error";else{let n=this.analyzeOutput(s.outputBuffer);n==="waiting"?i="waiting":n==="error"?i="error":n==="completed"?i="completed":i="idle"}this.scheduleStatusUpdate(e,i),(i==="completed"||i==="error")&&setTimeout(()=>{let n=this.states.get(e);n&&(n.status==="completed"||n.status==="error")&&this.scheduleStatusUpdate(e,"idle")},bs.IDLE_TIMEOUT_MS)}analyzeOutput(e){let s=this.normalizeBuffer(this.stripAnsi(e)).split(`
|
|
8
|
+
`).slice(-10),i=s.join(`
|
|
9
|
+
`),n=(s[s.length-1]||"").trim();for(let a of nn.waiting)if(a.test(n))return"waiting";for(let a of nn.working)if(a.test(n))return"working";for(let a of nn.completed)if(a.test(i))return"completed";for(let a of nn.idle)if(a.test(n))return"idle";return null}detectPrompt(e){let i=this.normalizeBuffer(this.stripAnsi(e)).split(`
|
|
10
|
+
`).slice(-20),n=i.join(`
|
|
11
|
+
`),a=i[i.length-1]||"",c=this.extractNumberedChoices(e);if(c.length>=2)return{type:"numbered-choice",question:this.extractQuestion(n)||"Select an option:",choices:c};let u=[/\[Y\/n\]/i,/\[y\/N\]/i,/\(y\/n\)/i,/\(yes\/no\)/i];for(let m of u)if(m.test(n))return{type:"yes-no",question:this.extractQuestion(n)||"Confirm?"};let d=[/Press Enter to continue/i,/Press Enter/i,/Hit Enter/i,/\[Enter\]/i,/press return/i];for(let m of d)if(m.test(n))return{type:"enter",question:this.extractQuestion(n)||"Press Enter to continue"};let p=[/Press any key/i,/press a key/i];for(let m of p)if(m.test(n))return{type:"any-key",question:this.extractQuestion(n)||"Press any key"};return(a.endsWith("?")||a.endsWith(":"))&&!a.startsWith("/")&&!a.includes("error")&&a.length<100?{type:"free-input",question:a}:null}extractNumberedChoices(e){let t=[],i=this.normalizeBuffer(this.stripAnsi(e)).split(`
|
|
12
|
+
`),n=/^\s*[❯>*›●]?\s*(?:(\d+)[.)]\s*|\[(\d+)\]\s*)(.+)$/;for(let a of i){let c=a.match(n);if(c){let u=c[1]||c[2],d=c[3].trim();if(u&&d&&d.length<100&&!d.includes("error")){let p=t.length+1;parseInt(u)===p&&t.push({key:u,label:d})}}}return t}extractQuestion(e){let t=e.split(`
|
|
13
|
+
`).filter(s=>s.trim());for(let s=t.length-1;s>=Math.max(0,t.length-5);s--){let i=t[s].trim();if(!i||/^\s*\d+[.)]\s/.test(i)||/^\s*\[/.test(i))continue;let n=this.stripAnsi(i);if(n.endsWith("?")||n.endsWith(":"))return n.replace(/\s*\[Y\/n\]\s*$/i,"").replace(/\s*\(y\/n\)\s*$/i,"").replace(/\s*\(yes\/no\)\s*$/i,"").trim()}return null}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,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g,"")}normalizeBuffer(e){return e.replace(/\r\n/g,`
|
|
12
14
|
`).replace(/\r/g,`
|
|
13
15
|
`).replace(/\n{3,}/g,`
|
|
14
16
|
|
|
15
|
-
`)}scheduleStatusUpdate(e,t){let
|
|
16
|
-
`);return P.substr(0,P.length-2)},this.getRequestHeader=function(P){return typeof P=="string"&&d[P]?d[P]:""},this.send=function(P){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(y)throw new Error("INVALID_STATE_ERR: send has already been called");var B=!1,te=!1,A=Qf.parse(a.url),ae;switch(A.protocol){case"https:":B=!0;case"http:":ae=A.hostname;break;case"file:":te=!0;break;case void 0:case"":ae="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)bi.readFile(unescape(A.pathname),function(E,U){E?e.handleError(E,E.errno||-1):(e.status=200,e.responseText=U.toString("utf8"),e.response=U,X(e.DONE))});else try{this.response=bi.readFileSync(unescape(A.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,X(e.DONE)}catch(E){this.handleError(E,E.errno||-1)}return}var pe=A.port||(B?443:80),Q=A.pathname+(A.search?A.search:"");if(d.Host=ae,B&&pe===443||pe===80||(d.Host+=":"+A.port),a.user){typeof a.password>"u"&&(a.password="");var Ne=new Buffer(a.user+":"+a.password);d.Authorization="Basic "+Ne.toString("base64")}if(a.method==="GET"||a.method==="HEAD")P=null;else if(P){d["Content-Length"]=Buffer.isBuffer(P)?P.length:Buffer.byteLength(P);var ve=Object.keys(d);ve.some(function(E){return E.toLowerCase()==="content-type"})||(d["Content-Type"]="text/plain;charset=UTF-8")}else a.method==="POST"&&(d["Content-Length"]=0);var ze=r.agent||!1,ee={host:ae,port:pe,path:Q,method:a.method,headers:d,agent:ze};if(B&&(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),b=!1,a.async){var Je=B?i.request:t.request;y=!0,e.dispatchEvent("readystatechange");var We=function(E){if(n=E,n.statusCode===302||n.statusCode===303||n.statusCode===307){a.url=n.headers.location;var U=Qf.parse(a.url);ae=U.hostname;var ue={hostname:U.hostname,port:U.port,path:U.path,method:n.statusCode===303?"GET":a.method,headers:d};B&&(ue.pfx=r.pfx,ue.key=r.key,ue.passphrase=r.passphrase,ue.cert=r.cert,ue.ca=r.ca,ue.ciphers=r.ciphers,ue.rejectUnauthorized=r.rejectUnauthorized!==!1),s=Je(ue,We).on("error",nt),s.end();return}X(e.HEADERS_RECEIVED),e.status=n.statusCode,n.on("data",function(Ve){if(Ve){var ct=Buffer.from(Ve);e.response=Buffer.concat([e.response,ct])}y&&X(e.LOADING)}),n.on("end",function(){y&&(y=!1,X(e.DONE),e.responseText=e.response.toString("utf8"))}),n.on("error",function(Ve){e.handleError(Ve)})},nt=function(E){if(s.reusedSocket&&E.code==="ECONNRESET")return Je(ee,We).on("error",nt);e.handleError(E)};s=Je(ee,We).on("error",nt),r.autoUnref&&s.on("socket",E=>{E.unref()}),P&&s.write(P),s.end(),e.dispatchEvent("loadstart")}else{var Me=".node-xmlhttprequest-content-"+process.pid,Te=".node-xmlhttprequest-sync-"+process.pid;bi.writeFileSync(Te,"","utf8");for(var ot="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(B?"s":"")+".request;var options = "+JSON.stringify(ee)+";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('"+Me+"', 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('"+Me+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Te+"');});}).on('error', function(error) {fs.writeFileSync('"+Me+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Te+"');});"+(P?"req.write('"+JSON.stringify(P).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",He=Jp(process.argv[0],["-e",ot]),vt;bi.existsSync(Te););if(e.responseText=bi.readFileSync(Me,"utf8"),He.stdin.end(),bi.unlinkSync(Me),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"));n={statusCode:e.status,headers:j.data.headers},e.responseText=j.data.text,e.response=Buffer.from(j.data.data,"base64"),X(e.DONE,!0)}}},this.handleError=function(P,B){this.status=B||0,this.statusText=P,this.responseText=P.stack,b=!0,X(this.DONE)},this.abort=function(){s&&(s.abort(),s=null),d=Object.assign({},u),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),b=T=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||y)&&this.readyState!==this.DONE&&(y=!1,X(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(P,B){P in C||(C[P]=[]),C[P].push(B)},this.removeEventListener=function(P,B){P in C&&(C[P]=C[P].filter(function(te){return te!==B}))},this.dispatchEvent=function(P){if(typeof e["on"+P]=="function"&&(this.readyState===this.DONE&&a.async?setTimeout(function(){e["on"+P]()},0):e["on"+P]()),P in C)for(let B=0,te=C[P].length;B<te;B++)this.readyState===this.DONE?setTimeout(function(){C[P][B].call(e)},0):C[P][B].call(e)};var X=function(P){if(!(e.readyState===P||e.readyState===e.UNSENT&&T)&&(e.readyState=P,(a.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let B;T?B="abort":b?B="error":B="load",e.dispatchEvent(B),e.dispatchEvent("loadend")}}}});var an=M(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.ERROR_PACKET=Ir.PACKET_TYPES_REVERSE=Ir.PACKET_TYPES=void 0;var Jt=Object.create(null);Ir.PACKET_TYPES=Jt;Jt.open="0";Jt.close="1";Jt.ping="2";Jt.pong="3";Jt.message="4";Jt.upgrade="5";Jt.noop="6";var ru=Object.create(null);Ir.PACKET_TYPES_REVERSE=ru;Object.keys(Jt).forEach(r=>{ru[Jt[r]]=r});var Zp={type:"error",data:"parser error"};Ir.ERROR_PACKET=Zp});var su=M(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});xi.encodePacket=void 0;xi.encodePacketToBinary=tg;var Qp=an(),eg=({type:r,data:e},t,i)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?i(t?e:"b"+iu(e,!0).toString("base64")):i(Qp.PACKET_TYPES[r]+(e||""));xi.encodePacket=eg;var iu=(r,e)=>Buffer.isBuffer(r)||r instanceof Uint8Array&&!e?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength),jo;function tg(r,e){if(r.data instanceof ArrayBuffer||ArrayBuffer.isView(r.data))return e(iu(r.data,!1));(0,xi.encodePacket)(r,!0,t=>{jo||(jo=new TextEncoder),e(jo.encode(t))})}});var ou=M(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.decodePacket=void 0;var cn=an(),rg=(r,e)=>{if(typeof r!="string")return{type:"message",data:nu(r,e)};let t=r.charAt(0);if(t==="b"){let i=Buffer.from(r.substring(1),"base64");return{type:"message",data:nu(i,e)}}return cn.PACKET_TYPES_REVERSE[t]?r.length>1?{type:cn.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:cn.PACKET_TYPES_REVERSE[t]}:cn.ERROR_PACKET};fn.decodePacket=rg;var nu=(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 Si=M(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.decodePayload=mt.decodePacket=mt.encodePayload=mt.encodePacket=mt.protocol=void 0;mt.createPacketEncoderStream=ng;mt.createPacketDecoderStream=og;var qo=su();Object.defineProperty(mt,"encodePacket",{enumerable:!0,get:function(){return qo.encodePacket}});var Wo=ou();Object.defineProperty(mt,"decodePacket",{enumerable:!0,get:function(){return Wo.decodePacket}});var au=an(),cu="",ig=(r,e)=>{let t=r.length,i=new Array(t),s=0;r.forEach((n,a)=>{(0,qo.encodePacket)(n,!1,c=>{i[a]=c,++s===t&&e(i.join(cu))})})};mt.encodePayload=ig;var sg=(r,e)=>{let t=r.split(cu),i=[];for(let s=0;s<t.length;s++){let n=(0,Wo.decodePacket)(t[s],e);if(i.push(n),n.type==="error")break}return i};mt.decodePayload=sg;function ng(){return new TransformStream({transform(r,e){(0,qo.encodePacketToBinary)(r,t=>{let i=t.length,s;if(i<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,i);else if(i<65536){s=new Uint8Array(3);let n=new DataView(s.buffer);n.setUint8(0,126),n.setUint16(1,i)}else{s=new Uint8Array(9);let n=new DataView(s.buffer);n.setUint8(0,127),n.setBigUint64(1,BigInt(i))}r.data&&typeof r.data!="string"&&(s[0]|=128),e.enqueue(s),e.enqueue(t)})}})}var Uo;function un(r){return r.reduce((e,t)=>e+t.length,0)}function ln(r,e){if(r[0].length===e)return r.shift();let t=new Uint8Array(e),i=0;for(let s=0;s<e;s++)t[s]=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 og(r,e){Uo||(Uo=new TextDecoder);let t=[],i=0,s=-1,n=!1;return new TransformStream({transform(a,c){for(t.push(a);;){if(i===0){if(un(t)<1)break;let u=ln(t,1);n=(u[0]&128)===128,s=u[0]&127,s<126?i=3:s===126?i=1:i=2}else if(i===1){if(un(t)<2)break;let u=ln(t,2);s=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),i=3}else if(i===2){if(un(t)<8)break;let u=ln(t,8),d=new DataView(u.buffer,u.byteOffset,u.length),p=d.getUint32(0);if(p>Math.pow(2,21)-1){c.enqueue(au.ERROR_PACKET);break}s=p*Math.pow(2,32)+d.getUint32(4),i=3}else{if(un(t)<s)break;let u=ln(t,s);c.enqueue((0,Wo.decodePacket)(n?u:Uo.decode(u),e)),i=0}if(s===0||s>r){c.enqueue(au.ERROR_PACKET);break}}}})}mt.protocol=4});var Zr=M(fu=>{fu.Emitter=dt;function dt(r){if(r)return ag(r)}function ag(r){for(var e in dt.prototype)r[e]=dt.prototype[e];return r}dt.prototype.on=dt.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};dt.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};dt.prototype.off=dt.prototype.removeListener=dt.prototype.removeAllListeners=dt.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,s=0;s<t.length;s++)if(i=t[s],i===e||i.fn===e){t.splice(s,1);break}return t.length===0&&delete this._callbacks["$"+r],this};dt.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,s=t.length;i<s;++i)t[i].apply(this,e)}return this};dt.prototype.emitReserved=dt.prototype.emit;dt.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};dt.prototype.hasListeners=function(r){return!!this.listeners(r).length}});var Qr=M(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.CookieJar=Rt.defaultBinaryType=Rt.globalThisShim=Rt.nextTick=void 0;Rt.createCookieJar=cg;Rt.parse=uu;Rt.nextTick=process.nextTick;Rt.globalThisShim=global;Rt.defaultBinaryType="nodebuffer";function cg(){return new hn}function uu(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 s=e[0].substring(t+1).trim();s.charCodeAt(0)===34&&(s=s.slice(1,-1));let n={name:i,value:s};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":n.expires=new Date(d);break;case"Max-Age":let p=new Date;p.setUTCSeconds(p.getUTCSeconds()+parseInt(d,10)),n.expires=p;break;default:}}return n}var hn=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let i=uu(t);i&&this._cookies.set(i.name,i)})}get cookies(){let e=Date.now();return this._cookies.forEach((t,i)=>{var s;((s=t.expires)===null||s===void 0?void 0:s.getTime())<e&&this._cookies.delete(i)}),this._cookies.entries()}addCookies(e){let t=[];for(let[i,s]of this.cookies)t.push(`${i}=${s.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}`)}};Rt.CookieJar=hn});var ei=M(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.pick=fg;Ti.installTimerFunctions=hg;Ti.byteLength=pg;Ti.randomString=mg;var Lr=Qr();function fg(r,...e){return e.reduce((t,i)=>(r.hasOwnProperty(i)&&(t[i]=r[i]),t),{})}var ug=Lr.globalThisShim.setTimeout,lg=Lr.globalThisShim.clearTimeout;function hg(r,e){e.useNativeTimers?(r.setTimeoutFn=ug.bind(Lr.globalThisShim),r.clearTimeoutFn=lg.bind(Lr.globalThisShim)):(r.setTimeoutFn=Lr.globalThisShim.setTimeout.bind(Lr.globalThisShim),r.clearTimeoutFn=Lr.globalThisShim.clearTimeout.bind(Lr.globalThisShim))}var dg=1.33;function pg(r){return typeof r=="string"?gg(r):Math.ceil((r.byteLength||r.size)*dg)}function gg(r){let e=0,t=0;for(let i=0,s=r.length;i<s;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 mg(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}});var Ho=M(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.encode=_g;dn.decode=yg;function _g(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function yg(r){let e={},t=r.split("&");for(let i=0,s=t.length;i<s;i++){let n=t[i].split("=");e[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return e}});var hu=M((KE,lu)=>{var Ci=1e3,Oi=Ci*60,ki=Oi*60,ti=ki*24,vg=ti*7,Eg=ti*365.25;lu.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return wg(r);if(t==="number"&&isFinite(r))return e.long?xg(r):bg(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function wg(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*Eg;case"weeks":case"week":case"w":return t*vg;case"days":case"day":case"d":return t*ti;case"hours":case"hour":case"hrs":case"hr":case"h":return t*ki;case"minutes":case"minute":case"mins":case"min":case"m":return t*Oi;case"seconds":case"second":case"secs":case"sec":case"s":return t*Ci;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function bg(r){var e=Math.abs(r);return e>=ti?Math.round(r/ti)+"d":e>=ki?Math.round(r/ki)+"h":e>=Oi?Math.round(r/Oi)+"m":e>=Ci?Math.round(r/Ci)+"s":r+"ms"}function xg(r){var e=Math.abs(r);return e>=ti?pn(r,e,ti,"day"):e>=ki?pn(r,e,ki,"hour"):e>=Oi?pn(r,e,Oi,"minute"):e>=Ci?pn(r,e,Ci,"second"):r+" ms"}function pn(r,e,t,i){var s=e>=t*1.5;return Math.round(r/t)+" "+i+(s?"s":"")}});var Vo=M((zE,du)=>{function Sg(r){t.debug=t,t.default=t,t.coerce=u,t.disable=a,t.enable=s,t.enabled=c,t.humanize=hu(),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 y=0;y<p.length;y++)m=(m<<5)-m+p.charCodeAt(y),m|=0;return t.colors[Math.abs(m)%t.colors.length]}t.selectColor=e;function t(p){let m,y=null,b,T;function C(...V){if(!C.enabled)return;let _e=C,X=Number(new Date),P=X-(m||X);_e.diff=P,_e.prev=m,_e.curr=X,m=X,V[0]=t.coerce(V[0]),typeof V[0]!="string"&&V.unshift("%O");let B=0;V[0]=V[0].replace(/%([a-zA-Z%])/g,(A,ae)=>{if(A==="%%")return"%";B++;let pe=t.formatters[ae];if(typeof pe=="function"){let Q=V[B];A=pe.call(_e,Q),V.splice(B,1),B--}return A}),t.formatArgs.call(_e,V),(_e.log||t.log).apply(_e,V)}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:()=>y!==null?y:(b!==t.namespaces&&(b=t.namespaces,T=t.enabled(p)),T),set:V=>{y=V}}),typeof t.init=="function"&&t.init(C),C}function i(p,m){let y=t(this.namespace+(typeof m>"u"?":":m)+p);return y.log=this.log,y}function s(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 y of m)y[0]==="-"?t.skips.push(y.slice(1)):t.names.push(y)}function n(p,m){let y=0,b=0,T=-1,C=0;for(;y<p.length;)if(b<m.length&&(m[b]===p[y]||m[b]==="*"))m[b]==="*"?(T=b,C=y,b++):(y++,b++);else if(T!==-1)b=T+1,C++,y=C;else return!1;for(;b<m.length&&m[b]==="*";)b++;return b===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(n(p,m))return!1;for(let m of t.names)if(n(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}du.exports=Sg});var pu=M((_t,gn)=>{_t.formatArgs=Cg;_t.save=Og;_t.load=kg;_t.useColors=Tg;_t.storage=Rg();_t.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`."))}})();_t.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 Tg(){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 Cg(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+gn.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,s=>{s!=="%%"&&(t++,s==="%c"&&(i=t))}),r.splice(i,0,e)}_t.log=console.debug||console.log||(()=>{});function Og(r){try{r?_t.storage.setItem("debug",r):_t.storage.removeItem("debug")}catch{}}function kg(){let r;try{r=_t.storage.getItem("debug")||_t.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Rg(){try{return localStorage}catch{}}gn.exports=Vo()(_t);var{formatters:Ag}=gn.exports;Ag.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var mu=M(($E,gu)=>{"use strict";gu.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",i=e.indexOf(t+r),s=e.indexOf("--");return i!==-1&&(s===-1||i<s)}});var vu=M((GE,yu)=>{"use strict";var Pg=require("os"),_u=require("tty"),At=mu(),{env:tt}=process,Nr;At("no-color")||At("no-colors")||At("color=false")||At("color=never")?Nr=0:(At("color")||At("colors")||At("color=true")||At("color=always"))&&(Nr=1);"FORCE_COLOR"in tt&&(tt.FORCE_COLOR==="true"?Nr=1:tt.FORCE_COLOR==="false"?Nr=0:Nr=tt.FORCE_COLOR.length===0?1:Math.min(parseInt(tt.FORCE_COLOR,10),3));function Ko(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function zo(r,e){if(Nr===0)return 0;if(At("color=16m")||At("color=full")||At("color=truecolor"))return 3;if(At("color=256"))return 2;if(r&&!e&&Nr===void 0)return 0;let t=Nr||0;if(tt.TERM==="dumb")return t;if(process.platform==="win32"){let i=Pg.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in tt)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(i=>i in tt)||tt.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in tt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(tt.TEAMCITY_VERSION)?1:0;if(tt.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in tt){let i=parseInt((tt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(tt.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(tt.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(tt.TERM)||"COLORTERM"in tt?1:t}function Ig(r){let e=zo(r,r&&r.isTTY);return Ko(e)}yu.exports={supportsColor:Ig,stdout:Ko(zo(!0,_u.isatty(1))),stderr:Ko(zo(!0,_u.isatty(2)))}});var wu=M((rt,_n)=>{var Lg=require("tty"),mn=require("util");rt.init=Ug;rt.log=Fg;rt.formatArgs=Dg;rt.save=Bg;rt.load=jg;rt.useColors=Ng;rt.destroy=mn.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");rt.colors=[6,2,3,4,5,1];try{let r=vu();r&&(r.stderr||r).level>=2&&(rt.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{}rt.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,n)=>n.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 Ng(){return"colors"in rt.inspectOpts?!!rt.inspectOpts.colors:Lg.isatty(process.stderr.fd)}function Dg(r){let{namespace:e,useColors:t}=this;if(t){let i=this.color,s="\x1B[3"+(i<8?i:"8;5;"+i),n=` ${s};1m${e} \x1B[0m`;r[0]=n+r[0].split(`
|
|
17
|
+
`)}scheduleStatusUpdate(e,t){let s=this.states.get(e);s&&s.status!==t&&s.pendingStatus!==t&&(s.pendingUpdate&&clearTimeout(s.pendingUpdate),s.pendingStatus=t,s.pendingUpdate=setTimeout(()=>{s.pendingStatus=null,this.emitStatus(e,t),s.pendingUpdate=null},bs.DEBOUNCE_MS))}emitStatus(e,t){let s=this.states.get(e);if(!s||s.status===t)return;s.status=t,s.lastUpdate=Date.now();let i;t==="waiting"&&(i=this.detectPrompt(s.outputBuffer)||void 0),this.onStatusChange(e,t,i)}resetWorkingTimeout(e,t){t.workingTimeout&&clearTimeout(t.workingTimeout),t.status==="working"&&(t.workingTimeout=setTimeout(()=>{let s=this.states.get(e);s&&s.status==="working"&&(this.analyzeOutput(s.outputBuffer)==="waiting"?this.emitStatus(e,"waiting"):this.onStatusChange(e,"working",void 0))},bs.WORKING_TIMEOUT_MS))}resolvePrompt(e){let t=this.states.get(e);t&&t.status==="waiting"&&(t.resolveGraceUntil=Date.now()+bs.RESOLVE_GRACE_MS,t.outputBuffer="",this.scheduleStatusUpdate(e,"working"))}forceStatus(e,t){this.emitStatus(e,t)}getStatus(e){return this.states.get(e)?.status??null}dispose(){for(let e of this.states.keys())this.stopTracking(e)}};on.StatusDetector=Fo});var tu=D((DE,eu)=>{var xs=require("fs"),Qf=require("url"),Jp=require("child_process").spawn;eu.exports=Bo;Bo.XMLHttpRequest=Bo;function Bo(r){"use strict";r=r||{};var e=this,t=require("http"),s=require("https"),i,n,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"],y=!1,b=!1,T=!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 V=function(P){return c||P&&p.indexOf(P.toLowerCase())===-1},_e=function(P){return P&&m.indexOf(P)===-1};this.open=function(P,B,te,A,ae){if(this.abort(),b=!1,T=!1,!_e(P))throw new Error("SecurityError: Request method not allowed");a={method:P,url:B.toString(),async:typeof te!="boolean"?!0:te,user:A||null,password:ae||null},X(this.OPENED)},this.setDisableHeaderCheck=function(P){c=P},this.setRequestHeader=function(P,B){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!V(P))return console.warn('Refused to set unsafe header "'+P+'"'),!1;if(y)throw new Error("INVALID_STATE_ERR: send flag is true");return d[P]=B,!0},this.getResponseHeader=function(P){return typeof P=="string"&&this.readyState>this.OPENED&&n.headers[P.toLowerCase()]&&!b?n.headers[P.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||b)return"";var P="";for(var B in n.headers)B!=="set-cookie"&&B!=="set-cookie2"&&(P+=B+": "+n.headers[B]+`\r
|
|
18
|
+
`);return P.substr(0,P.length-2)},this.getRequestHeader=function(P){return typeof P=="string"&&d[P]?d[P]:""},this.send=function(P){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(y)throw new Error("INVALID_STATE_ERR: send has already been called");var B=!1,te=!1,A=Qf.parse(a.url),ae;switch(A.protocol){case"https:":B=!0;case"http:":ae=A.hostname;break;case"file:":te=!0;break;case void 0:case"":ae="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)xs.readFile(unescape(A.pathname),function(E,U){E?e.handleError(E,E.errno||-1):(e.status=200,e.responseText=U.toString("utf8"),e.response=U,X(e.DONE))});else try{this.response=xs.readFileSync(unescape(A.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,X(e.DONE)}catch(E){this.handleError(E,E.errno||-1)}return}var pe=A.port||(B?443:80),Q=A.pathname+(A.search?A.search:"");if(d.Host=ae,B&&pe===443||pe===80||(d.Host+=":"+A.port),a.user){typeof a.password>"u"&&(a.password="");var Ne=new Buffer(a.user+":"+a.password);d.Authorization="Basic "+Ne.toString("base64")}if(a.method==="GET"||a.method==="HEAD")P=null;else if(P){d["Content-Length"]=Buffer.isBuffer(P)?P.length:Buffer.byteLength(P);var ve=Object.keys(d);ve.some(function(E){return E.toLowerCase()==="content-type"})||(d["Content-Type"]="text/plain;charset=UTF-8")}else a.method==="POST"&&(d["Content-Length"]=0);var Ke=r.agent||!1,ee={host:ae,port:pe,path:Q,method:a.method,headers:d,agent:Ke};if(B&&(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),b=!1,a.async){var Je=B?s.request:t.request;y=!0,e.dispatchEvent("readystatechange");var We=function(E){if(n=E,n.statusCode===302||n.statusCode===303||n.statusCode===307){a.url=n.headers.location;var U=Qf.parse(a.url);ae=U.hostname;var ue={hostname:U.hostname,port:U.port,path:U.path,method:n.statusCode===303?"GET":a.method,headers:d};B&&(ue.pfx=r.pfx,ue.key=r.key,ue.passphrase=r.passphrase,ue.cert=r.cert,ue.ca=r.ca,ue.ciphers=r.ciphers,ue.rejectUnauthorized=r.rejectUnauthorized!==!1),i=Je(ue,We).on("error",nt),i.end();return}X(e.HEADERS_RECEIVED),e.status=n.statusCode,n.on("data",function(Ve){if(Ve){var ct=Buffer.from(Ve);e.response=Buffer.concat([e.response,ct])}y&&X(e.LOADING)}),n.on("end",function(){y&&(y=!1,X(e.DONE),e.responseText=e.response.toString("utf8"))}),n.on("error",function(Ve){e.handleError(Ve)})},nt=function(E){if(i.reusedSocket&&E.code==="ECONNRESET")return Je(ee,We).on("error",nt);e.handleError(E)};i=Je(ee,We).on("error",nt),r.autoUnref&&i.on("socket",E=>{E.unref()}),P&&i.write(P),i.end(),e.dispatchEvent("loadstart")}else{var De=".node-xmlhttprequest-content-"+process.pid,Te=".node-xmlhttprequest-sync-"+process.pid;xs.writeFileSync(Te,"","utf8");for(var ot="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(B?"s":"")+".request;var options = "+JSON.stringify(ee)+";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('"+De+"', 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('"+De+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Te+"');});}).on('error', function(error) {fs.writeFileSync('"+De+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+Te+"');});"+(P?"req.write('"+JSON.stringify(P).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",He=Jp(process.argv[0],["-e",ot]),vt;xs.existsSync(Te););if(e.responseText=xs.readFileSync(De,"utf8"),He.stdin.end(),xs.unlinkSync(De),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"));n={statusCode:e.status,headers:j.data.headers},e.responseText=j.data.text,e.response=Buffer.from(j.data.data,"base64"),X(e.DONE,!0)}}},this.handleError=function(P,B){this.status=B||0,this.statusText=P,this.responseText=P.stack,b=!0,X(this.DONE)},this.abort=function(){i&&(i.abort(),i=null),d=Object.assign({},u),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),b=T=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||y)&&this.readyState!==this.DONE&&(y=!1,X(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(P,B){P in C||(C[P]=[]),C[P].push(B)},this.removeEventListener=function(P,B){P in C&&(C[P]=C[P].filter(function(te){return te!==B}))},this.dispatchEvent=function(P){if(typeof e["on"+P]=="function"&&(this.readyState===this.DONE&&a.async?setTimeout(function(){e["on"+P]()},0):e["on"+P]()),P in C)for(let B=0,te=C[P].length;B<te;B++)this.readyState===this.DONE?setTimeout(function(){C[P][B].call(e)},0):C[P][B].call(e)};var X=function(P){if(!(e.readyState===P||e.readyState===e.UNSENT&&T)&&(e.readyState=P,(a.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let B;T?B="abort":b?B="error":B="load",e.dispatchEvent(B),e.dispatchEvent("loadend")}}}});var an=D(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.ERROR_PACKET=Ir.PACKET_TYPES_REVERSE=Ir.PACKET_TYPES=void 0;var Jt=Object.create(null);Ir.PACKET_TYPES=Jt;Jt.open="0";Jt.close="1";Jt.ping="2";Jt.pong="3";Jt.message="4";Jt.upgrade="5";Jt.noop="6";var ru=Object.create(null);Ir.PACKET_TYPES_REVERSE=ru;Object.keys(Jt).forEach(r=>{ru[Jt[r]]=r});var Zp={type:"error",data:"parser error"};Ir.ERROR_PACKET=Zp});var iu=D(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.encodePacket=void 0;Ss.encodePacketToBinary=tg;var Qp=an(),eg=({type:r,data:e},t,s)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?s(t?e:"b"+su(e,!0).toString("base64")):s(Qp.PACKET_TYPES[r]+(e||""));Ss.encodePacket=eg;var su=(r,e)=>Buffer.isBuffer(r)||r instanceof Uint8Array&&!e?r:r instanceof ArrayBuffer?Buffer.from(r):Buffer.from(r.buffer,r.byteOffset,r.byteLength),jo;function tg(r,e){if(r.data instanceof ArrayBuffer||ArrayBuffer.isView(r.data))return e(su(r.data,!1));(0,Ss.encodePacket)(r,!0,t=>{jo||(jo=new TextEncoder),e(jo.encode(t))})}});var ou=D(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.decodePacket=void 0;var cn=an(),rg=(r,e)=>{if(typeof r!="string")return{type:"message",data:nu(r,e)};let t=r.charAt(0);if(t==="b"){let s=Buffer.from(r.substring(1),"base64");return{type:"message",data:nu(s,e)}}return cn.PACKET_TYPES_REVERSE[t]?r.length>1?{type:cn.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:cn.PACKET_TYPES_REVERSE[t]}:cn.ERROR_PACKET};fn.decodePacket=rg;var nu=(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 Ts=D(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.decodePayload=mt.decodePacket=mt.encodePayload=mt.encodePacket=mt.protocol=void 0;mt.createPacketEncoderStream=ng;mt.createPacketDecoderStream=og;var qo=iu();Object.defineProperty(mt,"encodePacket",{enumerable:!0,get:function(){return qo.encodePacket}});var Wo=ou();Object.defineProperty(mt,"decodePacket",{enumerable:!0,get:function(){return Wo.decodePacket}});var au=an(),cu="",sg=(r,e)=>{let t=r.length,s=new Array(t),i=0;r.forEach((n,a)=>{(0,qo.encodePacket)(n,!1,c=>{s[a]=c,++i===t&&e(s.join(cu))})})};mt.encodePayload=sg;var ig=(r,e)=>{let t=r.split(cu),s=[];for(let i=0;i<t.length;i++){let n=(0,Wo.decodePacket)(t[i],e);if(s.push(n),n.type==="error")break}return s};mt.decodePayload=ig;function ng(){return new TransformStream({transform(r,e){(0,qo.encodePacketToBinary)(r,t=>{let s=t.length,i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);let n=new DataView(i.buffer);n.setUint8(0,126),n.setUint16(1,s)}else{i=new Uint8Array(9);let n=new DataView(i.buffer);n.setUint8(0,127),n.setBigUint64(1,BigInt(s))}r.data&&typeof r.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(t)})}})}var Uo;function un(r){return r.reduce((e,t)=>e+t.length,0)}function ln(r,e){if(r[0].length===e)return r.shift();let t=new Uint8Array(e),s=0;for(let i=0;i<e;i++)t[i]=r[0][s++],s===r[0].length&&(r.shift(),s=0);return r.length&&s<r[0].length&&(r[0]=r[0].slice(s)),t}function og(r,e){Uo||(Uo=new TextDecoder);let t=[],s=0,i=-1,n=!1;return new TransformStream({transform(a,c){for(t.push(a);;){if(s===0){if(un(t)<1)break;let u=ln(t,1);n=(u[0]&128)===128,i=u[0]&127,i<126?s=3:i===126?s=1:s=2}else if(s===1){if(un(t)<2)break;let u=ln(t,2);i=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),s=3}else if(s===2){if(un(t)<8)break;let u=ln(t,8),d=new DataView(u.buffer,u.byteOffset,u.length),p=d.getUint32(0);if(p>Math.pow(2,21)-1){c.enqueue(au.ERROR_PACKET);break}i=p*Math.pow(2,32)+d.getUint32(4),s=3}else{if(un(t)<i)break;let u=ln(t,i);c.enqueue((0,Wo.decodePacket)(n?u:Uo.decode(u),e)),s=0}if(i===0||i>r){c.enqueue(au.ERROR_PACKET);break}}}})}mt.protocol=4});var Zr=D(fu=>{fu.Emitter=dt;function dt(r){if(r)return ag(r)}function ag(r){for(var e in dt.prototype)r[e]=dt.prototype[e];return r}dt.prototype.on=dt.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};dt.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};dt.prototype.off=dt.prototype.removeListener=dt.prototype.removeAllListeners=dt.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 s,i=0;i<t.length;i++)if(s=t[i],s===e||s.fn===e){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+r],this};dt.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],s=1;s<arguments.length;s++)e[s-1]=arguments[s];if(t){t=t.slice(0);for(var s=0,i=t.length;s<i;++s)t[s].apply(this,e)}return this};dt.prototype.emitReserved=dt.prototype.emit;dt.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};dt.prototype.hasListeners=function(r){return!!this.listeners(r).length}});var Qr=D(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.CookieJar=Rt.defaultBinaryType=Rt.globalThisShim=Rt.nextTick=void 0;Rt.createCookieJar=cg;Rt.parse=uu;Rt.nextTick=process.nextTick;Rt.globalThisShim=global;Rt.defaultBinaryType="nodebuffer";function cg(){return new hn}function uu(r){let e=r.split("; "),t=e[0].indexOf("=");if(t===-1)return;let s=e[0].substring(0,t).trim();if(!s.length)return;let i=e[0].substring(t+1).trim();i.charCodeAt(0)===34&&(i=i.slice(1,-1));let n={name:s,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":n.expires=new Date(d);break;case"Max-Age":let p=new Date;p.setUTCSeconds(p.getUTCSeconds()+parseInt(d,10)),n.expires=p;break;default:}}return n}var hn=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let s=uu(t);s&&this._cookies.set(s.name,s)})}get cookies(){let e=Date.now();return this._cookies.forEach((t,s)=>{var i;((i=t.expires)===null||i===void 0?void 0:i.getTime())<e&&this._cookies.delete(s)}),this._cookies.entries()}addCookies(e){let t=[];for(let[s,i]of this.cookies)t.push(`${s}=${i.value}`);t.length&&(e.setDisableHeaderCheck(!0),e.setRequestHeader("cookie",t.join("; ")))}appendCookies(e){for(let[t,s]of this.cookies)e.append("cookie",`${t}=${s.value}`)}};Rt.CookieJar=hn});var es=D(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});Cs.pick=fg;Cs.installTimerFunctions=hg;Cs.byteLength=pg;Cs.randomString=mg;var Lr=Qr();function fg(r,...e){return e.reduce((t,s)=>(r.hasOwnProperty(s)&&(t[s]=r[s]),t),{})}var ug=Lr.globalThisShim.setTimeout,lg=Lr.globalThisShim.clearTimeout;function hg(r,e){e.useNativeTimers?(r.setTimeoutFn=ug.bind(Lr.globalThisShim),r.clearTimeoutFn=lg.bind(Lr.globalThisShim)):(r.setTimeoutFn=Lr.globalThisShim.setTimeout.bind(Lr.globalThisShim),r.clearTimeoutFn=Lr.globalThisShim.clearTimeout.bind(Lr.globalThisShim))}var dg=1.33;function pg(r){return typeof r=="string"?gg(r):Math.ceil((r.byteLength||r.size)*dg)}function gg(r){let e=0,t=0;for(let s=0,i=r.length;s<i;s++)e=r.charCodeAt(s),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(s++,t+=4);return t}function mg(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}});var Ho=D(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.encode=_g;dn.decode=yg;function _g(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function yg(r){let e={},t=r.split("&");for(let s=0,i=t.length;s<i;s++){let n=t[s].split("=");e[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return e}});var hu=D((zE,lu)=>{var Os=1e3,ks=Os*60,Rs=ks*60,ts=Rs*24,vg=ts*7,Eg=ts*365.25;lu.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return wg(r);if(t==="number"&&isFinite(r))return e.long?xg(r):bg(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function wg(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]),s=(e[2]||"ms").toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return t*Eg;case"weeks":case"week":case"w":return t*vg;case"days":case"day":case"d":return t*ts;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Rs;case"minutes":case"minute":case"mins":case"min":case"m":return t*ks;case"seconds":case"second":case"secs":case"sec":case"s":return t*Os;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function bg(r){var e=Math.abs(r);return e>=ts?Math.round(r/ts)+"d":e>=Rs?Math.round(r/Rs)+"h":e>=ks?Math.round(r/ks)+"m":e>=Os?Math.round(r/Os)+"s":r+"ms"}function xg(r){var e=Math.abs(r);return e>=ts?pn(r,e,ts,"day"):e>=Rs?pn(r,e,Rs,"hour"):e>=ks?pn(r,e,ks,"minute"):e>=Os?pn(r,e,Os,"second"):r+" ms"}function pn(r,e,t,s){var i=e>=t*1.5;return Math.round(r/t)+" "+s+(i?"s":"")}});var Vo=D((KE,du)=>{function Sg(r){t.debug=t,t.default=t,t.coerce=u,t.disable=a,t.enable=i,t.enabled=c,t.humanize=hu(),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 y=0;y<p.length;y++)m=(m<<5)-m+p.charCodeAt(y),m|=0;return t.colors[Math.abs(m)%t.colors.length]}t.selectColor=e;function t(p){let m,y=null,b,T;function C(...V){if(!C.enabled)return;let _e=C,X=Number(new Date),P=X-(m||X);_e.diff=P,_e.prev=m,_e.curr=X,m=X,V[0]=t.coerce(V[0]),typeof V[0]!="string"&&V.unshift("%O");let B=0;V[0]=V[0].replace(/%([a-zA-Z%])/g,(A,ae)=>{if(A==="%%")return"%";B++;let pe=t.formatters[ae];if(typeof pe=="function"){let Q=V[B];A=pe.call(_e,Q),V.splice(B,1),B--}return A}),t.formatArgs.call(_e,V),(_e.log||t.log).apply(_e,V)}return C.namespace=p,C.useColors=t.useColors(),C.color=t.selectColor(p),C.extend=s,C.destroy=t.destroy,Object.defineProperty(C,"enabled",{enumerable:!0,configurable:!1,get:()=>y!==null?y:(b!==t.namespaces&&(b=t.namespaces,T=t.enabled(p)),T),set:V=>{y=V}}),typeof t.init=="function"&&t.init(C),C}function s(p,m){let y=t(this.namespace+(typeof m>"u"?":":m)+p);return y.log=this.log,y}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 y of m)y[0]==="-"?t.skips.push(y.slice(1)):t.names.push(y)}function n(p,m){let y=0,b=0,T=-1,C=0;for(;y<p.length;)if(b<m.length&&(m[b]===p[y]||m[b]==="*"))m[b]==="*"?(T=b,C=y,b++):(y++,b++);else if(T!==-1)b=T+1,C++,y=C;else return!1;for(;b<m.length&&m[b]==="*";)b++;return b===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(n(p,m))return!1;for(let m of t.names)if(n(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}du.exports=Sg});var pu=D((_t,gn)=>{_t.formatArgs=Cg;_t.save=Og;_t.load=kg;_t.useColors=Tg;_t.storage=Rg();_t.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`."))}})();_t.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 Tg(){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 Cg(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+gn.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,s=0;r[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(t++,i==="%c"&&(s=t))}),r.splice(s,0,e)}_t.log=console.debug||console.log||(()=>{});function Og(r){try{r?_t.storage.setItem("debug",r):_t.storage.removeItem("debug")}catch{}}function kg(){let r;try{r=_t.storage.getItem("debug")||_t.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Rg(){try{return localStorage}catch{}}gn.exports=Vo()(_t);var{formatters:Ag}=gn.exports;Ag.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var mu=D(($E,gu)=>{"use strict";gu.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",s=e.indexOf(t+r),i=e.indexOf("--");return s!==-1&&(i===-1||s<i)}});var vu=D((GE,yu)=>{"use strict";var Pg=require("os"),_u=require("tty"),At=mu(),{env:tt}=process,Nr;At("no-color")||At("no-colors")||At("color=false")||At("color=never")?Nr=0:(At("color")||At("colors")||At("color=true")||At("color=always"))&&(Nr=1);"FORCE_COLOR"in tt&&(tt.FORCE_COLOR==="true"?Nr=1:tt.FORCE_COLOR==="false"?Nr=0:Nr=tt.FORCE_COLOR.length===0?1:Math.min(parseInt(tt.FORCE_COLOR,10),3));function zo(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function Ko(r,e){if(Nr===0)return 0;if(At("color=16m")||At("color=full")||At("color=truecolor"))return 3;if(At("color=256"))return 2;if(r&&!e&&Nr===void 0)return 0;let t=Nr||0;if(tt.TERM==="dumb")return t;if(process.platform==="win32"){let s=Pg.release().split(".");return Number(s[0])>=10&&Number(s[2])>=10586?Number(s[2])>=14931?3:2:1}if("CI"in tt)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(s=>s in tt)||tt.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in tt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(tt.TEAMCITY_VERSION)?1:0;if(tt.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in tt){let s=parseInt((tt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(tt.TERM_PROGRAM){case"iTerm.app":return s>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(tt.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(tt.TERM)||"COLORTERM"in tt?1:t}function Ig(r){let e=Ko(r,r&&r.isTTY);return zo(e)}yu.exports={supportsColor:Ig,stdout:zo(Ko(!0,_u.isatty(1))),stderr:zo(Ko(!0,_u.isatty(2)))}});var wu=D((rt,_n)=>{var Lg=require("tty"),mn=require("util");rt.init=Ug;rt.log=Fg;rt.formatArgs=Mg;rt.save=Bg;rt.load=jg;rt.useColors=Ng;rt.destroy=mn.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");rt.colors=[6,2,3,4,5,1];try{let r=vu();r&&(r.stderr||r).level>=2&&(rt.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{}rt.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,n)=>n.toUpperCase()),s=process.env[e];return/^(yes|on|true|enabled)$/i.test(s)?s=!0:/^(no|off|false|disabled)$/i.test(s)?s=!1:s==="null"?s=null:s=Number(s),r[t]=s,r},{});function Ng(){return"colors"in rt.inspectOpts?!!rt.inspectOpts.colors:Lg.isatty(process.stderr.fd)}function Mg(r){let{namespace:e,useColors:t}=this;if(t){let s=this.color,i="\x1B[3"+(s<8?s:"8;5;"+s),n=` ${i};1m${e} \x1B[0m`;r[0]=n+r[0].split(`
|
|
17
19
|
`).join(`
|
|
18
|
-
`+n),r.push(
|
|
20
|
+
`+n),r.push(i+"m+"+_n.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=Dg()+e+" "+r[0]}function Dg(){return rt.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Fg(...r){return process.stderr.write(mn.formatWithOptions(rt.inspectOpts,...r)+`
|
|
19
21
|
`)}function Bg(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function jg(){return process.env.DEBUG}function Ug(r){r.inspectOpts={};let e=Object.keys(rt.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=rt.inspectOpts[e[t]]}_n.exports=Vo()(rt);var{formatters:Eu}=_n.exports;Eu.o=function(r){return this.inspectOpts.colors=this.useColors,mn.inspect(r,this.inspectOpts).split(`
|
|
20
|
-
`).map(e=>e.trim()).join(" ")};Eu.O=function(r){return this.inspectOpts.colors=this.useColors,mn.inspect(r,this.inspectOpts)}});var Pt=M((YE,$o)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?$o.exports=pu():$o.exports=wu()});var os=M(Dr=>{"use strict";var qg=Dr&&Dr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Dr,"__esModule",{value:!0});Dr.Transport=Dr.TransportError=void 0;var Wg=Si(),Hg=Zr(),Vg=ei(),Kg=Ho(),zg=qg(Pt()),$g=(0,zg.default)("engine.io-client:transport"),yn=class extends Error{constructor(e,t,i){super(e),this.description=t,this.context=i,this.type="TransportError"}};Dr.TransportError=yn;var Go=class extends Hg.Emitter{constructor(e){super(),this.writable=!1,(0,Vg.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 yn(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):$g("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=(0,Wg.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,Kg.encode)(e);return t.length?"?"+t:""}};Dr.Transport=Go});var Xo=M(Ri=>{"use strict";var Gg=Ri&&Ri.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ri,"__esModule",{value:!0});Ri.Polling=void 0;var Yg=os(),Xg=ei(),bu=Si(),Jg=Gg(Pt()),jt=(0,Jg.default)("engine.io-client:polling"),Yo=class extends Yg.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{jt("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let i=0;this._polling&&(jt("we are currently polling - waiting to pause"),i++,this.once("pollComplete",function(){jt("pre-pause polling complete"),--i||t()})),this.writable||(jt("we are currently writing - waiting to pause"),i++,this.once("drain",function(){jt("pre-pause writing complete"),--i||t()}))}else t()}_poll(){jt("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){jt("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,bu.decodePayload)(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():jt('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{jt("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(jt("transport open - closing"),e()):(jt("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,bu.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,Xg.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};Ri.Polling=Yo});var Su=M(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.hasCORS=void 0;var xu=!1;try{xu=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}vn.hasCORS=xu});var Qo=M(Zt=>{"use strict";var Zg=Zt&&Zt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Zt,"__esModule",{value:!0});Zt.XHR=Zt.Request=Zt.BaseXHR=void 0;var Qg=Xo(),em=Zr(),Tu=ei(),Ou=Qr(),tm=Su(),rm=Zg(Pt()),Jo=(0,rm.default)("engine.io-client:polling");function im(){}var En=class extends Qg.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",(s,n)=>{this.onError("xhr post error",s,n)})}doPoll(){Jo("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}};Zt.BaseXHR=En;var pr=class r extends em.Emitter{constructor(e,t,i){super(),this.createRequest=e,(0,Tu.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,Tu.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{Jo("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 s in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(s)&&i.setRequestHeader(s,this._opts.extraHeaders[s])}}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 s;i.readyState===3&&((s=this._opts.cookieJar)===null||s===void 0||s.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))},Jo("xhr data %s",this._data),i.send(this._data)}catch(s){this.setTimeoutFn(()=>{this._onError(s)},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=im,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()}};Zt.Request=pr;pr.requestsCount=0;pr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Cu);else if(typeof addEventListener=="function"){let r="onpagehide"in Ou.globalThisShim?"pagehide":"unload";addEventListener(r,Cu,!1)}}function Cu(){for(let r in pr.requests)pr.requests.hasOwnProperty(r)&&pr.requests[r].abort()}var sm=(function(){let r=ku({xdomain:!1});return r&&r.responseType!==null})(),Zo=class extends En{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=sm&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new pr(ku,this.uri(),e)}};Zt.XHR=Zo;function ku(r){let e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||tm.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new Ou.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}});var ta=M(Qt=>{"use strict";var nm=Qt&&Qt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),om=Qt&&Qt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),am=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)&&nm(e,r,t);return om(e,r),e};Object.defineProperty(Qt,"__esModule",{value:!0});Qt.XHR=void 0;var Ru=am(tu()),Au=Qo(),cm=Ru.default||Ru,ea=class extends Au.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 Au.Request(i=>new cm(i),this.uri(),e)}};Qt.XHR=ea});var gr=M((tw,Lu)=>{"use strict";var Pu=["nodebuffer","arraybuffer","fragments"],Iu=typeof Blob<"u";Iu&&Pu.push("blob");Lu.exports={BINARY_TYPES:Pu,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Iu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var as=M((rw,wn)=>{"use strict";var{EMPTY_BUFFER:fm}=gr(),ra=Buffer[Symbol.species];function um(r,e){if(r.length===0)return fm;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),i=0;for(let s=0;s<r.length;s++){let n=r[s];t.set(n,i),i+=n.length}return i<e?new ra(t.buffer,t.byteOffset,i):t}function Nu(r,e,t,i,s){for(let n=0;n<s;n++)t[i+n]=r[n]^e[n&3]}function Du(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function lm(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function ia(r){if(ia.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new ra(r):ArrayBuffer.isView(r)?e=new ra(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),ia.readOnly=!1),e}wn.exports={concat:um,mask:Nu,toArrayBuffer:lm,toBuffer:ia,unmask:Du};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");wn.exports.mask=function(e,t,i,s,n){n<48?Nu(e,t,i,s,n):r.mask(e,t,i,s,n)},wn.exports.unmask=function(e,t){e.length<32?Du(e,t):r.unmask(e,t)}}catch{}});var Bu=M((iw,Fu)=>{"use strict";var Mu=Symbol("kDone"),sa=Symbol("kRun"),na=class{constructor(e){this[Mu]=()=>{this.pending--,this[sa]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[sa]()}[sa](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Mu])}}};Fu.exports=na});var fs=M((sw,Wu)=>{"use strict";var cs=require("zlib"),ju=as(),hm=Bu(),{kStatusCode:Uu}=gr(),dm=Buffer[Symbol.species],pm=Buffer.from([0,0,255,255]),xn=Symbol("permessage-deflate"),mr=Symbol("total-length"),Ai=Symbol("callback"),Mr=Symbol("buffers"),Pi=Symbol("error"),bn,oa=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,!bn){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;bn=new hm(s)}}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[Ai];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(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.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 s=t[i];if(s.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(s=s[0],i==="client_max_window_bits"){if(s!==!0){let n=+s;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=n}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else if(i==="server_max_window_bits"){let n=+s;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${i}": ${s}`);s=n}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${s}`)}else throw new Error(`Unknown parameter "${i}"`);t[i]=s})}),e}decompress(e,t,i){bn.add(s=>{this._decompress(e,t,(n,a)=>{s(),i(n,a)})})}compress(e,t,i){bn.add(s=>{this._compress(e,t,(n,a)=>{s(),i(n,a)})})}_decompress(e,t,i){let s=this._isServer?"client":"server";if(!this._inflate){let n=`${s}_max_window_bits`,a=typeof this.params[n]!="number"?cs.Z_DEFAULT_WINDOWBITS:this.params[n];this._inflate=cs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[xn]=this,this._inflate[mr]=0,this._inflate[Mr]=[],this._inflate.on("error",mm),this._inflate.on("data",qu)}this._inflate[Ai]=i,this._inflate.write(e),t&&this._inflate.write(pm),this._inflate.flush(()=>{let n=this._inflate[Pi];if(n){this._inflate.close(),this._inflate=null,i(n);return}let a=ju.concat(this._inflate[Mr],this._inflate[mr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[mr]=0,this._inflate[Mr]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),i(null,a)})}_compress(e,t,i){let s=this._isServer?"server":"client";if(!this._deflate){let n=`${s}_max_window_bits`,a=typeof this.params[n]!="number"?cs.Z_DEFAULT_WINDOWBITS:this.params[n];this._deflate=cs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[mr]=0,this._deflate[Mr]=[],this._deflate.on("data",gm)}this._deflate[Ai]=i,this._deflate.write(e),this._deflate.flush(cs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let n=ju.concat(this._deflate[Mr],this._deflate[mr]);t&&(n=new dm(n.buffer,n.byteOffset,n.length-4)),this._deflate[Ai]=null,this._deflate[mr]=0,this._deflate[Mr]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),i(null,n)})}};Wu.exports=oa;function gm(r){this[Mr].push(r),this[mr]+=r.length}function qu(r){if(this[mr]+=r.length,this[xn]._maxPayload<1||this[mr]<=this[xn]._maxPayload){this[Mr].push(r);return}this[Pi]=new RangeError("Max payload size exceeded"),this[Pi].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Pi][Uu]=1009,this.removeListener("data",qu),this.reset()}function mm(r){if(this[xn]._inflate=null,this[Pi]){this[Ai](this[Pi]);return}r[Uu]=1007,this[Ai](r)}});var Ii=M((nw,Sn)=>{"use strict";var{isUtf8:Hu}=require("buffer"),{hasBlob:_m}=gr(),ym=[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 vm(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 Em(r){return _m&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Sn.exports={isBlob:Em,isValidStatusCode:vm,isValidUTF8:aa,tokenChars:ym};if(Hu)Sn.exports.isValidUTF8=function(r){return r.length<24?aa(r):Hu(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Sn.exports.isValidUTF8=function(e){return e.length<32?aa(e):r(e)}}catch{}});var ha=M((ow,Xu)=>{"use strict";var{Writable:wm}=require("stream"),Vu=fs(),{BINARY_TYPES:bm,EMPTY_BUFFER:Ku,kStatusCode:xm,kWebSocket:Sm}=gr(),{concat:ca,toArrayBuffer:Tm,unmask:Cm}=as(),{isValidStatusCode:Om,isValidUTF8:zu}=Ii(),Tn=Buffer[Symbol.species],It=0,$u=1,Gu=2,Yu=3,fa=4,ua=5,Cn=6,la=class extends wm{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||bm[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Sm]=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=It}_write(e,t,i){if(this._opcode===8&&this._state==It)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 Tn(i.buffer,i.byteOffset+e,i.length-e),new Tn(i.buffer,i.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let i=this._buffers[0],s=t.length-e;e>=i.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(i.buffer,i.byteOffset,e),s),this._buffers[0]=new Tn(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 It:this.getInfo(e);break;case $u:this.getPayloadLength16(e);break;case Gu:this.getPayloadLength64(e);break;case Yu:this.getMask();break;case fa:this.getData(e);break;case ua:case Cn: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 s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let i=(t[0]&64)===64;if(i&&!this._extensions[Vu.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(i){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(i){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=$u:this._payloadLength===127?this._state=Gu: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 s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);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=Yu:this._state=fa}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=fa}getData(e){let t=Ku;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&&Cm(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=ua,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Vu.extensionName].decompress(e,this._fin,(s,n)=>{if(s)return t(s);if(n.length){if(this._messageLength+=n.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(n)}this.dataMessage(t),this._state===It&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=It;return}let t=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=ca(i,t):this._binaryType==="arraybuffer"?s=Tm(ca(i,t)):this._binaryType==="blob"?s=new Blob(i):s=i,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=It):(this._state=Cn,setImmediate(()=>{this.emit("message",s,!0),this._state=It,this.startLoop(e)}))}else{let s=ca(i,t);if(!this._skipUTF8Validation&&!zu(s)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(n);return}this._state===ua||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=It):(this._state=Cn,setImmediate(()=>{this.emit("message",s,!1),this._state=It,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ku),this.end();else{let i=e.readUInt16BE(0);if(!Om(i)){let n=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(n);return}let s=new Tn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!zu(s)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(n);return}this._loop=!1,this.emit("conclude",i,s),this.end()}this._state=It;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=It):(this._state=Cn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=It,this.startLoop(t)}))}createError(e,t,i,s,n){this._loop=!1,this._errored=!0;let a=new e(i?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=n,a[xm]=s,a}};Xu.exports=la});var ga=M((cw,Qu)=>{"use strict";var{Duplex:aw}=require("stream"),{randomFillSync:km}=require("crypto"),Ju=fs(),{EMPTY_BUFFER:Rm,kWebSocket:Am,NOOP:Pm}=gr(),{isBlob:Li,isValidStatusCode:Im}=Ii(),{mask:Zu,toBuffer:ri}=as(),Lt=Symbol("kByteLength"),Lm=Buffer.alloc(4),On=8*1024,ii,Ni=On,Ut=0,Nm=1,Dm=2,da=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=Ut,this.onerror=Pm,this[Am]=void 0}static frame(e,t){let i,s=!1,n=2,a=!1;t.mask&&(i=t.maskBuffer||Lm,t.generateMask?t.generateMask(i):(Ni===On&&(ii===void 0&&(ii=Buffer.alloc(On)),km(ii,0,On),Ni=0),i[0]=ii[Ni++],i[1]=ii[Ni++],i[2]=ii[Ni++],i[3]=ii[Ni++]),a=(i[0]|i[1]|i[2]|i[3])===0,n=6);let c;typeof e=="string"?(!t.mask||a)&&t[Lt]!==void 0?c=t[Lt]:(e=Buffer.from(e),c=e.length):(c=e.length,s=t.mask&&t.readOnly&&!a);let u=c;c>=65536?(n+=8,u=127):c>125&&(n+=2,u=126);let d=Buffer.allocUnsafe(s?c+n:n);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[n-4]=i[0],d[n-3]=i[1],d[n-2]=i[2],d[n-1]=i[3],a?[d,e]:s?(Zu(e,i,d,n,c),[d]):(Zu(e,i,e,0,c),[d,e])):[d,e]}close(e,t,i,s){let n;if(e===void 0)n=Rm;else{if(typeof e!="number"||!Im(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)n=Buffer.allocUnsafe(2),n.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");n=Buffer.allocUnsafe(2+c),n.writeUInt16BE(e,0),typeof t=="string"?n.write(t,2):n.set(t,2)}}let a={[Lt]:n.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ut?this.enqueue([this.dispatch,n,!1,a,s]):this.sendFrame(r.frame(n,a),s)}ping(e,t,i){let s,n;if(typeof e=="string"?(s=Buffer.byteLength(e),n=!1):Li(e)?(s=e.size,n=!1):(e=ri(e),s=e.length,n=ri.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Lt]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:!1};Li(e)?this._state!==Ut?this.enqueue([this.getBlobData,e,!1,a,i]):this.getBlobData(e,!1,a,i):this._state!==Ut?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(r.frame(e,a),i)}pong(e,t,i){let s,n;if(typeof e=="string"?(s=Buffer.byteLength(e),n=!1):Li(e)?(s=e.size,n=!1):(e=ri(e),s=e.length,n=ri.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Lt]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:!1};Li(e)?this._state!==Ut?this.enqueue([this.getBlobData,e,!1,a,i]):this.getBlobData(e,!1,a,i):this._state!==Ut?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(r.frame(e,a),i)}send(e,t,i){let s=this._extensions[Ju.extensionName],n=t.binary?2:1,a=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):Li(e)?(c=e.size,u=!1):(e=ri(e),c=e.length,u=ri.readOnly),this._firstFragment?(this._firstFragment=!1,a&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=c>=s._threshold),this._compress=a):(a=!1,n=0),t.fin&&(this._firstFragment=!0);let d={[Lt]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:n,readOnly:u,rsv1:a};Li(e)?this._state!==Ut?this.enqueue([this.getBlobData,e,this._compress,d,i]):this.getBlobData(e,this._compress,d,i):this._state!==Ut?this.enqueue([this.dispatch,e,this._compress,d,i]):this.dispatch(e,this._compress,d,i)}getBlobData(e,t,i,s){this._bufferedBytes+=i[Lt],this._state=Dm,e.arrayBuffer().then(n=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(pa,this,c,s);return}this._bufferedBytes-=i[Lt];let a=ri(n);t?this.dispatch(a,t,i,s):(this._state=Ut,this.sendFrame(r.frame(a,i),s),this.dequeue())}).catch(n=>{process.nextTick(Mm,this,n,s)})}dispatch(e,t,i,s){if(!t){this.sendFrame(r.frame(e,i),s);return}let n=this._extensions[Ju.extensionName];this._bufferedBytes+=i[Lt],this._state=Nm,n.compress(e,i.fin,(a,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");pa(this,u,s);return}this._bufferedBytes-=i[Lt],this._state=Ut,i.readOnly=!1,this.sendFrame(r.frame(c,i),s),this.dequeue()})}dequeue(){for(;this._state===Ut&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Lt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Lt],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)}};Qu.exports=da;function pa(r,e,t){typeof t=="function"&&t(e);for(let i=0;i<r._queue.length;i++){let s=r._queue[i],n=s[s.length-1];typeof n=="function"&&n(e)}}function Mm(r,e,t){pa(r,e,t),r.onerror(e)}});var cl=M((fw,al)=>{"use strict";var{kForOnEventAttribute:us,kListener:ma}=gr(),el=Symbol("kCode"),tl=Symbol("kData"),rl=Symbol("kError"),il=Symbol("kMessage"),sl=Symbol("kReason"),Di=Symbol("kTarget"),nl=Symbol("kType"),ol=Symbol("kWasClean"),_r=class{constructor(e){this[Di]=null,this[nl]=e}get target(){return this[Di]}get type(){return this[nl]}};Object.defineProperty(_r.prototype,"target",{enumerable:!0});Object.defineProperty(_r.prototype,"type",{enumerable:!0});var si=class extends _r{constructor(e,t={}){super(e),this[el]=t.code===void 0?0:t.code,this[sl]=t.reason===void 0?"":t.reason,this[ol]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[el]}get reason(){return this[sl]}get wasClean(){return this[ol]}};Object.defineProperty(si.prototype,"code",{enumerable:!0});Object.defineProperty(si.prototype,"reason",{enumerable:!0});Object.defineProperty(si.prototype,"wasClean",{enumerable:!0});var Mi=class extends _r{constructor(e,t={}){super(e),this[rl]=t.error===void 0?null:t.error,this[il]=t.message===void 0?"":t.message}get error(){return this[rl]}get message(){return this[il]}};Object.defineProperty(Mi.prototype,"error",{enumerable:!0});Object.defineProperty(Mi.prototype,"message",{enumerable:!0});var ls=class extends _r{constructor(e,t={}){super(e),this[tl]=t.data===void 0?null:t.data}get data(){return this[tl]}};Object.defineProperty(ls.prototype,"data",{enumerable:!0});var Fm={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[us]&&s[ma]===e&&!s[us])return;let i;if(r==="message")i=function(n,a){let c=new ls("message",{data:a?n:n.toString()});c[Di]=this,kn(e,this,c)};else if(r==="close")i=function(n,a){let c=new si("close",{code:n,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Di]=this,kn(e,this,c)};else if(r==="error")i=function(n){let a=new Mi("error",{error:n,message:n.message});a[Di]=this,kn(e,this,a)};else if(r==="open")i=function(){let n=new _r("open");n[Di]=this,kn(e,this,n)};else return;i[us]=!!t[us],i[ma]=e,t.once?this.once(r,i):this.on(r,i)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[ma]===e&&!t[us]){this.removeListener(r,t);break}}};al.exports={CloseEvent:si,ErrorEvent:Mi,Event:_r,EventTarget:Fm,MessageEvent:ls};function kn(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var _a=M((uw,fl)=>{"use strict";var{tokenChars:hs}=Ii();function er(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function Bm(r){let e=Object.create(null),t=Object.create(null),i=!1,s=!1,n=!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&&hs[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 b=r.slice(u,p);d===44?(er(e,b,t),t=Object.create(null)):a=b,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(c===void 0)if(p===-1&&hs[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),er(t,r.slice(u,p),!0),d===44&&(er(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(s){if(hs[d]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);u===-1?u=m:i||(i=!0),s=!1}else if(n)if(hs[d]===1)u===-1&&(u=m);else if(d===34&&u!==-1)n=!1,p=m;else if(d===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(d===34&&r.charCodeAt(m-1)===61)n=!0;else if(p===-1&&hs[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 b=r.slice(u,p);i&&(b=b.replace(/\\/g,""),i=!1),er(t,c,b),d===44&&(er(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||n||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=m);let y=r.slice(u,p);return a===void 0?er(e,y,t):(c===void 0?er(t,y,!0):i?er(t,c,y.replace(/\\/g,"")):er(t,c,y),er(e,a,t)),e}function jm(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(s=>{let n=i[s];return Array.isArray(n)||(n=[n]),n.map(a=>a===!0?s:`${s}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}fl.exports={format:jm,parse:Bm}});var In=M((dw,wl)=>{"use strict";var Um=require("events"),qm=require("https"),Wm=require("http"),hl=require("net"),Hm=require("tls"),{randomBytes:Vm,createHash:Km}=require("crypto"),{Duplex:lw,Readable:hw}=require("stream"),{URL:ya}=require("url"),Fr=fs(),zm=ha(),$m=ga(),{isBlob:Gm}=Ii(),{BINARY_TYPES:ul,EMPTY_BUFFER:Rn,GUID:Ym,kForOnEventAttribute:va,kListener:Xm,kStatusCode:Jm,kWebSocket:it,NOOP:dl}=gr(),{EventTarget:{addEventListener:Zm,removeEventListener:Qm}}=cl(),{format:e0,parse:t0}=_a(),{toBuffer:r0}=as(),i0=30*1e3,pl=Symbol("kAborted"),Ea=[8,13],yr=["CONNECTING","OPEN","CLOSING","CLOSED"],s0=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ue=class r extends Um{constructor(e,t,i){super(),this._binaryType=ul[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Rn,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]),gl(this,e,t,i)):(this._autoPong=i.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ul.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 s=new zm({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),n=new $m(e,this._extensions,i.generateMask);this._receiver=s,this._sender=n,this._socket=e,s[it]=this,n[it]=this,e[it]=this,s.on("conclude",a0),s.on("drain",c0),s.on("error",f0),s.on("message",u0),s.on("ping",l0),s.on("pong",h0),n.onerror=d0,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",yl),e.on("data",Pn),e.on("end",vl),e.on("error",El),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[Fr.extensionName]&&this._extensions[Fr.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){Tt(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())}),_l(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){wa(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Rn,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){wa(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Rn,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){wa(this,e,i);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Fr.extensionName]||(s.compress=!1),this._sender.send(e||Rn,s,i)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Tt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ue,"CONNECTING",{enumerable:!0,value:yr.indexOf("CONNECTING")});Object.defineProperty(Ue.prototype,"CONNECTING",{enumerable:!0,value:yr.indexOf("CONNECTING")});Object.defineProperty(Ue,"OPEN",{enumerable:!0,value:yr.indexOf("OPEN")});Object.defineProperty(Ue.prototype,"OPEN",{enumerable:!0,value:yr.indexOf("OPEN")});Object.defineProperty(Ue,"CLOSING",{enumerable:!0,value:yr.indexOf("CLOSING")});Object.defineProperty(Ue.prototype,"CLOSING",{enumerable:!0,value:yr.indexOf("CLOSING")});Object.defineProperty(Ue,"CLOSED",{enumerable:!0,value:yr.indexOf("CLOSED")});Object.defineProperty(Ue.prototype,"CLOSED",{enumerable:!0,value:yr.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(Ue.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(Ue.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[va])return e[Xm];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})}})});Ue.prototype.addEventListener=Zm;Ue.prototype.removeEventListener=Qm;wl.exports=Ue;function gl(r,e,t,i){let s={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:Ea[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=s.autoPong,!Ea.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Ea.join(", ")})`);let n;if(e instanceof ya)n=e;else try{n=new ya(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),r._url=n.href;let a=n.protocol==="wss:",c=n.protocol==="ws+unix:",u;if(n.protocol!=="ws:"&&!a&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!n.pathname?u="The URL's pathname is empty":n.hash&&(u="The URL contains a fragment identifier"),u){let C=new SyntaxError(u);if(r._redirects===0)throw C;An(r,C);return}let d=a?443:80,p=Vm(16).toString("base64"),m=a?qm.request:Wm.request,y=new Set,b;if(s.createConnection=s.createConnection||(a?o0:n0),s.defaultPort=s.defaultPort||d,s.port=n.port||d,s.host=n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},s.path=n.pathname+n.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(b=new Fr(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=e0({[Fr.extensionName]:b.offer()})),t.length){for(let C of t){if(typeof C!="string"||!s0.test(C)||y.has(C))throw new SyntaxError("An invalid or duplicated subprotocol was specified");y.add(C)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(n.username||n.password)&&(s.auth=`${n.username}:${n.password}`),c){let C=s.path.split(":");s.socketPath=C[0],s.path=C[1]}let T;if(s.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=a,r._originalHostOrSocketPath=c?s.socketPath:n.host;let C=i&&i.headers;if(i={...i,headers:{}},C)for(let[V,_e]of Object.entries(C))i.headers[V.toLowerCase()]=_e}else if(r.listenerCount("redirect")===0){let C=c?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:n.host===r._originalHostOrSocketPath;(!C||r._originalSecure&&!a)&&(delete s.headers.authorization,delete s.headers.cookie,C||delete s.headers.host,s.auth=void 0)}s.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),T=r._req=m(s),r._redirects&&r.emit("redirect",r.url,T)}else T=r._req=m(s);s.timeout&&T.on("timeout",()=>{Tt(r,T,"Opening handshake has timed out")}),T.on("error",C=>{T===null||T[pl]||(T=r._req=null,An(r,C))}),T.on("response",C=>{let V=C.headers.location,_e=C.statusCode;if(V&&s.followRedirects&&_e>=300&&_e<400){if(++r._redirects>s.maxRedirects){Tt(r,T,"Maximum redirects exceeded");return}T.abort();let X;try{X=new ya(V,e)}catch{let B=new SyntaxError(`Invalid URL: ${V}`);An(r,B);return}gl(r,X,t,i)}else r.emit("unexpected-response",T,C)||Tt(r,T,`Unexpected server response: ${C.statusCode}`)}),T.on("upgrade",(C,V,_e)=>{if(r.emit("upgrade",C),r.readyState!==Ue.CONNECTING)return;T=r._req=null;let X=C.headers.upgrade;if(X===void 0||X.toLowerCase()!=="websocket"){Tt(r,V,"Invalid Upgrade header");return}let P=Km("sha1").update(p+Ym).digest("base64");if(C.headers["sec-websocket-accept"]!==P){Tt(r,V,"Invalid Sec-WebSocket-Accept header");return}let B=C.headers["sec-websocket-protocol"],te;if(B!==void 0?y.size?y.has(B)||(te="Server sent an invalid subprotocol"):te="Server sent a subprotocol but none was requested":y.size&&(te="Server sent no subprotocol"),te){Tt(r,V,te);return}B&&(r._protocol=B);let A=C.headers["sec-websocket-extensions"];if(A!==void 0){if(!b){Tt(r,V,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ae;try{ae=t0(A)}catch{Tt(r,V,"Invalid Sec-WebSocket-Extensions header");return}let pe=Object.keys(ae);if(pe.length!==1||pe[0]!==Fr.extensionName){Tt(r,V,"Server indicated an extension that was not requested");return}try{b.accept(ae[Fr.extensionName])}catch{Tt(r,V,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Fr.extensionName]=b}r.setSocket(V,_e,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(T,r):T.end()}function An(r,e){r._readyState=Ue.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function n0(r){return r.path=r.socketPath,hl.connect(r)}function o0(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=hl.isIP(r.host)?"":r.host),Hm.connect(r)}function Tt(r,e,t){r._readyState=Ue.CLOSING;let i=new Error(t);Error.captureStackTrace(i,Tt),e.setHeader?(e[pl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(An,r,i)):(e.destroy(i),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function wa(r,e,t){if(e){let i=Gm(e)?e.size:r0(e).length;r._socket?r._sender._bufferedBytes+=i:r._bufferedAmount+=i}if(t){let i=new Error(`WebSocket is not open: readyState ${r.readyState} (${yr[r.readyState]})`);process.nextTick(t,i)}}function a0(r,e){let t=this[it];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[it]!==void 0&&(t._socket.removeListener("data",Pn),process.nextTick(ml,t._socket),r===1005?t.close():t.close(r,e))}function c0(){let r=this[it];r.isPaused||r._socket.resume()}function f0(r){let e=this[it];e._socket[it]!==void 0&&(e._socket.removeListener("data",Pn),process.nextTick(ml,e._socket),e.close(r[Jm])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function ll(){this[it].emitClose()}function u0(r,e){this[it].emit("message",r,e)}function l0(r){let e=this[it];e._autoPong&&e.pong(r,!this._isServer,dl),e.emit("ping",r)}function h0(r){this[it].emit("pong",r)}function ml(r){r.resume()}function d0(r){let e=this[it];e.readyState!==Ue.CLOSED&&(e.readyState===Ue.OPEN&&(e._readyState=Ue.CLOSING,_l(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function _l(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),i0)}function yl(){let r=this[it];this.removeListener("close",yl),this.removeListener("data",Pn),this.removeListener("end",vl),r._readyState=Ue.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[it]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",ll),r._receiver.on("finish",ll))}function Pn(r){this[it]._receiver.write(r)||this.pause()}function vl(){let r=this[it];r._readyState=Ue.CLOSING,r._receiver.end(),this.end()}function El(){let r=this[it];this.removeListener("error",El),this.on("error",dl),r&&(r._readyState=Ue.CLOSING,this.destroy())}});var Tl=M((gw,Sl)=>{"use strict";var pw=In(),{Duplex:p0}=require("stream");function bl(r){r.emit("close")}function g0(){!this.destroyed&&this._writableState.finished&&this.destroy()}function xl(r){this.removeListener("error",xl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function m0(r,e){let t=!0,i=new p0({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(n,a){let c=!a&&i._readableState.objectMode?n.toString():n;i.push(c)||r.pause()}),r.once("error",function(n){i.destroyed||(t=!1,i.destroy(n))}),r.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(s,n){if(r.readyState===r.CLOSED){n(s),process.nextTick(bl,i);return}let a=!1;r.once("error",function(u){a=!0,n(u)}),r.once("close",function(){a||n(s),process.nextTick(bl,i)}),t&&r.terminate()},i._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){i._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),i._readableState.endEmitted&&i.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},i._read=function(){r.isPaused&&r.resume()},i._write=function(s,n,a){if(r.readyState===r.CONNECTING){r.once("open",function(){i._write(s,n,a)});return}r.send(s,a)},i.on("end",g0),i.on("error",xl),i}Sl.exports=m0});var Ol=M((mw,Cl)=>{"use strict";var{tokenChars:_0}=Ii();function y0(r){let e=new Set,t=-1,i=-1,s=0;for(s;s<r.length;s++){let a=r.charCodeAt(s);if(i===-1&&_0[a]===1)t===-1&&(t=s);else if(s!==0&&(a===32||a===9))i===-1&&t!==-1&&(i=s);else if(a===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);i===-1&&(i=s);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 ${s}`)}if(t===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let n=r.slice(t,s);if(e.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);return e.add(n),e}Cl.exports={parse:y0}});var Nl=M((yw,Ll)=>{"use strict";var v0=require("events"),Ln=require("http"),{Duplex:_w}=require("stream"),{createHash:E0}=require("crypto"),kl=_a(),ni=fs(),w0=Ol(),b0=In(),{GUID:x0,kWebSocket:S0}=gr(),T0=/^[+/0-9A-Za-z]{22}==$/,Rl=0,Al=1,Il=2,ba=class extends v0{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:b0,...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=Ln.createServer((i,s)=>{let n=Ln.STATUS_CODES[426];s.writeHead(426,{"Content-Length":n.length,"Content-Type":"text/plain"}),s.end(n)}),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=C0(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,n,a)=>{this.handleUpgrade(s,n,a,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Rl}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===Il){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ds,this);return}if(e&&this.once("close",e),this._state!==Al)if(this._state=Al,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(ds,this):process.nextTick(ds,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{ds(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,s){t.on("error",Pl);let n=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){oi(this,e,t,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){oi(this,e,t,400,"Invalid Upgrade header");return}if(n===void 0||!T0.test(n)){oi(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){oi(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ps(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=w0.parse(u)}catch{oi(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 y=new ni(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let b=kl.parse(p);b[ni.extensionName]&&(y.accept(b[ni.extensionName]),m[ni.extensionName]=y)}catch{oi(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let y={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(y,(b,T,C,V)=>{if(!b)return ps(t,T||401,C,V);this.completeUpgrade(m,n,d,e,t,i,s)});return}if(!this.options.verifyClient(y))return ps(t,401)}this.completeUpgrade(m,n,d,e,t,i,s)}completeUpgrade(e,t,i,s,n,a,c){if(!n.readable||!n.writable)return n.destroy();if(n[S0])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Rl)return ps(n,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${E0("sha1").update(t+x0).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(i.size){let m=this.options.handleProtocols?this.options.handleProtocols(i,s):i.values().next().value;m&&(d.push(`Sec-WebSocket-Protocol: ${m}`),p._protocol=m)}if(e[ni.extensionName]){let m=e[ni.extensionName].params,y=kl.format({[ni.extensionName]:[m]});d.push(`Sec-WebSocket-Extensions: ${y}`),p._extensions=e}this.emit("headers",d,s),n.write(d.concat(`\r
|
|
22
|
+
`).map(e=>e.trim()).join(" ")};Eu.O=function(r){return this.inspectOpts.colors=this.useColors,mn.inspect(r,this.inspectOpts)}});var Pt=D((YE,$o)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?$o.exports=pu():$o.exports=wu()});var oi=D(Mr=>{"use strict";var qg=Mr&&Mr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Mr,"__esModule",{value:!0});Mr.Transport=Mr.TransportError=void 0;var Wg=Ts(),Hg=Zr(),Vg=es(),zg=Ho(),Kg=qg(Pt()),$g=(0,Kg.default)("engine.io-client:transport"),yn=class extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}};Mr.TransportError=yn;var Go=class extends Hg.Emitter{constructor(e){super(),this.writable=!1,(0,Vg.installTimerFunctions)(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,s){return super.emitReserved("error",new yn(e,t,s)),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):$g("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=(0,Wg.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,zg.encode)(e);return t.length?"?"+t:""}};Mr.Transport=Go});var Xo=D(As=>{"use strict";var Gg=As&&As.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(As,"__esModule",{value:!0});As.Polling=void 0;var Yg=oi(),Xg=es(),bu=Ts(),Jg=Gg(Pt()),jt=(0,Jg.default)("engine.io-client:polling"),Yo=class extends Yg.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{jt("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let s=0;this._polling&&(jt("we are currently polling - waiting to pause"),s++,this.once("pollComplete",function(){jt("pre-pause polling complete"),--s||t()})),this.writable||(jt("we are currently writing - waiting to pause"),s++,this.once("drain",function(){jt("pre-pause writing complete"),--s||t()}))}else t()}_poll(){jt("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){jt("polling got data %s",e);let t=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};(0,bu.decodePayload)(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():jt('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{jt("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(jt("transport open - closing"),e()):(jt("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,(0,bu.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,Xg.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};As.Polling=Yo});var Su=D(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.hasCORS=void 0;var xu=!1;try{xu=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}vn.hasCORS=xu});var Qo=D(Zt=>{"use strict";var Zg=Zt&&Zt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Zt,"__esModule",{value:!0});Zt.XHR=Zt.Request=Zt.BaseXHR=void 0;var Qg=Xo(),em=Zr(),Tu=es(),Ou=Qr(),tm=Su(),rm=Zg(Pt()),Jo=(0,rm.default)("engine.io-client:polling");function sm(){}var En=class extends Qg.Polling{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",s=location.port;s||(s=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||s!==e.port}}doWrite(e,t){let s=this.request({method:"POST",data:e});s.on("success",t),s.on("error",(i,n)=>{this.onError("xhr post error",i,n)})}doPoll(){Jo("xhr poll");let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,s)=>{this.onError("xhr poll error",t,s)}),this.pollXhr=e}};Zt.BaseXHR=En;var pr=class r extends em.Emitter{constructor(e,t,s){super(),this.createRequest=e,(0,Tu.installTimerFunctions)(this,s),this._opts=s,this._method=s.method||"GET",this._uri=t,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var e;let t=(0,Tu.pick)(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let s=this._xhr=this.createRequest(t);try{Jo("xhr open %s: %s",this._method,this._uri),s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&s.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var i;s.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},Jo("xhr data %s",this._data),s.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=sm,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()}};Zt.Request=pr;pr.requestsCount=0;pr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Cu);else if(typeof addEventListener=="function"){let r="onpagehide"in Ou.globalThisShim?"pagehide":"unload";addEventListener(r,Cu,!1)}}function Cu(){for(let r in pr.requests)pr.requests.hasOwnProperty(r)&&pr.requests[r].abort()}var im=(function(){let r=ku({xdomain:!1});return r&&r.responseType!==null})(),Zo=class extends En{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=im&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new pr(ku,this.uri(),e)}};Zt.XHR=Zo;function ku(r){let e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||tm.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new Ou.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}});var ta=D(Qt=>{"use strict";var nm=Qt&&Qt.__createBinding||(Object.create?(function(r,e,t,s){s===void 0&&(s=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,s,i)}):(function(r,e,t,s){s===void 0&&(s=t),r[s]=e[t]})),om=Qt&&Qt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),am=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)&&nm(e,r,t);return om(e,r),e};Object.defineProperty(Qt,"__esModule",{value:!0});Qt.XHR=void 0;var Ru=am(tu()),Au=Qo(),cm=Ru.default||Ru,ea=class extends Au.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 Au.Request(s=>new cm(s),this.uri(),e)}};Qt.XHR=ea});var gr=D((tw,Lu)=>{"use strict";var Pu=["nodebuffer","arraybuffer","fragments"],Iu=typeof Blob<"u";Iu&&Pu.push("blob");Lu.exports={BINARY_TYPES:Pu,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Iu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ai=D((rw,wn)=>{"use strict";var{EMPTY_BUFFER:fm}=gr(),ra=Buffer[Symbol.species];function um(r,e){if(r.length===0)return fm;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),s=0;for(let i=0;i<r.length;i++){let n=r[i];t.set(n,s),s+=n.length}return s<e?new ra(t.buffer,t.byteOffset,s):t}function Nu(r,e,t,s,i){for(let n=0;n<i;n++)t[s+n]=r[n]^e[n&3]}function Mu(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function lm(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function sa(r){if(sa.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new ra(r):ArrayBuffer.isView(r)?e=new ra(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),sa.readOnly=!1),e}wn.exports={concat:um,mask:Nu,toArrayBuffer:lm,toBuffer:sa,unmask:Mu};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");wn.exports.mask=function(e,t,s,i,n){n<48?Nu(e,t,s,i,n):r.mask(e,t,s,i,n)},wn.exports.unmask=function(e,t){e.length<32?Mu(e,t):r.unmask(e,t)}}catch{}});var Bu=D((sw,Fu)=>{"use strict";var Du=Symbol("kDone"),ia=Symbol("kRun"),na=class{constructor(e){this[Du]=()=>{this.pending--,this[ia]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ia]()}[ia](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Du])}}};Fu.exports=na});var fi=D((iw,Wu)=>{"use strict";var ci=require("zlib"),ju=ai(),hm=Bu(),{kStatusCode:Uu}=gr(),dm=Buffer[Symbol.species],pm=Buffer.from([0,0,255,255]),xn=Symbol("permessage-deflate"),mr=Symbol("total-length"),Ps=Symbol("callback"),Dr=Symbol("buffers"),Is=Symbol("error"),bn,oa=class{constructor(e,t,s){if(this._maxPayload=s|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,!bn){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;bn=new hm(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[Ps];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,s=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(!s)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(s.server_no_context_takeover=!0),t.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(s.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?s.client_max_window_bits=t.clientMaxWindowBits:(s.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}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(s=>{let i=t[s];if(i.length>1)throw new Error(`Parameter "${s}" must have only a single value`);if(i=i[0],s==="client_max_window_bits"){if(i!==!0){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${s}": ${i}`);i=n}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${i}`)}else if(s==="server_max_window_bits"){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${s}": ${i}`);i=n}else if(s==="client_no_context_takeover"||s==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${s}": ${i}`)}else throw new Error(`Unknown parameter "${s}"`);t[s]=i})}),e}decompress(e,t,s){bn.add(i=>{this._decompress(e,t,(n,a)=>{i(),s(n,a)})})}compress(e,t,s){bn.add(i=>{this._compress(e,t,(n,a)=>{i(),s(n,a)})})}_decompress(e,t,s){let i=this._isServer?"client":"server";if(!this._inflate){let n=`${i}_max_window_bits`,a=typeof this.params[n]!="number"?ci.Z_DEFAULT_WINDOWBITS:this.params[n];this._inflate=ci.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[xn]=this,this._inflate[mr]=0,this._inflate[Dr]=[],this._inflate.on("error",mm),this._inflate.on("data",qu)}this._inflate[Ps]=s,this._inflate.write(e),t&&this._inflate.write(pm),this._inflate.flush(()=>{let n=this._inflate[Is];if(n){this._inflate.close(),this._inflate=null,s(n);return}let a=ju.concat(this._inflate[Dr],this._inflate[mr]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[mr]=0,this._inflate[Dr]=[],t&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),s(null,a)})}_compress(e,t,s){let i=this._isServer?"server":"client";if(!this._deflate){let n=`${i}_max_window_bits`,a=typeof this.params[n]!="number"?ci.Z_DEFAULT_WINDOWBITS:this.params[n];this._deflate=ci.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[mr]=0,this._deflate[Dr]=[],this._deflate.on("data",gm)}this._deflate[Ps]=s,this._deflate.write(e),this._deflate.flush(ci.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let n=ju.concat(this._deflate[Dr],this._deflate[mr]);t&&(n=new dm(n.buffer,n.byteOffset,n.length-4)),this._deflate[Ps]=null,this._deflate[mr]=0,this._deflate[Dr]=[],t&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),s(null,n)})}};Wu.exports=oa;function gm(r){this[Dr].push(r),this[mr]+=r.length}function qu(r){if(this[mr]+=r.length,this[xn]._maxPayload<1||this[mr]<=this[xn]._maxPayload){this[Dr].push(r);return}this[Is]=new RangeError("Max payload size exceeded"),this[Is].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Is][Uu]=1009,this.removeListener("data",qu),this.reset()}function mm(r){if(this[xn]._inflate=null,this[Is]){this[Ps](this[Is]);return}r[Uu]=1007,this[Ps](r)}});var Ls=D((nw,Sn)=>{"use strict";var{isUtf8:Hu}=require("buffer"),{hasBlob:_m}=gr(),ym=[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 vm(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 Em(r){return _m&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Sn.exports={isBlob:Em,isValidStatusCode:vm,isValidUTF8:aa,tokenChars:ym};if(Hu)Sn.exports.isValidUTF8=function(r){return r.length<24?aa(r):Hu(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Sn.exports.isValidUTF8=function(e){return e.length<32?aa(e):r(e)}}catch{}});var ha=D((ow,Xu)=>{"use strict";var{Writable:wm}=require("stream"),Vu=fi(),{BINARY_TYPES:bm,EMPTY_BUFFER:zu,kStatusCode:xm,kWebSocket:Sm}=gr(),{concat:ca,toArrayBuffer:Tm,unmask:Cm}=ai(),{isValidStatusCode:Om,isValidUTF8:Ku}=Ls(),Tn=Buffer[Symbol.species],It=0,$u=1,Gu=2,Yu=3,fa=4,ua=5,Cn=6,la=class extends wm{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||bm[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Sm]=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=It}_write(e,t,s){if(this._opcode===8&&this._state==It)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let s=this._buffers[0];return this._buffers[0]=new Tn(s.buffer,s.byteOffset+e,s.length-e),new Tn(s.buffer,s.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let s=this._buffers[0],i=t.length-e;e>=s.length?t.set(this._buffers.shift(),i):(t.set(new Uint8Array(s.buffer,s.byteOffset,e),i),this._buffers[0]=new Tn(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case It:this.getInfo(e);break;case $u:this.getPayloadLength16(e);break;case Gu:this.getPayloadLength64(e);break;case Yu:this.getMask();break;case fa:this.getData(e);break;case ua:case Cn: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 s=(t[0]&64)===64;if(s&&!this._extensions[Vu.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(s){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=s}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(s){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=$u:this._payloadLength===127?this._state=Gu: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),s=t.readUInt32BE(0);if(s>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=s*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=Yu:this._state=fa}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=fa}getData(e){let t=zu;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&&Cm(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=ua,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Vu.extensionName].decompress(e,this._fin,(i,n)=>{if(i)return t(i);if(n.length){if(this._messageLength+=n.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(n)}this.dataMessage(t),this._state===It&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=It;return}let t=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=ca(s,t):this._binaryType==="arraybuffer"?i=Tm(ca(s,t)):this._binaryType==="blob"?i=new Blob(s):i=s,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=It):(this._state=Cn,setImmediate(()=>{this.emit("message",i,!0),this._state=It,this.startLoop(e)}))}else{let i=ca(s,t);if(!this._skipUTF8Validation&&!Ku(i)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(n);return}this._state===ua||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=It):(this._state=Cn,setImmediate(()=>{this.emit("message",i,!1),this._state=It,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,zu),this.end();else{let s=e.readUInt16BE(0);if(!Om(s)){let n=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(n);return}let i=new Tn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ku(i)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(n);return}this._loop=!1,this.emit("conclude",s,i),this.end()}this._state=It;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=It):(this._state=Cn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=It,this.startLoop(t)}))}createError(e,t,s,i,n){this._loop=!1,this._errored=!0;let a=new e(s?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=n,a[xm]=i,a}};Xu.exports=la});var ga=D((cw,Qu)=>{"use strict";var{Duplex:aw}=require("stream"),{randomFillSync:km}=require("crypto"),Ju=fi(),{EMPTY_BUFFER:Rm,kWebSocket:Am,NOOP:Pm}=gr(),{isBlob:Ns,isValidStatusCode:Im}=Ls(),{mask:Zu,toBuffer:rs}=ai(),Lt=Symbol("kByteLength"),Lm=Buffer.alloc(4),On=8*1024,ss,Ms=On,Ut=0,Nm=1,Mm=2,da=class r{constructor(e,t,s){this._extensions=t||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Ut,this.onerror=Pm,this[Am]=void 0}static frame(e,t){let s,i=!1,n=2,a=!1;t.mask&&(s=t.maskBuffer||Lm,t.generateMask?t.generateMask(s):(Ms===On&&(ss===void 0&&(ss=Buffer.alloc(On)),km(ss,0,On),Ms=0),s[0]=ss[Ms++],s[1]=ss[Ms++],s[2]=ss[Ms++],s[3]=ss[Ms++]),a=(s[0]|s[1]|s[2]|s[3])===0,n=6);let c;typeof e=="string"?(!t.mask||a)&&t[Lt]!==void 0?c=t[Lt]:(e=Buffer.from(e),c=e.length):(c=e.length,i=t.mask&&t.readOnly&&!a);let u=c;c>=65536?(n+=8,u=127):c>125&&(n+=2,u=126);let d=Buffer.allocUnsafe(i?c+n:n);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[n-4]=s[0],d[n-3]=s[1],d[n-2]=s[2],d[n-1]=s[3],a?[d,e]:i?(Zu(e,s,d,n,c),[d]):(Zu(e,s,e,0,c),[d,e])):[d,e]}close(e,t,s,i){let n;if(e===void 0)n=Rm;else{if(typeof e!="number"||!Im(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)n=Buffer.allocUnsafe(2),n.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");n=Buffer.allocUnsafe(2+c),n.writeUInt16BE(e,0),typeof t=="string"?n.write(t,2):n.set(t,2)}}let a={[Lt]:n.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ut?this.enqueue([this.dispatch,n,!1,a,i]):this.sendFrame(r.frame(n,a),i)}ping(e,t,s){let i,n;if(typeof e=="string"?(i=Buffer.byteLength(e),n=!1):Ns(e)?(i=e.size,n=!1):(e=rs(e),i=e.length,n=rs.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Lt]:i,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:!1};Ns(e)?this._state!==Ut?this.enqueue([this.getBlobData,e,!1,a,s]):this.getBlobData(e,!1,a,s):this._state!==Ut?this.enqueue([this.dispatch,e,!1,a,s]):this.sendFrame(r.frame(e,a),s)}pong(e,t,s){let i,n;if(typeof e=="string"?(i=Buffer.byteLength(e),n=!1):Ns(e)?(i=e.size,n=!1):(e=rs(e),i=e.length,n=rs.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Lt]:i,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:!1};Ns(e)?this._state!==Ut?this.enqueue([this.getBlobData,e,!1,a,s]):this.getBlobData(e,!1,a,s):this._state!==Ut?this.enqueue([this.dispatch,e,!1,a,s]):this.sendFrame(r.frame(e,a),s)}send(e,t,s){let i=this._extensions[Ju.extensionName],n=t.binary?2:1,a=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):Ns(e)?(c=e.size,u=!1):(e=rs(e),c=e.length,u=rs.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,n=0),t.fin&&(this._firstFragment=!0);let d={[Lt]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:n,readOnly:u,rsv1:a};Ns(e)?this._state!==Ut?this.enqueue([this.getBlobData,e,this._compress,d,s]):this.getBlobData(e,this._compress,d,s):this._state!==Ut?this.enqueue([this.dispatch,e,this._compress,d,s]):this.dispatch(e,this._compress,d,s)}getBlobData(e,t,s,i){this._bufferedBytes+=s[Lt],this._state=Mm,e.arrayBuffer().then(n=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(pa,this,c,i);return}this._bufferedBytes-=s[Lt];let a=rs(n);t?this.dispatch(a,t,s,i):(this._state=Ut,this.sendFrame(r.frame(a,s),i),this.dequeue())}).catch(n=>{process.nextTick(Dm,this,n,i)})}dispatch(e,t,s,i){if(!t){this.sendFrame(r.frame(e,s),i);return}let n=this._extensions[Ju.extensionName];this._bufferedBytes+=s[Lt],this._state=Nm,n.compress(e,s.fin,(a,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");pa(this,u,i);return}this._bufferedBytes-=s[Lt],this._state=Ut,s.readOnly=!1,this.sendFrame(r.frame(c,s),i),this.dequeue()})}dequeue(){for(;this._state===Ut&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Lt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Lt],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)}};Qu.exports=da;function pa(r,e,t){typeof t=="function"&&t(e);for(let s=0;s<r._queue.length;s++){let i=r._queue[s],n=i[i.length-1];typeof n=="function"&&n(e)}}function Dm(r,e,t){pa(r,e,t),r.onerror(e)}});var cl=D((fw,al)=>{"use strict";var{kForOnEventAttribute:ui,kListener:ma}=gr(),el=Symbol("kCode"),tl=Symbol("kData"),rl=Symbol("kError"),sl=Symbol("kMessage"),il=Symbol("kReason"),Ds=Symbol("kTarget"),nl=Symbol("kType"),ol=Symbol("kWasClean"),_r=class{constructor(e){this[Ds]=null,this[nl]=e}get target(){return this[Ds]}get type(){return this[nl]}};Object.defineProperty(_r.prototype,"target",{enumerable:!0});Object.defineProperty(_r.prototype,"type",{enumerable:!0});var is=class extends _r{constructor(e,t={}){super(e),this[el]=t.code===void 0?0:t.code,this[il]=t.reason===void 0?"":t.reason,this[ol]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[el]}get reason(){return this[il]}get wasClean(){return this[ol]}};Object.defineProperty(is.prototype,"code",{enumerable:!0});Object.defineProperty(is.prototype,"reason",{enumerable:!0});Object.defineProperty(is.prototype,"wasClean",{enumerable:!0});var Fs=class extends _r{constructor(e,t={}){super(e),this[rl]=t.error===void 0?null:t.error,this[sl]=t.message===void 0?"":t.message}get error(){return this[rl]}get message(){return this[sl]}};Object.defineProperty(Fs.prototype,"error",{enumerable:!0});Object.defineProperty(Fs.prototype,"message",{enumerable:!0});var li=class extends _r{constructor(e,t={}){super(e),this[tl]=t.data===void 0?null:t.data}get data(){return this[tl]}};Object.defineProperty(li.prototype,"data",{enumerable:!0});var Fm={addEventListener(r,e,t={}){for(let i of this.listeners(r))if(!t[ui]&&i[ma]===e&&!i[ui])return;let s;if(r==="message")s=function(n,a){let c=new li("message",{data:a?n:n.toString()});c[Ds]=this,kn(e,this,c)};else if(r==="close")s=function(n,a){let c=new is("close",{code:n,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Ds]=this,kn(e,this,c)};else if(r==="error")s=function(n){let a=new Fs("error",{error:n,message:n.message});a[Ds]=this,kn(e,this,a)};else if(r==="open")s=function(){let n=new _r("open");n[Ds]=this,kn(e,this,n)};else return;s[ui]=!!t[ui],s[ma]=e,t.once?this.once(r,s):this.on(r,s)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[ma]===e&&!t[ui]){this.removeListener(r,t);break}}};al.exports={CloseEvent:is,ErrorEvent:Fs,Event:_r,EventTarget:Fm,MessageEvent:li};function kn(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var _a=D((uw,fl)=>{"use strict";var{tokenChars:hi}=Ls();function er(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function Bm(r){let e=Object.create(null),t=Object.create(null),s=!1,i=!1,n=!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&&hi[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 b=r.slice(u,p);d===44?(er(e,b,t),t=Object.create(null)):a=b,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(c===void 0)if(p===-1&&hi[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),er(t,r.slice(u,p),!0),d===44&&(er(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(hi[d]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);u===-1?u=m:s||(s=!0),i=!1}else if(n)if(hi[d]===1)u===-1&&(u=m);else if(d===34&&u!==-1)n=!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)n=!0;else if(p===-1&&hi[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 b=r.slice(u,p);s&&(b=b.replace(/\\/g,""),s=!1),er(t,c,b),d===44&&(er(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||n||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=m);let y=r.slice(u,p);return a===void 0?er(e,y,t):(c===void 0?er(t,y,!0):s?er(t,c,y.replace(/\\/g,"")):er(t,c,y),er(e,a,t)),e}function jm(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(s=>[e].concat(Object.keys(s).map(i=>{let n=s[i];return Array.isArray(n)||(n=[n]),n.map(a=>a===!0?i:`${i}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}fl.exports={format:jm,parse:Bm}});var In=D((dw,wl)=>{"use strict";var Um=require("events"),qm=require("https"),Wm=require("http"),hl=require("net"),Hm=require("tls"),{randomBytes:Vm,createHash:zm}=require("crypto"),{Duplex:lw,Readable:hw}=require("stream"),{URL:ya}=require("url"),Fr=fi(),Km=ha(),$m=ga(),{isBlob:Gm}=Ls(),{BINARY_TYPES:ul,EMPTY_BUFFER:Rn,GUID:Ym,kForOnEventAttribute:va,kListener:Xm,kStatusCode:Jm,kWebSocket:st,NOOP:dl}=gr(),{EventTarget:{addEventListener:Zm,removeEventListener:Qm}}=cl(),{format:e0,parse:t0}=_a(),{toBuffer:r0}=ai(),s0=30*1e3,pl=Symbol("kAborted"),Ea=[8,13],yr=["CONNECTING","OPEN","CLOSING","CLOSED"],i0=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ue=class r extends Um{constructor(e,t,s){super(),this._binaryType=ul[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Rn,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?(s=t,t=[]):t=[t]),gl(this,e,t,s)):(this._autoPong=s.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ul.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,s){let i=new Km({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),n=new $m(e,this._extensions,s.generateMask);this._receiver=i,this._sender=n,this._socket=e,i[st]=this,n[st]=this,e[st]=this,i.on("conclude",a0),i.on("drain",c0),i.on("error",f0),i.on("message",u0),i.on("ping",l0),i.on("pong",h0),n.onerror=d0,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",yl),e.on("data",Pn),e.on("end",vl),e.on("error",El),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[Fr.extensionName]&&this._extensions[Fr.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){Tt(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,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),_l(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,s){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=t=void 0):typeof t=="function"&&(s=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){wa(this,e,s);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Rn,t,s)}pong(e,t,s){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=t=void 0):typeof t=="function"&&(s=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){wa(this,e,s);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Rn,t,s)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,s){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(s=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){wa(this,e,s);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Fr.extensionName]||(i.compress=!1),this._sender.send(e||Rn,i,s)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Tt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ue,"CONNECTING",{enumerable:!0,value:yr.indexOf("CONNECTING")});Object.defineProperty(Ue.prototype,"CONNECTING",{enumerable:!0,value:yr.indexOf("CONNECTING")});Object.defineProperty(Ue,"OPEN",{enumerable:!0,value:yr.indexOf("OPEN")});Object.defineProperty(Ue.prototype,"OPEN",{enumerable:!0,value:yr.indexOf("OPEN")});Object.defineProperty(Ue,"CLOSING",{enumerable:!0,value:yr.indexOf("CLOSING")});Object.defineProperty(Ue.prototype,"CLOSING",{enumerable:!0,value:yr.indexOf("CLOSING")});Object.defineProperty(Ue,"CLOSED",{enumerable:!0,value:yr.indexOf("CLOSED")});Object.defineProperty(Ue.prototype,"CLOSED",{enumerable:!0,value:yr.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(Ue.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(Ue.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[va])return e[Xm];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})}})});Ue.prototype.addEventListener=Zm;Ue.prototype.removeEventListener=Qm;wl.exports=Ue;function gl(r,e,t,s){let i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:Ea[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,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,!Ea.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Ea.join(", ")})`);let n;if(e instanceof ya)n=e;else try{n=new ya(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),r._url=n.href;let a=n.protocol==="wss:",c=n.protocol==="ws+unix:",u;if(n.protocol!=="ws:"&&!a&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!n.pathname?u="The URL's pathname is empty":n.hash&&(u="The URL contains a fragment identifier"),u){let C=new SyntaxError(u);if(r._redirects===0)throw C;An(r,C);return}let d=a?443:80,p=Vm(16).toString("base64"),m=a?qm.request:Wm.request,y=new Set,b;if(i.createConnection=i.createConnection||(a?o0:n0),i.defaultPort=i.defaultPort||d,i.port=n.port||d,i.host=n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},i.path=n.pathname+n.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(b=new Fr(i.perMessageDeflate!==!0?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=e0({[Fr.extensionName]:b.offer()})),t.length){for(let C of t){if(typeof C!="string"||!i0.test(C)||y.has(C))throw new SyntaxError("An invalid or duplicated subprotocol was specified");y.add(C)}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),(n.username||n.password)&&(i.auth=`${n.username}:${n.password}`),c){let C=i.path.split(":");i.socketPath=C[0],i.path=C[1]}let T;if(i.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=a,r._originalHostOrSocketPath=c?i.socketPath:n.host;let C=s&&s.headers;if(s={...s,headers:{}},C)for(let[V,_e]of Object.entries(C))s.headers[V.toLowerCase()]=_e}else if(r.listenerCount("redirect")===0){let C=c?r._originalIpc?i.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:n.host===r._originalHostOrSocketPath;(!C||r._originalSecure&&!a)&&(delete i.headers.authorization,delete i.headers.cookie,C||delete i.headers.host,i.auth=void 0)}i.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),T=r._req=m(i),r._redirects&&r.emit("redirect",r.url,T)}else T=r._req=m(i);i.timeout&&T.on("timeout",()=>{Tt(r,T,"Opening handshake has timed out")}),T.on("error",C=>{T===null||T[pl]||(T=r._req=null,An(r,C))}),T.on("response",C=>{let V=C.headers.location,_e=C.statusCode;if(V&&i.followRedirects&&_e>=300&&_e<400){if(++r._redirects>i.maxRedirects){Tt(r,T,"Maximum redirects exceeded");return}T.abort();let X;try{X=new ya(V,e)}catch{let B=new SyntaxError(`Invalid URL: ${V}`);An(r,B);return}gl(r,X,t,s)}else r.emit("unexpected-response",T,C)||Tt(r,T,`Unexpected server response: ${C.statusCode}`)}),T.on("upgrade",(C,V,_e)=>{if(r.emit("upgrade",C),r.readyState!==Ue.CONNECTING)return;T=r._req=null;let X=C.headers.upgrade;if(X===void 0||X.toLowerCase()!=="websocket"){Tt(r,V,"Invalid Upgrade header");return}let P=zm("sha1").update(p+Ym).digest("base64");if(C.headers["sec-websocket-accept"]!==P){Tt(r,V,"Invalid Sec-WebSocket-Accept header");return}let B=C.headers["sec-websocket-protocol"],te;if(B!==void 0?y.size?y.has(B)||(te="Server sent an invalid subprotocol"):te="Server sent a subprotocol but none was requested":y.size&&(te="Server sent no subprotocol"),te){Tt(r,V,te);return}B&&(r._protocol=B);let A=C.headers["sec-websocket-extensions"];if(A!==void 0){if(!b){Tt(r,V,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ae;try{ae=t0(A)}catch{Tt(r,V,"Invalid Sec-WebSocket-Extensions header");return}let pe=Object.keys(ae);if(pe.length!==1||pe[0]!==Fr.extensionName){Tt(r,V,"Server indicated an extension that was not requested");return}try{b.accept(ae[Fr.extensionName])}catch{Tt(r,V,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Fr.extensionName]=b}r.setSocket(V,_e,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(T,r):T.end()}function An(r,e){r._readyState=Ue.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function n0(r){return r.path=r.socketPath,hl.connect(r)}function o0(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=hl.isIP(r.host)?"":r.host),Hm.connect(r)}function Tt(r,e,t){r._readyState=Ue.CLOSING;let s=new Error(t);Error.captureStackTrace(s,Tt),e.setHeader?(e[pl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(An,r,s)):(e.destroy(s),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function wa(r,e,t){if(e){let s=Gm(e)?e.size:r0(e).length;r._socket?r._sender._bufferedBytes+=s:r._bufferedAmount+=s}if(t){let s=new Error(`WebSocket is not open: readyState ${r.readyState} (${yr[r.readyState]})`);process.nextTick(t,s)}}function a0(r,e){let t=this[st];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[st]!==void 0&&(t._socket.removeListener("data",Pn),process.nextTick(ml,t._socket),r===1005?t.close():t.close(r,e))}function c0(){let r=this[st];r.isPaused||r._socket.resume()}function f0(r){let e=this[st];e._socket[st]!==void 0&&(e._socket.removeListener("data",Pn),process.nextTick(ml,e._socket),e.close(r[Jm])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function ll(){this[st].emitClose()}function u0(r,e){this[st].emit("message",r,e)}function l0(r){let e=this[st];e._autoPong&&e.pong(r,!this._isServer,dl),e.emit("ping",r)}function h0(r){this[st].emit("pong",r)}function ml(r){r.resume()}function d0(r){let e=this[st];e.readyState!==Ue.CLOSED&&(e.readyState===Ue.OPEN&&(e._readyState=Ue.CLOSING,_l(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function _l(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),s0)}function yl(){let r=this[st];this.removeListener("close",yl),this.removeListener("data",Pn),this.removeListener("end",vl),r._readyState=Ue.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[st]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",ll),r._receiver.on("finish",ll))}function Pn(r){this[st]._receiver.write(r)||this.pause()}function vl(){let r=this[st];r._readyState=Ue.CLOSING,r._receiver.end(),this.end()}function El(){let r=this[st];this.removeListener("error",El),this.on("error",dl),r&&(r._readyState=Ue.CLOSING,this.destroy())}});var Tl=D((gw,Sl)=>{"use strict";var pw=In(),{Duplex:p0}=require("stream");function bl(r){r.emit("close")}function g0(){!this.destroyed&&this._writableState.finished&&this.destroy()}function xl(r){this.removeListener("error",xl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function m0(r,e){let t=!0,s=new p0({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(n,a){let c=!a&&s._readableState.objectMode?n.toString():n;s.push(c)||r.pause()}),r.once("error",function(n){s.destroyed||(t=!1,s.destroy(n))}),r.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(i,n){if(r.readyState===r.CLOSED){n(i),process.nextTick(bl,s);return}let a=!1;r.once("error",function(u){a=!0,n(u)}),r.once("close",function(){a||n(i),process.nextTick(bl,s)}),t&&r.terminate()},s._final=function(i){if(r.readyState===r.CONNECTING){r.once("open",function(){s._final(i)});return}r._socket!==null&&(r._socket._writableState.finished?(i(),s._readableState.endEmitted&&s.destroy()):(r._socket.once("finish",function(){i()}),r.close()))},s._read=function(){r.isPaused&&r.resume()},s._write=function(i,n,a){if(r.readyState===r.CONNECTING){r.once("open",function(){s._write(i,n,a)});return}r.send(i,a)},s.on("end",g0),s.on("error",xl),s}Sl.exports=m0});var Ol=D((mw,Cl)=>{"use strict";var{tokenChars:_0}=Ls();function y0(r){let e=new Set,t=-1,s=-1,i=0;for(i;i<r.length;i++){let a=r.charCodeAt(i);if(s===-1&&_0[a]===1)t===-1&&(t=i);else if(i!==0&&(a===32||a===9))s===-1&&t!==-1&&(s=i);else if(a===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${i}`);s===-1&&(s=i);let c=r.slice(t,s);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),t=s=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(t===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let n=r.slice(t,i);if(e.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);return e.add(n),e}Cl.exports={parse:y0}});var Nl=D((yw,Ll)=>{"use strict";var v0=require("events"),Ln=require("http"),{Duplex:_w}=require("stream"),{createHash:E0}=require("crypto"),kl=_a(),ns=fi(),w0=Ol(),b0=In(),{GUID:x0,kWebSocket:S0}=gr(),T0=/^[+/0-9A-Za-z]{22}==$/,Rl=0,Al=1,Il=2,ba=class extends v0{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:b0,...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=Ln.createServer((s,i)=>{let n=Ln.STATUS_CODES[426];i.writeHead(426,{"Content-Length":n.length,"Content-Type":"text/plain"}),i.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let s=this.emit.bind(this,"connection");this._removeListeners=C0(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,n,a)=>{this.handleUpgrade(i,n,a,s)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Rl}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===Il){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(di,this);return}if(e&&this.once("close",e),this._state!==Al)if(this._state=Al,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(di,this):process.nextTick(di,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{di(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,s,i){t.on("error",Pl);let n=e.headers["sec-websocket-key"],a=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){os(this,e,t,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){os(this,e,t,400,"Invalid Upgrade header");return}if(n===void 0||!T0.test(n)){os(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){os(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){pi(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=w0.parse(u)}catch{os(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 y=new ns(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let b=kl.parse(p);b[ns.extensionName]&&(y.accept(b[ns.extensionName]),m[ns.extensionName]=y)}catch{os(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let y={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(y,(b,T,C,V)=>{if(!b)return pi(t,T||401,C,V);this.completeUpgrade(m,n,d,e,t,s,i)});return}if(!this.options.verifyClient(y))return pi(t,401)}this.completeUpgrade(m,n,d,e,t,s,i)}completeUpgrade(e,t,s,i,n,a,c){if(!n.readable||!n.writable)return n.destroy();if(n[S0])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Rl)return pi(n,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${E0("sha1").update(t+x0).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(s.size){let m=this.options.handleProtocols?this.options.handleProtocols(s,i):s.values().next().value;m&&(d.push(`Sec-WebSocket-Protocol: ${m}`),p._protocol=m)}if(e[ns.extensionName]){let m=e[ns.extensionName].params,y=kl.format({[ns.extensionName]:[m]});d.push(`Sec-WebSocket-Extensions: ${y}`),p._extensions=e}this.emit("headers",d,i),n.write(d.concat(`\r
|
|
21
23
|
`).join(`\r
|
|
22
|
-
`)),n.removeListener("error",Pl),p.setSocket(n,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(
|
|
23
|
-
`+Object.keys(
|
|
24
|
+
`)),n.removeListener("error",Pl),p.setSocket(n,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(di,this)})),c(p,i)}};Ll.exports=ba;function C0(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let s of Object.keys(e))r.removeListener(s,e[s])}}function di(r){r._state=Il,r.emit("close")}function Pl(){this.destroy()}function pi(r,e,t,s){t=t||Ln.STATUS_CODES[e],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...s},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${Ln.STATUS_CODES[e]}\r
|
|
25
|
+
`+Object.keys(s).map(i=>`${i}: ${s[i]}`).join(`\r
|
|
24
26
|
`)+`\r
|
|
25
27
|
\r
|
|
26
|
-
`+t)}function oi(r,e,t,i,s,n){if(r.listenerCount("wsClientError")){let a=new Error(s);Error.captureStackTrace(a,oi),r.emit("wsClientError",a,t,e)}else ps(t,i,s,n)}});var Ml=M((vw,Dl)=>{"use strict";var vr=In();vr.createWebSocketStream=Tl();vr.Server=Nl();vr.Receiver=ha();vr.Sender=ga();vr.WebSocket=vr;vr.WebSocketServer=vr.Server;Dl.exports=vr});var Ca=M(Br=>{"use strict";var O0=Br&&Br.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Br,"__esModule",{value:!0});Br.WS=Br.BaseWS=void 0;var k0=os(),Fl=ei(),R0=Si(),Sa=Qr(),A0=O0(Pt()),P0=(0,A0.default)("engine.io-client:websocket"),Bl=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Nn=class extends k0.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,i=Bl?{}:(0,Fl.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(s){return this.emitReserved("error",s)}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],s=t===e.length-1;(0,R0.encodePacket)(i,this.supportsBinary,n=>{try{this.doWrite(i,n)}catch{P0("websocket closed before onclose event")}s&&(0,Sa.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,Fl.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}};Br.BaseWS=Nn;var xa=Sa.globalThisShim.WebSocket||Sa.globalThisShim.MozWebSocket,Ta=class extends Nn{createSocket(e,t,i){return Bl?new xa(e,t,i):t?new xa(e,t):new xa(e)}doWrite(e,t){this.ws.send(t)}};Br.WS=Ta});var ka=M(tr=>{"use strict";var I0=tr&&tr.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),L0=tr&&tr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),N0=tr&&tr.__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)&&I0(e,r,t);return L0(e,r),e};Object.defineProperty(tr,"__esModule",{value:!0});tr.WS=void 0;var D0=N0(Ml()),M0=Ca(),Oa=class extends M0.BaseWS{createSocket(e,t,i){var s;if(!((s=this.socket)===null||s===void 0)&&s._cookieJar){i.headers=i.headers||{},i.headers.cookie=typeof i.headers.cookie=="string"?[i.headers.cookie]:i.headers.cookie||[];for(let[n,a]of this.socket._cookieJar.cookies)i.headers.cookie.push(`${n}=${a.value}`)}return new D0.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)}};tr.WS=Oa});var Aa=M(Fi=>{"use strict";var F0=Fi&&Fi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fi,"__esModule",{value:!0});Fi.WT=void 0;var B0=os(),j0=Qr(),jl=Si(),U0=F0(Pt()),gs=(0,U0.default)("engine.io-client:webtransport"),Ra=class extends B0.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(()=>{gs("transport closed gracefully"),this.onClose()}).catch(e=>{gs("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=(0,jl.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),s=(0,jl.createPacketEncoderStream)();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let n=()=>{i.read().then(({done:c,value:u})=>{if(c){gs("session is closed");return}gs("received chunk: %o",u),this.onPacket(u),n()}).catch(c=>{gs("an error occurred while reading: %s",c)})};n();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],s=t===e.length-1;this._writer.write(i).then(()=>{s&&(0,j0.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};Fi.WT=Ra});var Pa=M(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.transports=void 0;var q0=ta(),W0=ka(),H0=Aa();Dn.transports={websocket:W0.WS,webtransport:H0.WT,polling:q0.XHR}});var La=M(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.parse=z0;var V0=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,K0=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function z0(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 s=V0.exec(r||""),n={},a=14;for(;a--;)n[K0[a]]=s[a]||"";return t!=-1&&i!=-1&&(n.source=e,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=$0(n,n.path),n.queryKey=G0(n,n.query),n}function $0(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 G0(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(i,s,n){s&&(t[s]=n)}),t}});var Fa=M(rr=>{"use strict";var Y0=rr&&rr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(rr,"__esModule",{value:!0});rr.Socket=rr.SocketWithUpgrade=rr.SocketWithoutUpgrade=void 0;var X0=Pa(),Ul=ei(),J0=Ho(),ql=La(),Z0=Zr(),Wl=Si(),Na=Qr(),Q0=Y0(Pt()),De=(0,Q0.default)("engine.io-client:socket"),Da=typeof addEventListener=="function"&&typeof removeEventListener=="function",ms=[];Da&&addEventListener("offline",()=>{De("closing %d connection(s) because the network was lost",ms.length),ms.forEach(r=>r())},!1);var ai=class r extends Z0.Emitter{constructor(e,t){if(super(),this.binaryType=Na.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,ql.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,ql.parse)(t.host).host);(0,Ul.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 s=i.prototype.name;this.transports.push(s),this._transportsByName[s]=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,J0.decode)(this.opts.query)),Da&&(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"})},ms.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Na.createCookieJar)()),this._open()}createTransport(e){De('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Wl.protocol,t.transport=e,this.id&&(t.sid=this.id);let i=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return De("options: %j",i),new this._transportsByName[e](i)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let e=this.opts.rememberUpgrade&&r.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){De("setting transport %s",e.name),this.transport&&(De("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){De("socket open"),this.readyState="open",r.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(De('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}else De('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();De("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let i=0;i<this.writeBuffer.length;i++){let s=this.writeBuffer[i].data;if(s&&(t+=(0,Ul.byteLength)(s)),i>0&&t>this._maxPayload)return De("only send %d out of %d packets",i,this.writeBuffer.length),this.writeBuffer.slice(0,i);t+=2}return De("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(De("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,Na.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,s){if(typeof t=="function"&&(s=t,t=void 0),typeof i=="function"&&(s=i,i=null),this.readyState==="closing"||this.readyState==="closed")return;i=i||{},i.compress=i.compress!==!1;let n={type:e,data:t,options:i};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),s&&this.once("flush",s),this.flush()}close(){let e=()=>{this._onClose("forced close"),De("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},i=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?i():e()}):this.upgrading?i():e()),this}_onError(e){if(De("socket error %j",e),r.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return De("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(De('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Da&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let i=ms.indexOf(this._offlineEventListener);i!==-1&&(De("removing listener for the 'offline' event"),ms.splice(i,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};rr.SocketWithoutUpgrade=ai;ai.protocol=Wl.protocol;var Mn=class extends ai{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){De("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){De('probing transport "%s"',e);let t=this.createTransport(e),i=!1;ai.priorWebsocketSuccess=!1;let s=()=>{i||(De('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",m=>{if(!i)if(m.type==="pong"&&m.data==="probe"){if(De('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;ai.priorWebsocketSuccess=t.name==="websocket",De('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{i||this.readyState!=="closed"&&(De("changing transport and sending upgrade packet"),p(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{De('probe transport "%s" failed',e);let y=new Error("probe error");y.transport=t.name,this.emitReserved("upgradeError",y)}}))};function n(){i||(i=!0,p(),t.close(),t=null)}let a=m=>{let y=new Error("probe error: "+m);y.transport=t.name,n(),De('probe transport "%s" failed because of error: %s',e,m),this.emitReserved("upgradeError",y)};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),n())}let p=()=>{t.removeListener("open",s),t.removeListener("error",a),t.removeListener("close",c),this.off("close",u),this.off("upgrading",d)};t.once("open",s),t.once("error",a),t.once("close",c),this.once("close",u),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{i||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let i=0;i<e.length;i++)~this.transports.indexOf(e[i])&&t.push(e[i]);return t}};rr.SocketWithUpgrade=Mn;var Ma=class extends Mn{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(s=>X0.transports[s]).filter(s=>!!s)),super(e,i)}};rr.Socket=Ma});var Hl=M(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.Fetch=void 0;var e_=Xo(),Ba=class extends e_.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,s=new Headers(this.opts.extraHeaders);return i&&s.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(s),fetch(this.uri(),{method:i?"POST":"GET",body:i?e:null,headers:s,credentials:this.opts.withCredentials?"include":"omit"}).then(n=>{var a;return(a=this.socket._cookieJar)===null||a===void 0||a.parseCookies(n.headers.getSetCookie()),n})}};Fn.Fetch=Ba});var Bn=M(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.WebTransport=Se.WebSocket=Se.NodeWebSocket=Se.XHR=Se.NodeXHR=Se.Fetch=Se.nextTick=Se.parse=Se.installTimerFunctions=Se.transports=Se.TransportError=Se.Transport=Se.protocol=Se.SocketWithUpgrade=Se.SocketWithoutUpgrade=Se.Socket=void 0;var Vl=Fa();Object.defineProperty(Se,"Socket",{enumerable:!0,get:function(){return Vl.Socket}});var Kl=Fa();Object.defineProperty(Se,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return Kl.SocketWithoutUpgrade}});Object.defineProperty(Se,"SocketWithUpgrade",{enumerable:!0,get:function(){return Kl.SocketWithUpgrade}});Se.protocol=Vl.Socket.protocol;var zl=os();Object.defineProperty(Se,"Transport",{enumerable:!0,get:function(){return zl.Transport}});Object.defineProperty(Se,"TransportError",{enumerable:!0,get:function(){return zl.TransportError}});var t_=Pa();Object.defineProperty(Se,"transports",{enumerable:!0,get:function(){return t_.transports}});var r_=ei();Object.defineProperty(Se,"installTimerFunctions",{enumerable:!0,get:function(){return r_.installTimerFunctions}});var i_=La();Object.defineProperty(Se,"parse",{enumerable:!0,get:function(){return i_.parse}});var s_=Qr();Object.defineProperty(Se,"nextTick",{enumerable:!0,get:function(){return s_.nextTick}});var n_=Hl();Object.defineProperty(Se,"Fetch",{enumerable:!0,get:function(){return n_.Fetch}});var o_=ta();Object.defineProperty(Se,"NodeXHR",{enumerable:!0,get:function(){return o_.XHR}});var a_=Qo();Object.defineProperty(Se,"XHR",{enumerable:!0,get:function(){return a_.XHR}});var c_=ka();Object.defineProperty(Se,"NodeWebSocket",{enumerable:!0,get:function(){return c_.WS}});var f_=Ca();Object.defineProperty(Se,"WebSocket",{enumerable:!0,get:function(){return f_.WS}});var u_=Aa();Object.defineProperty(Se,"WebTransport",{enumerable:!0,get:function(){return u_.WT}})});var Gl=M(_s=>{"use strict";var l_=_s&&_s.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(_s,"__esModule",{value:!0});_s.url=p_;var h_=Bn(),d_=l_(Pt()),$l=(0,d_.default)("socket.io-client:url");function p_(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)||($l("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),$l("parse %s",r),i=(0,h_.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 n=i.host.indexOf(":")!==-1?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+n+":"+i.port+e,i.href=i.protocol+"://"+n+(t&&t.port===i.port?"":":"+i.port),i}});var ja=M(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.isBinary=Xl;Un.hasBinary=jn;var g_=typeof ArrayBuffer=="function",m_=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,Yl=Object.prototype.toString,__=typeof Blob=="function"||typeof Blob<"u"&&Yl.call(Blob)==="[object BlobConstructor]",y_=typeof File=="function"||typeof File<"u"&&Yl.call(File)==="[object FileConstructor]";function Xl(r){return g_&&(r instanceof ArrayBuffer||m_(r))||__&&r instanceof Blob||y_&&r instanceof File}function jn(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,i=r.length;t<i;t++)if(jn(r[t]))return!0;return!1}if(Xl(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return jn(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&jn(r[t]))return!0;return!1}});var Jl=M(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.deconstructPacket=E_;qn.reconstructPacket=w_;var v_=ja();function E_(r){let e=[],t=r.data,i=r;return i.data=Ua(t,e),i.attachments=e.length,{packet:i,buffers:e}}function Ua(r,e){if(!r)return r;if((0,v_.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]=Ua(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]=Ua(r[i],e));return t}return r}function w_(r,e){return r.data=qa(r.data,e),delete r.attachments,r}function qa(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]=qa(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=qa(r[t],e));return r}});var Hn=M(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.Decoder=qt.Encoder=qt.PacketType=qt.protocol=void 0;qt.isPacketValid=k_;var b_=Zr(),Zl=Jl(),Ql=ja(),x_=Pt(),Wa=(0,x_.default)("socket.io-parser"),eh=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];qt.protocol=5;var Le;(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"})(Le||(qt.PacketType=Le={}));var Ha=class{constructor(e){this.replacer=e}encode(e){return Wa("encoding packet %j",e),(e.type===Le.EVENT||e.type===Le.ACK)&&(0,Ql.hasBinary)(e)?this.encodeAsBinary({type:e.type===Le.EVENT?Le.BINARY_EVENT:Le.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Le.BINARY_EVENT||e.type===Le.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)),Wa("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,Zl.deconstructPacket)(e),i=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(i),s}};qt.Encoder=Ha;var Va=class r extends b_.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===Le.BINARY_EVENT;i||t.type===Le.BINARY_ACK?(t.type=i?Le.EVENT:Le.ACK,this.reconstructor=new Ka(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,Ql.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(Le[i.type]===void 0)throw new Error("unknown packet type "+i.type);if(i.type===Le.BINARY_EVENT||i.type===Le.BINARY_ACK){let n=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let a=e.substring(n,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");i.attachments=Number(a)}if(e.charAt(t+1)==="/"){let n=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););i.nsp=e.substring(n,t)}else i.nsp="/";let s=e.charAt(t+1);if(s!==""&&Number(s)==s){let n=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(n,t+1))}if(e.charAt(++t)){let n=this.tryParse(e.substr(t));if(r.isPayloadValid(i.type,n))i.data=n;else throw new Error("invalid payload")}return Wa("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 Le.CONNECT:return Wn(t);case Le.DISCONNECT:return t===void 0;case Le.CONNECT_ERROR:return typeof t=="string"||Wn(t);case Le.EVENT:case Le.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&eh.indexOf(t[0])===-1);case Le.ACK:case Le.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};qt.Decoder=Va;var Ka=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,Zl.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function S_(r){return typeof r=="string"}var T_=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function C_(r){return r===void 0||T_(r)}function Wn(r){return Object.prototype.toString.call(r)==="[object Object]"}function O_(r,e){switch(r){case Le.CONNECT:return e===void 0||Wn(e);case Le.DISCONNECT:return e===void 0;case Le.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&eh.indexOf(e[0])===-1);case Le.ACK:return Array.isArray(e);case Le.CONNECT_ERROR:return typeof e=="string"||Wn(e);default:return!1}}function k_(r){return S_(r.nsp)&&C_(r.id)&&O_(r.type,r.data)}});var $a=M(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.on=R_;function R_(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var Ya=M(Bi=>{"use strict";var A_=Bi&&Bi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Bi,"__esModule",{value:!0});Bi.Socket=void 0;var Wt=Hn(),Vn=$a(),P_=Zr(),I_=A_(Pt()),Qe=(0,I_.default)("socket.io-client:socket"),L_=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Ga=class extends P_.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,Vn.on)(e,"open",this.onopen.bind(this)),(0,Vn.on)(e,"packet",this.onpacket.bind(this)),(0,Vn.on)(e,"error",this.onerror.bind(this)),(0,Vn.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,s,n;if(L_.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:Wt.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let p=this.ids++;Qe("emitting packet with ack id %d",p);let m=t.pop();this._registerAckCallback(p,m),a.id=p}let c=(s=(i=this.io.engine)===null||i===void 0?void 0:i.transport)===null||s===void 0?void 0:s.writable,u=this.connected&&!(!((n=this.io.engine)===null||n===void 0)&&n._hasPingExpired());return this.flags.volatile&&!c?Qe("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 s=(i=this.flags.timeout)!==null&&i!==void 0?i:this._opts.ackTimeout;if(s===void 0){this.acks[e]=t;return}let n=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&(Qe("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));Qe("event with ack id %d has timed out after %d ms",e,s),t.call(this,new Error("operation has timed out"))},s),a=(...c)=>{this.io.clearTimeoutFn(n),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((i,s)=>{let n=(a,c)=>a?s(a):i(c);n.withError=!0,t.push(n),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((s,...n)=>i!==this._queue[0]?Qe("packet [%d] already acknowledged",i.id):(s!==null?i.tryCount>this._opts.retries&&(Qe("packet [%d] is discarded after %d tries",i.id,i.tryCount),this._queue.shift(),t&&t(s)):(Qe("packet [%d] was successfully sent",i.id),this._queue.shift(),t&&t(null,...n)),i.pending=!1,this._drainQueue())),this._queue.push(i),this._drainQueue()}_drainQueue(e=!1){if(Qe("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){Qe("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,Qe("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(){Qe("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Wt.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){Qe("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 Wt.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 Wt.PacketType.EVENT:case Wt.PacketType.BINARY_EVENT:this.onevent(e);break;case Wt.PacketType.ACK:case Wt.PacketType.BINARY_ACK:this.onack(e);break;case Wt.PacketType.DISCONNECT:this.ondisconnect();break;case Wt.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||[];Qe("emitting event %j",t),e.id!=null&&(Qe("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(...s){i||(i=!0,Qe("sending ack %j",s),t.packet({type:Wt.PacketType.ACK,id:e,data:s}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){Qe("bad ack %s",e.id);return}delete this.acks[e.id],Qe("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){Qe("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(){Qe("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&&(Qe("performing disconnect (%s)",this.nsp),this.packet({type:Wt.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)}}};Bi.Socket=Ga});var th=M(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.Backoff=ji;function ji(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}ji.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};ji.prototype.reset=function(){this.attempts=0};ji.prototype.setMin=function(r){this.ms=r};ji.prototype.setMax=function(r){this.max=r};ji.prototype.setJitter=function(r){this.jitter=r}});var rh=M(Nt=>{"use strict";var N_=Nt&&Nt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),D_=Nt&&Nt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),M_=Nt&&Nt.__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)&&N_(e,r,t);return D_(e,r),e},F_=Nt&&Nt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.Manager=void 0;var Ja=Bn(),B_=Ya(),j_=M_(Hn()),ci=$a(),U_=th(),q_=Zr(),W_=F_(Pt()),at=(0,W_.default)("socket.io-client:manager"),Za=class extends q_.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,Ja.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 U_.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 s=t.parser||j_;this.encoder=new s.Encoder,this.decoder=new s.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(at("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;at("opening %s",this.uri),this.engine=new Ja.Socket(this.uri,this.opts);let t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;let s=(0,ci.on)(t,"open",function(){i.onopen(),e&&e()}),n=c=>{at("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,ci.on)(t,"error",n);if(this._timeout!==!1){let c=this._timeout;at("connect attempt will timeout after %d",c);let u=this.setTimeoutFn(()=>{at("connect attempt timed out after %d",c),s(),n(new Error("timeout")),t.close()},c);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(s),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){at("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,ci.on)(e,"ping",this.onping.bind(this)),(0,ci.on)(e,"data",this.ondata.bind(this)),(0,ci.on)(e,"error",this.onerror.bind(this)),(0,ci.on)(e,"close",this.onclose.bind(this)),(0,ci.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,Ja.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){at("error",e),this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new B_.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){at("socket %s is still active, skipping close",i);return}this._close()}_packet(e){at("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(){at("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){at("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var i;at("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)at("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();at("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let i=this.setTimeoutFn(()=>{e.skipReconnect||(at("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(at("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(at("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)}};Nt.Manager=Za});var oh=M((Fe,nh)=>{"use strict";var H_=Fe&&Fe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fe,"__esModule",{value:!0});Fe.WebTransport=Fe.WebSocket=Fe.NodeWebSocket=Fe.XHR=Fe.NodeXHR=Fe.Fetch=Fe.Socket=Fe.Manager=Fe.protocol=void 0;Fe.io=fi;Fe.connect=fi;Fe.default=fi;var V_=Gl(),Kn=rh();Object.defineProperty(Fe,"Manager",{enumerable:!0,get:function(){return Kn.Manager}});var sh=Ya();Object.defineProperty(Fe,"Socket",{enumerable:!0,get:function(){return sh.Socket}});var K_=H_(Pt()),ih=(0,K_.default)("socket.io-client"),ys={};function fi(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,V_.url)(r,e.path||"/socket.io"),i=t.source,s=t.id,n=t.path,a=ys[s]&&n in ys[s].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||a,u;return c?(ih("ignoring socket cache for %s",i),u=new Kn.Manager(i,e)):(ys[s]||(ih("new io instance for %s",i),ys[s]=new Kn.Manager(i,e)),u=ys[s]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(fi,{Manager:Kn.Manager,Socket:sh.Socket,io:fi,connect:fi});var z_=Hn();Object.defineProperty(Fe,"protocol",{enumerable:!0,get:function(){return z_.protocol}});var Ui=Bn();Object.defineProperty(Fe,"Fetch",{enumerable:!0,get:function(){return Ui.Fetch}});Object.defineProperty(Fe,"NodeXHR",{enumerable:!0,get:function(){return Ui.NodeXHR}});Object.defineProperty(Fe,"XHR",{enumerable:!0,get:function(){return Ui.XHR}});Object.defineProperty(Fe,"NodeWebSocket",{enumerable:!0,get:function(){return Ui.NodeWebSocket}});Object.defineProperty(Fe,"WebSocket",{enumerable:!0,get:function(){return Ui.WebSocket}});Object.defineProperty(Fe,"WebTransport",{enumerable:!0,get:function(){return Ui.WebTransport}});nh.exports=fi});var ec=M(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.InputStreamReceiver=void 0;var $_=64,G_=30,Y_=4,X_=256,J_=16,Qa=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??$_),this.ackThrottleMs=Math.max(0,i.ackThrottleMs??G_)}get appliedSeq(){return this.lastAppliedSeq}receive(e,t,i){if(e<=this.lastAppliedSeq){this.flushAck();return}if(e===this.lastAppliedSeq+1){try{this.cb.onApply(t,i)}catch{}this.lastAppliedSeq=e,this.scheduleAck();return}this.flushAck();let s=Math.max(this.windowSize*Y_,X_);e-this.lastAppliedSeq>s||this.maybeResend(this.lastAppliedSeq+1)}maybeResend(e){if(e===this.lastResendFrom){if(++this.resendSuppressed<J_)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)}};zn.InputStreamReceiver=Qa});var uh=M($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.WebSocketService=void 0;var Z_=oh(),ah=dr(),ch=Ks(),fh=Ws(),Q_=ec(),tc=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,s,n,a,c="vscode",u=[]){this.authService=e,this.cryptoService=t,this.config=i,this.logger=s,this.notification=n,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,ch.getWsUrl)(this.config);this.logger.info("Connecting to WebSocket",t),this.statusChangeHandler?.("connecting");let i=await this.cryptoService.getPublicKey();return new Promise((s,n)=>{let a=Array.from(new Set([...ah.DEFAULT_CLIENT_CAPABILITIES,...this.extraCapabilities]));this.socket=(0,Z_.io)(`${t}/agent`,{auth:{token:e,protocolVersion:ah.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,s()}),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||n(c),this.scheduleReconnect()}),this.socket.on("terminal:input",c=>{this.handleTerminalInput(c)}),this.socket.on("crypto:keyExchange",async(c,u)=>{this.logger.info("Received key exchange request",c.terminalId,c.sessionId),this.rekeyingTerminals.add(c.terminalId),this.outputBuffer.set(c.terminalId,[]);try{if(await this.cryptoService.handleKeyExchange(c.terminalId,c.clientPublicKey,c.sessionId)){let p=await this.cryptoService.getPublicKey();u?.({success:!0,agentPublicKey:p||void 0}),this.flushOutputBuffer(c.terminalId)}else u?.({success:!1,error:"Key exchange failed"})}catch(d){this.logger.error("Key exchange error",d),u?.({success:!1,error:String(d)})}finally{this.rekeyingTerminals.delete(c.terminalId),this.outputBuffer.delete(c.terminalId)}}),this.socket.on("crypto:sessionCleanup",c=>{this.cryptoService.removeSession(c.terminalId,c.sessionId)}),this.socket.on("agent:keyExchangeRequest",async c=>{try{let u=await this.cryptoService.handleAgentKeyExchange(c.clientPublicKey,c.sessionId),d={agentId:c.agentId,sessionId:c.sessionId,ok:u,error:u?void 0:"Key exchange failed"};this.socket?.emit("agent:keyExchangeAck",d)}catch(u){this.logger.error("Agent key exchange error",u);let d={agentId:c.agentId,sessionId:c.sessionId,ok:!1,error:String(u)};this.socket?.emit("agent:keyExchangeAck",d)}}),this.socket.on("meta:keyExchange",async(c,u)=>{let{ok:d,isNew:p}=await this.cryptoService.handleMetaKeyExchange(c.clientIdentityPub),m=await this.cryptoService.getPublicKey()||void 0;u?.({ok:d,agentPublicKey:m}),d&&p&&this.metaSessionEstablishedHandler?.()}),this.socket.on("agent:sessionEnd",c=>{this.cryptoService.removeAgentSession(c.sessionId)}),this.socket.on("agent:renamed",c=>{this.logger.info("Agent renamed from web client",c.name),this.isRemoteRename=!0,this.config.setAgentName(c.name).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(c.name)}),this.socket.on("terminal:createRequest",c=>{this.createTerminalHandler?.(c.name)}),this.socket.on("terminal:getBuffer",(c,u)=>{if(!this.getBufferHandler){u?.({success:!1,error:"Buffer handler not set"});return}let d=this.getBufferHandler(c.terminalId);if(d===null){u?.({success:!1,error:"Terminal not found"});return}let p=this.cryptoService.encryptOutput(c.terminalId,d);if(!p){this.signalInvalidSession(void 0,c.terminalId),u?.({success:!1,error:"No E2E session"});return}u?.({success:!0,encrypted:p}),this.redrawHandler?.(c.terminalId)}),this.socket.on("terminal:resize",c=>{this.resizeHandler?.(c.terminalId,c.cols,c.rows)}),this.socket.on("workspace:clientAttached",c=>{this.attachedClientCount=c.clientCount,this.clientAttachedHandler?.(c)}),this.socket.on("workspace:clientDetached",c=>{this.attachedClientCount=c.clientCount,this.clientDetachedHandler?.(c)}),this.socket.on("file:view",c=>{this.fileViewRequestHandler?.(c.terminalId,c.request)}),this.socket.on("file:list",c=>{this.fileListRequestHandler?.(c.terminalId,c.request)}),this.socket.on("file:download:request",c=>{this.fileDownloadRequestHandler?.(c.terminalId,c.path,c.requestId)})})}disconnect(){this.isManualDisconnect=!0,this.hasConnectedOnce=!1,this.stopReconnect(),this.stopHeartbeat(),this.cryptoService.clearAllSessions(),this.socket&&(this.logger.info("Disconnecting WebSocket"),this.socket.disconnect(),this.socket=null)}softDisconnect(){this.stopReconnect(),this.stopHeartbeat(),this.socket&&(this.logger.info("Soft disconnecting WebSocket (for reconnect)"),this.socket.disconnect(),this.socket=null)}getStatus(){return{connected:this.socket?.connected??!1,agentId:this.agentId}}onInput(e){this.inputHandler=e}onCreateTerminalRequest(e){this.createTerminalHandler=e}onGetBufferRequest(e){this.getBufferHandler=e}onRedrawRequest(e){this.redrawHandler=e}onResizeRequest(e){this.resizeHandler=e}onReconnect(e){this.reconnectHandlers.push(e)}onAuthFailure(e){this.authFailureHandler=e}onFileViewRequest(e){this.fileViewRequestHandler=e}onFileListRequest(e){this.fileListRequestHandler=e}onFileDownloadRequest(e){this.fileDownloadRequestHandler=e}onStatusChange(e){this.statusChangeHandler=e}onAgentNameSync(e){this.agentNameSyncHandler=e}onClientAttached(e){this.clientAttachedHandler=e}onMetaSessionEstablished(e){this.metaSessionEstablishedHandler=e}onClientDetached(e){this.clientDetachedHandler=e}async registerWorkspace(e){return this.emit("workspace:register",e)}async unregisterWorkspace(e){await this.emit("workspace:unregister",{instanceId:e})}async terminalCreated(e){return this.emit("terminal:created",e)}async terminalClosed(e){this.cryptoService.removeSession(e.terminalId),await this.emit("terminal:closed",e)}terminalNotFound(e){this.socket?.emit("terminal:notFound",{terminalId:e})}sendPtyResized(e,t,i,s){this.socket?.connected&&this.socket.emit("agent:ptyResized",{instanceId:e,terminalId:t,cols:i,rows:s})}sendClaimControl(e,t,i,s){this.socket?.connected&&this.socket.emit("agent:claimControl",{instanceId:e,terminalId:t,cols:i,rows:s})}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 s=this.cryptoService.encryptOutput(t,i);if(!s){this.attachedClientCount>0&&this.signalInvalidSession(e,t);return}let n={instanceId:e,terminalId:t,encrypted:s};this.socket?.emit("terminal:output",n)}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:s}of t){let n=this.cryptoService.encryptOutput(e,s);if(!n){this.signalInvalidSession(i,e);continue}let a={instanceId:i,terminalId:e,encrypted:n};this.socket?.emit("terminal:output",a)}}}signalInvalidSession(e,t){let i=Date.now(),s=this.invalidSessionSignalAt.get(t)??0;i-s<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 s={instanceId:e,terminalId:t,event:i};this.socket?.emit("terminal:event",s)}hasCapability(e){return this.negotiatedCapabilities.includes(e)}sendFileChangedEvent(e,t,i){let s={instanceId:e,terminalId:t,event:i};this.socket?.emit("file:changed",s)}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,fh.generateCorrelationId)(),s=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:i}:t;return(0,fh.runWithCorrelation)(i,()=>new Promise((n,a)=>{if(!this.socket?.connected){a(new Error("WebSocket not connected"));return}this.socket.emit(e,s,c=>{c.success?n(c):a(new Error(c.error||"Unknown error"))})}))}startHeartbeat(){this.stopHeartbeat(),this.lastPongTime=Date.now(),this.startResumeWatchdog(),this.heartbeatTimer=setInterval(()=>{if(!this.socket?.connected){this.stopHeartbeat();return}if(Date.now()-this.lastPongTime>this.HEARTBEAT_INTERVAL+this.HEARTBEAT_TIMEOUT){this.logger.warn("Heartbeat timeout"),this.socket.disconnect();return}this.socket.emit("ping"),this.pongTimer=setTimeout(()=>{this.logger.warn("Pong timeout - server not responding, forcing teardown + reconnect"),this.statusChangeHandler?.("error"),this.socket?.disconnect()},this.HEARTBEAT_TIMEOUT)},this.HEARTBEAT_INTERVAL)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.clearPongTimeout(),this.stopResumeWatchdog()}startResumeWatchdog(){this.stopResumeWatchdog(),this.resumeWatchdogExpectedAt=Date.now()+this.RESUME_WATCHDOG_INTERVAL,this.resumeWatchdogTimer=setTimeout(()=>this.onResumeWatchdogTick(),this.RESUME_WATCHDOG_INTERVAL)}onResumeWatchdogTick(){let e=Date.now(),t=e-this.resumeWatchdogExpectedAt;if(t>this.RESUME_WATCHDOG_THRESHOLD&&(this.logger.warn(`Resume detected (clock drift ${t}ms) - forcing liveness re-check`),!this.isManualDisconnect&&this.socket)){this.statusChangeHandler?.("error"),this.socket.disconnect();return}this.isManualDisconnect||(this.resumeWatchdogExpectedAt=e+this.RESUME_WATCHDOG_INTERVAL,this.resumeWatchdogTimer=setTimeout(()=>this.onResumeWatchdogTick(),this.RESUME_WATCHDOG_INTERVAL))}stopResumeWatchdog(){this.resumeWatchdogTimer&&(clearTimeout(this.resumeWatchdogTimer),this.resumeWatchdogTimer=null)}clearPongTimeout(){this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}handleTerminalInput(e){let t;if(e.encrypted){let i=this.cryptoService.decryptInput(e.terminalId,e.encrypted);if(!i){this.logger.error("Failed to decrypt terminal input",e.terminalId),this.signalInvalidSession(e.instanceId,e.terminalId);return}t=i}else if(e.data)t=Buffer.from(e.data,"base64").toString("utf8");else{this.logger.error("Invalid terminal input payload");return}if(e.streamId&&typeof e.seq=="number"){let i=this.getOrCreateInputReceiver(e.terminalId,e.streamId,e.instanceId,e.dbTerminalId);if(!i)return;i.receive(e.seq,t,e.paste);return}this.inputHandler?.(e.terminalId,t,e.dbTerminalId)}getOrCreateInputReceiver(e,t,i,s){let n=this.inputReceivers.get(e);if(this.terminalActiveCheck&&!this.terminalActiveCheck(e))return n&&this.disposeInputStream(e),null;if(n&&n.receiver.streamId===t)return s&&(n.routeId=s),i&&(n.instanceId=i),n.receiver;if(n&&n.receiver.dispose(),!n&&this.inputReceivers.size>=this.MAX_INPUT_RECEIVERS)return this.logger.error("inputReceivers map at cap, dropping frame",e),null;let a=new Q_.InputStreamReceiver(t,{onApply:(c,u)=>this.inputHandler?.(e,c,this.routeIdFor(e),u),onAck:c=>this.sendInputAck(e,t,c),onResend:c=>this.sendInputResend(e,t,c)});return this.inputReceivers.set(e,{receiver:a,routeId:s??e,instanceId:i??""}),a}setTerminalActiveCheck(e){this.terminalActiveCheck=e}routeIdFor(e){return this.inputReceivers.get(e)?.routeId??e}sendInputAck(e,t,i){let s=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:ack",{instanceId:s,terminalId:e,streamId:t,ackSeq:i})}sendInputResend(e,t,i){let s=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:resend",{instanceId:s,terminalId:e,streamId:t,fromSeq:i})}sendInputResume(e){let t=this.inputReceivers.get(e);if(!t)return;let{streamId:i,lastAckSeq:s}=t.receiver.resumeState();this.socket?.emit("input:resume",{instanceId:t.instanceId,terminalId:e,streamId:i,lastAckSeq:s})}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,ch.getApiUrl)(this.config)}/health`,i=new AbortController,s=setTimeout(()=>i.abort(),5e3),n=await fetch(t,{method:"GET",signal:i.signal});return clearTimeout(s),this.logger.debug("Network check OK",String(n.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)}};$n.WebSocketService=tc});var hh=M(ir=>{"use strict";var ey=ir&&ir.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),ty=ir&&ir.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),ic=ir&&ir.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[i.length]=s);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),s=0;s<i.length;s++)i[s]!=="default"&&ey(t,e,i[s]);return ty(t,e),t}})();Object.defineProperty(ir,"__esModule",{value:!0});ir.FileTransferService=void 0;var Gn=ic(require("fs")),ry=ic(require("path")),lh=ic(require("crypto")),Be=dr(),rc=class{socket=null;activeTransfers=new Map;instanceId="";logger;fallbackDir;cryptoService=null;constructor(e,t="/tmp"){this.logger=e,this.fallbackDir=t}setCrypto(e){this.cryptoService=e}attach(e,t){this.socket=e,this.instanceId=t,this.setupEventHandlers(),this.logger.info("FileTransferService attached")}detach(){this.socket=null;for(let[e]of this.activeTransfers)this.cancelTransfer(e,"Disconnected");this.logger.info("FileTransferService detached")}async sendFile(e,t,i,s,n){let a=Gn.readFileSync(t),c=t.split("/").pop()||"file";return this.initAndSendChunks(e,a,c,{mimeType:this.getMimeType(c),requestId:n,onProgress:i,onComplete:s})}async sendBuffer(e,t,i,s,n){return this.initAndSendChunks(e,t,i,{mimeType:s,purpose:n?.purpose,viewMetadata:n?.viewMetadata,requestId:n?.requestId,onProgress:n?.onProgress,onComplete:n?.onComplete})}async initAndSendChunks(e,t,i,s){if(!this.socket)throw new Error("Socket not connected");let n=t.length,a=(0,Be.calculateTotalChunks)(n),c=this.calculateChecksum(t),u=lh.randomUUID(),d={id:u,terminalId:e,filename:i,size:n,totalChunks:a,direction:Be.TransferDirection.DOWNLOAD,status:Be.TransferStatus.PENDING,deliveredChunks:new Set,pendingChunks:new Map,checksum:c,checksumAlgorithm:"sha256",onProgress:s.onProgress?(m,y)=>s.onProgress(u,m,y):void 0,onComplete:s.onComplete?(m,y)=>s.onComplete(u,m,y):void 0,ackTimeouts:new Map};d.chunks=[];for(let m=0;m<a;m++){let y=m*Be.CHUNK_SIZE,b=Math.min(y+Be.CHUNK_SIZE,n);d.chunks.push(t.subarray(y,b))}this.activeTransfers.set(u,d);let p={transferId:u,terminalId:e,filename:i,size:n,totalChunks:a,mimeType:s.mimeType||"application/octet-stream",checksum:c,direction:Be.TransferDirection.DOWNLOAD,instanceId:this.instanceId};return s.requestId&&(p.requestId=s.requestId),s.purpose&&(p.purpose=s.purpose),s.viewMetadata&&(p.viewMetadata=s.viewMetadata),new Promise((m,y)=>{this.socket.emit("file:init",p,b=>{b.accepted?(d.status=Be.TransferStatus.ACTIVE,this.startSendingChunks(u),m(u)):(this.activeTransfers.delete(u),y(new Error(b.error||"Transfer rejected")))})})}async receiveFile(e,t,i,s,n,a,c,u="sha256",d,p){let m={id:e,terminalId:t,filename:i,filePath:c,size:s,totalChunks:n,direction:Be.TransferDirection.UPLOAD,status:Be.TransferStatus.ACTIVE,deliveredChunks:new Set,pendingChunks:new Map,chunks:new Array(n).fill(null),checksum:a,checksumAlgorithm:u,onProgress:d?(y,b)=>d(e,y,b):void 0,onComplete:p?(y,b)=>p(e,y,b):void 0,ackTimeouts:new Map};this.activeTransfers.set(e,m)}cancelTransfer(e,t){let i=this.activeTransfers.get(e);if(i){for(let s of i.ackTimeouts.values())clearTimeout(s);if(i.status=Be.TransferStatus.CANCELLED,i.onComplete?.(!1,t),this.socket){let s={transferId:e,reason:t};this.socket.emit("file:cancel",s)}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===Be.TransferStatus.EXPIRED){t.onComplete?.(!1,"Transfer expired"),this.activeTransfers.delete(e);return}if(i.deliveredChunks)for(let s of i.deliveredChunks)t.deliveredChunks.add(s);if(t.direction===Be.TransferDirection.DOWNLOAD&&i.missingChunks){t.status=Be.TransferStatus.ACTIVE;for(let s of i.missingChunks)this.sendChunk(t,s)}})}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=Be.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(Be.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 s=e.pendingChunks.get(t),n={seq:t,data:i,retries:s?s.retries:0,sentAt:Date.now()};e.pendingChunks.set(t,n);let a=this.cryptoService?.encryptFileChunk(e.terminalId,new Uint8Array(i.buffer,i.byteOffset,i.byteLength));if(!a){this.cancelTransfer(e.id,"No E2E session for file transfer");return}let c={transferId:e.id,seq:t,encrypted:a};this.socket.emit("file:chunk",c,d=>{d&&!d.success&&this.cancelTransfer(e.id,d.error||"Server rejected chunk")});let u=setTimeout(()=>{this.handleAckTimeout(e.id,t)},Be.ACK_TIMEOUT_MS);e.ackTimeouts.set(t,u)}handleChunkAck(e){let t=this.activeTransfers.get(e.transferId);if(!t||t.status===Be.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 s=e.seq+Be.WINDOW_SIZE;s<t.totalChunks&&!t.deliveredChunks.has(s)&&this.sendChunk(t,s),t.deliveredChunks.size===t.totalChunks&&this.finishSending(t)}handleAckTimeout(e,t){let i=this.activeTransfers.get(e);if(!i)return;let s=i.pendingChunks.get(t);s&&(s.retries<Be.MAX_RETRIES?(s.retries++,this.sendChunk(i,t)):this.cancelTransfer(e,"Max retries exceeded"))}finishSending(e){if(!this.socket)return;e.status=Be.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 s={transferId:e.transferId,seq:e.seq};this.socket.emit("file:chunk:ack",s)}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=Be.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 s=ry.dirname(e.filePath);Gn.existsSync(s)||Gn.mkdirSync(s,{recursive:!0}),Gn.writeFileSync(e.filePath,t),e.status=Be.TransferStatus.COMPLETED,e.onComplete?.(!0),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!0})}catch(s){let n=s instanceof Error?s.message:String(s);e.status=Be.TransferStatus.FAILED,e.onComplete?.(!1,`Failed to save file: ${n}`),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:`Failed to save file: ${n}`})}this.activeTransfers.delete(e.id)}handleComplete(e){let t=this.activeTransfers.get(e.transferId);if(t){e.success?(t.status=Be.TransferStatus.COMPLETED,t.onComplete?.(!0)):(t.status=Be.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 s=`${e.targetPath||this.fallbackDir}/${e.filename}`;this.receiveFile(e.transferId,e.terminalId,e.filename,e.size,e.totalChunks,e.checksum,s,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):lh.createHash("sha256").update(e).digest("hex")}fnv1aHash(e){let t=2166136261;for(let s=0;s<e.length;s++)t^=e[s],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"}};ir.FileTransferService=rc});var uc=M((jw,Jn)=>{function gh(r){return Array.isArray(r)?r:[r]}var iy=void 0,nc="",dh=" ",sc="\\",sy=/^\s+$/,ny=/(?:[^\\]|^)\\$/,oy=/^\\!/,ay=/^\\#/,cy=/\r?\n/g,fy=/^\.{0,2}\/|^\.{1,2}$/,uy=/\/$/,qi="/",mh="node-ignore";typeof Symbol<"u"&&(mh=Symbol.for("node-ignore"));var _h=mh,Wi=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),ly=/([0-z])-([0-z])/g,yh=()=>!1,hy=r=>r.replace(ly,(e,t,i)=>t.charCodeAt(0)<=i.charCodeAt(0)?e:nc),dy=r=>{let{length:e}=r;return r.slice(0,e-e%2)},py=[[/^\uFEFF/,()=>nc],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?dh:nc)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+dh}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let i=t.replace(/\\\*/g,"[^\\/]*");return e+i}],[/\\\\\\(?=[$.|*+(){^])/g,()=>sc],[/\\\\/g,()=>sc],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,i,s)=>e===sc?`\\[${t}${dy(i)}${s}`:s==="]"&&i.length%2===0?`[${hy(t)}${i}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],gy=/(^|\\\/)?\\\*$/,vs="regex",Yn="checkRegex",ph="_",my={[vs](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Yn](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},_y=r=>py.reduce((e,[t,i])=>e.replace(t,i.bind(r)),r),Xn=r=>typeof r=="string",yy=r=>r&&Xn(r)&&!sy.test(r)&&!ny.test(r)&&r.indexOf("#")!==0,vy=r=>r.split(cy).filter(Boolean),oc=class{constructor(e,t,i,s,n,a){this.pattern=e,this.mark=t,this.negative=n,Wi(this,"body",i),Wi(this,"ignoreCase",s),Wi(this,"regexPrefix",a)}get regex(){let e=ph+vs;return this[e]?this[e]:this._make(vs,e)}get checkRegex(){let e=ph+Yn;return this[e]?this[e]:this._make(Yn,e)}_make(e,t){let i=this.regexPrefix.replace(gy,my[e]),s=this.ignoreCase?new RegExp(i,"i"):new RegExp(i);return Wi(this,t,s)}},Ey=({pattern:r,mark:e},t)=>{let i=!1,s=r;s.indexOf("!")===0&&(i=!0,s=s.substr(1)),s=s.replace(oy,"!").replace(ay,"#");let n=_y(s);return new oc(r,e,s,t,i,n)},ac=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[_h]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(Xn(e)&&(e={pattern:e}),yy(e.pattern)){let t=Ey(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,gh(Xn(e)?vy(e):e).forEach(this._add,this),this._added}test(e,t,i){let s=!1,n=!1,a;this._rules.forEach(u=>{let{negative:d}=u;n===d&&s!==n||d&&!s&&!n&&!t||!u[i].test(e)||(s=!d,n=d,a=d?iy:u)});let c={ignored:s,unignored:n};return a&&(c.rule=a),c}},wy=(r,e)=>{throw new e(r)},Er=(r,e,t)=>Xn(r)?r?Er.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),vh=r=>fy.test(r);Er.isNotRelative=vh;Er.convert=r=>r;var cc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:i=!1}={}){Wi(this,_h,!0),this._rules=new ac(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,s){let n=e&&Er.convert(e);return Er(n,e,this._strictPathCheck?wy:yh),this._t(n,t,i,s)}checkIgnore(e){if(!uy.test(e))return this.test(e);let t=e.split(qi).filter(Boolean);if(t.pop(),t.length){let i=this._t(t.join(qi)+qi,this._testCache,!0,t);if(i.ignored)return i}return this._rules.test(e,!1,Yn)}_t(e,t,i,s){if(e in t)return t[e];if(s||(s=e.split(qi).filter(Boolean)),s.pop(),!s.length)return t[e]=this._rules.test(e,i,vs);let n=this._t(s.join(qi)+qi,t,i,s);return t[e]=n.ignored?n:this._rules.test(e,i,vs)}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)}},fc=r=>new cc(r),by=r=>Er(r&&Er.convert(r),r,yh),Eh=()=>{let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");Er.convert=r;let e=/^[a-z]:\//i;Er.isNotRelative=t=>e.test(t)||vh(t)};typeof process<"u"&&process.platform==="win32"&&Eh();Jn.exports=fc;fc.default=fc;Jn.exports.isPathValid=by;Wi(Jn.exports,Symbol.for("setupWindows"),Eh)});var bh=M(Dt=>{"use strict";var xy=Dt&&Dt.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),Sy=Dt&&Dt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),wh=Dt&&Dt.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[i.length]=s);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),s=0;s<i.length;s++)i[s]!=="default"&&xy(t,e,i[s]);return Sy(t,e),t}})(),Ty=Dt&&Dt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.FileListService=void 0;var Es=wh(require("path")),lc=wh(require("fs/promises")),Cy=Ty(uc()),hc=dr(),Oy=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],dc=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,Cy.default)(),this.ignoreFilter.add(Oy),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=Es.join(this.workspaceRoot,".gitignore");try{let t=await lc.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 lc.readdir(e,{withFileTypes:!0}),s=[];for(let n of i){let a=t==="."||t===""?n.name:Es.join(t,n.name);if(this.shouldHide(a,n.isDirectory()))continue;let c=Es.join(e,n.name),u={name:n.name,path:a,type:n.isDirectory()?hc.FileEntryType.DIRECTORY:hc.FileEntryType.FILE};if(!n.isDirectory())try{let d=await lc.stat(c);u.size=d.size,u.modified=d.mtime.toISOString()}catch{}s.push(u)}return s.sort((n,a)=>n.type!==a.type?n.type===hc.FileEntryType.DIRECTORY?-1:1:n.name.localeCompare(a.name))}shouldHide(e,t){let i=e.split(Es.sep).join("/"),s=t?`${i}/`:i;return this.ignoreFilter.ignores(s)}resolvePath(e){if(!this.workspaceRoot)throw new Error("No workspace root");if(e==="."||e==="")return this.workspaceRoot;let t=Es.join(this.workspaceRoot,e);if(!t.startsWith(this.workspaceRoot))throw new Error("Path outside workspace");return t}sendResponse(e){this.onResponseCallback?.(e)}dispose(){this.onResponseCallback=null}};Dt.FileListService=dc});var Sh=M(sr=>{"use strict";var ky=sr&&sr.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,s)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),Ry=sr&&sr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),xh=sr&&sr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[i.length]=s);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),s=0;s<i.length;s++)i[s]!=="default"&&ky(t,e,i[s]);return Ry(t,e),t}})();Object.defineProperty(sr,"__esModule",{value:!0});sr.FileTrackerService=void 0;var pc=xh(require("path")),ui=xh(require("fs/promises")),Ay=require("child_process"),Py=require("util"),Ht=dr(),gc=(0,Py.promisify)(Ay.exec),mc={toolStart:/⏺\s*(Write|Edit|NotebookEdit)\s*\(\s*(?:file_path|notebook_path)\s*=\s*"([^"]+)"/,toolSuccess:/[✓✔]\s*(?:Wrote|Edited|Updated|Created)\s+([^\s\n]+)/,toolError:/[✗✘]\s*(?:Failed|Error)/i},_c=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(s){this.logger.error("Error parsing tool calls",s)}}async parseToolCalls(e,t){let i=this.stripAnsi(t),s=i.match(mc.toolStart);if(s){let a=s[1],c=s[2],u=`${a}_${Date.now()}_${c}`;this.pendingToolCalls.has(u)||await this.handleToolStart(e,u,a,{file_path:c})}let n=i.match(mc.toolSuccess);if(n){let a=n[1];for(let[c,u]of this.pendingToolCalls)if(u.filePath===a||a.endsWith(u.filePath)||u.filePath.endsWith(a)){await this.handleToolEnd(e,c,u.toolName,"success");break}}if(mc.toolError.test(i))for(let[a,c]of this.pendingToolCalls)await this.handleToolEnd(e,a,c.toolName,"error")}stripAnsi(e){return e.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\x1b\][^\x07]*\x07/g,"").replace(/\x1b[()][AB012]/g,"").replace(/\x1b[=>]/g,"").replace(/\x1b[78DMEHc]/g,"")}async handleToolStart(e,t,i,s){if(!this.isFileModifyingTool(i))return;let n=this.extractFilePath(i,s);if(!n)return;let a=this.resolveFilePath(n),c={toolId:t,toolName:i,filePath:n,timestamp:new Date().toISOString()};this.pendingToolCalls.set(t,c);let u;try{u=await ui.readFile(a,"utf-8")}catch{u=void 0}let d={path:n,changeType:u===void 0?Ht.FileChangeType.CREATE:Ht.FileChangeType.MODIFY,toolName:i,toolId:t,timestamp:c.timestamp,previousContent:u},p=this.trackedFiles.get(e)||[];p.push(d),this.trackedFiles.set(e,p)}async handleToolEnd(e,t,i,s){if(!this.isFileModifyingTool(i)||!this.pendingToolCalls.get(t))return;if(this.pendingToolCalls.delete(t),s==="error"){let p=this.trackedFiles.get(e)||[],m=p.findIndex(y=>y.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 ui.stat(u);c.size=p.size}catch{c.changeType=Ht.FileChangeType.DELETE,c.size=void 0}let d={path:c.path,changeType:c.changeType,timestamp:new Date().toISOString(),source:"tool-call",toolName:c.toolName,toolId:c.toolId,size:c.size};this.onFileChangedCallback?.(e,d)}async handleViewRequest(e,t){let i=this.resolveFilePath(t.path),s=this.getViewableMimeType(t.path);if(s&&this.onFileViewTransferCallback){try{let a=await ui.readFile(i),c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:s};this.onFileViewTransferCallback(e,Buffer.from(a),c)}catch(a){let c={requestId:t.requestId,path:t.path,viewType:"content",mimeType:s,error:a instanceof Error?a.message:"Unknown error"};this.onFileViewTransferCallback(e,Buffer.alloc(0),c)}return}let n;try{t.type===Ht.FileViewType.CONTENT?n=await this.getFileContent(t,i):n=await this.getFileDiff(e,t,i)}catch(a){n={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:n.type===Ht.FileViewType.CONTENT?"content":"diff",language:n.language,truncated:n.truncated,error:n.error},c=Buffer.from(n.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,s=await ui.stat(t),n=await ui.readFile(t,"utf-8"),a=!1,c=n;return n.length>i&&(c=n.slice(0,i),a=!0),{requestId:e.requestId,path:e.path,type:Ht.FileViewType.CONTENT,content:c,language:(0,Ht.getLanguageFromPath)(e.path),size:s.size,truncated:a}}async getFileDiff(e,t,i){let s=t.diffBase||Ht.DiffBase.GIT,n;return s===Ht.DiffBase.GIT?n=await this.getGitDiff(i):n=await this.getPreviousDiff(e,t.path,i),{requestId:t.requestId,path:t.path,type:Ht.FileViewType.DIFF,content:n,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await gc(`git diff --cached -- "${e}"`,{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:i}=await gc(`git diff -- "${e}"`,{cwd:this.workspaceRoot});if(i.trim())return i;let{stdout:s}=await gc(`git status --porcelain -- "${e}"`,{cwd:this.workspaceRoot});if(s.startsWith("??")||s.startsWith("A ")){let a=(await ui.readFile(e,"utf-8")).split(`
|
|
28
|
+
`+t)}function os(r,e,t,s,i,n){if(r.listenerCount("wsClientError")){let a=new Error(i);Error.captureStackTrace(a,os),r.emit("wsClientError",a,t,e)}else pi(t,s,i,n)}});var Dl=D((vw,Ml)=>{"use strict";var vr=In();vr.createWebSocketStream=Tl();vr.Server=Nl();vr.Receiver=ha();vr.Sender=ga();vr.WebSocket=vr;vr.WebSocketServer=vr.Server;Ml.exports=vr});var Ca=D(Br=>{"use strict";var O0=Br&&Br.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Br,"__esModule",{value:!0});Br.WS=Br.BaseWS=void 0;var k0=oi(),Fl=es(),R0=Ts(),Sa=Qr(),A0=O0(Pt()),P0=(0,A0.default)("engine.io-client:websocket"),Bl=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Nn=class extends k0.Transport{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,s=Bl?{}:(0,Fl.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,s)}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 s=e[t],i=t===e.length-1;(0,R0.encodePacket)(s,this.supportsBinary,n=>{try{this.doWrite(s,n)}catch{P0("websocket closed before onclose event")}i&&(0,Sa.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,Fl.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}};Br.BaseWS=Nn;var xa=Sa.globalThisShim.WebSocket||Sa.globalThisShim.MozWebSocket,Ta=class extends Nn{createSocket(e,t,s){return Bl?new xa(e,t,s):t?new xa(e,t):new xa(e)}doWrite(e,t){this.ws.send(t)}};Br.WS=Ta});var ka=D(tr=>{"use strict";var I0=tr&&tr.__createBinding||(Object.create?(function(r,e,t,s){s===void 0&&(s=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,s,i)}):(function(r,e,t,s){s===void 0&&(s=t),r[s]=e[t]})),L0=tr&&tr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),N0=tr&&tr.__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)&&I0(e,r,t);return L0(e,r),e};Object.defineProperty(tr,"__esModule",{value:!0});tr.WS=void 0;var M0=N0(Dl()),D0=Ca(),Oa=class extends D0.BaseWS{createSocket(e,t,s){var i;if(!((i=this.socket)===null||i===void 0)&&i._cookieJar){s.headers=s.headers||{},s.headers.cookie=typeof s.headers.cookie=="string"?[s.headers.cookie]:s.headers.cookie||[];for(let[n,a]of this.socket._cookieJar.cookies)s.headers.cookie.push(`${n}=${a.value}`)}return new M0.WebSocket(e,t,s)}doWrite(e,t){let s={};e.options&&(s.compress=e.options.compress),this.opts.perMessageDeflate&&(typeof t=="string"?Buffer.byteLength(t):t.length)<this.opts.perMessageDeflate.threshold&&(s.compress=!1),this.ws.send(t,s)}};tr.WS=Oa});var Aa=D(Bs=>{"use strict";var F0=Bs&&Bs.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Bs,"__esModule",{value:!0});Bs.WT=void 0;var B0=oi(),j0=Qr(),jl=Ts(),U0=F0(Pt()),gi=(0,U0.default)("engine.io-client:webtransport"),Ra=class extends B0.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(()=>{gi("transport closed gracefully"),this.onClose()}).catch(e=>{gi("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=(0,jl.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),i=(0,jl.createPacketEncoderStream)();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();let n=()=>{s.read().then(({done:c,value:u})=>{if(c){gi("session is closed");return}gi("received chunk: %o",u),this.onPacket(u),n()}).catch(c=>{gi("an error occurred while reading: %s",c)})};n();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 s=e[t],i=t===e.length-1;this._writer.write(s).then(()=>{i&&(0,j0.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};Bs.WT=Ra});var Pa=D(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.transports=void 0;var q0=ta(),W0=ka(),H0=Aa();Mn.transports={websocket:W0.WS,webtransport:H0.WT,polling:q0.XHR}});var La=D(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.parse=K0;var V0=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,z0=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function K0(r){if(r.length>8e3)throw"URI too long";let e=r,t=r.indexOf("["),s=r.indexOf("]");t!=-1&&s!=-1&&(r=r.substring(0,t)+r.substring(t,s).replace(/:/g,";")+r.substring(s,r.length));let i=V0.exec(r||""),n={},a=14;for(;a--;)n[z0[a]]=i[a]||"";return t!=-1&&s!=-1&&(n.source=e,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=$0(n,n.path),n.queryKey=G0(n,n.query),n}function $0(r,e){let t=/\/{2,9}/g,s=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&s.splice(0,1),e.slice(-1)=="/"&&s.splice(s.length-1,1),s}function G0(r,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,i,n){i&&(t[i]=n)}),t}});var Fa=D(rr=>{"use strict";var Y0=rr&&rr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(rr,"__esModule",{value:!0});rr.Socket=rr.SocketWithUpgrade=rr.SocketWithoutUpgrade=void 0;var X0=Pa(),Ul=es(),J0=Ho(),ql=La(),Z0=Zr(),Wl=Ts(),Na=Qr(),Q0=Y0(Pt()),Me=(0,Q0.default)("engine.io-client:socket"),Ma=typeof addEventListener=="function"&&typeof removeEventListener=="function",mi=[];Ma&&addEventListener("offline",()=>{Me("closing %d connection(s) because the network was lost",mi.length),mi.forEach(r=>r())},!1);var as=class r extends Z0.Emitter{constructor(e,t){if(super(),this.binaryType=Na.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 s=(0,ql.parse)(e);t.hostname=s.host,t.secure=s.protocol==="https"||s.protocol==="wss",t.port=s.port,s.query&&(t.query=s.query)}else t.host&&(t.hostname=(0,ql.parse)(t.host).host);(0,Ul.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(s=>{let i=s.prototype.name;this.transports.push(i),this._transportsByName[i]=s}),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,J0.decode)(this.opts.query)),Ma&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(Me("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},mi.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Na.createCookieJar)()),this._open()}createTransport(e){Me('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Wl.protocol,t.transport=e,this.id&&(t.sid=this.id);let s=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return Me("options: %j",s),new this._transportsByName[e](s)}_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){Me("setting transport %s",e.name),this.transport&&(Me("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(){Me("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(Me('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 Me('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();Me("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 s=0;s<this.writeBuffer.length;s++){let i=this.writeBuffer[s].data;if(i&&(t+=(0,Ul.byteLength)(i)),s>0&&t>this._maxPayload)return Me("only send %d out of %d packets",s,this.writeBuffer.length),this.writeBuffer.slice(0,s);t+=2}return Me("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&&(Me("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,Na.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,s){return this._sendPacket("message",e,t,s),this}send(e,t,s){return this._sendPacket("message",e,t,s),this}_sendPacket(e,t,s,i){if(typeof t=="function"&&(i=t,t=void 0),typeof s=="function"&&(i=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;let n={type:e,data:t,options:s};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),i&&this.once("flush",i),this.flush()}close(){let e=()=>{this._onClose("forced close"),Me("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},s=()=>{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?s():e()}):this.upgrading?s():e()),this}_onError(e){if(Me("socket error %j",e),r.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return Me("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(Me('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Ma&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let s=mi.indexOf(this._offlineEventListener);s!==-1&&(Me("removing listener for the 'offline' event"),mi.splice(s,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};rr.SocketWithoutUpgrade=as;as.protocol=Wl.protocol;var Dn=class extends as{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){Me("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){Me('probing transport "%s"',e);let t=this.createTransport(e),s=!1;as.priorWebsocketSuccess=!1;let i=()=>{s||(Me('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",m=>{if(!s)if(m.type==="pong"&&m.data==="probe"){if(Me('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;as.priorWebsocketSuccess=t.name==="websocket",Me('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{s||this.readyState!=="closed"&&(Me("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{Me('probe transport "%s" failed',e);let y=new Error("probe error");y.transport=t.name,this.emitReserved("upgradeError",y)}}))};function n(){s||(s=!0,p(),t.close(),t=null)}let a=m=>{let y=new Error("probe error: "+m);y.transport=t.name,n(),Me('probe transport "%s" failed because of error: %s',e,m),this.emitReserved("upgradeError",y)};function c(){a("transport closed")}function u(){a("socket closed")}function d(m){t&&m.name!==t.name&&(Me('"%s" works - aborting "%s"',m.name,t.name),n())}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(()=>{s||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let s=0;s<e.length;s++)~this.transports.indexOf(e[s])&&t.push(e[s]);return t}};rr.SocketWithUpgrade=Dn;var Da=class extends Dn{constructor(e,t={}){let s=typeof e=="object"?e:t;(!s.transports||s.transports&&typeof s.transports[0]=="string")&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(i=>X0.transports[i]).filter(i=>!!i)),super(e,s)}};rr.Socket=Da});var Hl=D(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.Fetch=void 0;var e_=Xo(),Ba=class extends e_.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(s=>{if(!s.ok)return this.onError("fetch write error",s.status,s);t()}).catch(s=>{this.onError("fetch write error",s)})}_fetch(e){var t;let s=e!==void 0,i=new Headers(this.opts.extraHeaders);return s&&i.set("content-type","text/plain;charset=UTF-8"),(t=this.socket._cookieJar)===null||t===void 0||t.appendCookies(i),fetch(this.uri(),{method:s?"POST":"GET",body:s?e:null,headers:i,credentials:this.opts.withCredentials?"include":"omit"}).then(n=>{var a;return(a=this.socket._cookieJar)===null||a===void 0||a.parseCookies(n.headers.getSetCookie()),n})}};Fn.Fetch=Ba});var Bn=D(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.WebTransport=Se.WebSocket=Se.NodeWebSocket=Se.XHR=Se.NodeXHR=Se.Fetch=Se.nextTick=Se.parse=Se.installTimerFunctions=Se.transports=Se.TransportError=Se.Transport=Se.protocol=Se.SocketWithUpgrade=Se.SocketWithoutUpgrade=Se.Socket=void 0;var Vl=Fa();Object.defineProperty(Se,"Socket",{enumerable:!0,get:function(){return Vl.Socket}});var zl=Fa();Object.defineProperty(Se,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return zl.SocketWithoutUpgrade}});Object.defineProperty(Se,"SocketWithUpgrade",{enumerable:!0,get:function(){return zl.SocketWithUpgrade}});Se.protocol=Vl.Socket.protocol;var Kl=oi();Object.defineProperty(Se,"Transport",{enumerable:!0,get:function(){return Kl.Transport}});Object.defineProperty(Se,"TransportError",{enumerable:!0,get:function(){return Kl.TransportError}});var t_=Pa();Object.defineProperty(Se,"transports",{enumerable:!0,get:function(){return t_.transports}});var r_=es();Object.defineProperty(Se,"installTimerFunctions",{enumerable:!0,get:function(){return r_.installTimerFunctions}});var s_=La();Object.defineProperty(Se,"parse",{enumerable:!0,get:function(){return s_.parse}});var i_=Qr();Object.defineProperty(Se,"nextTick",{enumerable:!0,get:function(){return i_.nextTick}});var n_=Hl();Object.defineProperty(Se,"Fetch",{enumerable:!0,get:function(){return n_.Fetch}});var o_=ta();Object.defineProperty(Se,"NodeXHR",{enumerable:!0,get:function(){return o_.XHR}});var a_=Qo();Object.defineProperty(Se,"XHR",{enumerable:!0,get:function(){return a_.XHR}});var c_=ka();Object.defineProperty(Se,"NodeWebSocket",{enumerable:!0,get:function(){return c_.WS}});var f_=Ca();Object.defineProperty(Se,"WebSocket",{enumerable:!0,get:function(){return f_.WS}});var u_=Aa();Object.defineProperty(Se,"WebTransport",{enumerable:!0,get:function(){return u_.WT}})});var Gl=D(_i=>{"use strict";var l_=_i&&_i.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(_i,"__esModule",{value:!0});_i.url=p_;var h_=Bn(),d_=l_(Pt()),$l=(0,d_.default)("socket.io-client:url");function p_(r,e="",t){let s=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)||($l("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),$l("parse %s",r),s=(0,h_.parse)(r)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";let n=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+n+":"+s.port+e,s.href=s.protocol+"://"+n+(t&&t.port===s.port?"":":"+s.port),s}});var ja=D(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.isBinary=Xl;Un.hasBinary=jn;var g_=typeof ArrayBuffer=="function",m_=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,Yl=Object.prototype.toString,__=typeof Blob=="function"||typeof Blob<"u"&&Yl.call(Blob)==="[object BlobConstructor]",y_=typeof File=="function"||typeof File<"u"&&Yl.call(File)==="[object FileConstructor]";function Xl(r){return g_&&(r instanceof ArrayBuffer||m_(r))||__&&r instanceof Blob||y_&&r instanceof File}function jn(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,s=r.length;t<s;t++)if(jn(r[t]))return!0;return!1}if(Xl(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return jn(r.toJSON(),!0);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&jn(r[t]))return!0;return!1}});var Jl=D(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.deconstructPacket=E_;qn.reconstructPacket=w_;var v_=ja();function E_(r){let e=[],t=r.data,s=r;return s.data=Ua(t,e),s.attachments=e.length,{packet:s,buffers:e}}function Ua(r,e){if(!r)return r;if((0,v_.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 s=0;s<r.length;s++)t[s]=Ua(r[s],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){let t={};for(let s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t[s]=Ua(r[s],e));return t}return r}function w_(r,e){return r.data=qa(r.data,e),delete r.attachments,r}function qa(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]=qa(r[t],e);else if(typeof r=="object")for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=qa(r[t],e));return r}});var Hn=D(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.Decoder=qt.Encoder=qt.PacketType=qt.protocol=void 0;qt.isPacketValid=k_;var b_=Zr(),Zl=Jl(),Ql=ja(),x_=Pt(),Wa=(0,x_.default)("socket.io-parser"),eh=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];qt.protocol=5;var Le;(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"})(Le||(qt.PacketType=Le={}));var Ha=class{constructor(e){this.replacer=e}encode(e){return Wa("encoding packet %j",e),(e.type===Le.EVENT||e.type===Le.ACK)&&(0,Ql.hasBinary)(e)?this.encodeAsBinary({type:e.type===Le.EVENT?Le.BINARY_EVENT:Le.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Le.BINARY_EVENT||e.type===Le.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)),Wa("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=(0,Zl.deconstructPacket)(e),s=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(s),i}};qt.Encoder=Ha;var Va=class r extends b_.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 s=t.type===Le.BINARY_EVENT;s||t.type===Le.BINARY_ACK?(t.type=s?Le.EVENT:Le.ACK,this.reconstructor=new za(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,Ql.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,s={type:Number(e.charAt(0))};if(Le[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===Le.BINARY_EVENT||s.type===Le.BINARY_ACK){let n=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let a=e.substring(n,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");s.attachments=Number(a)}if(e.charAt(t+1)==="/"){let n=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););s.nsp=e.substring(n,t)}else s.nsp="/";let i=e.charAt(t+1);if(i!==""&&Number(i)==i){let n=t+1;for(;++t;){let a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}s.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){let n=this.tryParse(e.substr(t));if(r.isPayloadValid(s.type,n))s.data=n;else throw new Error("invalid payload")}return Wa("decoded %s as %j",e,s),s}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Le.CONNECT:return Wn(t);case Le.DISCONNECT:return t===void 0;case Le.CONNECT_ERROR:return typeof t=="string"||Wn(t);case Le.EVENT:case Le.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&eh.indexOf(t[0])===-1);case Le.ACK:case Le.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}};qt.Decoder=Va;var za=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,Zl.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function S_(r){return typeof r=="string"}var T_=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function C_(r){return r===void 0||T_(r)}function Wn(r){return Object.prototype.toString.call(r)==="[object Object]"}function O_(r,e){switch(r){case Le.CONNECT:return e===void 0||Wn(e);case Le.DISCONNECT:return e===void 0;case Le.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&eh.indexOf(e[0])===-1);case Le.ACK:return Array.isArray(e);case Le.CONNECT_ERROR:return typeof e=="string"||Wn(e);default:return!1}}function k_(r){return S_(r.nsp)&&C_(r.id)&&O_(r.type,r.data)}});var $a=D(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.on=R_;function R_(r,e,t){return r.on(e,t),function(){r.off(e,t)}}});var Ya=D(js=>{"use strict";var A_=js&&js.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(js,"__esModule",{value:!0});js.Socket=void 0;var Wt=Hn(),Vn=$a(),P_=Zr(),I_=A_(Pt()),Qe=(0,I_.default)("socket.io-client:socket"),L_=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Ga=class extends P_.Emitter{constructor(e,t,s){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,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[(0,Vn.on)(e,"open",this.onopen.bind(this)),(0,Vn.on)(e,"packet",this.onpacket.bind(this)),(0,Vn.on)(e,"error",this.onerror.bind(this)),(0,Vn.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 s,i,n;if(L_.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:Wt.PacketType.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let p=this.ids++;Qe("emitting packet with ack id %d",p);let m=t.pop();this._registerAckCallback(p,m),a.id=p}let c=(i=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||i===void 0?void 0:i.writable,u=this.connected&&!(!((n=this.io.engine)===null||n===void 0)&&n._hasPingExpired());return this.flags.volatile&&!c?Qe("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 s;let i=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}let n=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&(Qe("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(c,1));Qe("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(n),t.apply(this,c)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((s,i)=>{let n=(a,c)=>a?i(a):s(c);n.withError=!0,t.push(n),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...n)=>s!==this._queue[0]?Qe("packet [%d] already acknowledged",s.id):(i!==null?s.tryCount>this._opts.retries&&(Qe("packet [%d] is discarded after %d tries",s.id,s.tryCount),this._queue.shift(),t&&t(i)):(Qe("packet [%d] was successfully sent",s.id),this._queue.shift(),t&&t(null,...n)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(Qe("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){Qe("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,Qe("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(){Qe("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Wt.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){Qe("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(s=>String(s.id)===e)){let s=this.acks[e];delete this.acks[e],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Wt.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 Wt.PacketType.EVENT:case Wt.PacketType.BINARY_EVENT:this.onevent(e);break;case Wt.PacketType.ACK:case Wt.PacketType.BINARY_ACK:this.onack(e);break;case Wt.PacketType.DISCONNECT:this.ondisconnect();break;case Wt.PacketType.CONNECT_ERROR:this.destroy();let s=new Error(e.data.message);s.data=e.data.data,this.emitReserved("connect_error",s);break}}onevent(e){let t=e.data||[];Qe("emitting event %j",t),e.id!=null&&(Qe("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 s of t)s.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,s=!1;return function(...i){s||(s=!0,Qe("sending ack %j",i),t.packet({type:Wt.PacketType.ACK,id:e,data:i}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){Qe("bad ack %s",e.id);return}delete this.acks[e.id],Qe("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){Qe("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(){Qe("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&&(Qe("performing disconnect (%s)",this.nsp),this.packet({type:Wt.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 s=0;s<t.length;s++)if(e===t[s])return t.splice(s,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 s=0;s<t.length;s++)if(e===t[s])return t.splice(s,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 s of t)s.apply(this,e.data)}}};js.Socket=Ga});var th=D(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.Backoff=Us;function Us(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}Us.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};Us.prototype.reset=function(){this.attempts=0};Us.prototype.setMin=function(r){this.ms=r};Us.prototype.setMax=function(r){this.max=r};Us.prototype.setJitter=function(r){this.jitter=r}});var rh=D(Nt=>{"use strict";var N_=Nt&&Nt.__createBinding||(Object.create?(function(r,e,t,s){s===void 0&&(s=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,s,i)}):(function(r,e,t,s){s===void 0&&(s=t),r[s]=e[t]})),M_=Nt&&Nt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),D_=Nt&&Nt.__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)&&N_(e,r,t);return M_(e,r),e},F_=Nt&&Nt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.Manager=void 0;var Ja=Bn(),B_=Ya(),j_=D_(Hn()),cs=$a(),U_=th(),q_=Zr(),W_=F_(Pt()),at=(0,W_.default)("socket.io-client:manager"),Za=class extends q_.Emitter{constructor(e,t){var s;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,Ja.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((s=t.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new U_.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||j_;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(at("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;at("opening %s",this.uri),this.engine=new Ja.Socket(this.uri,this.opts);let t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;let i=(0,cs.on)(t,"open",function(){s.onopen(),e&&e()}),n=c=>{at("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},a=(0,cs.on)(t,"error",n);if(this._timeout!==!1){let c=this._timeout;at("connect attempt will timeout after %d",c);let u=this.setTimeoutFn(()=>{at("connect attempt timed out after %d",c),i(),n(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(){at("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push((0,cs.on)(e,"ping",this.onping.bind(this)),(0,cs.on)(e,"data",this.ondata.bind(this)),(0,cs.on)(e,"error",this.onerror.bind(this)),(0,cs.on)(e,"close",this.onclose.bind(this)),(0,cs.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,Ja.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){at("error",e),this.emitReserved("error",e)}socket(e,t){let s=this.nsps[e];return s?this._autoConnect&&!s.active&&s.connect():(s=new B_.Socket(this,e,t),this.nsps[e]=s),s}_destroy(e){let t=Object.keys(this.nsps);for(let s of t)if(this.nsps[s].active){at("socket %s is still active, skipping close",s);return}this._close()}_packet(e){at("writing packet %j",e);let t=this.encoder.encode(e);for(let s=0;s<t.length;s++)this.engine.write(t[s],e.options)}cleanup(){at("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){at("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var s;at("closed due to %s",e),this.cleanup(),(s=this.engine)===null||s===void 0||s.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)at("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();at("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let s=this.setTimeoutFn(()=>{e.skipReconnect||(at("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(at("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):(at("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};Nt.Manager=Za});var oh=D((Fe,nh)=>{"use strict";var H_=Fe&&Fe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fe,"__esModule",{value:!0});Fe.WebTransport=Fe.WebSocket=Fe.NodeWebSocket=Fe.XHR=Fe.NodeXHR=Fe.Fetch=Fe.Socket=Fe.Manager=Fe.protocol=void 0;Fe.io=fs;Fe.connect=fs;Fe.default=fs;var V_=Gl(),zn=rh();Object.defineProperty(Fe,"Manager",{enumerable:!0,get:function(){return zn.Manager}});var ih=Ya();Object.defineProperty(Fe,"Socket",{enumerable:!0,get:function(){return ih.Socket}});var z_=H_(Pt()),sh=(0,z_.default)("socket.io-client"),yi={};function fs(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};let t=(0,V_.url)(r,e.path||"/socket.io"),s=t.source,i=t.id,n=t.path,a=yi[i]&&n in yi[i].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||a,u;return c?(sh("ignoring socket cache for %s",s),u=new zn.Manager(s,e)):(yi[i]||(sh("new io instance for %s",s),yi[i]=new zn.Manager(s,e)),u=yi[i]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(fs,{Manager:zn.Manager,Socket:ih.Socket,io:fs,connect:fs});var K_=Hn();Object.defineProperty(Fe,"protocol",{enumerable:!0,get:function(){return K_.protocol}});var qs=Bn();Object.defineProperty(Fe,"Fetch",{enumerable:!0,get:function(){return qs.Fetch}});Object.defineProperty(Fe,"NodeXHR",{enumerable:!0,get:function(){return qs.NodeXHR}});Object.defineProperty(Fe,"XHR",{enumerable:!0,get:function(){return qs.XHR}});Object.defineProperty(Fe,"NodeWebSocket",{enumerable:!0,get:function(){return qs.NodeWebSocket}});Object.defineProperty(Fe,"WebSocket",{enumerable:!0,get:function(){return qs.WebSocket}});Object.defineProperty(Fe,"WebTransport",{enumerable:!0,get:function(){return qs.WebTransport}});nh.exports=fs});var ec=D(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.InputStreamReceiver=void 0;var $_=64,G_=30,Y_=4,X_=256,J_=16,Qa=class{streamId;lastAppliedSeq=0;cb;windowSize;ackThrottleMs;ackTimer=null;framesSinceAck=0;lastResendFrom=0;resendSuppressed=0;constructor(e,t,s={}){this.streamId=e,this.cb=t,this.windowSize=Math.max(1,s.windowSize??$_),this.ackThrottleMs=Math.max(0,s.ackThrottleMs??G_)}get appliedSeq(){return this.lastAppliedSeq}receive(e,t,s){if(e<=this.lastAppliedSeq){this.flushAck();return}if(e===this.lastAppliedSeq+1){try{this.cb.onApply(t,s)}catch{}this.lastAppliedSeq=e,this.scheduleAck();return}this.flushAck();let i=Math.max(this.windowSize*Y_,X_);e-this.lastAppliedSeq>i||this.maybeResend(this.lastAppliedSeq+1)}maybeResend(e){if(e===this.lastResendFrom){if(++this.resendSuppressed<J_)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)}};Kn.InputStreamReceiver=Qa});var uh=D($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.WebSocketService=void 0;var Z_=oh(),ah=dr(),ch=zi(),fh=Wi(),Q_=ec(),tc=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,s,i,n,a,c="vscode",u=[]){this.authService=e,this.cryptoService=t,this.config=s,this.logger=i,this.notification=n,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,ch.getWsUrl)(this.config);this.logger.info("Connecting to WebSocket",t),this.statusChangeHandler?.("connecting");let s=await this.cryptoService.getPublicKey();return new Promise((i,n)=>{let a=Array.from(new Set([...ah.DEFAULT_CLIENT_CAPABILITIES,...this.extraCapabilities]));this.socket=(0,Z_.io)(`${t}/agent`,{auth:{token:e,protocolVersion:ah.PROTOCOL_VERSION,deviceId:this.deviceId,platform:this.platform,capabilities:a,publicKey:s},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||n(c),this.scheduleReconnect()}),this.socket.on("terminal:input",c=>{this.handleTerminalInput(c)}),this.socket.on("crypto:keyExchange",async(c,u)=>{this.logger.info("Received key exchange request",c.terminalId,c.sessionId),this.rekeyingTerminals.add(c.terminalId),this.outputBuffer.set(c.terminalId,[]);try{if(await this.cryptoService.handleKeyExchange(c.terminalId,c.clientPublicKey,c.sessionId)){let p=await this.cryptoService.getPublicKey();u?.({success:!0,agentPublicKey:p||void 0}),this.flushOutputBuffer(c.terminalId)}else u?.({success:!1,error:"Key exchange failed"})}catch(d){this.logger.error("Key exchange error",d),u?.({success:!1,error:String(d)})}finally{this.rekeyingTerminals.delete(c.terminalId),this.outputBuffer.delete(c.terminalId)}}),this.socket.on("crypto:sessionCleanup",c=>{this.cryptoService.removeSession(c.terminalId,c.sessionId)}),this.socket.on("agent:keyExchangeRequest",async c=>{try{let u=await this.cryptoService.handleAgentKeyExchange(c.clientPublicKey,c.sessionId),d={agentId:c.agentId,sessionId:c.sessionId,ok:u,error:u?void 0:"Key exchange failed"};this.socket?.emit("agent:keyExchangeAck",d)}catch(u){this.logger.error("Agent key exchange error",u);let d={agentId:c.agentId,sessionId:c.sessionId,ok:!1,error:String(u)};this.socket?.emit("agent:keyExchangeAck",d)}}),this.socket.on("meta:keyExchange",async(c,u)=>{let{ok:d,isNew:p}=await this.cryptoService.handleMetaKeyExchange(c.clientIdentityPub),m=await this.cryptoService.getPublicKey()||void 0;u?.({ok:d,agentPublicKey:m}),d&&p&&this.metaSessionEstablishedHandler?.()}),this.socket.on("agent:sessionEnd",c=>{this.cryptoService.removeAgentSession(c.sessionId)}),this.socket.on("agent:renamed",c=>{this.logger.info("Agent renamed from web client",c.name),this.isRemoteRename=!0,this.config.setAgentName(c.name).then(()=>{setTimeout(()=>{this.isRemoteRename=!1},100)}),this.agentNameSyncHandler?.(c.name)}),this.socket.on("terminal:createRequest",c=>{this.createTerminalHandler?.(c.name)}),this.socket.on("terminal:getBuffer",(c,u)=>{if(!this.getBufferHandler){u?.({success:!1,error:"Buffer handler not set"});return}let d=this.getBufferHandler(c.terminalId);if(d===null){u?.({success:!1,error:"Terminal not found"});return}let p=this.cryptoService.encryptOutput(c.terminalId,d);if(!p){this.signalInvalidSession(void 0,c.terminalId),u?.({success:!1,error:"No E2E session"});return}u?.({success:!0,encrypted:p}),this.redrawHandler?.(c.terminalId)}),this.socket.on("terminal:resize",c=>{this.resizeHandler?.(c.terminalId,c.cols,c.rows)}),this.socket.on("workspace:clientAttached",c=>{this.attachedClientCount=c.clientCount,this.clientAttachedHandler?.(c)}),this.socket.on("workspace:clientDetached",c=>{this.attachedClientCount=c.clientCount,this.clientDetachedHandler?.(c)}),this.socket.on("file:view",c=>{this.fileViewRequestHandler?.(c.terminalId,c.request)}),this.socket.on("file:list",c=>{this.fileListRequestHandler?.(c.terminalId,c.request)}),this.socket.on("file:download:request",c=>{this.fileDownloadRequestHandler?.(c.terminalId,c.path,c.requestId)})})}disconnect(){this.isManualDisconnect=!0,this.hasConnectedOnce=!1,this.stopReconnect(),this.stopHeartbeat(),this.cryptoService.clearAllSessions(),this.socket&&(this.logger.info("Disconnecting WebSocket"),this.socket.disconnect(),this.socket=null)}softDisconnect(){this.stopReconnect(),this.stopHeartbeat(),this.socket&&(this.logger.info("Soft disconnecting WebSocket (for reconnect)"),this.socket.disconnect(),this.socket=null)}getStatus(){return{connected:this.socket?.connected??!1,agentId:this.agentId}}onInput(e){this.inputHandler=e}onCreateTerminalRequest(e){this.createTerminalHandler=e}onGetBufferRequest(e){this.getBufferHandler=e}onRedrawRequest(e){this.redrawHandler=e}onResizeRequest(e){this.resizeHandler=e}onReconnect(e){this.reconnectHandlers.push(e)}onAuthFailure(e){this.authFailureHandler=e}onFileViewRequest(e){this.fileViewRequestHandler=e}onFileListRequest(e){this.fileListRequestHandler=e}onFileDownloadRequest(e){this.fileDownloadRequestHandler=e}onStatusChange(e){this.statusChangeHandler=e}onAgentNameSync(e){this.agentNameSyncHandler=e}onClientAttached(e){this.clientAttachedHandler=e}onMetaSessionEstablished(e){this.metaSessionEstablishedHandler=e}onClientDetached(e){this.clientDetachedHandler=e}async registerWorkspace(e){return this.emit("workspace:register",e)}async unregisterWorkspace(e){await this.emit("workspace:unregister",{instanceId:e})}async terminalCreated(e){return this.emit("terminal:created",e)}async terminalClosed(e){this.cryptoService.removeSession(e.terminalId),await this.emit("terminal:closed",e)}terminalNotFound(e){this.socket?.emit("terminal:notFound",{terminalId:e})}sendPtyResized(e,t,s,i){this.socket?.connected&&this.socket.emit("agent:ptyResized",{instanceId:e,terminalId:t,cols:s,rows:i})}sendClaimControl(e,t,s,i){this.socket?.connected&&this.socket.emit("agent:claimControl",{instanceId:e,terminalId:t,cols:s,rows:i})}sendOutput(e,t,s){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:s});return}let i=this.cryptoService.encryptOutput(t,s);if(!i){this.attachedClientCount>0&&this.signalInvalidSession(e,t);return}let n={instanceId:e,terminalId:t,encrypted:i};this.socket?.emit("terminal:output",n)}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:s,data:i}of t){let n=this.cryptoService.encryptOutput(e,i);if(!n){this.signalInvalidSession(s,e);continue}let a={instanceId:s,terminalId:e,encrypted:n};this.socket?.emit("terminal:output",a)}}}signalInvalidSession(e,t){let s=Date.now(),i=this.invalidSessionSignalAt.get(t)??0;s-i<this.INVALID_SESSION_SIGNAL_THROTTLE_MS||(this.invalidSessionSignalAt.set(t,s),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,s){let i={instanceId:e,terminalId:t,event:s};this.socket?.emit("terminal:event",i)}hasCapability(e){return this.negotiatedCapabilities.includes(e)}sendFileChangedEvent(e,t,s){let i={instanceId:e,terminalId:t,event:s};this.socket?.emit("file:changed",i)}sendFileListResponse(e,t){let s={instanceId:e,response:t};this.socket?.emit("file:list:response",s)}sendAgentRename(e){this.socket?.emit("agent:rename",{name:e})}isRemoteRenameInProgress(){return this.isRemoteRename}getSocket(){return this.socket}emit(e,t){let s=(0,fh.generateCorrelationId)(),i=t&&typeof t=="object"&&!Array.isArray(t)?{...t,_cid:s}:t;return(0,fh.runWithCorrelation)(s,()=>new Promise((n,a)=>{if(!this.socket?.connected){a(new Error("WebSocket not connected"));return}this.socket.emit(e,i,c=>{c.success?n(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 s=this.cryptoService.decryptInput(e.terminalId,e.encrypted);if(!s){this.logger.error("Failed to decrypt terminal input",e.terminalId),this.signalInvalidSession(e.instanceId,e.terminalId);return}t=s}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 s=this.getOrCreateInputReceiver(e.terminalId,e.streamId,e.instanceId,e.dbTerminalId);if(!s)return;s.receive(e.seq,t,e.paste);return}this.inputHandler?.(e.terminalId,t,e.dbTerminalId)}getOrCreateInputReceiver(e,t,s,i){let n=this.inputReceivers.get(e);if(this.terminalActiveCheck&&!this.terminalActiveCheck(e))return n&&this.disposeInputStream(e),null;if(n&&n.receiver.streamId===t)return i&&(n.routeId=i),s&&(n.instanceId=s),n.receiver;if(n&&n.receiver.dispose(),!n&&this.inputReceivers.size>=this.MAX_INPUT_RECEIVERS)return this.logger.error("inputReceivers map at cap, dropping frame",e),null;let a=new Q_.InputStreamReceiver(t,{onApply:(c,u)=>this.inputHandler?.(e,c,this.routeIdFor(e),u),onAck:c=>this.sendInputAck(e,t,c),onResend:c=>this.sendInputResend(e,t,c)});return this.inputReceivers.set(e,{receiver:a,routeId:i??e,instanceId:s??""}),a}setTerminalActiveCheck(e){this.terminalActiveCheck=e}routeIdFor(e){return this.inputReceivers.get(e)?.routeId??e}sendInputAck(e,t,s){let i=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:ack",{instanceId:i,terminalId:e,streamId:t,ackSeq:s})}sendInputResend(e,t,s){let i=this.inputReceivers.get(e)?.instanceId;this.socket?.emit("input:resend",{instanceId:i,terminalId:e,streamId:t,fromSeq:s})}sendInputResume(e){let t=this.inputReceivers.get(e);if(!t)return;let{streamId:s,lastAckSeq:i}=t.receiver.resumeState();this.socket?.emit("input:resume",{instanceId:t.instanceId,terminalId:e,streamId:s,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(s){this.logger.warn("Reconnect failed",s),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,ch.getApiUrl)(this.config)}/health`,s=new AbortController,i=setTimeout(()=>s.abort(),5e3),n=await fetch(t,{method:"GET",signal:s.signal});return clearTimeout(i),this.logger.debug("Network check OK",String(n.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)}};$n.WebSocketService=tc});var hh=D(sr=>{"use strict";var ey=sr&&sr.__createBinding||(Object.create?(function(r,e,t,s){s===void 0&&(s=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,s,i)}):(function(r,e,t,s){s===void 0&&(s=t),r[s]=e[t]})),ty=sr&&sr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),sc=sr&&sr.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var s=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(s[s.length]=i);return s},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var s=r(e),i=0;i<s.length;i++)s[i]!=="default"&&ey(t,e,s[i]);return ty(t,e),t}})();Object.defineProperty(sr,"__esModule",{value:!0});sr.FileTransferService=void 0;var Gn=sc(require("fs")),ry=sc(require("path")),lh=sc(require("crypto")),Be=dr(),rc=class{socket=null;activeTransfers=new Map;instanceId="";logger;fallbackDir;cryptoService=null;constructor(e,t="/tmp"){this.logger=e,this.fallbackDir=t}setCrypto(e){this.cryptoService=e}attach(e,t){this.socket=e,this.instanceId=t,this.setupEventHandlers(),this.logger.info("FileTransferService attached")}detach(){this.socket=null;for(let[e]of this.activeTransfers)this.cancelTransfer(e,"Disconnected");this.logger.info("FileTransferService detached")}async sendFile(e,t,s,i,n){let a=Gn.readFileSync(t),c=t.split("/").pop()||"file";return this.initAndSendChunks(e,a,c,{mimeType:this.getMimeType(c),requestId:n,onProgress:s,onComplete:i})}async sendBuffer(e,t,s,i,n){return this.initAndSendChunks(e,t,s,{mimeType:i,purpose:n?.purpose,viewMetadata:n?.viewMetadata,requestId:n?.requestId,onProgress:n?.onProgress,onComplete:n?.onComplete})}async initAndSendChunks(e,t,s,i){if(!this.socket)throw new Error("Socket not connected");let n=t.length,a=(0,Be.calculateTotalChunks)(n),c=this.calculateChecksum(t),u=lh.randomUUID(),d={id:u,terminalId:e,filename:s,size:n,totalChunks:a,direction:Be.TransferDirection.DOWNLOAD,status:Be.TransferStatus.PENDING,deliveredChunks:new Set,pendingChunks:new Map,checksum:c,checksumAlgorithm:"sha256",onProgress:i.onProgress?(m,y)=>i.onProgress(u,m,y):void 0,onComplete:i.onComplete?(m,y)=>i.onComplete(u,m,y):void 0,ackTimeouts:new Map};d.chunks=[];for(let m=0;m<a;m++){let y=m*Be.CHUNK_SIZE,b=Math.min(y+Be.CHUNK_SIZE,n);d.chunks.push(t.subarray(y,b))}this.activeTransfers.set(u,d);let p={transferId:u,terminalId:e,filename:s,size:n,totalChunks:a,mimeType:i.mimeType||"application/octet-stream",checksum:c,direction:Be.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,y)=>{this.socket.emit("file:init",p,b=>{b.accepted?(d.status=Be.TransferStatus.ACTIVE,this.startSendingChunks(u),m(u)):(this.activeTransfers.delete(u),y(new Error(b.error||"Transfer rejected")))})})}async receiveFile(e,t,s,i,n,a,c,u="sha256",d,p){let m={id:e,terminalId:t,filename:s,filePath:c,size:i,totalChunks:n,direction:Be.TransferDirection.UPLOAD,status:Be.TransferStatus.ACTIVE,deliveredChunks:new Set,pendingChunks:new Map,chunks:new Array(n).fill(null),checksum:a,checksumAlgorithm:u,onProgress:d?(y,b)=>d(e,y,b):void 0,onComplete:p?(y,b)=>p(e,y,b):void 0,ackTimeouts:new Map};this.activeTransfers.set(e,m)}cancelTransfer(e,t){let s=this.activeTransfers.get(e);if(s){for(let i of s.ackTimeouts.values())clearTimeout(i);if(s.status=Be.TransferStatus.CANCELLED,s.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},s=>{if(s.status===Be.TransferStatus.EXPIRED){t.onComplete?.(!1,"Transfer expired"),this.activeTransfers.delete(e);return}if(s.deliveredChunks)for(let i of s.deliveredChunks)t.deliveredChunks.add(i);if(t.direction===Be.TransferDirection.DOWNLOAD&&s.missingChunks){t.status=Be.TransferStatus.ACTIVE;for(let i of s.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 s of t.ackTimeouts.values())clearTimeout(s);t.status=Be.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 s=0;s<Math.min(Be.WINDOW_SIZE,t.totalChunks);s++)t.deliveredChunks.has(s)||this.sendChunk(t,s)}sendChunk(e,t){if(!this.socket||!e.chunks)return;let s=e.chunks[t];if(!s)return;let i=e.pendingChunks.get(t),n={seq:t,data:s,retries:i?i.retries:0,sentAt:Date.now()};e.pendingChunks.set(t,n);let a=this.cryptoService?.encryptFileChunk(e.terminalId,new Uint8Array(s.buffer,s.byteOffset,s.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)},Be.ACK_TIMEOUT_MS);e.ackTimeouts.set(t,u)}handleChunkAck(e){let t=this.activeTransfers.get(e.transferId);if(!t||t.status===Be.TransferStatus.COMPLETED)return;let s=t.ackTimeouts.get(e.seq);s&&(clearTimeout(s),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+Be.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 s=this.activeTransfers.get(e);if(!s)return;let i=s.pendingChunks.get(t);i&&(i.retries<Be.MAX_RETRIES?(i.retries++,this.sendChunk(s,t)):this.cancelTransfer(e,"Max retries exceeded"))}finishSending(e){if(!this.socket)return;e.status=Be.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 s=e.encrypted?this.cryptoService?.decryptFileChunk(t.terminalId,e.encrypted):null;if(!s){this.cancelTransfer(e.transferId,"Chunk decryption failed (no E2E session?)");return}if(t.chunks[e.seq]=Buffer.from(s),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=Be.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=ry.dirname(e.filePath);Gn.existsSync(i)||Gn.mkdirSync(i,{recursive:!0}),Gn.writeFileSync(e.filePath,t),e.status=Be.TransferStatus.COMPLETED,e.onComplete?.(!0),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!0})}catch(i){let n=i instanceof Error?i.message:String(i);e.status=Be.TransferStatus.FAILED,e.onComplete?.(!1,`Failed to save file: ${n}`),this.socket&&this.socket.emit("file:complete",{transferId:e.id,success:!1,error:`Failed to save file: ${n}`})}this.activeTransfers.delete(e.id)}handleComplete(e){let t=this.activeTransfers.get(e.transferId);if(t){e.success?(t.status=Be.TransferStatus.COMPLETED,t.onComplete?.(!0)):(t.status=Be.TransferStatus.FAILED,t.onComplete?.(!1,e.error));for(let s of t.ackTimeouts.values())clearTimeout(s);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=`${e.targetPath||this.fallbackDir}/${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):lh.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"}};sr.FileTransferService=rc});var uc=D((jw,Jn)=>{function gh(r){return Array.isArray(r)?r:[r]}var sy=void 0,nc="",dh=" ",ic="\\",iy=/^\s+$/,ny=/(?:[^\\]|^)\\$/,oy=/^\\!/,ay=/^\\#/,cy=/\r?\n/g,fy=/^\.{0,2}\/|^\.{1,2}$/,uy=/\/$/,Ws="/",mh="node-ignore";typeof Symbol<"u"&&(mh=Symbol.for("node-ignore"));var _h=mh,Hs=(r,e,t)=>(Object.defineProperty(r,e,{value:t}),t),ly=/([0-z])-([0-z])/g,yh=()=>!1,hy=r=>r.replace(ly,(e,t,s)=>t.charCodeAt(0)<=s.charCodeAt(0)?e:nc),dy=r=>{let{length:e}=r;return r.slice(0,e-e%2)},py=[[/^\uFEFF/,()=>nc],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?dh:nc)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+dh}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let s=t.replace(/\\\*/g,"[^\\/]*");return e+s}],[/\\\\\\(?=[$.|*+(){^])/g,()=>ic],[/\\\\/g,()=>ic],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,s,i)=>e===ic?`\\[${t}${dy(s)}${i}`:i==="]"&&s.length%2===0?`[${hy(t)}${s}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`]],gy=/(^|\\\/)?\\\*$/,vi="regex",Yn="checkRegex",ph="_",my={[vi](r,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Yn](r,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},_y=r=>py.reduce((e,[t,s])=>e.replace(t,s.bind(r)),r),Xn=r=>typeof r=="string",yy=r=>r&&Xn(r)&&!iy.test(r)&&!ny.test(r)&&r.indexOf("#")!==0,vy=r=>r.split(cy).filter(Boolean),oc=class{constructor(e,t,s,i,n,a){this.pattern=e,this.mark=t,this.negative=n,Hs(this,"body",s),Hs(this,"ignoreCase",i),Hs(this,"regexPrefix",a)}get regex(){let e=ph+vi;return this[e]?this[e]:this._make(vi,e)}get checkRegex(){let e=ph+Yn;return this[e]?this[e]:this._make(Yn,e)}_make(e,t){let s=this.regexPrefix.replace(gy,my[e]),i=this.ignoreCase?new RegExp(s,"i"):new RegExp(s);return Hs(this,t,i)}},Ey=({pattern:r,mark:e},t)=>{let s=!1,i=r;i.indexOf("!")===0&&(s=!0,i=i.substr(1)),i=i.replace(oy,"!").replace(ay,"#");let n=_y(i);return new oc(r,e,i,t,s,n)},ac=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[_h]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(Xn(e)&&(e={pattern:e}),yy(e.pattern)){let t=Ey(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,gh(Xn(e)?vy(e):e).forEach(this._add,this),this._added}test(e,t,s){let i=!1,n=!1,a;this._rules.forEach(u=>{let{negative:d}=u;n===d&&i!==n||d&&!i&&!n&&!t||!u[s].test(e)||(i=!d,n=d,a=d?sy:u)});let c={ignored:i,unignored:n};return a&&(c.rule=a),c}},wy=(r,e)=>{throw new e(r)},Er=(r,e,t)=>Xn(r)?r?Er.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),vh=r=>fy.test(r);Er.isNotRelative=vh;Er.convert=r=>r;var cc=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:s=!1}={}){Hs(this,_h,!0),this._rules=new ac(t),this._strictPathCheck=!s,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,s,i){let n=e&&Er.convert(e);return Er(n,e,this._strictPathCheck?wy:yh),this._t(n,t,s,i)}checkIgnore(e){if(!uy.test(e))return this.test(e);let t=e.split(Ws).filter(Boolean);if(t.pop(),t.length){let s=this._t(t.join(Ws)+Ws,this._testCache,!0,t);if(s.ignored)return s}return this._rules.test(e,!1,Yn)}_t(e,t,s,i){if(e in t)return t[e];if(i||(i=e.split(Ws).filter(Boolean)),i.pop(),!i.length)return t[e]=this._rules.test(e,s,vi);let n=this._t(i.join(Ws)+Ws,t,s,i);return t[e]=n.ignored?n:this._rules.test(e,s,vi)}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)}},fc=r=>new cc(r),by=r=>Er(r&&Er.convert(r),r,yh),Eh=()=>{let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");Er.convert=r;let e=/^[a-z]:\//i;Er.isNotRelative=t=>e.test(t)||vh(t)};typeof process<"u"&&process.platform==="win32"&&Eh();Jn.exports=fc;fc.default=fc;Jn.exports.isPathValid=by;Hs(Jn.exports,Symbol.for("setupWindows"),Eh)});var bh=D(Mt=>{"use strict";var xy=Mt&&Mt.__createBinding||(Object.create?(function(r,e,t,s){s===void 0&&(s=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,s,i)}):(function(r,e,t,s){s===void 0&&(s=t),r[s]=e[t]})),Sy=Mt&&Mt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),wh=Mt&&Mt.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var s=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(s[s.length]=i);return s},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var s=r(e),i=0;i<s.length;i++)s[i]!=="default"&&xy(t,e,s[i]);return Sy(t,e),t}})(),Ty=Mt&&Mt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Mt,"__esModule",{value:!0});Mt.FileListService=void 0;var Ei=wh(require("path")),lc=wh(require("fs/promises")),Cy=Ty(uc()),hc=dr(),Oy=["node_modules",".pnpm","vendor",".git","dist","build","out",".next",".nuxt",".output",".cache",".turbo",".idea",".vscode",".DS_Store","Thumbs.db"],dc=class{ignoreFilter;workspaceRoot;onResponseCallback=null;logger;constructor(e,t){this.logger=e,this.workspaceRoot=t,this.ignoreFilter=(0,Cy.default)(),this.ignoreFilter.add(Oy),this.workspaceRoot&&this.loadGitignore(),this.logger.info("FileListService initialized",t||"null")}async loadGitignore(){if(!this.workspaceRoot)return;let e=Ei.join(this.workspaceRoot,".gitignore");try{let t=await lc.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),s=await this.listDirectory(t,e.path);this.sendResponse({requestId:e.requestId,path:e.path,entries:s})}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 s=await lc.readdir(e,{withFileTypes:!0}),i=[];for(let n of s){let a=t==="."||t===""?n.name:Ei.join(t,n.name);if(this.shouldHide(a,n.isDirectory()))continue;let c=Ei.join(e,n.name),u={name:n.name,path:a,type:n.isDirectory()?hc.FileEntryType.DIRECTORY:hc.FileEntryType.FILE};if(!n.isDirectory())try{let d=await lc.stat(c);u.size=d.size,u.modified=d.mtime.toISOString()}catch{}i.push(u)}return i.sort((n,a)=>n.type!==a.type?n.type===hc.FileEntryType.DIRECTORY?-1:1:n.name.localeCompare(a.name))}shouldHide(e,t){let s=e.split(Ei.sep).join("/"),i=t?`${s}/`:s;return this.ignoreFilter.ignores(i)}resolvePath(e){if(!this.workspaceRoot)throw new Error("No workspace root");if(e==="."||e==="")return this.workspaceRoot;let t=Ei.join(this.workspaceRoot,e);if(!t.startsWith(this.workspaceRoot))throw new Error("Path outside workspace");return t}sendResponse(e){this.onResponseCallback?.(e)}dispose(){this.onResponseCallback=null}};Mt.FileListService=dc});var Sh=D(ir=>{"use strict";var ky=ir&&ir.__createBinding||(Object.create?(function(r,e,t,s){s===void 0&&(s=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,s,i)}):(function(r,e,t,s){s===void 0&&(s=t),r[s]=e[t]})),Ry=ir&&ir.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),xh=ir&&ir.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var s=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(s[s.length]=i);return s},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var s=r(e),i=0;i<s.length;i++)s[i]!=="default"&&ky(t,e,s[i]);return Ry(t,e),t}})();Object.defineProperty(ir,"__esModule",{value:!0});ir.FileTrackerService=void 0;var pc=xh(require("path")),us=xh(require("fs/promises")),Ay=require("child_process"),Py=require("util"),Ht=dr(),gc=(0,Py.promisify)(Ay.exec),mc={toolStart:/⏺\s*(Write|Edit|NotebookEdit)\s*\(\s*(?:file_path|notebook_path)\s*=\s*"([^"]+)"/,toolSuccess:/[✓✔]\s*(?:Wrote|Edited|Updated|Created)\s+([^\s\n]+)/,toolError:/[✗✘]\s*(?:Failed|Error)/i},_c=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 s=this.outputBuffers.get(e)||"";s+=t,s.length>10240&&(s=s.slice(-10240)),this.outputBuffers.set(e,s);try{await this.parseToolCalls(e,s)}catch(i){this.logger.error("Error parsing tool calls",i)}}async parseToolCalls(e,t){let s=this.stripAnsi(t),i=s.match(mc.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 n=s.match(mc.toolSuccess);if(n){let a=n[1];for(let[c,u]of this.pendingToolCalls)if(u.filePath===a||a.endsWith(u.filePath)||u.filePath.endsWith(a)){await this.handleToolEnd(e,c,u.toolName,"success");break}}if(mc.toolError.test(s))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,s,i){if(!this.isFileModifyingTool(s))return;let n=this.extractFilePath(s,i);if(!n)return;let a=this.resolveFilePath(n),c={toolId:t,toolName:s,filePath:n,timestamp:new Date().toISOString()};this.pendingToolCalls.set(t,c);let u;try{u=await us.readFile(a,"utf-8")}catch{u=void 0}let d={path:n,changeType:u===void 0?Ht.FileChangeType.CREATE:Ht.FileChangeType.MODIFY,toolName:s,toolId:t,timestamp:c.timestamp,previousContent:u},p=this.trackedFiles.get(e)||[];p.push(d),this.trackedFiles.set(e,p)}async handleToolEnd(e,t,s,i){if(!this.isFileModifyingTool(s)||!this.pendingToolCalls.get(t))return;if(this.pendingToolCalls.delete(t),i==="error"){let p=this.trackedFiles.get(e)||[],m=p.findIndex(y=>y.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 us.stat(u);c.size=p.size}catch{c.changeType=Ht.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 s=this.resolveFilePath(t.path),i=this.getViewableMimeType(t.path);if(i&&this.onFileViewTransferCallback){try{let a=await us.readFile(s),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 n;try{t.type===Ht.FileViewType.CONTENT?n=await this.getFileContent(t,s):n=await this.getFileDiff(e,t,s)}catch(a){n={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:n.type===Ht.FileViewType.CONTENT?"content":"diff",language:n.language,truncated:n.truncated,error:n.error},c=Buffer.from(n.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 s=e.maxSize||1048576,i=await us.stat(t),n=await us.readFile(t,"utf-8"),a=!1,c=n;return n.length>s&&(c=n.slice(0,s),a=!0),{requestId:e.requestId,path:e.path,type:Ht.FileViewType.CONTENT,content:c,language:(0,Ht.getLanguageFromPath)(e.path),size:i.size,truncated:a}}async getFileDiff(e,t,s){let i=t.diffBase||Ht.DiffBase.GIT,n;return i===Ht.DiffBase.GIT?n=await this.getGitDiff(s):n=await this.getPreviousDiff(e,t.path,s),{requestId:t.requestId,path:t.path,type:Ht.FileViewType.DIFF,content:n,language:"diff"}}async getGitDiff(e){if(!this.workspaceRoot)throw new Error("No workspace root");try{let{stdout:t}=await gc(`git diff --cached -- "${e}"`,{cwd:this.workspaceRoot});if(t.trim())return t;let{stdout:s}=await gc(`git diff -- "${e}"`,{cwd:this.workspaceRoot});if(s.trim())return s;let{stdout:i}=await gc(`git status --porcelain -- "${e}"`,{cwd:this.workspaceRoot});if(i.startsWith("??")||i.startsWith("A ")){let a=(await us.readFile(e,"utf-8")).split(`
|
|
27
29
|
`),c=pc.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(`
|
|
28
|
-
`)}return"(no changes)"}catch{throw new Error("Git not available")}}async getPreviousDiff(e,t,
|
|
29
|
-
`)}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){return pc.isAbsolute(e)?e:this.workspaceRoot?pc.join(this.workspaceRoot,e):e}dispose(){this.trackedFiles.clear(),this.pendingToolCalls.clear(),this.onFileChangedCallback=null,this.onFileViewTransferCallback=null}};sr.FileTrackerService=_c});var Th=M(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.InputStreamReceiver=st.FileTrackerService=st.FileListService=st.FileTransferService=st.WebSocketService=st.StatusDetector=st.AuthService=st.CryptoService=void 0;var Iy=Xf();Object.defineProperty(st,"CryptoService",{enumerable:!0,get:function(){return Iy.CryptoService}});var Ly=Jf();Object.defineProperty(st,"AuthService",{enumerable:!0,get:function(){return Ly.AuthService}});var Ny=Zf();Object.defineProperty(st,"StatusDetector",{enumerable:!0,get:function(){return Ny.StatusDetector}});var Dy=uh();Object.defineProperty(st,"WebSocketService",{enumerable:!0,get:function(){return Dy.WebSocketService}});var My=hh();Object.defineProperty(st,"FileTransferService",{enumerable:!0,get:function(){return My.FileTransferService}});var Fy=bh();Object.defineProperty(st,"FileListService",{enumerable:!0,get:function(){return Fy.FileListService}});var By=Sh();Object.defineProperty(st,"FileTrackerService",{enumerable:!0,get:function(){return By.FileTrackerService}});var jy=ec();Object.defineProperty(st,"InputStreamReceiver",{enumerable:!0,get:function(){return jy.InputStreamReceiver}})});var ws=M(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.InputStreamReceiver=we.FileTrackerService=we.FileListService=we.FileTransferService=we.WebSocketService=we.StatusDetector=we.AuthService=we.CryptoService=we.getCurrentCorrelationId=we.runWithCorrelation=we.generateCorrelationId=we.getWsUrl=we.getApiUrl=we.CircularBuffer=we.formatLogLine=we.shouldLog=we.LOG_LEVELS=void 0;var yc=gf();Object.defineProperty(we,"LOG_LEVELS",{enumerable:!0,get:function(){return yc.LOG_LEVELS}});Object.defineProperty(we,"shouldLog",{enumerable:!0,get:function(){return yc.shouldLog}});Object.defineProperty(we,"formatLogLine",{enumerable:!0,get:function(){return yc.formatLogLine}});var Hi=yf();Object.defineProperty(we,"CircularBuffer",{enumerable:!0,get:function(){return Hi.CircularBuffer}});Object.defineProperty(we,"getApiUrl",{enumerable:!0,get:function(){return Hi.getApiUrl}});Object.defineProperty(we,"getWsUrl",{enumerable:!0,get:function(){return Hi.getWsUrl}});Object.defineProperty(we,"generateCorrelationId",{enumerable:!0,get:function(){return Hi.generateCorrelationId}});Object.defineProperty(we,"runWithCorrelation",{enumerable:!0,get:function(){return Hi.runWithCorrelation}});Object.defineProperty(we,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Hi.getCurrentCorrelationId}});var jr=Th();Object.defineProperty(we,"CryptoService",{enumerable:!0,get:function(){return jr.CryptoService}});Object.defineProperty(we,"AuthService",{enumerable:!0,get:function(){return jr.AuthService}});Object.defineProperty(we,"StatusDetector",{enumerable:!0,get:function(){return jr.StatusDetector}});Object.defineProperty(we,"WebSocketService",{enumerable:!0,get:function(){return jr.WebSocketService}});Object.defineProperty(we,"FileTransferService",{enumerable:!0,get:function(){return jr.FileTransferService}});Object.defineProperty(we,"FileListService",{enumerable:!0,get:function(){return jr.FileListService}});Object.defineProperty(we,"FileTrackerService",{enumerable:!0,get:function(){return jr.FileTrackerService}});Object.defineProperty(we,"InputStreamReceiver",{enumerable:!0,get:function(){return jr.InputStreamReceiver}})});var bc=M((xs,wc)=>{(function(r,e){typeof xs=="object"&&typeof wc=="object"?wc.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof xs=="object"?xs["electron-machine-id"]=e(require("child_process"),require("crypto")):r["electron-machine-id"]=e(r.child_process,r.crypto)})(xs,function(r,e){return(function(t){function i(n){if(s[n])return s[n].exports;var a=s[n]={exports:{},id:n,loaded:!1};return t[n].call(a.exports,a,a.exports,i),a.loaded=!0,a.exports}var s={};return i.m=t,i.c=s,i.p="",i(0)})([function(t,i,s){t.exports=s(34)},function(t,i,s){var n=s(29)("wks"),a=s(33),c=s(2).Symbol,u=typeof c=="function",d=t.exports=function(p){return n[p]||(n[p]=u&&c[p]||(u?c:a)("Symbol."+p))};d.store=n},function(t,i){var s=t.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=s)},function(t,i,s){var n=s(9);t.exports=function(a){if(!n(a))throw TypeError(a+" is not an object!");return a}},function(t,i,s){t.exports=!s(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(t,i,s){var n=s(12),a=s(17);t.exports=s(4)?function(c,u,d){return n.f(c,u,a(1,d))}:function(c,u,d){return c[u]=d,c}},function(t,i){var s=t.exports={version:"2.4.0"};typeof __e=="number"&&(__e=s)},function(t,i,s){var n=s(14);t.exports=function(a,c,u){if(n(a),c===void 0)return a;switch(u){case 1:return function(d){return a.call(c,d)};case 2:return function(d,p){return a.call(c,d,p)};case 3:return function(d,p,m){return a.call(c,d,p,m)}}return function(){return a.apply(c,arguments)}}},function(t,i){var s={}.hasOwnProperty;t.exports=function(n,a){return s.call(n,a)}},function(t,i){t.exports=function(s){return typeof s=="object"?s!==null:typeof s=="function"}},function(t,i){t.exports={}},function(t,i){var s={}.toString;t.exports=function(n){return s.call(n).slice(8,-1)}},function(t,i,s){var n=s(3),a=s(26),c=s(32),u=Object.defineProperty;i.f=s(4)?Object.defineProperty:function(d,p,m){if(n(d),p=c(p,!0),n(m),a)try{return u(d,p,m)}catch{}if("get"in m||"set"in m)throw TypeError("Accessors not supported!");return"value"in m&&(d[p]=m.value),d}},function(t,i,s){var n=s(42),a=s(15);t.exports=function(c){return n(a(c))}},function(t,i){t.exports=function(s){if(typeof s!="function")throw TypeError(s+" is not a function!");return s}},function(t,i){t.exports=function(s){if(s==null)throw TypeError("Can't call method on "+s);return s}},function(t,i,s){var n=s(9),a=s(2).document,c=n(a)&&n(a.createElement);t.exports=function(u){return c?a.createElement(u):{}}},function(t,i){t.exports=function(s,n){return{enumerable:!(1&s),configurable:!(2&s),writable:!(4&s),value:n}}},function(t,i,s){var n=s(12).f,a=s(8),c=s(1)("toStringTag");t.exports=function(u,d,p){u&&!a(u=p?u:u.prototype,c)&&n(u,c,{configurable:!0,value:d})}},function(t,i,s){var n=s(29)("keys"),a=s(33);t.exports=function(c){return n[c]||(n[c]=a(c))}},function(t,i){var s=Math.ceil,n=Math.floor;t.exports=function(a){return isNaN(a=+a)?0:(a>0?n:s)(a)}},function(t,i,s){var n=s(11),a=s(1)("toStringTag"),c=n((function(){return arguments})())=="Arguments",u=function(d,p){try{return d[p]}catch{}};t.exports=function(d){var p,m,y;return d===void 0?"Undefined":d===null?"Null":typeof(m=u(p=Object(d),a))=="string"?m:c?n(p):(y=n(p))=="Object"&&typeof p.callee=="function"?"Arguments":y}},function(t,i){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,i,s){var n=s(2),a=s(6),c=s(7),u=s(5),d="prototype",p=function(m,y,b){var T,C,V,_e=m&p.F,X=m&p.G,P=m&p.S,B=m&p.P,te=m&p.B,A=m&p.W,ae=X?a:a[y]||(a[y]={}),pe=ae[d],Q=X?n:P?n[y]:(n[y]||{})[d];X&&(b=y);for(T in b)C=!_e&&Q&&Q[T]!==void 0,C&&T in ae||(V=C?Q[T]:b[T],ae[T]=X&&typeof Q[T]!="function"?b[T]:te&&C?c(V,n):A&&Q[T]==V?(function(Ne){var ve=function(ze,ee,Je){if(this instanceof Ne){switch(arguments.length){case 0:return new Ne;case 1:return new Ne(ze);case 2:return new Ne(ze,ee)}return new Ne(ze,ee,Je)}return Ne.apply(this,arguments)};return ve[d]=Ne[d],ve})(V):B&&typeof V=="function"?c(Function.call,V):V,B&&((ae.virtual||(ae.virtual={}))[T]=V,m&p.R&&pe&&!pe[T]&&u(pe,T,V)))};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(s){try{return!!s()}catch{return!0}}},function(t,i,s){t.exports=s(2).document&&document.documentElement},function(t,i,s){t.exports=!s(4)&&!s(24)(function(){return Object.defineProperty(s(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(t,i,s){"use strict";var n=s(28),a=s(23),c=s(57),u=s(5),d=s(8),p=s(10),m=s(45),y=s(18),b=s(52),T=s(1)("iterator"),C=!([].keys&&"next"in[].keys()),V="@@iterator",_e="keys",X="values",P=function(){return this};t.exports=function(B,te,A,ae,pe,Q,Ne){m(A,te,ae);var ve,ze,ee,Je=function(j){if(!C&&j in Te)return Te[j];switch(j){case _e:return function(){return new A(this,j)};case X:return function(){return new A(this,j)}}return function(){return new A(this,j)}},We=te+" Iterator",nt=pe==X,Me=!1,Te=B.prototype,ot=Te[T]||Te[V]||pe&&Te[pe],He=ot||Je(pe),vt=pe?nt?Je("entries"):He:void 0,L=te=="Array"&&Te.entries||ot;if(L&&(ee=b(L.call(new B)),ee!==Object.prototype&&(y(ee,We,!0),n||d(ee,T)||u(ee,T,P))),nt&&ot&&ot.name!==X&&(Me=!0,He=function(){return ot.call(this)}),n&&!Ne||!C&&!Me&&Te[T]||u(Te,T,He),p[te]=He,p[We]=P,pe)if(ve={values:nt?He:Je(X),keys:Q?He:Je(_e),entries:vt},Ne)for(ze in ve)ze in Te||c(Te,ze,ve[ze]);else a(a.P+a.F*(C||Me),te,ve);return ve}},function(t,i){t.exports=!0},function(t,i,s){var n=s(2),a="__core-js_shared__",c=n[a]||(n[a]={});t.exports=function(u){return c[u]||(c[u]={})}},function(t,i,s){var n,a,c,u=s(7),d=s(41),p=s(25),m=s(16),y=s(2),b=y.process,T=y.setImmediate,C=y.clearImmediate,V=y.MessageChannel,_e=0,X={},P="onreadystatechange",B=function(){var A=+this;if(X.hasOwnProperty(A)){var ae=X[A];delete X[A],ae()}},te=function(A){B.call(A.data)};T&&C||(T=function(A){for(var ae=[],pe=1;arguments.length>pe;)ae.push(arguments[pe++]);return X[++_e]=function(){d(typeof A=="function"?A:Function(A),ae)},n(_e),_e},C=function(A){delete X[A]},s(11)(b)=="process"?n=function(A){b.nextTick(u(B,A,1))}:V?(a=new V,c=a.port2,a.port1.onmessage=te,n=u(c.postMessage,c,1)):y.addEventListener&&typeof postMessage=="function"&&!y.importScripts?(n=function(A){y.postMessage(A+"","*")},y.addEventListener("message",te,!1)):n=P in m("script")?function(A){p.appendChild(m("script"))[P]=function(){p.removeChild(this),B.call(A)}}:function(A){setTimeout(u(B,A,1),0)}),t.exports={set:T,clear:C}},function(t,i,s){var n=s(20),a=Math.min;t.exports=function(c){return c>0?a(n(c),9007199254740991):0}},function(t,i,s){var n=s(9);t.exports=function(a,c){if(!n(a))return a;var u,d;if(c&&typeof(u=a.toString)=="function"&&!n(d=u.call(a))||typeof(u=a.valueOf)=="function"&&!n(d=u.call(a))||!c&&typeof(u=a.toString)=="function"&&!n(d=u.call(a)))return d;throw TypeError("Can't convert object to primitive value")}},function(t,i){var s=0,n=Math.random();t.exports=function(a){return"Symbol(".concat(a===void 0?"":a,")_",(++s+n).toString(36))}},function(t,i,s){"use strict";function n(P){return P&&P.__esModule?P:{default:P}}function a(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function c(P){return(0,T.createHash)("sha256").update(P).digest("hex")}function u(P){switch(V){case"darwin":return P.split("IOPlatformUUID")[1].split(`
|
|
30
|
-
`)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return P.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return P.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return P.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function d(P){var B=u((0,b.execSync)(X[V]).toString());return P?B:c(B)}function p(P){return new y.default(function(B,te){return(0,b.exec)(X[V],{},function(A,ae,pe){if(A)return te(new Error("Error while obtaining machine id: "+A.stack));var Q=u(ae.toString());return B(P?Q:c(Q))})})}Object.defineProperty(i,"__esModule",{value:!0});var m=s(35),y=n(m);i.machineIdSync=d,i.machineId=p;var b=s(70),T=s(71),C=process,V=C.platform,_e={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},X={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:_e[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,s){t.exports={default:s(36),__esModule:!0}},function(t,i,s){s(66),s(68),s(69),s(67),t.exports=s(6).Promise},function(t,i){t.exports=function(){}},function(t,i){t.exports=function(s,n,a,c){if(!(s instanceof n)||c!==void 0&&c in s)throw TypeError(a+": incorrect invocation!");return s}},function(t,i,s){var n=s(13),a=s(31),c=s(62);t.exports=function(u){return function(d,p,m){var y,b=n(d),T=a(b.length),C=c(m,T);if(u&&p!=p){for(;T>C;)if(y=b[C++],y!=y)return!0}else for(;T>C;C++)if((u||C in b)&&b[C]===p)return u||C||0;return!u&&-1}}},function(t,b,s){var n=s(7),a=s(44),c=s(43),u=s(3),d=s(31),p=s(64),m={},y={},b=t.exports=function(T,C,V,_e,X){var P,B,te,A,ae=X?function(){return T}:p(T),pe=n(V,_e,C?2:1),Q=0;if(typeof ae!="function")throw TypeError(T+" is not iterable!");if(c(ae)){for(P=d(T.length);P>Q;Q++)if(A=C?pe(u(B=T[Q])[0],B[1]):pe(T[Q]),A===m||A===y)return A}else for(te=ae.call(T);!(B=te.next()).done;)if(A=a(te,pe,B.value,C),A===m||A===y)return A};b.BREAK=m,b.RETURN=y},function(t,i){t.exports=function(s,n,a){var c=a===void 0;switch(n.length){case 0:return c?s():s.call(a);case 1:return c?s(n[0]):s.call(a,n[0]);case 2:return c?s(n[0],n[1]):s.call(a,n[0],n[1]);case 3:return c?s(n[0],n[1],n[2]):s.call(a,n[0],n[1],n[2]);case 4:return c?s(n[0],n[1],n[2],n[3]):s.call(a,n[0],n[1],n[2],n[3])}return s.apply(a,n)}},function(t,i,s){var n=s(11);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(a){return n(a)=="String"?a.split(""):Object(a)}},function(t,i,s){var n=s(10),a=s(1)("iterator"),c=Array.prototype;t.exports=function(u){return u!==void 0&&(n.Array===u||c[a]===u)}},function(t,i,s){var n=s(3);t.exports=function(a,c,u,d){try{return d?c(n(u)[0],u[1]):c(u)}catch(m){var p=a.return;throw p!==void 0&&n(p.call(a)),m}}},function(t,i,s){"use strict";var n=s(49),a=s(17),c=s(18),u={};s(5)(u,s(1)("iterator"),function(){return this}),t.exports=function(d,p,m){d.prototype=n(u,{next:a(1,m)}),c(d,p+" Iterator")}},function(t,i,s){var n=s(1)("iterator"),a=!1;try{var c=[7][n]();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],y=m[n]();y.next=function(){return{done:p=!0}},m[n]=function(){return y},u(m)}catch{}return p}},function(t,i){t.exports=function(s,n){return{value:n,done:!!s}}},function(t,i,s){var n=s(2),a=s(30).set,c=n.MutationObserver||n.WebKitMutationObserver,u=n.process,d=n.Promise,p=s(11)(u)=="process";t.exports=function(){var m,y,b,T=function(){var X,P;for(p&&(X=u.domain)&&X.exit();m;){P=m.fn,m=m.next;try{P()}catch(B){throw m?b():y=void 0,B}}y=void 0,X&&X.enter()};if(p)b=function(){u.nextTick(T)};else if(c){var C=!0,V=document.createTextNode("");new c(T).observe(V,{characterData:!0}),b=function(){V.data=C=!C}}else if(d&&d.resolve){var _e=d.resolve();b=function(){_e.then(T)}}else b=function(){a.call(n,T)};return function(X){var P={fn:X,next:void 0};y&&(y.next=P),m||(m=P,b()),y=P}}},function(t,i,s){var n=s(3),a=s(50),c=s(22),u=s(19)("IE_PROTO"),d=function(){},p="prototype",m=function(){var y,b=s(16)("iframe"),T=c.length,C=">";for(b.style.display="none",s(25).appendChild(b),b.src="javascript:",y=b.contentWindow.document,y.open(),y.write("<script>document.F=Object</script"+C),y.close(),m=y.F;T--;)delete m[p][c[T]];return m()};t.exports=Object.create||function(y,b){var T;return y!==null?(d[p]=n(y),T=new d,d[p]=null,T[u]=y):T=m(),b===void 0?T:a(T,b)}},function(t,i,s){var n=s(12),a=s(3),c=s(54);t.exports=s(4)?Object.defineProperties:function(u,d){a(u);for(var p,m=c(d),y=m.length,b=0;y>b;)n.f(u,p=m[b++],d[p]);return u}},function(t,i,s){var n=s(55),a=s(17),c=s(13),u=s(32),d=s(8),p=s(26),m=Object.getOwnPropertyDescriptor;i.f=s(4)?m:function(y,b){if(y=c(y),b=u(b,!0),p)try{return m(y,b)}catch{}if(d(y,b))return a(!n.f.call(y,b),y[b])}},function(t,i,s){var n=s(8),a=s(63),c=s(19)("IE_PROTO"),u=Object.prototype;t.exports=Object.getPrototypeOf||function(d){return d=a(d),n(d,c)?d[c]:typeof d.constructor=="function"&&d instanceof d.constructor?d.constructor.prototype:d instanceof Object?u:null}},function(t,i,s){var n=s(8),a=s(13),c=s(39)(!1),u=s(19)("IE_PROTO");t.exports=function(d,p){var m,y=a(d),b=0,T=[];for(m in y)m!=u&&n(y,m)&&T.push(m);for(;p.length>b;)n(y,m=p[b++])&&(~c(T,m)||T.push(m));return T}},function(t,i,s){var n=s(53),a=s(22);t.exports=Object.keys||function(c){return n(c,a)}},function(t,i){i.f={}.propertyIsEnumerable},function(t,i,s){var n=s(5);t.exports=function(a,c,u){for(var d in c)u&&a[d]?a[d]=c[d]:n(a,d,c[d]);return a}},function(t,i,s){t.exports=s(5)},function(t,i,s){var n=s(9),a=s(3),c=function(u,d){if(a(u),!n(d)&&d!==null)throw TypeError(d+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?(function(u,d,p){try{p=s(7)(Function.call,s(51).f(Object.prototype,"__proto__").set,2),p(u,[]),d=!(u instanceof Array)}catch{d=!0}return function(m,y){return c(m,y),d?m.__proto__=y:p(m,y),m}})({},!1):void 0),check:c}},function(t,i,s){"use strict";var n=s(2),a=s(6),c=s(12),u=s(4),d=s(1)("species");t.exports=function(p){var m=typeof a[p]=="function"?a[p]:n[p];u&&m&&!m[d]&&c.f(m,d,{configurable:!0,get:function(){return this}})}},function(t,i,s){var n=s(3),a=s(14),c=s(1)("species");t.exports=function(u,d){var p,m=n(u).constructor;return m===void 0||(p=n(m)[c])==null?d:a(p)}},function(t,i,s){var n=s(20),a=s(15);t.exports=function(c){return function(u,d){var p,m,y=String(a(u)),b=n(d),T=y.length;return b<0||b>=T?c?"":void 0:(p=y.charCodeAt(b),p<55296||p>56319||b+1===T||(m=y.charCodeAt(b+1))<56320||m>57343?c?y.charAt(b):p:c?y.slice(b,b+2):(p-55296<<10)+(m-56320)+65536)}}},function(t,i,s){var n=s(20),a=Math.max,c=Math.min;t.exports=function(u,d){return u=n(u),u<0?a(u+d,0):c(u,d)}},function(t,i,s){var n=s(15);t.exports=function(a){return Object(n(a))}},function(t,i,s){var n=s(21),a=s(1)("iterator"),c=s(10);t.exports=s(6).getIteratorMethod=function(u){if(u!=null)return u[a]||u["@@iterator"]||c[n(u)]}},function(t,i,s){"use strict";var n=s(37),a=s(47),c=s(10),u=s(13);t.exports=s(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,n("keys"),n("values"),n("entries")},function(t,i){},function(t,i,s){"use strict";var n,a,c,u=s(28),d=s(2),p=s(7),m=s(21),y=s(23),b=s(9),T=(s(3),s(14)),C=s(38),V=s(40),_e=(s(58).set,s(60)),X=s(30).set,P=s(48)(),B="Promise",te=d.TypeError,ae=d.process,A=d[B],ae=d.process,pe=m(ae)=="process",Q=function(){},Ne=!!(function(){try{var L=A.resolve(1),j=(L.constructor={})[s(1)("species")]=function(E){E(Q,Q)};return(pe||typeof PromiseRejectionEvent=="function")&&L.then(Q)instanceof j}catch{}})(),ve=function(L,j){return L===j||L===A&&j===c},ze=function(L){var j;return!(!b(L)||typeof(j=L.then)!="function")&&j},ee=function(L){return ve(A,L)?new Je(L):new a(L)},Je=a=function(L){var j,E;this.promise=new L(function(U,ue){if(j!==void 0||E!==void 0)throw te("Bad Promise constructor");j=U,E=ue}),this.resolve=T(j),this.reject=T(E)},We=function(L){try{L()}catch(j){return{error:j}}},nt=function(L,j){if(!L._n){L._n=!0;var E=L._c;P(function(){for(var U=L._v,ue=L._s==1,Ve=0,ct=function(Et){var wt,or,Tr=ue?Et.ok:Et.fail,Kr=Et.resolve,Cr=Et.reject,gi=Et.domain;try{Tr?(ue||(L._h==2&&ot(L),L._h=1),Tr===!0?wt=U:(gi&&gi.enter(),wt=Tr(U),gi&&gi.exit()),wt===Et.promise?Cr(te("Promise-chain cycle")):(or=ze(wt))?or.call(wt,Kr,Cr):Kr(wt)):Cr(U)}catch(Is){Cr(Is)}};E.length>Ve;)ct(E[Ve++]);L._c=[],L._n=!1,j&&!L._h&&Me(L)})}},Me=function(L){X.call(d,function(){var j,E,U,ue=L._v;if(Te(L)&&(j=We(function(){pe?ae.emit("unhandledRejection",ue,L):(E=d.onunhandledrejection)?E({promise:L,reason:ue}):(U=d.console)&&U.error&&U.error("Unhandled promise rejection",ue)}),L._h=pe||Te(L)?2:1),L._a=void 0,j)throw j.error})},Te=function(L){if(L._h==1)return!1;for(var j,E=L._a||L._c,U=0;E.length>U;)if(j=E[U++],j.fail||!Te(j.promise))return!1;return!0},ot=function(L){X.call(d,function(){var j;pe?ae.emit("rejectionHandled",L):(j=d.onrejectionhandled)&&j({promise:L,reason:L._v})})},He=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()),nt(j,!0))},vt=function(L){var j,E=this;if(!E._d){E._d=!0,E=E._w||E;try{if(E===L)throw te("Promise can't be resolved itself");(j=ze(L))?P(function(){var U={_w:E,_d:!1};try{j.call(L,p(vt,U,1),p(He,U,1))}catch(ue){He.call(U,ue)}}):(E._v=L,E._s=1,nt(E,!1))}catch(U){He.call({_w:E,_d:!1},U)}}};Ne||(A=function(L){C(this,A,B,"_h"),T(L),n.call(this);try{L(p(vt,this,1),p(He,this,1))}catch(j){He.call(this,j)}},n=function(L){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},n.prototype=s(56)(A.prototype,{then:function(L,j){var E=ee(_e(this,A));return E.ok=typeof L!="function"||L,E.fail=typeof j=="function"&&j,E.domain=pe?ae.domain:void 0,this._c.push(E),this._a&&this._a.push(E),this._s&&nt(this,!1),E.promise},catch:function(L){return this.then(void 0,L)}}),Je=function(){var L=new n;this.promise=L,this.resolve=p(vt,L,1),this.reject=p(He,L,1)}),y(y.G+y.W+y.F*!Ne,{Promise:A}),s(18)(A,B),s(59)(B),c=s(6)[B],y(y.S+y.F*!Ne,B,{reject:function(L){var j=ee(this),E=j.reject;return E(L),j.promise}}),y(y.S+y.F*(u||!Ne),B,{resolve:function(L){if(L instanceof A&&ve(L.constructor,this))return L;var j=ee(this),E=j.resolve;return E(L),j.promise}}),y(y.S+y.F*!(Ne&&s(46)(function(L){A.all(L).catch(Q)})),B,{all:function(L){var j=this,E=ee(j),U=E.resolve,ue=E.reject,Ve=We(function(){var ct=[],Et=0,wt=1;V(L,!1,function(or){var Tr=Et++,Kr=!1;ct.push(void 0),wt++,j.resolve(or).then(function(Cr){Kr||(Kr=!0,ct[Tr]=Cr,--wt||U(ct))},ue)}),--wt||U(ct)});return Ve&&ue(Ve.error),E.promise},race:function(L){var j=this,E=ee(j),U=E.reject,ue=We(function(){V(L,!1,function(Ve){j.resolve(Ve).then(E.resolve,U)})});return ue&&U(ue.error),E.promise}})},function(t,i,s){"use strict";var n=s(61)(!0);s(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=n(c,u),this._i+=a.length,{value:a,done:!1})})},function(t,i,s){s(65);for(var n=s(2),a=s(5),c=s(10),u=s(1)("toStringTag"),d=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],p=0;p<5;p++){var m=d[p],y=n[m],b=y&&y.prototype;b&&!b[u]&&a(b,u,m),c[m]=c.Array}},function(t,i){t.exports=require("child_process")},function(t,i){t.exports=require("crypto")}])})});function Vy(){try{return Sc.default.statSync("/.dockerenv"),!0}catch{return!1}}function Ky(){try{return Sc.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Tc(){return xc===void 0&&(xc=Vy()||Ky()),xc}var Sc,xc,Ah=Ft(()=>{Sc=ce(require("node:fs"),1)});function Vi(){return Cc===void 0&&(Cc=zy()||Tc()),Cc}var Ph,Cc,zy,Oc=Ft(()=>{Ph=ce(require("node:fs"),1);Ah();zy=()=>{try{return Ph.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var kc,Lh,Nh,Ih,qr,Rc=Ft(()=>{kc=ce(require("node:process"),1),Lh=ce(require("node:os"),1),Nh=ce(require("node:fs"),1);Oc();Ih=()=>{if(kc.default.platform!=="linux")return!1;if(Lh.default.release().toLowerCase().includes("microsoft"))return!Vi();try{return Nh.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!Vi():!1}catch{return!1}},qr=kc.default.env.__IS_WSL_TEST__?Ih:Ih()});var Ac,Cs,$y,Gy,Pc,Dh=Ft(()=>{Ac=ce(require("node:process"),1),Cs=ce(require("node:fs/promises"),1);Rc();Rc();$y=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",i=!1;try{await Cs.default.access(t,Cs.constants.F_OK),i=!0}catch{}if(!i)return r;let s=await Cs.default.readFile(t,{encoding:"utf8"}),n=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return n?(e=n.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),Gy=async()=>`${await $y()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Pc=async()=>qr?Gy():`${Ac.default.env.SYSTEMROOT||Ac.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Wr(r,e,t){let i=s=>Object.defineProperty(r,e,{value:s,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let s=t();return i(s),s},set(s){i(s)}}),r}var Mh=Ft(()=>{});async function Ic(){if(Bh.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await Yy("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 Fh,Bh,jh,Yy,Uh=Ft(()=>{Fh=require("node:util"),Bh=ce(require("node:process"),1),jh=require("node:child_process"),Yy=(0,Fh.promisify)(jh.execFile)});async function Hh(r,{humanReadableOutput:e=!0,signal:t}={}){if(qh.default.platform!=="darwin")throw new Error("macOS only");let i=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:n}=await Xy("osascript",["-e",r,i],s);return n.trim()}var qh,Wh,Lc,Xy,Vh=Ft(()=>{qh=ce(require("node:process"),1),Wh=require("node:util"),Lc=require("node:child_process"),Xy=(0,Wh.promisify)(Lc.execFile)});async function Nc(r){return Hh(`tell application "Finder" to set app_path to application file id "${r}" as string
|
|
31
|
-
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var
|
|
32
|
-
`,{encoding:"utf8"})}catch{}}var
|
|
33
|
-
`)}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 kh=ce(require("os")),Rh=ce(bc()),Ss=class{cachedId=null;name;constructor(e){this.name=e||kh.hostname()||"CLI"}async getMachineId(){if(this.cachedId)return this.cachedId;try{this.cachedId=(0,Rh.machineIdSync)()}catch{this.cachedId=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}return this.cachedId}getMachineName(){return this.name}};var Ts=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 ks=class{async openUrl(e){let{default:t}=await Promise.resolve().then(()=>(nd(),sd));await t(e)}};var od=ce(require("fs")),Hc=ce(require("path"));function io(r){let e=r?[r]:[Hc.join(__dirname,"..","package.json"),Hc.join(__dirname,"..","..","package.json")];for(let t of e)try{let i=JSON.parse(od.readFileSync(t,"utf8"));if(typeof i.version=="string"&&i.version.length>0)return i.version}catch{}return"unknown"}function ad(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 Vc=new Set(["--cid","--token","--server","--log-level"]),cd=new Set(["--help","-h","--version","-V","--verbose","-v","--watch","-w","--log-to-file","--statusline","--multi-viewer","--force"]);function fd(r,e,t){for(let i=0;i<r.length;i++){let s=r[i];if(!s.startsWith("-"))continue;let n=s.includes("=")?s.slice(0,s.indexOf("=")):s;if(e.has(n)||t.has(n)){e.has(n)&&!s.includes("=")&&i++;continue}return s}}var Fd=ce(require("path")),yt=ce(ws()),Bd=ce(dr());var ud=ce(require("os")),ld=require("crypto"),hd=ce(require("node-pty")),dd=ce(ws()),so=class r{ptyProcess=null;outputBuffer=new dd.CircularBuffer(100);streamId=null;logger;onOutput=null;onExit=null;preWriteHook=null;onResize=null;onLocalClaim=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||(ud.platform()==="win32"?"powershell.exe":"/bin/bash"),s=process.stdout.columns||80,n=process.stdout.rows||24,a=Math.max(1,n-t);this.reservedBottomRows=t,this.ptyProcess=hd.spawn(i,[],{name:"xterm-256color",cols:s,rows:a,cwd:e,env:{...process.env,TERMIQ_SESSION_ACTIVE:"1"}}),this.onResize?.(s,a),this.streamId=(0,ld.randomUUID)();let c=`cli_${this.ptyProcess.pid}`;return this.ptyProcess.onData(u=>{this.preWriteHook?.(u),process.stdout.write(u),this.outputBuffer.append(u),this.onOutput?.(u)}),this.ptyProcess.onExit(({exitCode:u})=>{this.logger.info("Shell exited",String(u)),this.onExit?.(u)}),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u=>{this.multiViewerMode&&this.maybeClaimLocalControl(),this.ptyProcess?.write(u.toString())}),this.sigwinchListener=()=>{let u=process.stdout.columns||80,d=Math.max(1,(process.stdout.rows||24)-this.reservedBottomRows);if(this.multiViewerMode){this.logger.info("Local resize claims control",{cols:u,rows:d}),this.resize(u,d),this.onLocalClaim?.(u,d);return}if(this.desiredCols!==null&&this.desiredRows!==null){this.logger.info("Local resize ignored (PWA desired-size set)",{host:{cols:u,rows:d},desired:{cols:this.desiredCols,rows:this.desiredRows}});return}if(!this.sigwinchEnabled){this.logger.info("Local resize ignored (PWA viewers attached)",{cols:u,rows:d});return}this.logger.info("Local resize applied",{cols:u,rows:d}),this.ptyProcess?.resize(u,d),this.onResize?.(u,d)},process.platform==="win32"?process.stdout.on("resize",this.sigwinchListener):process.on("SIGWINCH",this.sigwinchListener),this.logger.info("Shell spawned",i,c),c}write(e,t=!1){if(this.ptyProcess){if(!t&&!this.draining){this.ptyProcess.write(e);return}for(let i of e)this.writeQueue.push(i);this.drainWriteQueue()}}drainWriteQueue(){if(this.draining)return;this.draining=!0;let e=()=>{let t=this.writeQueue.shift();if(t===void 0||!this.ptyProcess){this.draining=!1;return}this.ptyProcess.write(t),this.drainTimer=setTimeout(e,r.PASTE_CHAR_DELAY_MS)};e()}getStreamId(){return this.streamId}getPtyCols(){return this.ptyProcess?.cols??0}getPtyRows(){return this.ptyProcess?.rows??0}resize(e,t){this.desiredCols=e,this.desiredRows=t,this.ptyProcess?.resize(e,t),this.onResize?.(e,t),this.cancelRebroadcast();for(let i of r.REBROADCAST_DELAYS_MS)this.rebroadcastTimers.push(setTimeout(()=>{this.ptyProcess&&(this.desiredCols!==e||this.desiredRows!==t||this.ptyProcess.resize(e,t))},i))}cancelRebroadcast(){for(let e of this.rebroadcastTimers)clearTimeout(e);this.rebroadcastTimers=[]}redrawNoResize(){if(this.ptyProcess){if(this.desiredCols===null||this.desiredRows===null){this.logger.info("Redraw skipped (no desired-size set yet)");return}this.ptyProcess.resize(this.desiredCols,this.desiredRows)}}maybeClaimLocalControl(){if(!this.ptyProcess)return;let e=process.stdout.columns||80,t=Math.max(1,(process.stdout.rows||24)-this.reservedBottomRows);this.ptyProcess.cols===e&&this.ptyProcess.rows===t||(this.logger.info("Local input claims control",{cols:e,rows:t}),this.resize(e,t),this.onLocalClaim?.(e,t))}setOnLocalClaim(e){this.onLocalClaim=e}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 Vr=ce(require("path")),$i=ce(require("fs"));var Rd=require("node:events"),Ad=require("node:fs"),ho=require("node:fs/promises"),Ee=ce(require("node:path"),1);var wr=require("node:fs/promises"),br=require("node:path"),_d=require("node:stream"),Ct={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},Kc={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:Ct.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(Kc);var yd="READDIRP_RECURSIVE_ERROR",ov=new Set(["ENOENT","EPERM","EACCES","ELOOP",yd]),pd=[Ct.DIR_TYPE,Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE,Ct.FILE_TYPE],av=new Set([Ct.DIR_TYPE,Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE]),cv=new Set([Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE,Ct.FILE_TYPE]),fv=r=>ov.has(r.code),uv=process.platform==="win32",gd=r=>!0,md=r=>{if(r===void 0)return gd;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 gd},zc=class extends _d.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={...Kc,...e},{root:i,type:s}=t;this._fileFilter=md(t.fileFilter),this._directoryFilter=md(t.directoryFilter);let n=t.lstat?wr.lstat:wr.stat;uv?this._stat=a=>n(a,{bigint:!0}):this._stat=n,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:Kc.depth,this._wantsDir=s?av.has(s):!1,this._wantsFile=s?cv.has(s):!1,this._wantsEverything=s===Ct.EVERYTHING_TYPE,this._root=(0,br.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:s,depth:n}=t,a=i.splice(0,e).map(u=>this._formatEntry(u,s)),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)?(n<=this._maxDepth&&this.parents.push(this._exploreDir(u.fullPath,n+1)),this._wantsDir&&(this.push(u),e--)):(d==="file"||this._includeAsFile(u))&&this._fileFilter(u)&&this._wantsFile&&(this.push(u),e--)}}else{let s=this.parents.pop();if(!s){this.push(null);break}if(this.parent=await s,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let i;try{i=await(0,wr.readdir)(e,this._rdOptions)}catch(s){this._onError(s)}return{files:i,depth:t,path:e}}async _formatEntry(e,t){let i,s=this._isDirent?e.name:e;try{let n=(0,br.resolve)((0,br.join)(t,s));i={path:(0,br.relative)(this._root,n),fullPath:n,basename:s},i[this._statsProp]=this._isDirent?e:await this._stat(n)}catch(n){this._onError(n);return}return i}_onError(e){fv(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 s=await(0,wr.realpath)(i),n=await(0,wr.lstat)(s);if(n.isFile())return"file";if(n.isDirectory()){let a=s.length;if(i.startsWith(s)&&i.substr(a,1)===br.sep){let c=new Error(`Circular symlink detected: "${i}" points to "${s}"`);return c.code=yd,this._onError(c)}return"directory"}}catch(s){return this._onError(s),""}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function vd(r,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=Ct.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&&!pd.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${pd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new zc(e)}var hi=require("node:fs"),Kt=require("node:fs/promises"),wd=require("node:os"),qe=ce(require("node:path"),1),lv="data",Yc="end",bd="close",fo=()=>{};var uo=process.platform,Xc=uo==="win32",hv=uo==="darwin",dv=uo==="linux",pv=uo==="freebsd",xd=(0,wd.type)()==="OS400",Ke={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Vt=Ke,gv="watch",mv={lstat:Kt.lstat,stat:Kt.stat},li="listeners",no="errHandlers",zi="rawEmitters",_v=[li,no,zi],yv=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"]),vv=r=>yv.has(qe.extname(r).slice(1).toLowerCase()),Gc=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},Rs=(r,e,t)=>{let i=r[e];i instanceof Set||(r[e]=i=new Set([i])),i.add(t)},Ev=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},As=(r,e,t)=>{let i=r[e];i instanceof Set?i.delete(t):i===t&&delete r[e]},Sd=r=>r instanceof Set?r.size===0:!r,oo=new Map;function Ed(r,e,t,i,s){let n=(a,c)=>{t(r),s(a,c,{watchedPath:r}),c&&r!==c&&ao(qe.resolve(r,c),li,qe.join(r,c))};try{return(0,hi.watch)(r,{persistent:e.persistent},n)}catch(a){i(a);return}}var ao=(r,e,t,i,s)=>{let n=oo.get(r);n&&Gc(n[e],a=>{a(t,i,s)})},wv=(r,e,t,i)=>{let{listener:s,errHandler:n,rawEmitter:a}=i,c=oo.get(e),u;if(!t.persistent)return u=Ed(r,t,s,n,a),u?u.close.bind(u):void 0;if(c)Rs(c,li,s),Rs(c,no,n),Rs(c,zi,a);else{if(u=Ed(r,t,ao.bind(null,e,li),n,ao.bind(null,e,zi)),!u)return;u.on(Vt.ERROR,async d=>{let p=ao.bind(null,e,no);if(c&&(c.watcherUnusable=!0),Xc&&d.code==="EPERM")try{await(await(0,Kt.open)(r,"r")).close(),p(d)}catch{}else p(d)}),c={listeners:s,errHandlers:n,rawEmitters:a,watcher:u},oo.set(e,c)}return()=>{As(c,li,s),As(c,no,n),As(c,zi,a),Sd(c.listeners)&&(c.watcher.close(),oo.delete(e),_v.forEach(Ev(c)),c.watcher=void 0,Object.freeze(c))}},$c=new Map,bv=(r,e,t,i)=>{let{listener:s,rawEmitter:n}=i,a=$c.get(e),c=a&&a.options;return c&&(c.persistent<t.persistent||c.interval>t.interval)&&((0,hi.unwatchFile)(e),a=void 0),a?(Rs(a,li,s),Rs(a,zi,n)):(a={listeners:s,rawEmitters:n,options:t,watcher:(0,hi.watchFile)(e,t,(u,d)=>{Gc(a.rawEmitters,m=>{m(Vt.CHANGE,e,{curr:u,prev:d})});let p=u.mtimeMs;(u.size!==d.size||p>d.mtimeMs||p===0)&&Gc(a.listeners,m=>m(r,u))})},$c.set(e,a)),()=>{As(a,li,s),As(a,zi,n),Sd(a.listeners)&&($c.delete(e),(0,hi.unwatchFile)(e),a.options=a.watcher=void 0,Object.freeze(a))}},co=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let i=this.fsw.options,s=qe.dirname(e),n=qe.basename(e);this.fsw._getWatchedDir(s).add(n);let c=qe.resolve(e),u={persistent:i.persistent};t||(t=fo);let d;if(i.usePolling){let p=i.interval!==i.binaryInterval;u.interval=p&&vv(n)?i.binaryInterval:i.interval,d=bv(e,c,u,{listener:t,rawEmitter:this.fsw._emitRaw})}else d=wv(e,c,u,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return d}_handleFile(e,t,i){if(this.fsw.closed)return;let s=qe.dirname(e),n=qe.basename(e),a=this.fsw._getWatchedDir(s),c=t;if(a.has(n))return;let u=async(p,m)=>{if(this.fsw._throttle(gv,e,5)){if(!m||m.mtimeMs===0)try{let y=await(0,Kt.stat)(e);if(this.fsw.closed)return;let b=y.atimeMs,T=y.mtimeMs;if((!b||b<=T||T!==c.mtimeMs)&&this.fsw._emit(Vt.CHANGE,e,y),(hv||dv||pv)&&c.ino!==y.ino){this.fsw._closeFile(p),c=y;let C=this._watchWithNodeFs(e,u);C&&this.fsw._addPathCloser(p,C)}else c=y}catch{this.fsw._remove(s,n)}else if(a.has(n)){let y=m.atimeMs,b=m.mtimeMs;(!y||y<=b||b!==c.mtimeMs)&&this.fsw._emit(Vt.CHANGE,e,m),c=m}}},d=this._watchWithNodeFs(e,u);if(!(i&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Vt.ADD,e,0))return;this.fsw._emit(Vt.ADD,e,t)}return d}async _handleSymlink(e,t,i,s){if(this.fsw.closed)return;let n=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let c;try{c=await(0,Kt.realpath)(i)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(s)?this.fsw._symlinkPaths.get(n)!==c&&(this.fsw._symlinkPaths.set(n,c),this.fsw._emit(Vt.CHANGE,i,e.stats)):(a.add(s),this.fsw._symlinkPaths.set(n,c),this.fsw._emit(Vt.ADD,i,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(n))return!0;this.fsw._symlinkPaths.set(n,!0)}_handleRead(e,t,i,s,n,a,c){e=qe.join(e,"");let u=s?`${e}:${s}`:e;if(c=this.fsw._throttle("readdir",u,1e3),!c)return;let d=this.fsw._getWatchedDir(i.path),p=new Set,m=this.fsw._readdirp(e,{fileFilter:y=>i.filterPath(y),directoryFilter:y=>i.filterDir(y)});if(m)return m.on(lv,async y=>{if(this.fsw.closed){m=void 0;return}let b=y.path,T=qe.join(e,b);if(p.add(b),!(y.stats.isSymbolicLink()&&await this._handleSymlink(y,e,T,b))){if(this.fsw.closed){m=void 0;return}(b===s||!s&&!d.has(b))&&(this.fsw._incrReadyCount(),T=qe.join(n,qe.relative(n,T)),this._addToNodeFs(T,t,i,a+1))}}).on(Vt.ERROR,this._boundHandleError),new Promise((y,b)=>{if(!m)return b();m.once(Yc,()=>{if(this.fsw.closed){m=void 0;return}let T=c?c.clear():!1;y(void 0),d.getChildren().filter(C=>C!==e&&!p.has(C)).forEach(C=>{this.fsw._remove(e,C)}),m=void 0,T&&this._handleRead(e,!1,i,s,n,a,c)})})}async _handleDir(e,t,i,s,n,a,c){let u=this.fsw._getWatchedDir(qe.dirname(e)),d=u.has(qe.basename(e));!(i&&this.fsw.options.ignoreInitial)&&!n&&!d&&this.fsw._emit(Vt.ADD_DIR,e,t),u.add(qe.basename(e)),this.fsw._getWatchedDir(e);let p,m,y=this.fsw.options.depth;if((y==null||s<=y)&&!this.fsw._symlinkPaths.has(c)){if(!n&&(await this._handleRead(e,i,a,n,e,s,p),this.fsw.closed))return;m=this._watchWithNodeFs(e,(b,T)=>{T&&T.mtimeMs===0||this._handleRead(b,!1,a,n,e,s,p)})}return m}async _addToNodeFs(e,t,i,s,n){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 mv[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),y=d?await(0,Kt.realpath)(e):e;if(this.fsw.closed||(p=await this._handleDir(c.watchPath,u,t,s,n,c,y),this.fsw.closed))return;m!==y&&y!==void 0&&this.fsw._symlinkPaths.set(m,y)}else if(u.isSymbolicLink()){let m=d?await(0,Kt.realpath)(e):e;if(this.fsw.closed)return;let y=qe.dirname(c.watchPath);if(this.fsw._getWatchedDir(y).add(c.watchPath),this.fsw._emit(Vt.ADD,c.watchPath,u),p=await this._handleDir(y,u,t,s,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 Jc="/",xv="//",Pd=".",Sv="..",Tv="string",Cv=/\\/g,Id=/\/\//g,Ov=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,kv=/^\.[/\\]/;function lo(r){return Array.isArray(r)?r:[r]}var Zc=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function Rv(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=Ee.relative(r.path,e);return t?!t.startsWith("..")&&!Ee.isAbsolute(t):!1}return!1}:()=>!1}function Av(r){if(typeof r!="string")throw new Error("string expected");r=Ee.normalize(r),r=r.replace(/\\/g,"/");let e=!1;return r.startsWith("//")&&(e=!0),r=r.replace(Id,"/"),e&&(r="/"+r),r}function Td(r,e,t){let i=Av(e);for(let s=0;s<r.length;s++){let n=r[s];if(n(i,t))return!0}return!1}function Pv(r,e){if(r==null)throw new TypeError("anymatch: specify first argument");let i=lo(r).map(s=>Rv(s));return e==null?(s,n)=>Td(i,s,n):Td(i,e)}var Cd=r=>{let e=lo(r).flat();if(!e.every(t=>typeof t===Tv))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Ld)},Od=r=>{let e=r.replace(Cv,Jc),t=!1;return e.startsWith(xv)&&(t=!0),e=e.replace(Id,Jc),t&&(e=Jc+e),e},Ld=r=>Od(Ee.normalize(Od(r))),kd=(r="")=>e=>typeof e=="string"?Ld(Ee.isAbsolute(e)?e:Ee.join(r,e)):e,Iv=(r,e)=>Ee.isAbsolute(r)?r:Ee.join(e,r),Lv=Object.freeze(new Set),Qc=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!==Pd&&e!==Sv&&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,ho.readdir)(i)}catch{this._removeWatcher&&this._removeWatcher(Ee.dirname(i),Ee.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=fo,this.items=Lv,Object.freeze(this)}},Nv="stat",Dv="lstat",ef=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,i){this.fsw=i;let s=e;this.path=e=e.replace(kv,""),this.watchPath=s,this.fullWatchPath=Ee.resolve(s),this.dirParts=[],this.dirParts.forEach(n=>{n.length>1&&n.pop()}),this.followSymlinks=t,this.statMethod=t?Nv:Dv}entryPath(e){return Ee.join(this.watchPath,Ee.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)}},tf=class extends Rd.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},s={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?i:typeof t=="object"?{...i,...t}:!1};xd&&(s.usePolling=!0),s.atomic===void 0&&(s.atomic=!s.usePolling);let n=process.env.CHOKIDAR_USEPOLLING;if(n!==void 0){let u=n.toLowerCase();u==="false"||u==="0"?s.usePolling=!1:u==="true"||u==="1"?s.usePolling=!0:s.usePolling=!!u}let a=process.env.CHOKIDAR_INTERVAL;a&&(s.interval=Number.parseInt(a,10));let c=0;this._emitReady=()=>{c++,c>=this._readyCount&&(this._emitReady=fo,this._readyEmitted=!0,process.nextTick(()=>this.emit(Ke.READY)))},this._emitRaw=(...u)=>this.emit(Ke.RAW,...u),this._boundRemove=this._remove.bind(this),this.options=s,this._nodeFsHandler=new co(this),Object.freeze(s)}_addIgnoredPath(e){if(Zc(e)){for(let t of this._ignoredPaths)if(Zc(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)Zc(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,i){let{cwd:s}=this.options;this.closed=!1,this._closePromise=void 0;let n=Cd(e);return s&&(n=n.map(a=>Iv(a,s))),n.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=n.length,Promise.all(n.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(Ee.dirname(c),Ee.basename(t||c))})}),this}unwatch(e){if(this.closed)return this;let t=Cd(e),{cwd:i}=this.options;return t.forEach(s=>{!Ee.isAbsolute(s)&&!this._closers.has(s)&&(i&&(s=Ee.join(i,s)),s=Ee.resolve(s)),this._closePath(s),this._addIgnoredPath(s),this._watched.has(s)&&this._addIgnoredPath({path:s,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 s=i();s instanceof Promise&&e.push(s)})),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 n=(this.options.cwd?Ee.relative(this.options.cwd,i):i)||Pd;e[n]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==Ke.ERROR&&this.emit(Ke.ALL,e,...t)}async _emit(e,t,i){if(this.closed)return;let s=this.options;Xc&&(t=Ee.normalize(t)),s.cwd&&(t=Ee.relative(s.cwd,t));let n=[t];i!=null&&n.push(i);let a=s.awaitWriteFinish,c;if(a&&(c=this._pendingWrites.get(t)))return c.lastChange=new Date,this;if(s.atomic){if(e===Ke.UNLINK)return this._pendingUnlinks.set(t,[e,...n]),setTimeout(()=>{this._pendingUnlinks.forEach((u,d)=>{this.emit(...u),this.emit(Ke.ALL,...u),this._pendingUnlinks.delete(d)})},typeof s.atomic=="number"?s.atomic:100),this;e===Ke.ADD&&this._pendingUnlinks.has(t)&&(e=Ke.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===Ke.ADD||e===Ke.CHANGE)&&this._readyEmitted){let u=(d,p)=>{d?(e=Ke.ERROR,n[0]=d,this.emitWithAll(e,n)):p&&(n.length>1?n[1]=p:n.push(p),this.emitWithAll(e,n))};return this._awaitWriteFinish(t,a.stabilityThreshold,e,u),this}if(e===Ke.CHANGE&&!this._throttle(Ke.CHANGE,t,50))return this;if(s.alwaysStat&&i===void 0&&(e===Ke.ADD||e===Ke.ADD_DIR||e===Ke.CHANGE)){let u=s.cwd?Ee.join(s.cwd,t):t,d;try{d=await(0,ho.stat)(u)}catch{}if(!d||this.closed)return;n.push(d)}return this.emitWithAll(e,n),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(Ke.ERROR,e),e||this.closed}_throttle(e,t,i){this._throttled.has(e)||this._throttled.set(e,new Map);let s=this._throttled.get(e);if(!s)throw new Error("invalid throttle");let n=s.get(t);if(n)return n.count++,!1;let a,c=()=>{let d=s.get(t),p=d?d.count:0;return s.delete(t),clearTimeout(a),d&&clearTimeout(d.timeoutObject),p};a=setTimeout(c,i);let u={timeoutObject:a,clear:c,count:0};return s.set(t,u),u}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,i,s){let n=this.options.awaitWriteFinish;if(typeof n!="object")return;let a=n.pollInterval,c,u=e;this.options.cwd&&!Ee.isAbsolute(e)&&(u=Ee.join(this.options.cwd,e));let d=new Date,p=this._pendingWrites;function m(y){(0,Ad.stat)(u,(b,T)=>{if(b||!p.has(e)){b&&b.code!=="ENOENT"&&s(b);return}let C=Number(new Date);y&&T.size!==y.size&&(p.get(e).lastChange=C);let V=p.get(e);C-V.lastChange>=t?(p.delete(e),s(void 0,T)):c=setTimeout(m,a,T)})}p.has(e)||(p.set(e,{lastChange:d,cancelWait:()=>(p.delete(e),clearTimeout(c),i)}),c=setTimeout(m,a))}_isIgnored(e,t){if(this.options.atomic&&Ov.test(e))return!0;if(!this._userIgnored){let{cwd:i}=this.options,n=(this.options.ignored||[]).map(kd(i)),c=[...[...this._ignoredPaths].map(kd(i)),...n];this._userIgnored=Pv(c,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new ef(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=Ee.resolve(e);return this._watched.has(t)||this._watched.set(t,new Qc(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,i){let s=Ee.join(e,t),n=Ee.resolve(s);if(i=i??(this._watched.has(s)||this._watched.has(n)),!this._throttle("remove",s,100))return;!i&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(s).getChildren().forEach(y=>this._remove(s,y));let u=this._getWatchedDir(e),d=u.has(t);u.remove(t),this._symlinkPaths.has(n)&&this._symlinkPaths.delete(n);let p=s;if(this.options.cwd&&(p=Ee.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(p)&&this._pendingWrites.get(p).cancelWait()===Ke.ADD)return;this._watched.delete(s),this._watched.delete(n);let m=i?Ke.UNLINK_DIR:Ke.UNLINK;d&&!this._isIgnored(s)&&this._emit(m,s),this._closePath(s)}_closePath(e){this._closeFile(e);let t=Ee.dirname(e);this._getWatchedDir(t).remove(Ee.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:Ke.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},s=vd(e,i);return this._streams.add(s),s.once(bd,()=>{s=void 0}),s.once(Yc,()=>{s&&(this._streams.delete(s),s=void 0)}),s}};function Nd(r,e={}){let t=new tf(e);return t.add(r),t}var Dd=ce(uc()),nr=ce(dr()),Mv=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/*.log"],Fv=300,po=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,Dd.default)(),this.initializeIgnoreFilter()}initializeIgnoreFilter(){this.ignoreFilter.add(Mv);let e=Vr.join(this.workspaceRoot,".gitignore");try{if($i.existsSync(e)){let t=$i.readFileSync(e,"utf-8");this.ignoreFilter.add(t)}}catch{}}onFileChanged(e){this.onFileChangedCallback=e}start(){this.watcher||(this.watcher=Nd(this.workspaceRoot,{ignored:e=>{let t=Vr.relative(this.workspaceRoot,e);if(!t||t===".")return!1;let i=t.split(Vr.sep).join("/");return this.ignoreFilter.ignores(i)},persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50}}),this.watcher.on("add",e=>this.handleEvent(e,nr.FileChangeType.CREATE)),this.watcher.on("change",e=>this.handleEvent(e,nr.FileChangeType.MODIFY)),this.watcher.on("unlink",e=>this.handleEvent(e,nr.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=Vr.relative(this.workspaceRoot,e);if(!i)return;let s=this.pendingEvents.get(i);s&&clearTimeout(s);let n=this.pendingTypes.get(i);this.pendingTypes.set(i,this.mergeTypes(n,t));let a=setTimeout(()=>{this.emit(i,this.pendingTypes.get(i)||t),this.pendingEvents.delete(i),this.pendingTypes.delete(i)},Fv);this.pendingEvents.set(i,a)}mergeTypes(e,t){return e?t===nr.FileChangeType.DELETE||e===nr.FileChangeType.DELETE?nr.FileChangeType.DELETE:e===nr.FileChangeType.CREATE?nr.FileChangeType.CREATE:t:t}emit(e,t){let i={path:e,changeType:t,timestamp:new Date().toISOString(),source:"watcher"};if(t!==nr.FileChangeType.DELETE)try{let s=Vr.join(this.workspaceRoot,e),n=$i.statSync(s);i.size=n.size}catch{}this.onFileChangedCallback?.(i)}dispose(){this.stop(),this.onFileChangedCallback=null}};var Bv={online:!1,viewerCount:0},go=class r{enabled=!1;state={...Bv};altScreenActive=!1;logger;refreshTimer=null;static REFRESH_INTERVAL_MS=1e3;constructor(e){this.logger=e}reservedRows(){return this.enabled&&process.stdout.isTTY?1:0}enable(){if(!process.stdout.isTTY){this.logger.warn("StatusLine: stdout is not a TTY, cannot enable");return}this.enabled=!0,this.installScrollRegion(),this.startRefreshTimer(),this.logger.info("StatusLine enabled")}startRefreshTimer(){this.stopRefreshTimer(),this.refreshTimer=setInterval(()=>{!this.enabled||this.altScreenActive||this.render()},r.REFRESH_INTERVAL_MS)}stopRefreshTimer(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null)}installScrollRegion(){let e=process.stdout.rows;!e||e<2||(process.stdout.write(`\x1B[1;${e-1}r`),process.stdout.write("\x1B[1;1H"))}resetScrollRegion(){process.stdout.write("\x1B[r")}update(e){this.state={...this.state,...e},this.render()}render(){if(!this.enabled||this.altScreenActive)return;let e=process.stdout.rows;if(!e||e<2)return;let t=this.formatLine(),i=`\x1B[1;${e-1}r\x1B7\x1B[${e};1H\x1B[2K${t}\x1B8`;process.stdout.write(i)}clear(){if(!this.enabled)return;let e=process.stdout.rows;!e||e<2||process.stdout.write(`\x1B7\x1B[${e};1H\x1B[2K\x1B8`)}disable(){this.enabled&&(this.stopRefreshTimer(),this.clear(),this.resetScrollRegion(),this.enabled=!1)}inspectPtyOutput(e){if(this.enabled){if(e.includes("\x1B[?1049h")||e.includes("\x1B[?47h")){this.altScreenActive=!0;return}(e.includes("\x1B[?1049l")||e.includes("\x1B[?47l"))&&(this.altScreenActive=!1,this.render())}}getState(){return this.state}isEnabled(){return this.enabled}isAltScreenActive(){return this.altScreenActive}formatLine(){let e=[];if(e.push(this.state.online?"\u25CF online":"\u25CB offline"),this.state.viewerCount>0){let t=this.state.viewerCount===1?"1 viewer":`${this.state.viewerCount} viewers`;e.push(t)}else e.push("no viewers");return this.state.agentName&&e.push(this.state.agentName),this.state.ptyCols&&this.state.ptyRows&&e.push(`${this.state.ptyCols}\xD7${this.state.ptyRows}`)," "+e.join(" \xB7 ")+" "}};async function mo(r,e,t,i){if(i)return process.stderr.write(`Logging in with API key...
|
|
34
|
-
`),await r.loginWithApiKey(
|
|
30
|
+
`)}return"(no changes)"}catch{throw new Error("Git not available")}}async getPreviousDiff(e,t,s){let a=(this.trackedFiles.get(e)||[]).find(d=>d.path===t&&d.previousContent!==void 0)?.previousContent||"",c;try{c=await us.readFile(s,"utf-8")}catch{c=""}let u=(0,Ht.createSimpleDiff)(a,c,t);return this.diffContentToUnifiedText(u)}diffContentToUnifiedText(e){let t=[];t.push(`--- a/${e.path}`),t.push(`+++ b/${e.path}`);for(let s of e.hunks){t.push(`@@ -${s.oldStart},${s.oldLines} +${s.newStart},${s.newLines} @@`);for(let i of s.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(s=>({path:s.path,changeType:s.changeType,timestamp:s.timestamp,source:"tool-call",toolName:s.toolName,toolId:s.toolId,size:s.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){return pc.isAbsolute(e)?e:this.workspaceRoot?pc.join(this.workspaceRoot,e):e}dispose(){this.trackedFiles.clear(),this.pendingToolCalls.clear(),this.onFileChangedCallback=null,this.onFileViewTransferCallback=null}};ir.FileTrackerService=_c});var Th=D(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.InputStreamReceiver=it.FileTrackerService=it.FileListService=it.FileTransferService=it.WebSocketService=it.StatusDetector=it.AuthService=it.CryptoService=void 0;var Iy=Xf();Object.defineProperty(it,"CryptoService",{enumerable:!0,get:function(){return Iy.CryptoService}});var Ly=Jf();Object.defineProperty(it,"AuthService",{enumerable:!0,get:function(){return Ly.AuthService}});var Ny=Zf();Object.defineProperty(it,"StatusDetector",{enumerable:!0,get:function(){return Ny.StatusDetector}});var My=uh();Object.defineProperty(it,"WebSocketService",{enumerable:!0,get:function(){return My.WebSocketService}});var Dy=hh();Object.defineProperty(it,"FileTransferService",{enumerable:!0,get:function(){return Dy.FileTransferService}});var Fy=bh();Object.defineProperty(it,"FileListService",{enumerable:!0,get:function(){return Fy.FileListService}});var By=Sh();Object.defineProperty(it,"FileTrackerService",{enumerable:!0,get:function(){return By.FileTrackerService}});var jy=ec();Object.defineProperty(it,"InputStreamReceiver",{enumerable:!0,get:function(){return jy.InputStreamReceiver}})});var wi=D(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.InputStreamReceiver=we.FileTrackerService=we.FileListService=we.FileTransferService=we.WebSocketService=we.StatusDetector=we.AuthService=we.CryptoService=we.getCurrentCorrelationId=we.runWithCorrelation=we.generateCorrelationId=we.getWsUrl=we.getApiUrl=we.CircularBuffer=we.formatLogLine=we.shouldLog=we.LOG_LEVELS=void 0;var yc=gf();Object.defineProperty(we,"LOG_LEVELS",{enumerable:!0,get:function(){return yc.LOG_LEVELS}});Object.defineProperty(we,"shouldLog",{enumerable:!0,get:function(){return yc.shouldLog}});Object.defineProperty(we,"formatLogLine",{enumerable:!0,get:function(){return yc.formatLogLine}});var Vs=yf();Object.defineProperty(we,"CircularBuffer",{enumerable:!0,get:function(){return Vs.CircularBuffer}});Object.defineProperty(we,"getApiUrl",{enumerable:!0,get:function(){return Vs.getApiUrl}});Object.defineProperty(we,"getWsUrl",{enumerable:!0,get:function(){return Vs.getWsUrl}});Object.defineProperty(we,"generateCorrelationId",{enumerable:!0,get:function(){return Vs.generateCorrelationId}});Object.defineProperty(we,"runWithCorrelation",{enumerable:!0,get:function(){return Vs.runWithCorrelation}});Object.defineProperty(we,"getCurrentCorrelationId",{enumerable:!0,get:function(){return Vs.getCurrentCorrelationId}});var jr=Th();Object.defineProperty(we,"CryptoService",{enumerable:!0,get:function(){return jr.CryptoService}});Object.defineProperty(we,"AuthService",{enumerable:!0,get:function(){return jr.AuthService}});Object.defineProperty(we,"StatusDetector",{enumerable:!0,get:function(){return jr.StatusDetector}});Object.defineProperty(we,"WebSocketService",{enumerable:!0,get:function(){return jr.WebSocketService}});Object.defineProperty(we,"FileTransferService",{enumerable:!0,get:function(){return jr.FileTransferService}});Object.defineProperty(we,"FileListService",{enumerable:!0,get:function(){return jr.FileListService}});Object.defineProperty(we,"FileTrackerService",{enumerable:!0,get:function(){return jr.FileTrackerService}});Object.defineProperty(we,"InputStreamReceiver",{enumerable:!0,get:function(){return jr.InputStreamReceiver}})});var bc=D((xi,wc)=>{(function(r,e){typeof xi=="object"&&typeof wc=="object"?wc.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof xi=="object"?xi["electron-machine-id"]=e(require("child_process"),require("crypto")):r["electron-machine-id"]=e(r.child_process,r.crypto)})(xi,function(r,e){return(function(t){function s(n){if(i[n])return i[n].exports;var a=i[n]={exports:{},id:n,loaded:!1};return t[n].call(a.exports,a,a.exports,s),a.loaded=!0,a.exports}var i={};return s.m=t,s.c=i,s.p="",s(0)})([function(t,s,i){t.exports=i(34)},function(t,s,i){var n=i(29)("wks"),a=i(33),c=i(2).Symbol,u=typeof c=="function",d=t.exports=function(p){return n[p]||(n[p]=u&&c[p]||(u?c:a)("Symbol."+p))};d.store=n},function(t,s){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,s,i){var n=i(9);t.exports=function(a){if(!n(a))throw TypeError(a+" is not an object!");return a}},function(t,s,i){t.exports=!i(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(t,s,i){var n=i(12),a=i(17);t.exports=i(4)?function(c,u,d){return n.f(c,u,a(1,d))}:function(c,u,d){return c[u]=d,c}},function(t,s){var i=t.exports={version:"2.4.0"};typeof __e=="number"&&(__e=i)},function(t,s,i){var n=i(14);t.exports=function(a,c,u){if(n(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,s){var i={}.hasOwnProperty;t.exports=function(n,a){return i.call(n,a)}},function(t,s){t.exports=function(i){return typeof i=="object"?i!==null:typeof i=="function"}},function(t,s){t.exports={}},function(t,s){var i={}.toString;t.exports=function(n){return i.call(n).slice(8,-1)}},function(t,s,i){var n=i(3),a=i(26),c=i(32),u=Object.defineProperty;s.f=i(4)?Object.defineProperty:function(d,p,m){if(n(d),p=c(p,!0),n(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,s,i){var n=i(42),a=i(15);t.exports=function(c){return n(a(c))}},function(t,s){t.exports=function(i){if(typeof i!="function")throw TypeError(i+" is not a function!");return i}},function(t,s){t.exports=function(i){if(i==null)throw TypeError("Can't call method on "+i);return i}},function(t,s,i){var n=i(9),a=i(2).document,c=n(a)&&n(a.createElement);t.exports=function(u){return c?a.createElement(u):{}}},function(t,s){t.exports=function(i,n){return{enumerable:!(1&i),configurable:!(2&i),writable:!(4&i),value:n}}},function(t,s,i){var n=i(12).f,a=i(8),c=i(1)("toStringTag");t.exports=function(u,d,p){u&&!a(u=p?u:u.prototype,c)&&n(u,c,{configurable:!0,value:d})}},function(t,s,i){var n=i(29)("keys"),a=i(33);t.exports=function(c){return n[c]||(n[c]=a(c))}},function(t,s){var i=Math.ceil,n=Math.floor;t.exports=function(a){return isNaN(a=+a)?0:(a>0?n:i)(a)}},function(t,s,i){var n=i(11),a=i(1)("toStringTag"),c=n((function(){return arguments})())=="Arguments",u=function(d,p){try{return d[p]}catch{}};t.exports=function(d){var p,m,y;return d===void 0?"Undefined":d===null?"Null":typeof(m=u(p=Object(d),a))=="string"?m:c?n(p):(y=n(p))=="Object"&&typeof p.callee=="function"?"Arguments":y}},function(t,s){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,s,i){var n=i(2),a=i(6),c=i(7),u=i(5),d="prototype",p=function(m,y,b){var T,C,V,_e=m&p.F,X=m&p.G,P=m&p.S,B=m&p.P,te=m&p.B,A=m&p.W,ae=X?a:a[y]||(a[y]={}),pe=ae[d],Q=X?n:P?n[y]:(n[y]||{})[d];X&&(b=y);for(T in b)C=!_e&&Q&&Q[T]!==void 0,C&&T in ae||(V=C?Q[T]:b[T],ae[T]=X&&typeof Q[T]!="function"?b[T]:te&&C?c(V,n):A&&Q[T]==V?(function(Ne){var ve=function(Ke,ee,Je){if(this instanceof Ne){switch(arguments.length){case 0:return new Ne;case 1:return new Ne(Ke);case 2:return new Ne(Ke,ee)}return new Ne(Ke,ee,Je)}return Ne.apply(this,arguments)};return ve[d]=Ne[d],ve})(V):B&&typeof V=="function"?c(Function.call,V):V,B&&((ae.virtual||(ae.virtual={}))[T]=V,m&p.R&&pe&&!pe[T]&&u(pe,T,V)))};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,s){t.exports=function(i){try{return!!i()}catch{return!0}}},function(t,s,i){t.exports=i(2).document&&document.documentElement},function(t,s,i){t.exports=!i(4)&&!i(24)(function(){return Object.defineProperty(i(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(t,s,i){"use strict";var n=i(28),a=i(23),c=i(57),u=i(5),d=i(8),p=i(10),m=i(45),y=i(18),b=i(52),T=i(1)("iterator"),C=!([].keys&&"next"in[].keys()),V="@@iterator",_e="keys",X="values",P=function(){return this};t.exports=function(B,te,A,ae,pe,Q,Ne){m(A,te,ae);var ve,Ke,ee,Je=function(j){if(!C&&j in Te)return Te[j];switch(j){case _e:return function(){return new A(this,j)};case X:return function(){return new A(this,j)}}return function(){return new A(this,j)}},We=te+" Iterator",nt=pe==X,De=!1,Te=B.prototype,ot=Te[T]||Te[V]||pe&&Te[pe],He=ot||Je(pe),vt=pe?nt?Je("entries"):He:void 0,L=te=="Array"&&Te.entries||ot;if(L&&(ee=b(L.call(new B)),ee!==Object.prototype&&(y(ee,We,!0),n||d(ee,T)||u(ee,T,P))),nt&&ot&&ot.name!==X&&(De=!0,He=function(){return ot.call(this)}),n&&!Ne||!C&&!De&&Te[T]||u(Te,T,He),p[te]=He,p[We]=P,pe)if(ve={values:nt?He:Je(X),keys:Q?He:Je(_e),entries:vt},Ne)for(Ke in ve)Ke in Te||c(Te,Ke,ve[Ke]);else a(a.P+a.F*(C||De),te,ve);return ve}},function(t,s){t.exports=!0},function(t,s,i){var n=i(2),a="__core-js_shared__",c=n[a]||(n[a]={});t.exports=function(u){return c[u]||(c[u]={})}},function(t,s,i){var n,a,c,u=i(7),d=i(41),p=i(25),m=i(16),y=i(2),b=y.process,T=y.setImmediate,C=y.clearImmediate,V=y.MessageChannel,_e=0,X={},P="onreadystatechange",B=function(){var A=+this;if(X.hasOwnProperty(A)){var ae=X[A];delete X[A],ae()}},te=function(A){B.call(A.data)};T&&C||(T=function(A){for(var ae=[],pe=1;arguments.length>pe;)ae.push(arguments[pe++]);return X[++_e]=function(){d(typeof A=="function"?A:Function(A),ae)},n(_e),_e},C=function(A){delete X[A]},i(11)(b)=="process"?n=function(A){b.nextTick(u(B,A,1))}:V?(a=new V,c=a.port2,a.port1.onmessage=te,n=u(c.postMessage,c,1)):y.addEventListener&&typeof postMessage=="function"&&!y.importScripts?(n=function(A){y.postMessage(A+"","*")},y.addEventListener("message",te,!1)):n=P in m("script")?function(A){p.appendChild(m("script"))[P]=function(){p.removeChild(this),B.call(A)}}:function(A){setTimeout(u(B,A,1),0)}),t.exports={set:T,clear:C}},function(t,s,i){var n=i(20),a=Math.min;t.exports=function(c){return c>0?a(n(c),9007199254740991):0}},function(t,s,i){var n=i(9);t.exports=function(a,c){if(!n(a))return a;var u,d;if(c&&typeof(u=a.toString)=="function"&&!n(d=u.call(a))||typeof(u=a.valueOf)=="function"&&!n(d=u.call(a))||!c&&typeof(u=a.toString)=="function"&&!n(d=u.call(a)))return d;throw TypeError("Can't convert object to primitive value")}},function(t,s){var i=0,n=Math.random();t.exports=function(a){return"Symbol(".concat(a===void 0?"":a,")_",(++i+n).toString(36))}},function(t,s,i){"use strict";function n(P){return P&&P.__esModule?P:{default:P}}function a(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function c(P){return(0,T.createHash)("sha256").update(P).digest("hex")}function u(P){switch(V){case"darwin":return P.split("IOPlatformUUID")[1].split(`
|
|
32
|
+
`)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return P.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return P.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return P.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function d(P){var B=u((0,b.execSync)(X[V]).toString());return P?B:c(B)}function p(P){return new y.default(function(B,te){return(0,b.exec)(X[V],{},function(A,ae,pe){if(A)return te(new Error("Error while obtaining machine id: "+A.stack));var Q=u(ae.toString());return B(P?Q:c(Q))})})}Object.defineProperty(s,"__esModule",{value:!0});var m=i(35),y=n(m);s.machineIdSync=d,s.machineId=p;var b=i(70),T=i(71),C=process,V=C.platform,_e={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},X={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:_e[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,s,i){t.exports={default:i(36),__esModule:!0}},function(t,s,i){i(66),i(68),i(69),i(67),t.exports=i(6).Promise},function(t,s){t.exports=function(){}},function(t,s){t.exports=function(i,n,a,c){if(!(i instanceof n)||c!==void 0&&c in i)throw TypeError(a+": incorrect invocation!");return i}},function(t,s,i){var n=i(13),a=i(31),c=i(62);t.exports=function(u){return function(d,p,m){var y,b=n(d),T=a(b.length),C=c(m,T);if(u&&p!=p){for(;T>C;)if(y=b[C++],y!=y)return!0}else for(;T>C;C++)if((u||C in b)&&b[C]===p)return u||C||0;return!u&&-1}}},function(t,b,i){var n=i(7),a=i(44),c=i(43),u=i(3),d=i(31),p=i(64),m={},y={},b=t.exports=function(T,C,V,_e,X){var P,B,te,A,ae=X?function(){return T}:p(T),pe=n(V,_e,C?2:1),Q=0;if(typeof ae!="function")throw TypeError(T+" is not iterable!");if(c(ae)){for(P=d(T.length);P>Q;Q++)if(A=C?pe(u(B=T[Q])[0],B[1]):pe(T[Q]),A===m||A===y)return A}else for(te=ae.call(T);!(B=te.next()).done;)if(A=a(te,pe,B.value,C),A===m||A===y)return A};b.BREAK=m,b.RETURN=y},function(t,s){t.exports=function(i,n,a){var c=a===void 0;switch(n.length){case 0:return c?i():i.call(a);case 1:return c?i(n[0]):i.call(a,n[0]);case 2:return c?i(n[0],n[1]):i.call(a,n[0],n[1]);case 3:return c?i(n[0],n[1],n[2]):i.call(a,n[0],n[1],n[2]);case 4:return c?i(n[0],n[1],n[2],n[3]):i.call(a,n[0],n[1],n[2],n[3])}return i.apply(a,n)}},function(t,s,i){var n=i(11);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(a){return n(a)=="String"?a.split(""):Object(a)}},function(t,s,i){var n=i(10),a=i(1)("iterator"),c=Array.prototype;t.exports=function(u){return u!==void 0&&(n.Array===u||c[a]===u)}},function(t,s,i){var n=i(3);t.exports=function(a,c,u,d){try{return d?c(n(u)[0],u[1]):c(u)}catch(m){var p=a.return;throw p!==void 0&&n(p.call(a)),m}}},function(t,s,i){"use strict";var n=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=n(u,{next:a(1,m)}),c(d,p+" Iterator")}},function(t,s,i){var n=i(1)("iterator"),a=!1;try{var c=[7][n]();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],y=m[n]();y.next=function(){return{done:p=!0}},m[n]=function(){return y},u(m)}catch{}return p}},function(t,s){t.exports=function(i,n){return{value:n,done:!!i}}},function(t,s,i){var n=i(2),a=i(30).set,c=n.MutationObserver||n.WebKitMutationObserver,u=n.process,d=n.Promise,p=i(11)(u)=="process";t.exports=function(){var m,y,b,T=function(){var X,P;for(p&&(X=u.domain)&&X.exit();m;){P=m.fn,m=m.next;try{P()}catch(B){throw m?b():y=void 0,B}}y=void 0,X&&X.enter()};if(p)b=function(){u.nextTick(T)};else if(c){var C=!0,V=document.createTextNode("");new c(T).observe(V,{characterData:!0}),b=function(){V.data=C=!C}}else if(d&&d.resolve){var _e=d.resolve();b=function(){_e.then(T)}}else b=function(){a.call(n,T)};return function(X){var P={fn:X,next:void 0};y&&(y.next=P),m||(m=P,b()),y=P}}},function(t,s,i){var n=i(3),a=i(50),c=i(22),u=i(19)("IE_PROTO"),d=function(){},p="prototype",m=function(){var y,b=i(16)("iframe"),T=c.length,C=">";for(b.style.display="none",i(25).appendChild(b),b.src="javascript:",y=b.contentWindow.document,y.open(),y.write("<script>document.F=Object</script"+C),y.close(),m=y.F;T--;)delete m[p][c[T]];return m()};t.exports=Object.create||function(y,b){var T;return y!==null?(d[p]=n(y),T=new d,d[p]=null,T[u]=y):T=m(),b===void 0?T:a(T,b)}},function(t,s,i){var n=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),y=m.length,b=0;y>b;)n.f(u,p=m[b++],d[p]);return u}},function(t,s,i){var n=i(55),a=i(17),c=i(13),u=i(32),d=i(8),p=i(26),m=Object.getOwnPropertyDescriptor;s.f=i(4)?m:function(y,b){if(y=c(y),b=u(b,!0),p)try{return m(y,b)}catch{}if(d(y,b))return a(!n.f.call(y,b),y[b])}},function(t,s,i){var n=i(8),a=i(63),c=i(19)("IE_PROTO"),u=Object.prototype;t.exports=Object.getPrototypeOf||function(d){return d=a(d),n(d,c)?d[c]:typeof d.constructor=="function"&&d instanceof d.constructor?d.constructor.prototype:d instanceof Object?u:null}},function(t,s,i){var n=i(8),a=i(13),c=i(39)(!1),u=i(19)("IE_PROTO");t.exports=function(d,p){var m,y=a(d),b=0,T=[];for(m in y)m!=u&&n(y,m)&&T.push(m);for(;p.length>b;)n(y,m=p[b++])&&(~c(T,m)||T.push(m));return T}},function(t,s,i){var n=i(53),a=i(22);t.exports=Object.keys||function(c){return n(c,a)}},function(t,s){s.f={}.propertyIsEnumerable},function(t,s,i){var n=i(5);t.exports=function(a,c,u){for(var d in c)u&&a[d]?a[d]=c[d]:n(a,d,c[d]);return a}},function(t,s,i){t.exports=i(5)},function(t,s,i){var n=i(9),a=i(3),c=function(u,d){if(a(u),!n(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,y){return c(m,y),d?m.__proto__=y:p(m,y),m}})({},!1):void 0),check:c}},function(t,s,i){"use strict";var n=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]:n[p];u&&m&&!m[d]&&c.f(m,d,{configurable:!0,get:function(){return this}})}},function(t,s,i){var n=i(3),a=i(14),c=i(1)("species");t.exports=function(u,d){var p,m=n(u).constructor;return m===void 0||(p=n(m)[c])==null?d:a(p)}},function(t,s,i){var n=i(20),a=i(15);t.exports=function(c){return function(u,d){var p,m,y=String(a(u)),b=n(d),T=y.length;return b<0||b>=T?c?"":void 0:(p=y.charCodeAt(b),p<55296||p>56319||b+1===T||(m=y.charCodeAt(b+1))<56320||m>57343?c?y.charAt(b):p:c?y.slice(b,b+2):(p-55296<<10)+(m-56320)+65536)}}},function(t,s,i){var n=i(20),a=Math.max,c=Math.min;t.exports=function(u,d){return u=n(u),u<0?a(u+d,0):c(u,d)}},function(t,s,i){var n=i(15);t.exports=function(a){return Object(n(a))}},function(t,s,i){var n=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[n(u)]}},function(t,s,i){"use strict";var n=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,n("keys"),n("values"),n("entries")},function(t,s){},function(t,s,i){"use strict";var n,a,c,u=i(28),d=i(2),p=i(7),m=i(21),y=i(23),b=i(9),T=(i(3),i(14)),C=i(38),V=i(40),_e=(i(58).set,i(60)),X=i(30).set,P=i(48)(),B="Promise",te=d.TypeError,ae=d.process,A=d[B],ae=d.process,pe=m(ae)=="process",Q=function(){},Ne=!!(function(){try{var L=A.resolve(1),j=(L.constructor={})[i(1)("species")]=function(E){E(Q,Q)};return(pe||typeof PromiseRejectionEvent=="function")&&L.then(Q)instanceof j}catch{}})(),ve=function(L,j){return L===j||L===A&&j===c},Ke=function(L){var j;return!(!b(L)||typeof(j=L.then)!="function")&&j},ee=function(L){return ve(A,L)?new Je(L):new a(L)},Je=a=function(L){var j,E;this.promise=new L(function(U,ue){if(j!==void 0||E!==void 0)throw te("Bad Promise constructor");j=U,E=ue}),this.resolve=T(j),this.reject=T(E)},We=function(L){try{L()}catch(j){return{error:j}}},nt=function(L,j){if(!L._n){L._n=!0;var E=L._c;P(function(){for(var U=L._v,ue=L._s==1,Ve=0,ct=function(Et){var wt,or,Tr=ue?Et.ok:Et.fail,zr=Et.resolve,Cr=Et.reject,gs=Et.domain;try{Tr?(ue||(L._h==2&&ot(L),L._h=1),Tr===!0?wt=U:(gs&&gs.enter(),wt=Tr(U),gs&&gs.exit()),wt===Et.promise?Cr(te("Promise-chain cycle")):(or=Ke(wt))?or.call(wt,zr,Cr):zr(wt)):Cr(U)}catch(Ii){Cr(Ii)}};E.length>Ve;)ct(E[Ve++]);L._c=[],L._n=!1,j&&!L._h&&De(L)})}},De=function(L){X.call(d,function(){var j,E,U,ue=L._v;if(Te(L)&&(j=We(function(){pe?ae.emit("unhandledRejection",ue,L):(E=d.onunhandledrejection)?E({promise:L,reason:ue}):(U=d.console)&&U.error&&U.error("Unhandled promise rejection",ue)}),L._h=pe||Te(L)?2:1),L._a=void 0,j)throw j.error})},Te=function(L){if(L._h==1)return!1;for(var j,E=L._a||L._c,U=0;E.length>U;)if(j=E[U++],j.fail||!Te(j.promise))return!1;return!0},ot=function(L){X.call(d,function(){var j;pe?ae.emit("rejectionHandled",L):(j=d.onrejectionhandled)&&j({promise:L,reason:L._v})})},He=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()),nt(j,!0))},vt=function(L){var j,E=this;if(!E._d){E._d=!0,E=E._w||E;try{if(E===L)throw te("Promise can't be resolved itself");(j=Ke(L))?P(function(){var U={_w:E,_d:!1};try{j.call(L,p(vt,U,1),p(He,U,1))}catch(ue){He.call(U,ue)}}):(E._v=L,E._s=1,nt(E,!1))}catch(U){He.call({_w:E,_d:!1},U)}}};Ne||(A=function(L){C(this,A,B,"_h"),T(L),n.call(this);try{L(p(vt,this,1),p(He,this,1))}catch(j){He.call(this,j)}},n=function(L){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},n.prototype=i(56)(A.prototype,{then:function(L,j){var E=ee(_e(this,A));return E.ok=typeof L!="function"||L,E.fail=typeof j=="function"&&j,E.domain=pe?ae.domain:void 0,this._c.push(E),this._a&&this._a.push(E),this._s&&nt(this,!1),E.promise},catch:function(L){return this.then(void 0,L)}}),Je=function(){var L=new n;this.promise=L,this.resolve=p(vt,L,1),this.reject=p(He,L,1)}),y(y.G+y.W+y.F*!Ne,{Promise:A}),i(18)(A,B),i(59)(B),c=i(6)[B],y(y.S+y.F*!Ne,B,{reject:function(L){var j=ee(this),E=j.reject;return E(L),j.promise}}),y(y.S+y.F*(u||!Ne),B,{resolve:function(L){if(L instanceof A&&ve(L.constructor,this))return L;var j=ee(this),E=j.resolve;return E(L),j.promise}}),y(y.S+y.F*!(Ne&&i(46)(function(L){A.all(L).catch(Q)})),B,{all:function(L){var j=this,E=ee(j),U=E.resolve,ue=E.reject,Ve=We(function(){var ct=[],Et=0,wt=1;V(L,!1,function(or){var Tr=Et++,zr=!1;ct.push(void 0),wt++,j.resolve(or).then(function(Cr){zr||(zr=!0,ct[Tr]=Cr,--wt||U(ct))},ue)}),--wt||U(ct)});return Ve&&ue(Ve.error),E.promise},race:function(L){var j=this,E=ee(j),U=E.reject,ue=We(function(){V(L,!1,function(Ve){j.resolve(Ve).then(E.resolve,U)})});return ue&&U(ue.error),E.promise}})},function(t,s,i){"use strict";var n=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=n(c,u),this._i+=a.length,{value:a,done:!1})})},function(t,s,i){i(65);for(var n=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],y=n[m],b=y&&y.prototype;b&&!b[u]&&a(b,u,m),c[m]=c.Array}},function(t,s){t.exports=require("child_process")},function(t,s){t.exports=require("crypto")}])})});function Vy(){try{return Sc.default.statSync("/.dockerenv"),!0}catch{return!1}}function zy(){try{return Sc.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Tc(){return xc===void 0&&(xc=Vy()||zy()),xc}var Sc,xc,Ah=Ft(()=>{Sc=ce(require("node:fs"),1)});function zs(){return Cc===void 0&&(Cc=Ky()||Tc()),Cc}var Ph,Cc,Ky,Oc=Ft(()=>{Ph=ce(require("node:fs"),1);Ah();Ky=()=>{try{return Ph.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var kc,Lh,Nh,Ih,qr,Rc=Ft(()=>{kc=ce(require("node:process"),1),Lh=ce(require("node:os"),1),Nh=ce(require("node:fs"),1);Oc();Ih=()=>{if(kc.default.platform!=="linux")return!1;if(Lh.default.release().toLowerCase().includes("microsoft"))return!zs();try{return Nh.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!zs():!1}catch{return!1}},qr=kc.default.env.__IS_WSL_TEST__?Ih:Ih()});var Ac,Ci,$y,Gy,Pc,Mh=Ft(()=>{Ac=ce(require("node:process"),1),Ci=ce(require("node:fs/promises"),1);Rc();Rc();$y=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",s=!1;try{await Ci.default.access(t,Ci.constants.F_OK),s=!0}catch{}if(!s)return r;let i=await Ci.default.readFile(t,{encoding:"utf8"}),n=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return n?(e=n.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),Gy=async()=>`${await $y()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Pc=async()=>qr?Gy():`${Ac.default.env.SYSTEMROOT||Ac.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Wr(r,e,t){let s=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 s(i),i},set(i){s(i)}}),r}var Dh=Ft(()=>{});async function Ic(){if(Bh.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await Yy("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 Fh,Bh,jh,Yy,Uh=Ft(()=>{Fh=require("node:util"),Bh=ce(require("node:process"),1),jh=require("node:child_process"),Yy=(0,Fh.promisify)(jh.execFile)});async function Hh(r,{humanReadableOutput:e=!0,signal:t}={}){if(qh.default.platform!=="darwin")throw new Error("macOS only");let s=e?[]:["-ss"],i={};t&&(i.signal=t);let{stdout:n}=await Xy("osascript",["-e",r,s],i);return n.trim()}var qh,Wh,Lc,Xy,Vh=Ft(()=>{qh=ce(require("node:process"),1),Wh=require("node:util"),Lc=require("node:child_process"),Xy=(0,Wh.promisify)(Lc.execFile)});async function Nc(r){return Hh(`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 zh=Ft(()=>{Vh()});async function Dc(r=Jy){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 Mc(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:s}=t.groups,i=s.lastIndexOf("."),n=s.lastIndexOf("-"),a=i===-1?void 0:s.slice(0,i),c=n===-1?void 0:s.slice(0,n);return Qn[s]??Qn[a]??Qn[c]??{name:s,id:s}}var Kh,$h,Jy,Qn,ob,Mc,Gh=Ft(()=>{Kh=require("node:util"),$h=require("node:child_process"),Jy=(0,Kh.promisify)($h.execFile),Qn={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"}},ob=new Map(Object.entries(Qn)),Mc=class extends Error{}});async function Fc(){if(eo.default.platform==="darwin"){let r=await Ic();return{name:await Nc(r),id:r}}if(eo.default.platform==="linux"){let{stdout:r}=await Zy("xdg-mime",["query","default","x-scheme-handler/http"]),e=r.trim();return{name:Qy(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(eo.default.platform==="win32")return Dc();throw new Error("Only macOS, Linux, and Windows are supported")}var Yh,eo,Xh,Zy,Qy,Jh=Ft(()=>{Yh=require("node:util"),eo=ce(require("node:process"),1),Xh=require("node:child_process");Uh();zh();Gh();Zy=(0,Yh.promisify)(Xh.execFile),Qy=r=>r.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var id={};ep(id,{apps:()=>Hr,default:()=>iv,openApp:()=>sv});async function tv(){let r=await Pc(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=Uc.Buffer.from(e,"utf16le").toString("base64"),{stdout:s}=await ev(r,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),i=s.trim(),n={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return n[i]?{id:n[i]}:{}}function td(r){if(typeof r=="string"||Array.isArray(r))return r;let{[Qh]:e}=r;if(!e)throw new Error(`${Qh} is not supported`);return e}function ro({[Ks]:r},{wsl:e}){if(e&&qr)return td(e);if(!r)throw new Error(`${Ks} is not supported`);return td(r)}var jc,Uc,qc,rd,sd,Wc,to,nv,ev,Bc,Zh,Ks,Qh,ed,Oi,rv,sv,Hr,iv,nd=Ft(()=>{jc=ce(require("node:process"),1),Uc=require("node:buffer"),qc=ce(require("node:path"),1),rd=require("node:url"),sd=require("node:util"),Wc=ce(require("node:child_process"),1),to=ce(require("node:fs/promises"),1);Mh();Dh();Jh();Oc();nv={},ev=(0,sd.promisify)(Wc.default.execFile),Bc=qc.default.dirname((0,rd.fileURLToPath)(nv.url)),Zh=qc.default.join(Bc,"xdg-open"),{platform:Ks,arch:Qh}=jc.default;ed=async(r,e)=>{let t;for(let s of r)try{return await e(s)}catch(i){t=i}throw t},Oi=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return ed(r.app,c=>Oi({...r,app:c}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return ed(e,c=>Oi({...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=qr?await tv():await Fc();if(d.id in c){let p=c[d.id];return e==="browserPrivate"&&t.push(u[p]),Oi({...r,app:{name:Hr[p],arguments:t}})}throw new Error(`${d.name} is not supported as a default browser`)}let s,i=[],n={};if(Ks==="darwin")s="open",r.wait&&i.push("--wait-apps"),r.background&&i.push("--background"),r.newInstance&&i.push("--new"),e&&i.push("-a",e);else if(Ks==="win32"||qr&&!zs()&&!e){s=await Pc(),i.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),qr||(n.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=Uc.Buffer.from(c.join(" "),"utf16le").toString("base64")}else{if(e)s=e;else{let c=!Bc||Bc==="/",u=!1;try{await to.default.access(Zh,to.constants.X_OK),u=!0}catch{}s=jc.default.versions.electron??(Ks==="android"||c||!u)?"xdg-open":Zh}t.length>0&&i.push(...t),r.wait||(n.stdio="ignore",n.detached=!0)}Ks==="darwin"&&t.length>0&&i.push("--args",...t),r.target&&i.push(r.target);let a=Wc.default.spawn(s,i,n);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)},rv=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a `target`");return Oi({...e,target:r})},sv=(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 Oi({...e,app:{name:r,arguments:t}})};Hr={};Wr(Hr,"chrome",()=>ro({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"]}}));Wr(Hr,"brave",()=>ro({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"]}}));Wr(Hr,"firefox",()=>ro({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Wr(Hr,"edge",()=>ro({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Wr(Hr,"browser",()=>"browser");Wr(Hr,"browserPrivate",()=>"browserPrivate");iv=rv});var cr=ce(require("fs")),Ui=ce(require("path"));var uf=ce(require("os")),lf=ce(require("path")),Bi=ce(require("fs"));function ji(){let r=lf.join(uf.homedir(),".termiq");return Bi.existsSync(r)||Bi.mkdirSync(r,{recursive:!0,mode:448}),r}var ei=class{filePath;data={};constructor(){this.filePath=Ui.join(ji(),"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(cr.existsSync(this.filePath)){let e=cr.readFileSync(this.filePath,"utf-8");this.data=JSON.parse(e)}}catch{this.data={}}}save(){let e=Ui.dirname(this.filePath);cr.existsSync(e)||cr.mkdirSync(e,{recursive:!0,mode:448}),cr.writeFileSync(this.filePath,JSON.stringify(this.data,null,2),{mode:384})}};var fr=ce(require("fs")),qi=ce(require("path"));var rp={serverUrl:"https://termiq.io",agentName:"",multiViewer:!1},ti=class{config;filePath;constructor(e){this.filePath=qi.join(ji(),"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(fr.existsSync(this.filePath)){let e=fr.readFileSync(this.filePath,"utf-8");return JSON.parse(e)}}catch{}return{}}saveToFile(){let e=qi.dirname(this.filePath);fr.existsSync(e)||fr.mkdirSync(e,{recursive:!0,mode:448}),fr.writeFileSync(this.filePath,JSON.stringify(this.config,null,2))}};var pt=ce(require("fs")),Ec=ce(require("path")),Oh=ce(require("os")),Zn=ce(wi()),Uy="cli",vc=Ec.join(Oh.homedir(),".termiq","logs"),Ur=Ec.join(vc,"cli.log"),qy=5*1024*1024,Ch=3;function Wy(){try{if(!pt.existsSync(Ur)||pt.statSync(Ur).size<qy)return;for(let e=Ch-1;e>=1;e--){let t=`${Ur}.${e}`,s=`${Ur}.${e+1}`;pt.existsSync(t)&&(e+1>Ch?pt.unlinkSync(t):pt.renameSync(t,s))}pt.renameSync(Ur,`${Ur}.1`)}catch{}}function Hy(r){try{pt.existsSync(vc)||pt.mkdirSync(vc,{recursive:!0}),Wy(),pt.appendFileSync(Ur,r+`
|
|
34
|
+
`,{encoding:"utf8"})}catch{}}var bi=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 Ur}write(e,t,s){if(!(0,Zn.shouldLog)(e,this.level))return;let i=(0,Zn.formatLogLine)(e,Uy,t,s);this.toFile?Hy(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 kh=ce(require("os")),Rh=ce(bc()),Si=class{cachedId=null;name;constructor(e){this.name=e||kh.hostname()||"CLI"}async getMachineId(){if(this.cachedId)return this.cachedId;try{this.cachedId=(0,Rh.machineIdSync)()}catch{this.cachedId=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}return this.cachedId}getMachineName(){return this.name}};var Ti=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 ki=class{async openUrl(e){let{default:t}=await Promise.resolve().then(()=>(nd(),id));await t(e)}};var od=ce(require("fs")),Hc=ce(require("path"));function so(r){let e=r?[r]:[Hc.join(__dirname,"..","package.json"),Hc.join(__dirname,"..","..","package.json")];for(let t of e)try{let s=JSON.parse(od.readFileSync(t,"utf8"));if(typeof s.version=="string"&&s.version.length>0)return s.version}catch{}return"unknown"}function ad(r,e){for(let t=0;t<r.length;t++){let s=r[t];if(s.startsWith("-")){e.has(s)&&t++;continue}return s}}var Vc=new Set(["--cid","--token","--server","--log-level"]),cd=new Set(["--help","-h","--version","-V","--verbose","-v","--watch","-w","--log-to-file","--statusline","--multi-viewer","--force"]);function fd(r,e,t){for(let s=0;s<r.length;s++){let i=r[s];if(!i.startsWith("-"))continue;let n=i.includes("=")?i.slice(0,i.indexOf("=")):i;if(e.has(n)||t.has(n)){e.has(n)&&!i.includes("=")&&s++;continue}return i}}var Fd=ce(require("path")),yt=ce(wi()),Bd=ce(dr());var ud=ce(require("os")),ld=require("crypto"),hd=ce(require("node-pty")),dd=ce(wi()),io=class r{ptyProcess=null;outputBuffer=new dd.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 s=process.env.SHELL||(ud.platform()==="win32"?"powershell.exe":"/bin/bash"),i=process.stdout.columns||80,n=process.stdout.rows||24,a=Math.max(1,n-t);this.reservedBottomRows=t,this.ptyProcess=hd.spawn(s,[],{name:"xterm-256color",cols:i,rows:a,cwd:e,env:{...process.env,TERMIQ_SESSION_ACTIVE:"1"}}),this.onResize?.(i,a),this.streamId=(0,ld.randomUUID)();let c=`cli_${this.ptyProcess.pid}`;return this.ptyProcess.onData(u=>{this.preWriteHook?.(u),process.stdout.write(u),this.outputBuffer.append(u),this.onOutput?.(u)}),this.ptyProcess.onExit(({exitCode:u})=>{this.logger.info("Shell exited",String(u)),this.onExit?.(u)}),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u=>{this.multiViewerMode&&this.maybeClaimLocalControl(),this.onLocalInput?.(),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",s,c),c}write(e,t=!1){if(this.ptyProcess){if(!t&&!this.draining){this.ptyProcess.write(e);return}for(let s of e)this.writeQueue.push(s);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 s of r.REBROADCAST_DELAYS_MS)this.rebroadcastTimers.push(setTimeout(()=>{this.ptyProcess&&(this.desiredCols!==e||this.desiredRows!==t||this.ptyProcess.resize(e,t))},s))}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 Vr=ce(require("path")),Gs=ce(require("fs"));var Rd=require("node:events"),Ad=require("node:fs"),ho=require("node:fs/promises"),Ee=ce(require("node:path"),1);var wr=require("node:fs/promises"),br=require("node:path"),_d=require("node:stream"),Ct={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},zc={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:Ct.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(zc);var yd="READDIRP_RECURSIVE_ERROR",ov=new Set(["ENOENT","EPERM","EACCES","ELOOP",yd]),pd=[Ct.DIR_TYPE,Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE,Ct.FILE_TYPE],av=new Set([Ct.DIR_TYPE,Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE]),cv=new Set([Ct.EVERYTHING_TYPE,Ct.FILE_DIR_TYPE,Ct.FILE_TYPE]),fv=r=>ov.has(r.code),uv=process.platform==="win32",gd=r=>!0,md=r=>{if(r===void 0)return gd;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(s=>t.basename===s)}return gd},Kc=class extends _d.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={...zc,...e},{root:s,type:i}=t;this._fileFilter=md(t.fileFilter),this._directoryFilter=md(t.directoryFilter);let n=t.lstat?wr.lstat:wr.stat;uv?this._stat=a=>n(a,{bigint:!0}):this._stat=n,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:zc.depth,this._wantsDir=i?av.has(i):!1,this._wantsFile=i?cv.has(i):!1,this._wantsEverything=i===Ct.EVERYTHING_TYPE,this._root=(0,br.resolve)(s),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(s,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,s=t&&t.files;if(s&&s.length>0){let{path:i,depth:n}=t,a=s.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)?(n<=this._maxDepth&&this.parents.push(this._exploreDir(u.fullPath,n+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 s;try{s=await(0,wr.readdir)(e,this._rdOptions)}catch(i){this._onError(i)}return{files:s,depth:t,path:e}}async _formatEntry(e,t){let s,i=this._isDirent?e.name:e;try{let n=(0,br.resolve)((0,br.join)(t,i));s={path:(0,br.relative)(this._root,n),fullPath:n,basename:i},s[this._statsProp]=this._isDirent?e:await this._stat(n)}catch(n){this._onError(n);return}return s}_onError(e){fv(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 s=e.fullPath;try{let i=await(0,wr.realpath)(s),n=await(0,wr.lstat)(i);if(n.isFile())return"file";if(n.isDirectory()){let a=i.length;if(s.startsWith(i)&&s.substr(a,1)===br.sep){let c=new Error(`Circular symlink detected: "${s}" points to "${i}"`);return c.code=yd,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 vd(r,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=Ct.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&&!pd.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${pd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new Kc(e)}var hs=require("node:fs"),zt=require("node:fs/promises"),wd=require("node:os"),qe=ce(require("node:path"),1),lv="data",Yc="end",bd="close",fo=()=>{};var uo=process.platform,Xc=uo==="win32",hv=uo==="darwin",dv=uo==="linux",pv=uo==="freebsd",xd=(0,wd.type)()==="OS400",ze={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Vt=ze,gv="watch",mv={lstat:zt.lstat,stat:zt.stat},ls="listeners",no="errHandlers",$s="rawEmitters",_v=[ls,no,$s],yv=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"]),vv=r=>yv.has(qe.extname(r).slice(1).toLowerCase()),Gc=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},Ri=(r,e,t)=>{let s=r[e];s instanceof Set||(r[e]=s=new Set([s])),s.add(t)},Ev=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},Ai=(r,e,t)=>{let s=r[e];s instanceof Set?s.delete(t):s===t&&delete r[e]},Sd=r=>r instanceof Set?r.size===0:!r,oo=new Map;function Ed(r,e,t,s,i){let n=(a,c)=>{t(r),i(a,c,{watchedPath:r}),c&&r!==c&&ao(qe.resolve(r,c),ls,qe.join(r,c))};try{return(0,hs.watch)(r,{persistent:e.persistent},n)}catch(a){s(a);return}}var ao=(r,e,t,s,i)=>{let n=oo.get(r);n&&Gc(n[e],a=>{a(t,s,i)})},wv=(r,e,t,s)=>{let{listener:i,errHandler:n,rawEmitter:a}=s,c=oo.get(e),u;if(!t.persistent)return u=Ed(r,t,i,n,a),u?u.close.bind(u):void 0;if(c)Ri(c,ls,i),Ri(c,no,n),Ri(c,$s,a);else{if(u=Ed(r,t,ao.bind(null,e,ls),n,ao.bind(null,e,$s)),!u)return;u.on(Vt.ERROR,async d=>{let p=ao.bind(null,e,no);if(c&&(c.watcherUnusable=!0),Xc&&d.code==="EPERM")try{await(await(0,zt.open)(r,"r")).close(),p(d)}catch{}else p(d)}),c={listeners:i,errHandlers:n,rawEmitters:a,watcher:u},oo.set(e,c)}return()=>{Ai(c,ls,i),Ai(c,no,n),Ai(c,$s,a),Sd(c.listeners)&&(c.watcher.close(),oo.delete(e),_v.forEach(Ev(c)),c.watcher=void 0,Object.freeze(c))}},$c=new Map,bv=(r,e,t,s)=>{let{listener:i,rawEmitter:n}=s,a=$c.get(e),c=a&&a.options;return c&&(c.persistent<t.persistent||c.interval>t.interval)&&((0,hs.unwatchFile)(e),a=void 0),a?(Ri(a,ls,i),Ri(a,$s,n)):(a={listeners:i,rawEmitters:n,options:t,watcher:(0,hs.watchFile)(e,t,(u,d)=>{Gc(a.rawEmitters,m=>{m(Vt.CHANGE,e,{curr:u,prev:d})});let p=u.mtimeMs;(u.size!==d.size||p>d.mtimeMs||p===0)&&Gc(a.listeners,m=>m(r,u))})},$c.set(e,a)),()=>{Ai(a,ls,i),Ai(a,$s,n),Sd(a.listeners)&&($c.delete(e),(0,hs.unwatchFile)(e),a.options=a.watcher=void 0,Object.freeze(a))}},co=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let s=this.fsw.options,i=qe.dirname(e),n=qe.basename(e);this.fsw._getWatchedDir(i).add(n);let c=qe.resolve(e),u={persistent:s.persistent};t||(t=fo);let d;if(s.usePolling){let p=s.interval!==s.binaryInterval;u.interval=p&&vv(n)?s.binaryInterval:s.interval,d=bv(e,c,u,{listener:t,rawEmitter:this.fsw._emitRaw})}else d=wv(e,c,u,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return d}_handleFile(e,t,s){if(this.fsw.closed)return;let i=qe.dirname(e),n=qe.basename(e),a=this.fsw._getWatchedDir(i),c=t;if(a.has(n))return;let u=async(p,m)=>{if(this.fsw._throttle(gv,e,5)){if(!m||m.mtimeMs===0)try{let y=await(0,zt.stat)(e);if(this.fsw.closed)return;let b=y.atimeMs,T=y.mtimeMs;if((!b||b<=T||T!==c.mtimeMs)&&this.fsw._emit(Vt.CHANGE,e,y),(hv||dv||pv)&&c.ino!==y.ino){this.fsw._closeFile(p),c=y;let C=this._watchWithNodeFs(e,u);C&&this.fsw._addPathCloser(p,C)}else c=y}catch{this.fsw._remove(i,n)}else if(a.has(n)){let y=m.atimeMs,b=m.mtimeMs;(!y||y<=b||b!==c.mtimeMs)&&this.fsw._emit(Vt.CHANGE,e,m),c=m}}},d=this._watchWithNodeFs(e,u);if(!(s&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Vt.ADD,e,0))return;this.fsw._emit(Vt.ADD,e,t)}return d}async _handleSymlink(e,t,s,i){if(this.fsw.closed)return;let n=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let c;try{c=await(0,zt.realpath)(s)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(i)?this.fsw._symlinkPaths.get(n)!==c&&(this.fsw._symlinkPaths.set(n,c),this.fsw._emit(Vt.CHANGE,s,e.stats)):(a.add(i),this.fsw._symlinkPaths.set(n,c),this.fsw._emit(Vt.ADD,s,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(n))return!0;this.fsw._symlinkPaths.set(n,!0)}_handleRead(e,t,s,i,n,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(s.path),p=new Set,m=this.fsw._readdirp(e,{fileFilter:y=>s.filterPath(y),directoryFilter:y=>s.filterDir(y)});if(m)return m.on(lv,async y=>{if(this.fsw.closed){m=void 0;return}let b=y.path,T=qe.join(e,b);if(p.add(b),!(y.stats.isSymbolicLink()&&await this._handleSymlink(y,e,T,b))){if(this.fsw.closed){m=void 0;return}(b===i||!i&&!d.has(b))&&(this.fsw._incrReadyCount(),T=qe.join(n,qe.relative(n,T)),this._addToNodeFs(T,t,s,a+1))}}).on(Vt.ERROR,this._boundHandleError),new Promise((y,b)=>{if(!m)return b();m.once(Yc,()=>{if(this.fsw.closed){m=void 0;return}let T=c?c.clear():!1;y(void 0),d.getChildren().filter(C=>C!==e&&!p.has(C)).forEach(C=>{this.fsw._remove(e,C)}),m=void 0,T&&this._handleRead(e,!1,s,i,n,a,c)})})}async _handleDir(e,t,s,i,n,a,c){let u=this.fsw._getWatchedDir(qe.dirname(e)),d=u.has(qe.basename(e));!(s&&this.fsw.options.ignoreInitial)&&!n&&!d&&this.fsw._emit(Vt.ADD_DIR,e,t),u.add(qe.basename(e)),this.fsw._getWatchedDir(e);let p,m,y=this.fsw.options.depth;if((y==null||i<=y)&&!this.fsw._symlinkPaths.has(c)){if(!n&&(await this._handleRead(e,s,a,n,e,i,p),this.fsw.closed))return;m=this._watchWithNodeFs(e,(b,T)=>{T&&T.mtimeMs===0||this._handleRead(b,!1,a,n,e,i,p)})}return m}async _addToNodeFs(e,t,s,i,n){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let c=this.fsw._getWatchHelpers(e);s&&(c.filterPath=u=>s.filterPath(u),c.filterDir=u=>s.filterDir(u));try{let u=await mv[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),y=d?await(0,zt.realpath)(e):e;if(this.fsw.closed||(p=await this._handleDir(c.watchPath,u,t,i,n,c,y),this.fsw.closed))return;m!==y&&y!==void 0&&this.fsw._symlinkPaths.set(m,y)}else if(u.isSymbolicLink()){let m=d?await(0,zt.realpath)(e):e;if(this.fsw.closed)return;let y=qe.dirname(c.watchPath);if(this.fsw._getWatchedDir(y).add(c.watchPath),this.fsw._emit(Vt.ADD,c.watchPath,u),p=await this._handleDir(y,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 Jc="/",xv="//",Pd=".",Sv="..",Tv="string",Cv=/\\/g,Id=/\/\//g,Ov=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,kv=/^\.[/\\]/;function lo(r){return Array.isArray(r)?r:[r]}var Zc=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function Rv(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=Ee.relative(r.path,e);return t?!t.startsWith("..")&&!Ee.isAbsolute(t):!1}return!1}:()=>!1}function Av(r){if(typeof r!="string")throw new Error("string expected");r=Ee.normalize(r),r=r.replace(/\\/g,"/");let e=!1;return r.startsWith("//")&&(e=!0),r=r.replace(Id,"/"),e&&(r="/"+r),r}function Td(r,e,t){let s=Av(e);for(let i=0;i<r.length;i++){let n=r[i];if(n(s,t))return!0}return!1}function Pv(r,e){if(r==null)throw new TypeError("anymatch: specify first argument");let s=lo(r).map(i=>Rv(i));return e==null?(i,n)=>Td(s,i,n):Td(s,e)}var Cd=r=>{let e=lo(r).flat();if(!e.every(t=>typeof t===Tv))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Ld)},Od=r=>{let e=r.replace(Cv,Jc),t=!1;return e.startsWith(xv)&&(t=!0),e=e.replace(Id,Jc),t&&(e=Jc+e),e},Ld=r=>Od(Ee.normalize(Od(r))),kd=(r="")=>e=>typeof e=="string"?Ld(Ee.isAbsolute(e)?e:Ee.join(r,e)):e,Iv=(r,e)=>Ee.isAbsolute(r)?r:Ee.join(e,r),Lv=Object.freeze(new Set),Qc=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!==Pd&&e!==Sv&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let s=this.path;try{await(0,ho.readdir)(s)}catch{this._removeWatcher&&this._removeWatcher(Ee.dirname(s),Ee.basename(s))}}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=fo,this.items=Lv,Object.freeze(this)}},Nv="stat",Mv="lstat",ef=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,s){this.fsw=s;let i=e;this.path=e=e.replace(kv,""),this.watchPath=i,this.fullWatchPath=Ee.resolve(i),this.dirParts=[],this.dirParts.forEach(n=>{n.length>1&&n.pop()}),this.followSymlinks=t,this.statMethod=t?Nv:Mv}entryPath(e){return Ee.join(this.watchPath,Ee.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let s=this.entryPath(e);return this.fsw._isntIgnored(s,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},tf=class extends Rd.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,s={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?s:typeof t=="object"?{...s,...t}:!1};xd&&(i.usePolling=!0),i.atomic===void 0&&(i.atomic=!i.usePolling);let n=process.env.CHOKIDAR_USEPOLLING;if(n!==void 0){let u=n.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=fo,this._readyEmitted=!0,process.nextTick(()=>this.emit(ze.READY)))},this._emitRaw=(...u)=>this.emit(ze.RAW,...u),this._boundRemove=this._remove.bind(this),this.options=i,this._nodeFsHandler=new co(this),Object.freeze(i)}_addIgnoredPath(e){if(Zc(e)){for(let t of this._ignoredPaths)if(Zc(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)Zc(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,s){let{cwd:i}=this.options;this.closed=!1,this._closePromise=void 0;let n=Cd(e);return i&&(n=n.map(a=>Iv(a,i))),n.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=n.length,Promise.all(n.map(async a=>{let c=await this._nodeFsHandler._addToNodeFs(a,!s,void 0,0,t);return c&&this._emitReady(),c})).then(a=>{this.closed||a.forEach(c=>{c&&this.add(Ee.dirname(c),Ee.basename(t||c))})}),this}unwatch(e){if(this.closed)return this;let t=Cd(e),{cwd:s}=this.options;return t.forEach(i=>{!Ee.isAbsolute(i)&&!this._closers.has(i)&&(s&&(i=Ee.join(s,i)),i=Ee.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(s=>{let i=s();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,s)=>{let n=(this.options.cwd?Ee.relative(this.options.cwd,s):s)||Pd;e[n]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==ze.ERROR&&this.emit(ze.ALL,e,...t)}async _emit(e,t,s){if(this.closed)return;let i=this.options;Xc&&(t=Ee.normalize(t)),i.cwd&&(t=Ee.relative(i.cwd,t));let n=[t];s!=null&&n.push(s);let a=i.awaitWriteFinish,c;if(a&&(c=this._pendingWrites.get(t)))return c.lastChange=new Date,this;if(i.atomic){if(e===ze.UNLINK)return this._pendingUnlinks.set(t,[e,...n]),setTimeout(()=>{this._pendingUnlinks.forEach((u,d)=>{this.emit(...u),this.emit(ze.ALL,...u),this._pendingUnlinks.delete(d)})},typeof i.atomic=="number"?i.atomic:100),this;e===ze.ADD&&this._pendingUnlinks.has(t)&&(e=ze.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===ze.ADD||e===ze.CHANGE)&&this._readyEmitted){let u=(d,p)=>{d?(e=ze.ERROR,n[0]=d,this.emitWithAll(e,n)):p&&(n.length>1?n[1]=p:n.push(p),this.emitWithAll(e,n))};return this._awaitWriteFinish(t,a.stabilityThreshold,e,u),this}if(e===ze.CHANGE&&!this._throttle(ze.CHANGE,t,50))return this;if(i.alwaysStat&&s===void 0&&(e===ze.ADD||e===ze.ADD_DIR||e===ze.CHANGE)){let u=i.cwd?Ee.join(i.cwd,t):t,d;try{d=await(0,ho.stat)(u)}catch{}if(!d||this.closed)return;n.push(d)}return this.emitWithAll(e,n),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(ze.ERROR,e),e||this.closed}_throttle(e,t,s){this._throttled.has(e)||this._throttled.set(e,new Map);let i=this._throttled.get(e);if(!i)throw new Error("invalid throttle");let n=i.get(t);if(n)return n.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,s);let u={timeoutObject:a,clear:c,count:0};return i.set(t,u),u}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,s,i){let n=this.options.awaitWriteFinish;if(typeof n!="object")return;let a=n.pollInterval,c,u=e;this.options.cwd&&!Ee.isAbsolute(e)&&(u=Ee.join(this.options.cwd,e));let d=new Date,p=this._pendingWrites;function m(y){(0,Ad.stat)(u,(b,T)=>{if(b||!p.has(e)){b&&b.code!=="ENOENT"&&i(b);return}let C=Number(new Date);y&&T.size!==y.size&&(p.get(e).lastChange=C);let V=p.get(e);C-V.lastChange>=t?(p.delete(e),i(void 0,T)):c=setTimeout(m,a,T)})}p.has(e)||(p.set(e,{lastChange:d,cancelWait:()=>(p.delete(e),clearTimeout(c),s)}),c=setTimeout(m,a))}_isIgnored(e,t){if(this.options.atomic&&Ov.test(e))return!0;if(!this._userIgnored){let{cwd:s}=this.options,n=(this.options.ignored||[]).map(kd(s)),c=[...[...this._ignoredPaths].map(kd(s)),...n];this._userIgnored=Pv(c,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new ef(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=Ee.resolve(e);return this._watched.has(t)||this._watched.set(t,new Qc(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,s){let i=Ee.join(e,t),n=Ee.resolve(i);if(s=s??(this._watched.has(i)||this._watched.has(n)),!this._throttle("remove",i,100))return;!s&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(i).getChildren().forEach(y=>this._remove(i,y));let u=this._getWatchedDir(e),d=u.has(t);u.remove(t),this._symlinkPaths.has(n)&&this._symlinkPaths.delete(n);let p=i;if(this.options.cwd&&(p=Ee.relative(this.options.cwd,i)),this.options.awaitWriteFinish&&this._pendingWrites.has(p)&&this._pendingWrites.get(p).cancelWait()===ze.ADD)return;this._watched.delete(i),this._watched.delete(n);let m=s?ze.UNLINK_DIR:ze.UNLINK;d&&!this._isIgnored(i)&&this._emit(m,i),this._closePath(i)}_closePath(e){this._closeFile(e);let t=Ee.dirname(e);this._getWatchedDir(t).remove(Ee.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(s=>s()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let s=this._closers.get(e);s||(s=[],this._closers.set(e,s)),s.push(t)}_readdirp(e,t){if(this.closed)return;let s={type:ze.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},i=vd(e,s);return this._streams.add(i),i.once(bd,()=>{i=void 0}),i.once(Yc,()=>{i&&(this._streams.delete(i),i=void 0)}),i}};function Nd(r,e={}){let t=new tf(e);return t.add(r),t}var Md=ce(uc()),nr=ce(dr()),Dv=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/*.log"],Fv=300,po=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,Md.default)(),this.initializeIgnoreFilter()}initializeIgnoreFilter(){this.ignoreFilter.add(Dv);let e=Vr.join(this.workspaceRoot,".gitignore");try{if(Gs.existsSync(e)){let t=Gs.readFileSync(e,"utf-8");this.ignoreFilter.add(t)}}catch{}}onFileChanged(e){this.onFileChangedCallback=e}start(){this.watcher||(this.watcher=Nd(this.workspaceRoot,{ignored:e=>{let t=Vr.relative(this.workspaceRoot,e);if(!t||t===".")return!1;let s=t.split(Vr.sep).join("/");return this.ignoreFilter.ignores(s)},persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50}}),this.watcher.on("add",e=>this.handleEvent(e,nr.FileChangeType.CREATE)),this.watcher.on("change",e=>this.handleEvent(e,nr.FileChangeType.MODIFY)),this.watcher.on("unlink",e=>this.handleEvent(e,nr.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 s=Vr.relative(this.workspaceRoot,e);if(!s)return;let i=this.pendingEvents.get(s);i&&clearTimeout(i);let n=this.pendingTypes.get(s);this.pendingTypes.set(s,this.mergeTypes(n,t));let a=setTimeout(()=>{this.emit(s,this.pendingTypes.get(s)||t),this.pendingEvents.delete(s),this.pendingTypes.delete(s)},Fv);this.pendingEvents.set(s,a)}mergeTypes(e,t){return e?t===nr.FileChangeType.DELETE||e===nr.FileChangeType.DELETE?nr.FileChangeType.DELETE:e===nr.FileChangeType.CREATE?nr.FileChangeType.CREATE:t:t}emit(e,t){let s={path:e,changeType:t,timestamp:new Date().toISOString(),source:"watcher"};if(t!==nr.FileChangeType.DELETE)try{let i=Vr.join(this.workspaceRoot,e),n=Gs.statSync(i);s.size=n.size}catch{}this.onFileChangedCallback?.(s)}dispose(){this.stop(),this.onFileChangedCallback=null}};var Bv={online:!1,viewerCount:0},go=class r{enabled=!1;state={...Bv};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(),s=`\x1B[1;${e-1}r\x1B7\x1B[${e};1H\x1B[2K${t}\x1B8`;process.stdout.write(s)}clear(){if(!this.enabled)return;let e=process.stdout.rows;!e||e<2||process.stdout.write(`\x1B7\x1B[${e};1H\x1B[2K\x1B8`)}disable(){this.enabled&&(this.stopRefreshTimer(),this.clear(),this.resetScrollRegion(),this.enabled=!1)}inspectPtyOutput(e){if(this.enabled){if(e.includes("\x1B[?1049h")||e.includes("\x1B[?47h")){this.altScreenActive=!0;return}(e.includes("\x1B[?1049l")||e.includes("\x1B[?47l"))&&(this.altScreenActive=!1,this.render())}}getState(){return this.state}isEnabled(){return this.enabled}isAltScreenActive(){return this.altScreenActive}formatLine(){let e=[];if(e.push(this.state.online?"\u25CF online":"\u25CB offline"),this.state.viewerCount>0){let t=this.state.viewerCount===1?"1 viewer":`${this.state.viewerCount} viewers`;e.push(t)}else e.push("no viewers");return this.state.agentName&&e.push(this.state.agentName),this.state.ptyCols&&this.state.ptyRows&&e.push(`${this.state.ptyCols}\xD7${this.state.ptyRows}`)," "+e.join(" \xB7 ")+" "}};async function mo(r,e,t,s){if(s)return process.stderr.write(`Logging in with API key...
|
|
36
|
+
`),await r.loginWithApiKey(s)?(process.stderr.write(`Login successful.
|
|
35
37
|
`),!0):(process.stderr.write(`Login failed. Check your API key.
|
|
36
|
-
`),!1);try{let
|
|
37
|
-
`),process.stderr.write(` Open this URL: ${
|
|
38
|
-
`),process.stderr.write(` Enter code: ${
|
|
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}
|
|
39
41
|
`),process.stderr.write(`
|
|
40
42
|
`),process.stderr.write(` Waiting for authorization...
|
|
41
|
-
`);try{await e.openUrl(
|
|
43
|
+
`);try{await e.openUrl(i.verificationUri)}catch{}let n=await r.pollForToken(i.deviceCode);return n&&n.status==="success"?(process.stderr.write(` Login successful!
|
|
42
44
|
|
|
43
45
|
`),!0):(process.stderr.write(` Login failed or expired.
|
|
44
46
|
|
|
45
|
-
`),!1)}catch(
|
|
46
|
-
`),!1}}var
|
|
47
|
-
`),await mo(V,a,
|
|
48
|
-
`),ae=!0}m.update({online:!0})}else E==="disconnected"?(
|
|
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 Ys=ce(dr());function jv(r){switch(r){case"numbered-choice":return"select";case"free-input":return"input";default:return"confirmation"}}function Dd(r,e,t){let s=new Date().toISOString();switch(r){case"working":return e==="idle"?{type:Ys.TerminalEventType.SESSION_START,timestamp:s}:null;case"waiting":return{type:Ys.TerminalEventType.WAITING_INPUT,timestamp:s,promptType:jv(t?.type),question:t?.question||"Confirm action?",options:t?.choices?.map(i=>i.label)};case"completed":return{type:Ys.TerminalEventType.SESSION_END,timestamp:s,status:"success"};case"error":return e==="working"?{type:Ys.TerminalEventType.SESSION_END,timestamp:s,status:"error"}:{type:Ys.TerminalEventType.ERROR,timestamp:s,severity:"error",message:"Command failed"};default:return null}}async function jd(r){let{storage:e,config:t,logger:s,machineId:i,notification:n,browser:a,cwd:c,watch:u,statusLine:d,multiViewer:p}=r,m=new go(s);d&&m.enable();let y=t.getServerUrl(),b=new URL(y).host,T=await i.getMachineId(),C=new yt.CryptoService(e,s,b,T);await C.initialize();let V=new yt.AuthService(e,C,i,t,s,n,a,b,T),_e=await V.hasValidToken();_e||await V.refreshAccessToken()||(process.stderr.write(`Not logged in. Starting login flow...
|
|
49
|
+
`),await mo(V,a,s)||process.exit(1),_e=!0);let X;try{let{machineIdSync:E}=await Promise.resolve().then(()=>ce(bc()));X=E()}catch{X=`cli_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}let P,B=new yt.StatusDetector((E,U,ue)=>{if(!A.getStatus().connected)return;let Ve=P;P=U,A.updateStatus({instanceId:Q,terminalId:E,status:U,encryptedPrompt:ue&&C.encryptPromptInfo(ue)||void 0}).catch(()=>{});let ct=Dd(U,Ve,ue);ct&&A.sendTerminalEvent(Q,E,ct)}),te=p?[Bd.Capability.MULTI_VIEWER_RENDER]:[],A=new yt.WebSocketService(V,C,t,s,n,X,"cli",te);p&&s.info("Multi-viewer rendering capability advertised");let ae=!1;A.onStatusChange(E=>{if(E==="connected"){if(ae)s.info("Reconnected to termiq.io");else{let U=p?" (multi-viewer mode)":"";process.stderr.write(`Connected to termiq.io${U}
|
|
50
|
+
`),ae=!0}m.update({online:!0})}else E==="disconnected"?(s.info("Disconnected from termiq.io (will retry)"),m.update({online:!1})):E==="error"&&(s.warn("Connection degraded (no server response) \u2014 reconnecting"),m.update({online:!1}))}),A.onAuthFailure(()=>{process.stderr.write(`Session expired. Please run "termiq login" again.
|
|
49
51
|
`),j(),process.exit(1)});try{await A.connect()}catch(E){process.stderr.write(`Connection failed: ${E instanceof Error?E.message:String(E)}
|
|
50
|
-
`),process.exit(1)}let pe=Fd.basename(c),Q=`cli_${Date.now()}`,Ne=C.encryptWorkspaceInfo({name:pe,path:c});await A.registerWorkspace({instanceId:Q,encryptedInfo:Ne||void 0});let ve=new
|
|
52
|
+
`),process.exit(1)}let pe=Fd.basename(c),Q=`cli_${Date.now()}`,Ne=C.encryptWorkspaceInfo({name:pe,path:c});await A.registerWorkspace({instanceId:Q,encryptedInfo:Ne||void 0});let ve=new io(s);p&&ve.setMultiViewerMode(!0),ve.setPreWriteHook(E=>m.inspectPtyOutput(E));let Ke=null;ve.setOnResize((E,U)=>{m.update({ptyCols:E,ptyRows:U}),p&&Ke&&A.sendPtyResized(Q,Ke,E,U)}),ve.setOnLocalClaim((E,U)=>{p&&Ke&&A.sendClaimControl(Q,Ke,E,U)});let ee=ve.spawn(c,m.reservedRows()),Je=`CLI: ${pe}`,We=process.env.SHELL||"/bin/bash",nt=C.encryptTerminalInfo({name:Je,command:We,cwd:c});await A.terminalCreated({instanceId:Q,terminalId:ee,encryptedInfo:nt||void 0,streamId:ve.getStreamId()??void 0}),Ke=ee,p&&A.sendPtyResized(Q,ee,ve.getPtyCols(),ve.getPtyRows());let De=new yt.FileTransferService(s);De.setCrypto(C);let Te=new yt.FileTrackerService(s,c),ot=new yt.FileListService(s,c),He=u?new po(s,c):null,vt=A.getSocket();vt&&De.attach(vt,Q),Te.onFileChanged((E,U)=>{A.sendFileChangedEvent(Q,E,U)}),Te.onFileViewTransfer(async(E,U,ue)=>{try{await De.sendBuffer(E,U,ue.path.split("/").pop()||"view",ue.mimeType||"text/plain",{purpose:"view",viewMetadata:ue})}catch(Ve){s.error("File view transfer failed",Ve)}}),A.onFileViewRequest((E,U)=>{Te.handleViewRequest(E,U)}),A.onFileListRequest((E,U)=>{ot.handleListRequest(U)}),ot.onResponse(E=>{A.sendFileListResponse(Q,E)}),A.onFileDownloadRequest(async(E,U,ue)=>{try{await De.sendFile(E,U,void 0,void 0,ue)}catch(Ve){s.error("File download failed",Ve)}}),He&&(He.onFileChanged(E=>{A.sendFileChangedEvent(Q,ee,E)}),He.start()),B.startTracking(ee),ve.setOnOutput(E=>{A.sendOutput(Q,ee,E),B.processOutput(ee,E),Te.processOutput(ee,E)}),ve.setOnLocalInput(()=>B.resolvePrompt(ee)),A.onInput((E,U,ue,Ve)=>{E===ee&&(B.resolvePrompt(ee),ve.write(U,Ve))}),A.setTerminalActiveCheck(E=>E===ee&&ve.isAlive()),A.onResizeRequest((E,U,ue)=>{E===ee&&(s.info("Remote resize received",{terminalId:E,cols:U,rows:ue}),ve.resize(U,ue))}),A.onClientAttached(({clientCount:E})=>{ve.setSigwinchEnabled(!1),m.update({viewerCount:E}),A.sendInputResume(ee)}),A.onClientDetached(({clientCount:E})=>{E===0&&ve.setSigwinchEnabled(!0),m.update({viewerCount:E})}),A.onGetBufferRequest(E=>E===ee?ve.getBuffer():null),A.onRedrawRequest(E=>{E===ee&&ve.redrawNoResize()});async function L(){let E=C.encryptWorkspaceInfo({name:pe,path:c});await A.registerWorkspace({instanceId:Q,encryptedInfo:E||void 0});let U=C.encryptTerminalInfo({name:Je,command:We,cwd:c});await A.terminalCreated({instanceId:Q,terminalId:ee,encryptedInfo:U||void 0,streamId:ve.getStreamId()??void 0})}A.onMetaSessionEstablished(()=>{L().catch(E=>{s.error("Failed to re-register metadata after meta session",E)})}),A.onReconnect(async()=>{try{await L();let E=A.getSocket();E&&De.attach(E,Q)}catch(E){s.error("Failed to re-register on reconnect",E)}});function j(){He?.dispose(),De.detach(),Te.dispose(),ot.dispose(),B.stopTracking(ee),B.dispose(),A.disposeInputStream(ee),A.terminalClosed({instanceId:Q,terminalId:ee}).catch(()=>{}),A.unregisterWorkspace(Q).catch(()=>{}),A.disconnect(),ve.dispose()}ve.setOnExit(()=>{m.disable(),process.stderr.write(`Session ended.
|
|
51
53
|
`),j(),process.exit(0)}),process.on("SIGINT",()=>{m.disable(),process.stderr.write(`Session ended.
|
|
52
54
|
`),j(),process.exit(0)}),process.on("SIGTERM",()=>{m.disable(),process.stderr.write(`Session ended.
|
|
53
55
|
`),j(),process.exit(0)})}async function Ud(r){await r.logout(),process.stderr.write(`Logged out.
|
|
@@ -55,8 +57,8 @@ tell application "System Events" to get value of property list item "CFBundleNam
|
|
|
55
57
|
`),t&&process.stderr.write(`Agent ID: ${t}
|
|
56
58
|
`)):(process.stderr.write(`Status: not logged in
|
|
57
59
|
`),process.stderr.write(`Run 'termiq login' to authenticate.
|
|
58
|
-
`))}var
|
|
59
|
-
termiq v${
|
|
60
|
+
`))}var Dt=ce(wi()),Ae=process.argv.slice(2);(Ae.includes("--help")||Ae.includes("-h"))&&(process.stderr.write(`
|
|
61
|
+
termiq v${so()} \u2014 Access terminals from anywhere
|
|
60
62
|
|
|
61
63
|
Usage:
|
|
62
64
|
termiq Start a shell with cloud access (default)
|
|
@@ -84,16 +86,16 @@ tell application "System Events" to get value of property list item "CFBundleNam
|
|
|
84
86
|
Environment:
|
|
85
87
|
TERMIQ_TOKEN API key (equivalent to --token)
|
|
86
88
|
|
|
87
|
-
`),process.exit(0));(Ae.includes("--version")||Ae.includes("-V"))&&(process.stdout.write(`${
|
|
89
|
+
`),process.exit(0));(Ae.includes("--version")||Ae.includes("-V"))&&(process.stdout.write(`${so()}
|
|
88
90
|
`),process.exit(0));var Wd=fd(Ae,Vc,cd);Wd&&(process.stderr.write(`Unknown flag: ${Wd}
|
|
89
91
|
Run 'termiq --help' for usage.
|
|
90
|
-
`),process.exit(1));var Hd=ad(Ae,Vc)??"start",Uv=Ae.includes("--verbose")||Ae.includes("-v"),qv=Ae.includes("--watch")||Ae.includes("-w"),Wv=Ae.includes("--log-to-file"),Hv=Ae.includes("--statusline"),Vv=Ae.includes("--multi-viewer"),
|
|
92
|
+
`),process.exit(1));var Hd=ad(Ae,Vc)??"start",Uv=Ae.includes("--verbose")||Ae.includes("-v"),qv=Ae.includes("--watch")||Ae.includes("-w"),Wv=Ae.includes("--log-to-file"),Hv=Ae.includes("--statusline"),Vv=Ae.includes("--multi-viewer"),zv=Ae.includes("--force"),Kv=Ae.find(r=>r.startsWith("--token="))?.split("=")[1]||(Ae.includes("--token")?Ae[Ae.indexOf("--token")+1]:void 0),Vd=Ae.find(r=>r.startsWith("--server="))?.split("=")[1]||(Ae.includes("--server")?Ae[Ae.indexOf("--server")+1]:void 0),rf=Ae.find(r=>r.startsWith("--log-level="))?.split("=")[1]||(Ae.includes("--log-level")?Ae[Ae.indexOf("--log-level")+1]:void 0),$v=["silent","error","warn","info","debug"],Gv=rf&&$v.includes(rf)?rf:Uv?"info":"silent",Yv=Ae.find(r=>r.startsWith("--cid="))?.split("=")[1]||(Ae.includes("--cid")?Ae[Ae.indexOf("--cid")+1]:void 0),Xv=Yv||(0,Dt.generateCorrelationId)(),Jv=process.env.TERMIQ_TOKEN,Sr=new bi(Gv,Wv),ds=new ei,xr=new ti(Vd?{serverUrl:Vd}:void 0),ps=new Si,_o=new Ti(Sr),Pi=new ki;async function Zv(){switch(Hd){case"start":case void 0:{process.env.TERMIQ_SESSION_ACTIVE==="1"&&!zv&&(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).
|
|
91
93
|
\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.
|
|
92
|
-
`),process.exit(1)),Vv&&await xr.setMultiViewer(!0);let r=xr.getMultiViewer();await jd({storage:
|
|
94
|
+
`),process.exit(1)),Vv&&await xr.setMultiViewer(!0);let r=xr.getMultiViewer();await jd({storage:ds,config:xr,logger:Sr,machineId:ps,notification:_o,browser:Pi,cwd:process.cwd(),watch:qv,statusLine:Hv,multiViewer:r});break}case"login":{let r=new URL(xr.getServerUrl()).host,e=await ps.getMachineId(),t=new Dt.CryptoService(ds,Sr,r,e);await t.initialize();let s=new Dt.AuthService(ds,t,ps,xr,Sr,_o,Pi,r,e),i=await mo(s,Pi,Sr,Kv||Jv);process.exit(i?0:1);break}case"logout":{let r=new URL(xr.getServerUrl()).host,e=await ps.getMachineId(),t=new Dt.CryptoService(ds,Sr,r,e);await t.initialize();let s=new Dt.AuthService(ds,t,ps,xr,Sr,_o,Pi,r,e);await Ud(s),process.exit(0);break}case"status":{let r=new URL(xr.getServerUrl()).host,e=await ps.getMachineId(),t=new Dt.CryptoService(ds,Sr,r,e);await t.initialize();let s=new Dt.AuthService(ds,t,ps,xr,Sr,_o,Pi,r,e);await qd(s),process.exit(0);break}case"version":{process.stdout.write(`${so()}
|
|
93
95
|
`),process.exit(0);break}case"help":{process.stderr.write(`Run 'termiq --help' for full usage.
|
|
94
96
|
`),process.exit(0);break}default:process.stderr.write(`Unknown command: ${Hd}
|
|
95
97
|
Run 'termiq --help' for usage.
|
|
96
|
-
`),process.exit(1)}}(0,
|
|
98
|
+
`),process.exit(1)}}(0,Dt.runWithCorrelation)(Xv,()=>Zv().catch(r=>{process.stderr.write(`Fatal error: ${r instanceof Error?r.message:String(r)}
|
|
97
99
|
`),process.exit(1)}));
|
|
98
100
|
/*! Bundled license information:
|
|
99
101
|
|